Algorithmadvanced
Extended finite element method
Also called XFEM, X-FEM.
Enriches the approximation through a partition of unity with discontinuous and singular functions, so cracks can grow without remeshing.
- Time
- Θ(n) worst
- Space
- Θ(n) extra
- Where
- n = the number of nodes of the one dimensional mesh
- Model
- Real RAM
- Properties
- deterministicnot iterativekeeps nodal values with shifted enrichmentmesh independent of discontinuitypartition of unity enrichmentsymmetric stiffness
- Evidence
- Proof sketchCode in 1 languages
- Origin
- T. Belytschko, T. Black, N. Moës, J. Dolbow, J. M. Melenk, I. Babuška, 1999
The extended finite element method (XFEM) puts a crack, a material interface or another known feature of the solution into a finite element space without making the mesh follow it. The standard shape functions form a partition of unity, . XFEM multiplies some of them by an enrichment function that has the known feature, for example a jump across the crack or a kink at the interface, and adds the products to the space with new unknowns . Only the nodes whose support the feature touches get the extra unknowns. The Galerkin method then works in this larger space with the normal weak form, and the quadrature splits the cut elements along the feature. When the crack grows, only the set of enriched nodes and the enrichment change. The mesh stays the same, which is the main gain over remeshing.
In plain words
A finite element mesh is a set of small pieces, and inside each piece the solution is a simple smooth shape. A crack makes the solution jump, and a smooth shape cannot jump inside a piece. The usual remedy is to cut the mesh along the crack, which is hard when the crack grows. XFEM keeps the mesh. In each piece that the crack cuts, it adds a second shape that has the jump in it, so the piece can now show a jump at the right place. A piece that the crack does not touch stays as it was. When the crack grows into the next piece, that piece also gets the extra shape, and nothing else changes.
The problem
Input. A domain with a mesh of standard finite elements, a known curve (a point in one dimension) where the solution has a jump, a kink or a singularity, and a linear elliptic problem, here the bar equation on with and . The stiffness is for and for .
Output. A Galerkin approximation that has the feature at for any position of in the mesh.
The two features of the reference code.
- Cohesive crack. The bar is cut at , can jump there, the force is continuous, and a spring of stiffness transmits it: with . The weak form is for all with , where may jump at .
- Material interface. is continuous at and jumps, because jumps and is continuous. The weak form is the standard one in .
The enriched space. With the level set , let be the cut element that contains , and let be its nodes. Then
with the shifted Heaviside function for the crack and the ridge function of Moës, Cloirec, Cartraud and Remacle for the interface. Both enrichments are zero at every node, so and the Dirichlet values are set on as usual. In two and three dimensions, the nodes of the elements that contain a crack tip also get the four branch functions of the asymptotic crack tip field.
The algorithm
XFEM-1D(nodes, c, kind, E, f, u_0, u_L, k)- 1
find the element e with x_e < c < x_{e+1}; enrich its two nodes with one new unknown each - 2
for each element, split it at c if c is inside, else keep it whole - 3
at each Gauss point of each piece, evaluate N_I, N_I psi_I and their derivatives - 4
add w E (phi_i)' (phi_j)' to K and w f phi_i to F for all pairs of nonzero functions - 5
for a cohesive crack, add k [phi_i] [phi_j] to K, where [N_I psi_I] = N_I(c) - 6
set u_1 = u_0 and u_n = u_L, and solve K z = F for the other unknowns - 7
u_h(x) <- sum of N_I(x) u_I + sum over enriched I of N_I(x) psi_I(x) a_I - 8
return u_h
Line L2 is what makes the quadrature correct. The enriched functions have a jump or a kink at , so a Gauss rule on the whole element would integrate them with an error that does not go away. On each piece the integrands of are polynomials of degree at most 2, and the two point Gauss rule is exact up to degree 3. Line L5 uses that the jump of at is for both nodes of the cut element.
Example
One element with a cohesive crack. Take the mesh , , , , , and . The enriched functions are and , with derivatives and . Their stiffness entries are , and for the pair. The jumps at are , so line L5 adds to all four entries. The coupling with is and . The system is
Then to the left of the crack and to the right. This is the exact solution: the force is and the jump is . One element without remeshing holds the crack.
Two elements with an interface. Take the mesh , , , , , and . The exact force is and . Standard linear elements on the same mesh, with the stiffness integrated exactly, give . XFEM with the ridge enrichment gives and is exact everywhere.
Convergence. The reference tests take , , and uniform meshes with elements. The table shows the energy norm error and the observed order per halving of .
| XFEM, | standard, | XFEM, | standard, | |
|---|---|---|---|---|
| 4 | ||||
| 16 | (order ) | (order ) | (order ) | |
| 64 | (order ) | (order ) | (order ) | |
| 256 | (order ) | (order ) | (order ) |
XFEM keeps the optimal order 1 of linear elements. Standard elements drop to order , because one element must fit a kinked function with a straight line.
Correctness
The proof has four steps. First, on the cut element the four functions of the crack span exactly the functions that are linear on each side of , with any jump. The ridge space contains every continuous function that is linear on each side. Both sets of functions are linearly independent, so the stiffness matrix is nonsingular. Second, the bilinear form is symmetric and coercive, so the Galerkin solution is the best approximation in the energy norm (Céa's lemma with constant 1). Third, for the exact solution is linear on each side of , so it lies in the space and XFEM returns it to rounding error for any position of . Fourth, for a load , the function that interpolates at the nodes and at lies in the space, and the interpolation error on each piece gives the bound , which is order 1 in .
Proof: The one dimensional XFEM space contains the kinked and cracked solutions, and the Galerkin error is of order hfull
Setting. Nodes with spacing at most , hat functions , and a point with . Put , , , and let on and on , with . The crack enrichments are and . The interface enrichment is the ridge on , extended by zero outside (as in the code, which uses it on the cut element only), for both nodes. The discrete space is spanned by all and by (crack) or (interface).
For the crack, is the set of functions in and (separately), and with . For the interface, and . In both cases is the subspace with , the energy norm is , and the exact and discrete solutions satisfy for all in and in , with and .
Lemma 1 (the enrichments are local and vanish at the nodes). Every enriched function is zero outside and at every node.
Proof. is zero outside . On we have , so there. In the same way is zero outside , and on . The ridge is zero outside by definition, and zero at and because and there, and symmetrically at . So it is continuous on . At the nodes and the crack functions are , , and .
So for every node, the Dirichlet values of line L6 are the boundary values of , and : the crack functions are linear on each side of , and the ridge functions are continuous (they vanish at and ).
Lemma 2 (span on the cut element). On :
- The crack functions span exactly the functions that are linear on and linear on , a space of dimension 4, so they are linearly independent.
- The ridge functions are linearly independent, and their span contains every continuous function that is linear on and on .
Proof. (1) The four functions are linear on each side, so the span is inside that space, which has dimension . On , , so a combination is . On it is . Any pair of linear functions comes from , , , . So the span has dimension 4 and the four functions are independent.
(2) Since on , the span contains . The function is continuous, linear on each side of , zero at and , and . A continuous function that is linear on each side is fixed by , and , and , because both sides are linear on each side and agree at , and . For independence, let . At and the ridge is zero, so . The function is convex and not affine on , so its chord is strictly above it on and there. Then on , so .
With Lemma 1, the global functions are linearly independent too: outside only the standard hats are nonzero, and they are independent of each other and of the local functions.
Lemma 3 (coercivity). is symmetric and for every nonzero . On the finite dimensional the stiffness matrix is therefore symmetric positive definite and line L6 has a unique solution.
Proof. Symmetry is clear. If , then on and on , and (crack) because . So is constant on each side. makes the left constant zero and the right one. In the interface case is continuous and constant, so as well. A symmetric matrix with for every nonzero coefficient vector (nonzero by the linear independence above) is positive definite.
Theorem 1 (best approximation). .
Proof. For such , , and subtracting the two weak forms gives the orthogonality for . Then .
Theorem 2 (exactness for piecewise linear solutions). If , then for every position of .
Proof. With , on each side, so is constant on each side. The interface condition (continuity of , or of the force through the spring) makes it one constant , and is linear on and on , continuous for the interface and with jump for the crack. Integrating, (no last term for the interface), which is the formula of the reference code. Such a is linear on each uncut element, so it is a combination of hats there, and on it lies in the span of Lemma 2. So with the right boundary values, and Theorem 1 gives . By Lemma 3 applied to , .
Theorem 3 (order h with a load). Let restricted to and to be in . Then
Proof. Let be the function that is linear on each uncut element and on and , with at all nodes and . For the interface , so is continuous. By Lemma 2, is in , and has the boundary values of . On every piece (an uncut element, or ), the error vanishes at and , so has mean zero on . The Poincaré inequality for functions with mean zero on an interval of length , (Wirtinger's inequality, from the cosine series of ), applied to with , gives . For the crack , so and the spring term of is zero. Summing over the pieces with , , and Theorem 1 finishes the proof.
Remark (standard elements). Without enrichment, the best linear approximation on the cut element of a function whose derivative jumps by has a derivative error of order on a set of length of order , so the energy error is of order . The reference tests measure the order for and at the finest mesh for . Theorems 2 and 3 show that XFEM removes this loss and keeps the order of linear elements.
Complexity
In one dimension each element has at most four nonzero functions and only one element is enriched, so assembly takes time. The matrix is banded except for the two enriched rows, which couple only to the two nodes of the cut element, so a banded or sparse solver takes time and memory. The reference code uses dense Gaussian elimination that skips zero multipliers, which takes time and memory. In two dimensions a crack through a mesh with nodes enriches about nodes with the jump and a fixed number of nodes with the 4 branch functions. The cost is that of a standard finite element solve with a few more unknowns, plus the subdivision of the cut elements for quadrature.
Properties
- The mesh does not follow the discontinuity. The position of enters only through the choice of enriched nodes, the enrichment and the quadrature split. Crack growth changes these and nothing else.
- Conforming for the interface. The ridge enrichment is continuous and zero outside the cut element, so the space is a subspace of and the method is a standard conforming Galerkin method.
- Nodal values keep their meaning. With shifted enrichments, . The Dirichlet values are set as in standard finite elements, and post processing at the nodes needs no correction.
- Symmetric positive definite. The stiffness matrix is symmetric, and positive definite on the free unknowns when the enrichment is linearly independent of the standard functions.
- No blending problem in one dimension. Here the enrichment is zero outside the cut element. In two dimensions, elements where only some nodes are enriched (blending elements) do not reproduce the enrichment and can reduce the order.
Variants and improvements
- Crack tip enrichment. In 2D and 3D linear fracture, the nodes near the tip also get the four branch functions. With enrichment in a fixed radius around the tip (geometric enrichment), not only in the tip element, the order of convergence is optimal.
- Generalized finite element method (GFEM). The same partition of unity idea with enrichments taken from local numerical solutions or from analytic solutions of local problems, as in Melenk and Babuška.
- Level set description. Two level sets describe a crack in 2D or 3D, one for the crack surface and one for its front. The level set method or the fast marching method moves them as the crack grows.
- Stable GFEM. Babuška and Banerjee subtract the interpolant of the enrichment from the enrichment. This keeps the condition number close to that of standard elements when the feature is near a node.
- Cut finite element method. The cut finite element method also leaves the mesh fixed but doubles the unknowns of the cut elements and imposes the interface conditions weakly with Nitsche's method and a ghost penalty for stability.
When to use it
Use XFEM when a crack, a material interface, a void or a contact surface moves through a fixed mesh, or when the mesh of a complex microstructure would be hard to make conforming. It is common for crack growth in 2D and 3D linear fracture mechanics, for inclusions and voids in composite materials, and for two phase flow with a level set interface. If the feature does not move and a conforming mesh is easy to make, standard finite elements with the mesh on the interface are simpler and have no quadrature or conditioning issues.
Pitfalls
- Quadrature over cut elements. Gauss points on the whole cut element integrate the jump and the kink with an error that does not converge. Split the element along the feature (line L2), or use a quadrature that adapts to it.
- Conditioning when the feature is near a node. If is close to a node, the enriched functions are almost zero, and the matrix is nearly singular. In the reference test with 4 elements, and , the small diagonal entry of the ridge unknowns is at , at and at , and the error goes from to . Remove the enrichment of nodes whose cut part is very small, or scale the unknowns.
- Blending elements. In 2D and 3D, elements with some enriched and some standard nodes do not form a partition of unity for the enrichment. The error there can reduce the order. Corrected or shifted enrichments and the ridge function reduce this effect.
- Unshifted enrichment. Without the shift, , so the Dirichlet values and the nodal output need a correction. The space is the same, so the answer does not change if this is done right.
- Crack tip singularity in a plain Heaviside model. A jump enrichment alone puts the tip at an element edge and misses the field. Stress intensity factors from such a model are wrong unless the tip is enriched or the mesh is very fine.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extended-finite-element-method/. The authors are listed in prov/R1XMNZ.jsonl.
"""Extended finite element method (XFEM) for a one-dimensional bar.
Solves -(E u')' = f on (0, L) with u(0) = u0 and u(L) = uL and an interface
at x = c that may lie anywhere inside an element:
kind "crack": a cohesive crack, E u' = k [u] on both sides, [E u'] = 0
(Heaviside enrichment, shifted so that it is 0 at the nodes),
kind "interface": a material interface, [u] = 0 and [E u'] = 0
(ridge enrichment of Moes and coauthors 2003),
kind "none": standard linear elements on the same mesh, no enrichment.
E is E1 to the left of c and E2 to the right. The mesh never moves with c.
"""
import math
import scimat
GAUSS2 = [(-1 / math.sqrt(3), 1.0), (1 / math.sqrt(3), 1.0)]
class XFEM1D:
def __init__(self, nodes, c, kind, E1, E2, f=None, u0=0.0, uL=0.0, k=None):
self.x = list(nodes)
self.c, self.kind, self.E1, self.E2 = c, kind, E1, E2
n = len(self.x)
f = f or (lambda t: 0.0)
cut = next(e for e in range(n - 1) if self.x[e] < c < self.x[e + 1]) if kind != "none" else None # @line L1
self.cut = cut
self.enriched = [cut, cut + 1] if cut is not None else []
self.ndof = n + len(self.enriched)
kmat = scimat.zeros(self.ndof)
rhs = [0.0] * self.ndof
for e in range(n - 1):
a, b = self.x[e], self.x[e + 1]
pieces = [(a, c), (c, b)] if a < c < b else [(a, b)] # @line L2
for (p, q) in pieces:
for t, w in GAUSS2:
xq = (p + q) / 2 + t * (q - p) / 2
wq = w * (q - p) / 2
dofs, vals, ders = self._functions(e, xq) # @line L3
ex = E1 if xq < c else E2
for i, vi, di in zip(dofs, vals, ders):
rhs[i] += wq * vi * f(xq)
for j, dj in zip(dofs, ders):
kmat[i][j] += wq * ex * di * dj # @line L4
if kind == "crack":
# cohesive term k [u][v] at x = c; the jump of the shifted Heaviside term is N_I(c)
jumps = [(n + m, self._hat(cut, node, c)) for m, node in enumerate(self.enriched)]
for i, ji in jumps:
for j, jj in jumps:
kmat[i][j] += k * ji * jj # @line L5
# Dirichlet values at the two ends (all enrichments vanish at the nodes)
fixed = {0: u0, n - 1: uL}
free = [d for d in range(self.ndof) if d not in fixed]
a_ff = [[kmat[i][j] for j in free] for i in free]
b_f = [rhs[i] - sum(kmat[i][j] * v for j, v in fixed.items()) for i in free]
sol = scimat.solve(a_ff, b_f) # @line L6
self.u = [0.0] * self.ndof
for d, v in fixed.items():
self.u[d] = v
for d, v in zip(free, sol):
self.u[d] = v
self.stiffness = kmat
def _hat(self, e, node, xq):
a, b = self.x[e], self.x[e + 1]
return (b - xq) / (b - a) if node == e else (xq - a) / (b - a)
def _enrichment(self, xq, node):
"""Return (psi, psi') of the enrichment function attached to the node, at xq."""
if self.kind == "crack":
h = 1.0 if xq > self.c else 0.0
hn = 1.0 if self.x[node] > self.c else 0.0
return h - hn, 0.0
# ridge: sum_I N_I |phi_I| - |sum_I N_I phi_I| on the cut element, phi = x - c
a, b = self.x[self.cut], self.x[self.cut + 1]
na, nb = (b - xq) / (b - a), (xq - a) / (b - a)
psi = na * abs(a - self.c) + nb * abs(b - self.c) - abs(xq - self.c)
dpsi = (abs(b - self.c) - abs(a - self.c)) / (b - a) - (1.0 if xq > self.c else -1.0)
return psi, dpsi
def _functions(self, e, xq):
"""Return the global dofs, values and derivatives of the nonzero functions at xq in element e."""
a, b = self.x[e], self.x[e + 1]
h = b - a
dofs = [e, e + 1]
vals = [(b - xq) / h, (xq - a) / h]
ders = [-1 / h, 1 / h]
if e == self.cut:
for m, node in enumerate(self.enriched):
psi, dpsi = self._enrichment(xq, node)
nv, nd = vals[m], ders[m]
dofs.append(len(self.x) + m)
vals.append(nv * psi)
ders.append(nd * psi + nv * dpsi)
return dofs, vals, ders
def value(self, xq):
"""Return (u_h(xq), u_h'(xq)); at xq = c the left limit is taken."""
e = max(0, min(len(self.x) - 2, next((i for i in range(len(self.x) - 1) if xq <= self.x[i + 1]), len(self.x) - 2)))
dofs, vals, ders = self._functions(e, xq)
u = sum(self.u[d] * v for d, v in zip(dofs, vals)) # @line L7
du = sum(self.u[d] * v for d, v in zip(dofs, ders))
return u, du # @line L8
def energy_error(self, du_exact):
"""Return the energy norm error sqrt(int E (u_h' - u')^2) by splitting every element at c."""
total = 0.0
for e in range(len(self.x) - 1):
a, b = self.x[e], self.x[e + 1]
pieces = [(a, self.c), (self.c, b)] if a < self.c < b else [(a, b)]
for p, q in pieces:
for t, w in GAUSS2:
xq = (p + q) / 2 + t * (q - p) / 2
dofs, _, ders = self._functions(e, xq)
duh = sum(self.u[d] * v for d, v in zip(dofs, ders))
ex = self.E1 if xq < self.c else self.E2
total += w * (q - p) / 2 * ex * (duh - du_exact(xq)) ** 2
return math.sqrt(total)
def exact_piecewise_linear(c, E1, E2, u0, uL, L=1.0, k=None):
"""Return (u, du, sigma) of the exact solution for f = 0, with an optional cohesive crack."""
compliance = c / E1 + (L - c) / E2 + (1 / k if k else 0.0)
sigma = (uL - u0) / compliance
jump = sigma / k if k else 0.0
def u(x):
if x <= c:
return u0 + sigma / E1 * x
return u0 + sigma / E1 * c + jump + sigma / E2 * (x - c)
def du(x):
return sigma / E1 if x < c else sigma / E2
return u, du, sigma
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_extended_finite_element_method.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/extended-finite-element-method/. The authors are listed in prov/R1XMNZ.jsonl.
import random
import scimat
from extended_finite_element_method import XFEM1D, exact_piecewise_linear
def uniform(n):
return [i / n for i in range(n + 1)]
def max_error(model, u, c):
pts = [j / 97 for j in range(98)]
return max(abs(model.value(x)[0] - u(x)) for x in pts if abs(x - c) > 1e-12)
def interface_load_solution(c, e1, e2):
"""Exact derivative for -(E u')' = 1, u(0) = u(1) = 0, with a material interface at c."""
s0 = (c * c / (2 * e1) + (1 - c * c) / (2 * e2)) / (c / e1 + (1 - c) / e2)
return lambda x: (s0 - x) / (e1 if x < c else e2)
def test_hand_example_one_element_cohesive_crack():
model = XFEM1D([0.0, 1.0], 0.5, "crack", 1.0, 1.0, u0=0.0, uL=1.0, k=2.0)
assert all(abs(a - b) < 1e-15 for a, b in zip(model.u, [0.0, 1.0, 1 / 3, 1 / 3]))
k = model.stiffness
assert abs(k[2][2] - 1.0) < 1e-15 and abs(k[2][3] - 0.5) < 1e-15 and abs(k[2][1] + 0.5) < 1e-15
# the jump of the solution is sigma / k with sigma = 2/3
left, right = model.value(0.5 - 1e-12)[0], model.value(0.5 + 1e-12)[0]
assert abs(right - left - 1 / 3) < 1e-10
def test_hand_example_two_elements_interface():
exact, _, sigma = exact_piecewise_linear(0.3, 1.0, 4.0, 0.0, 1.0)
assert abs(sigma - 40 / 19) < 1e-14
xfem = XFEM1D([0.0, 0.5, 1.0], 0.3, "interface", 1.0, 4.0, u0=0.0, uL=1.0)
plain = XFEM1D([0.0, 0.5, 1.0], 0.3, "none", 1.0, 4.0, u0=0.0, uL=1.0)
assert abs(xfem.u[1] - 14 / 19) < 1e-14
assert abs(plain.u[1] - 20 / 31) < 1e-14
assert max_error(xfem, exact, 0.3) < 1e-14
def test_piecewise_linear_solutions_are_exact_for_any_position():
rng = random.Random(11)
for _ in range(40):
n = rng.randint(2, 30)
c = rng.uniform(0.02, 0.98)
if min(abs(c - i / n) for i in range(n + 1)) < 1e-6:
continue
e1, e2 = rng.uniform(0.5, 5), rng.uniform(0.5, 5)
u0, ul = rng.uniform(-1, 1), rng.uniform(-1, 1)
for kind, k in (("interface", None), ("crack", rng.uniform(0.5, 10))):
exact, du, _ = exact_piecewise_linear(c, e1, e2, u0, ul, k=k)
model = XFEM1D(uniform(n), c, kind, e1, e2, u0=u0, uL=ul, k=k)
assert max_error(model, exact, c) < 1e-12
assert model.energy_error(du) < 1e-11
def test_shifted_enrichment_keeps_nodal_values():
c, k = 0.43, 2.5
exact, _, _ = exact_piecewise_linear(c, 2.0, 1.0, 0.0, 1.0, k=k)
model = XFEM1D(uniform(7), c, "crack", 2.0, 1.0, u0=0.0, uL=1.0, k=k)
for i, x in enumerate(uniform(7)):
assert abs(model.u[i] - exact(x)) < 1e-14
def test_only_the_cut_element_carries_enrichment():
model = XFEM1D(uniform(6), 0.4, "interface", 1.0, 3.0, u0=0.0, uL=1.0)
assert model.cut == 2 and model.enriched == [2, 3] and model.ndof == 9
for e in range(6):
dofs, _, _ = model._functions(e, (e + 0.5) / 6)
assert (len(dofs) == 4) == (e == 2)
def test_standard_elements_lose_accuracy_at_the_interface():
c, e1, e2 = 1 / 3, 1.0, 10.0
exact, du, _ = exact_piecewise_linear(c, e1, e2, 0.0, 1.0)
errs = [XFEM1D(uniform(n), c, "none", e1, e2, u0=0.0, uL=1.0).energy_error(du) for n in (4, 16, 64, 256)]
rates = [r / 2 for r in scimat.observed_order(errs)]
assert all(abs(r - 0.5) < 0.06 for r in rates)
assert errs[-1] > 0.07
def test_convergence_with_a_load():
c, e1, e2 = 1 / 3, 1.0, 10.0
du = interface_load_solution(c, e1, e2)
xfem, plain = [], []
for n in (4, 16, 64, 256):
nodes = uniform(n)
xfem.append(XFEM1D(nodes, c, "interface", e1, e2, f=lambda x: 1.0).energy_error(du))
plain.append(XFEM1D(nodes, c, "none", e1, e2, f=lambda x: 1.0).energy_error(du))
rx = [r / 2 for r in scimat.observed_order(xfem)]
rp = [r / 2 for r in scimat.observed_order(plain)]
assert rx[-1] > 0.98 and rp[-1] < 0.6
assert plain[-1] > 3 * xfem[-1]
def test_cohesive_crack_with_a_load():
c, e1, e2, k = 1 / 3, 1.0, 10.0, 5.0
s1 = (c * c / (2 * e1) + (1 - c * c) / (2 * e2) + c / k) / (c / e1 + (1 - c) / e2 + 1 / k)
def du(x):
return (s1 - x) / (e1 if x < c else e2)
errs = [XFEM1D(uniform(n), c, "crack", e1, e2, f=lambda x: 1.0, k=k).energy_error(du) for n in (4, 16, 64)]
rates = [r / 2 for r in scimat.observed_order(errs)]
assert rates[-1] > 0.95
model = XFEM1D(uniform(64), c, "crack", e1, e2, f=lambda x: 1.0, k=k)
jump = model.value(c + 1e-12)[0] - model.value(c - 1e-12)[0]
assert abs(jump - (s1 - c) / k) < 1e-6
def test_stiffness_is_symmetric():
model = XFEM1D(uniform(5), 0.47, "crack", 1.0, 2.0, u0=0.0, uL=1.0, k=4.0)
kmat = model.stiffness
n = len(kmat)
assert all(abs(kmat[i][j] - kmat[j][i]) < 1e-14 for i in range(n) for j in range(n))
def test_conditioning_degrades_near_a_node():
diag, errs = [], []
for eps in (1e-2, 1e-6, 1e-10):
c = 0.5 + eps
exact, _, _ = exact_piecewise_linear(c, 1.0, 10.0, 0.0, 1.0)
model = XFEM1D(uniform(4), c, "interface", 1.0, 10.0, u0=0.0, uL=1.0)
diag.append(model.stiffness[6][6])
errs.append(max_error(model, exact, c))
assert diag[0] > 1e-3 and diag[-1] < 1e-17
assert errs[0] < 1e-14 and errs[-1] > 1e-11
History
Melenk and Babuška in 1996 proved that local approximation spaces glued by a partition of unity give a global space with the same local accuracy, and called it the partition of unity method. Belytschko and Black in 1999 used this idea to enrich the elements near a crack with the asymptotic crack tip fields, so a crack needed only a small amount of remeshing. Moës, Dolbow and Belytschko in the same year added the Heaviside enrichment for the crack faces, removed the remeshing completely and named the method the extended finite element method. The level set descriptions of cracks and interfaces, the ridge enrichment of Moës and coauthors in 2003, and the work on blending and conditioning followed. The overview of Fries and Belytschko from 2010 lists the main variants and applications.
References
- T. Belytschko and T. Black, Elastic crack growth in finite elements with minimal remeshing, International Journal for Numerical Methods in Engineering 45(5) (1999) 601-620, the enrichment of the nodes near a crack tip with the asymptotic crack tip fields through the partition of unity of the element shape functions
- N. Moës, J. Dolbow and T. Belytschko, A finite element method for crack growth without remeshing, International Journal for Numerical Methods in Engineering 46(1) (1999) 131-150, the jump enrichment of the nodes whose support the crack cuts, the four branch functions at the tip, and crack growth on a fixed mesh
- J. M. Melenk and I. Babuška, The partition of unity finite element method, basic theory and applications, Computer Methods in Applied Mechanics and Engineering 139(1-4) (1996) 289-314, the approximation theorem, local approximation spaces glued by a partition of unity give a global space with the same accuracy
- N. Moës, M. Cloirec, P. Cartraud and J.-F. Remacle, A computational approach to handle complex microstructure geometries, Computer Methods in Applied Mechanics and Engineering 192(28-30) (2003) 3163-3177, the ridge enrichment for material interfaces defined by a level set, and its optimal convergence
- T. P. Fries and T. Belytschko, The extended/generalized finite element method, an overview of the method and its applications, International Journal for Numerical Methods in Engineering 84(3) (2010) 253-304, the shifted enrichment, blending elements, the integration of enriched functions, conditioning, and the list of applications
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag R1XMNZ Edit this page History Report an error Markdown