Algorithmadvanced
Finite cell method
Also called Parvizian-Duster-Rank finite cell method.
Parvizian, Duster and Rank's fictitious domain method that embeds a part in a grid of high-order cells and integrates only over the material by adaptive quadrature.
- Solves
- Poisson equation
- Time
- O(m (d + 1) g p^2 + (m p)^3) worst
- Space
- O((m p)^2) extra
- Where
- d = bisection depth; g = Gauss points per subcell; m = number of active cells; p = polynomial degree
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jamshid Parvizian, Alexander Düster, Ernst Rank, 2007
The finite cell method (FCM) solves a boundary value problem on a complicated part without a mesh that fits the part. It embeds the part in a simple grid of large cells, uses a high-order basis on the cells, sets the material stiffness to a small value times the real one outside the part, and integrates the cells that the boundary cuts with an adaptive rule that refines toward the boundary. The geometry enters only through an inside or outside test at the quadrature points, for example a signed distance function or a level set. It differs from the other immersed methods of this site by its high order basis and the small stiffness in the fictitious part: CutFEM stabilizes the cut cells with a ghost penalty instead, immersogeometric analysis integrates the exact CAD boundary in a background spline mesh, and trimmed isogeometric analysis cuts the CAD patches themselves, with no background mesh. This page shows the method on a 1D bar, where every effect of can be proved and measured.
In plain words
Making a mesh that follows every hole and fillet of a part is slow and fails often. The finite cell method skips it. It puts the part inside a box, cuts the box into a few large, equal cells, and gives each cell a rich set of smooth functions.
The space outside the part is filled with a very soft fake material, so that the equations stay solvable. To add up the energy of a cell, the computer asks for each sample point whether it is inside the part. In cells that the border crosses, it uses more and more sample points near the border, to see the border well.
The softer the fake material, the closer the answer gets to that of the part alone. But a very soft fake material makes the equations hard to solve with good accuracy, so in practice it stays small but not zero.
The problem
The physical problem is a bar with stiffness , load , a fixed end and a free or loaded end:
It is the 1D form of the Poisson equation and of linear elasticity. The bar is embedded in the domain , , cut into equal cells . The point need not be a cell vertex. The FCM problem on the embedding domain has the stiffness
the load on only, the point load at , and the natural (traction free) condition at . The weak form is: find with
where is the space of continuous functions with that are polynomials of degree on each active cell. A cell is active if it holds some material, that is . Cells that lie fully outside are dropped.
The basis on a cell is the hierarchic p-version basis on : the two nodal modes , and for the integrated Legendre polynomials , which vanish at both ends of the cell and have the derivative .
The algorithm
FINITE-CELL-BAR(cells, p, a, α, f, P)- 1
for each cell c = [x_0, x_1] with x_0 < a do ▷ cells with no material are dropped - 2
S ← subcells of c: split exactly at a, or bisect toward a to depth d - 3
for each subcell of S and each of its Gauss points x with weight ω do - 4
k ← E if x < a, else α E ▷ the inside test - 5
k_e[i][j] += k N_i'(x) N_j'(x) ω; if x < a then f_e[i] += f(x) N_i(x) ω - 6
add k_e and f_e into K and F by the degrees of freedom of c - 7
skip the degree of freedom of the vertex x = 0 ▷ u(0) = 0 - 8
solve K u = F
Line L2 is where FCM differs from a plain finite element method. In 2D and 3D the boundary is curved and cannot be followed exactly, so the cut cell is bisected into a quadtree or an octree toward the boundary, and each leaf gets a Gauss-Legendre rule. Line L4 then takes the coefficient at each Gauss point, so that a leaf crossed by the boundary is integrated with a discontinuous integrand. This is a form of adaptive quadrature that trades accuracy for simplicity. In 1D the exact split is possible, and the code offers both, so that the error of the bisection can be measured. The code uses Gauss points per subcell. A point load is added to at , and the dense solver of line L8 stands in for the sparse or banded solver of a real code.
Example
One cell, closed form. Take with one cell, , , , and . The exact solution is , with . The space is , and solving the system by hand gives
So the error is for , about for small , and grows with . The code matches this formula to for seven values of .
A smooth solution, p-extension. Take , four cells, (inside the third cell), , and . The table gives the error in the energy norm on with the exact split of line L2:
| 2 | |||
| 3 | |||
| 4 | |||
| 5 | |||
| 6 | |||
| 7 | |||
| 8 |
With the error falls exponentially in , as for a fitted mesh. With it stalls at a level set by , near times a constant once is large. This is the bound of the Correctness section: the term is small for low , but grows fast with ( for , for , for and for ), and then the bound takes over.
Conditioning. The price of is the condition number of , which grows from for to for and for in the same example. At the error with () is already larger than at , an effect of round-off. With the condition number stays below about for all up to 9.
Bisection. With and , the largest error on for the bisection depths is , , , and , and at it is , against for the exact split. The error falls by about 4 every two levels, that is about linearly in the size of the leaf that holds . Without bisection () the cut cell is integrated as if it were all material or all void at each Gauss point, and the error is . The quadrature error, not the basis, limits the method unless the cut cells are integrated well.
Correctness
The proof page proves four facts for the bar.
- The continuous problem is exact. For every the FCM solution on is the exact solution on and is constant on . The fictitious material carries no force, because the far end is free and it carries no load.
- The discrete problem is well posed for . The stiffness splits as , with from and from the fictitious part. Because only active cells are kept, is symmetric positive definite, so exists, and it is the Galerkin solution of the physical bar on the mesh whose last element is the cut part .
- The error as . In the energy norm of the physical part,
where is the energy in the fictitious part and is the largest eigenvalue of . So the total energy error is at most the best approximation error of the fitted mesh plus this term, and it tends to that of . 4. The one-cell formula of the example.
The test checks both bounds for and four values of . The rates in , the growth of , the conditioning and the effect of the bisection are measured, not proved. Dauge, Düster and Rank (2015) analyze the effect of in 2D and 3D.
Proof: The finite cell method for a bar, exactness of the continuous problem, well posedness for alpha = 0 and the error as alpha goes to 0full
We use the notation of the page. The physical bar is with , and , where is constant and . The embedding domain is with , the stiffness is on and on , the load is on only, and the end is free. All integrals are exact. The exact split of line L2 makes this true for polynomial , and the bisection only approximates it.
Theorem 1 (the continuous problem). Let and let . The problem: find with for all , has a unique solution, and on and on .
Proof. The bilinear form is bounded and, since and , coercive on by the Poincaré inequality . The right side is a bounded functional, because . So the Lax-Milgram lemma gives a unique solution. Let be the function of the statement. It is in , because is in and is continuous at . For , on , so . Integration by parts on with , and gives . So solves the problem, and by uniqueness it is the solution.
So for every the continuous FCM problem gives the exact solution on the physical part. The error of the discrete method comes from the discrete space, which ties the values on to those on through the polynomials of the cut cell, and from the quadrature.
The discrete problem. Let be the space of the page: continuous on the union of the active cells, a polynomial of degree on each active cell, and . With a basis of , the matrix of line L8 is , where
is the right end of the last active cell, and does not depend on . We write and . is symmetric and positive semi-definite.
Lemma 1 ( is positive definite). If only active cells are kept, is symmetric positive definite.
Proof. Symmetry is clear. Let with . Then on , and since is continuous with , on . Each active cell has , so it meets in an interval of positive length. On that interval the polynomial has infinitely many zeros, so on the whole cell. So .
If a cell with were kept, its inner modes would have no stiffness for , and would be singular. This is line L1.
Corollary (the case alpha = 0). For the system has a unique solution, and restricted to is the Galerkin solution of the physical bar in the space of continuous piecewise polynomials on the mesh , with the cut part as the last element. By Galerkin orthogonality it is the best approximation of in the energy norm of from that space.
Proof. The restriction to is a bijection from onto that space, because a polynomial on a cut cell is fixed by its values on the part inside, and every piecewise polynomial on the truncated mesh extends to the full cut cell by the same polynomial. Both and only see . So the system is the Galerkin system of the physical bar. Galerkin orthogonality, for all , gives the best approximation property.
Theorem 2 (the error as alpha goes to 0). Let solve for , and let be the largest eigenvalue of , that is the largest value of over . Then
Proof. is positive definite by Lemma 1, so exists. Let . Then . Multiply by :
by the Cauchy-Schwarz inequality for the semi-definite form .
For the first bound, drop and use twice: . Divide by if it is not zero.
For the second bound, use . Then , so .
Corollary (the total error). By the triangle inequality and the first corollary, the energy error on satisfies
and the second term tends to as . If is in the restricted space, the first term is , , and the error is .
Proposition (one cell). Let with one cell, , , , and . Then .
Proof. is the space of quadratics with , with the basis and . With on and on :
from , , , , , and . The determinant is with . Cramer's rule gives and , so . The exact value is , and the difference is .
What is not proved here. The exponential rate in of the best approximation for an analytic is the known rate of the p-version of the finite element method and is only measured on the page. The growth of with and with a small cut, the condition numbers, and the error of the bisection quadrature are measured, not proved.
Complexity
In the real RAM model, with active cells, degree , bisection depth and Gauss points per subcell:
- Assembly. A cut cell has leaves in 1D, because each level splits only the leaf that holds . Each Gauss point costs for the basis and for the cell matrix, so the assembly costs . In a quadtree or octree of depth has leaves along the boundary, which makes the integration of the cut cells the main cost of FCM in 3D.
- Solve. There are unknowns. The dense solver of the code costs time and space. The matrix is banded with bandwidth in 1D, so a banded solver costs .
Properties
- No fitted mesh. The geometry is only an inside test, so CAD models, voxel images from CT scans and implicit models can all be used directly.
- High order. With , a smooth solution and exact integration, the rate in is that of the p-version of the finite element method, since the cut cell is just a smaller element.
- A modeling error from . For the method solves a slightly different problem, with an error of order for low and in the worst case.
- Weak essential conditions. A Dirichlet condition on a boundary that cuts a cell cannot be set on the degrees of freedom. It is imposed weakly, usually by Nitsche's method or a penalty.
- Not exact. The quadrature of cut cells and both add errors.
Variants and improvements
- Spline bases. B-spline and hierarchical B-spline bases replace the p-version basis, which links FCM to isogeometric analysis and to immersogeometric analysis.
- Better cut cell integration. Moment fitting, the smart octree and the integration on a local tetrahedral subdivision of the cut cells reduce the number of quadrature points compared with plain bisection.
- Weak boundary conditions. Nitsche's method for Dirichlet conditions on the cut boundary, as reviewed by Schillinger and Ruess (2015).
- Stabilization. Instead of a small , a ghost penalty as in CutFEM or the removal of basis functions with small support controls the conditioning.
- Nonlinear and multi-physics problems. Plasticity, large deformation and thermal problems on CT data of bones and foams.
When to use it
Use FCM when the geometry is hard to mesh but easy to query: CT and voxel data, porous and cellular materials, and CAD models with many small features or gaps, as in the trimmed setting. It pays off most when a high order basis can be used, because the cells are large. Use a fitted mesh when one is cheap, when stresses on the boundary must be very accurate, or when the solution has boundary layers that the cell grid cannot follow.
Pitfalls
- A Dirichlet condition on the fictitious part. If the far end of the embedding domain is clamped instead of free, the fictitious material carries load. For , and , the flux at becomes instead of . Keep the fictitious boundary free, or impose the physical conditions on the physical boundary only.
- Integration of the cut cells. A plain Gauss rule on a cut cell can be very wrong, as the error of at shows. Refine toward the boundary, and check the result for convergence in .
- Small cut cells. When a cell holds only a sliver of material, is nearly singular and is very large. Then the bound is useless, and the error can reach the level.
- The choice of . A large adds a modeling error, and gives a badly conditioned or singular matrix in floating point. Values from to are common. Check that the result does not change when is divided by 100.
- Stresses on the boundary. The solution is accurate in energy, but values on the cut boundary converge more slowly. Do not read peak stresses off a cut cell without checking them.
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/finite-cell-method/. The authors are listed in prov/DX2BFW.jsonl.
"""The finite cell method for a 1D bar.
The physical bar is (0, a) with stiffness E, load f and u(0) = 0, and its
end x = a is free or carries a point load P. It is embedded in the cells of
(0, L), L > a. The fictitious part (a, L) gets the stiffness alpha E and no
load. The basis is the p-version basis of integrated Legendre polynomials,
continuous across cells. Cut cells are integrated either by splitting them
exactly at x = a, or by recursive bisection toward x = a with the
coefficient taken at each Gauss point, as the method does in 2D and 3D.
"""
from __future__ import annotations
from typing import Callable, List, Optional, Tuple
from ig2kit import gauss_legendre, solve_dense
def shapes(xi: float, p: int) -> Tuple[List[float], List[float]]:
"""Values and xi-derivatives of the p + 1 shape functions on [-1, 1].
N_0 = (1 - xi)/2 and N_1 = (1 + xi)/2 are the nodal modes. For k = 2..p,
N_k = (P_k - P_{k-2}) / (2k - 1), the integral of the Legendre polynomial
P_{k-1} from -1; it vanishes at both ends, and its derivative is P_{k-1}.
"""
leg = [1.0, xi]
for k in range(2, p + 1):
leg.append(((2 * k - 1) * xi * leg[-1] - (k - 1) * leg[-2]) / k)
val = [(1 - xi) / 2, (1 + xi) / 2]
der = [-0.5, 0.5]
for k in range(2, p + 1):
val.append((leg[k] - leg[k - 2]) / (2 * k - 1))
der.append(leg[k - 1])
return val, der
class FiniteCellBar:
def __init__(
self,
length: float,
ncell: int,
p: int,
a: float,
alpha: float,
f: Callable[[float], float],
E: float = 1.0,
P: float = 0.0,
depth: Optional[int] = None,
ng: Optional[int] = None,
):
self.L, self.p, self.a, self.alpha, self.f, self.E, self.P = length, p, a, alpha, f, E, P
self.depth = depth # None: split cut cells at a; an integer: bisect that many times
self.ng = ng or p + 3
self.x = [length * c / ncell for c in range(ncell + 1)]
# Keep only the cells that hold some material (L1).
self.cells = [c for c in range(ncell) if self.x[c] < a]
nc = len(self.cells)
# Dofs: vertex k has dof k - 1 (vertex 0 is fixed by u(0) = 0), then p - 1 inner modes per cell.
self.ndof = nc + nc * (p - 1)
def dofs(self, c: int) -> List[Optional[int]]:
nc, p = len(self.cells), self.p
left = None if c == 0 else c - 1
inner = [nc + c * (p - 1) + k for k in range(p - 1)]
return [left, c] + inner
def subcells(self, x0: float, x1: float) -> List[Tuple[float, float]]:
a = self.a
if not (x0 < a < x1):
return [(x0, x1)]
if self.depth is None:
return [(x0, a), (a, x1)] # @line L2
leaves, todo = [], [(x0, x1, 0)]
while todo:
s0, s1, d = todo.pop()
if s0 < a < s1 and d < self.depth:
m = 0.5 * (s0 + s1)
todo += [(s0, m, d + 1), (m, s1, d + 1)]
else:
leaves.append((s0, s1))
return sorted(leaves)
def assemble(self):
n, p = self.ndof, self.p
K = [[0.0] * n for _ in range(n)]
F = [0.0] * n
gx, gw = gauss_legendre(self.ng)
for c in self.cells: # @line L1
x0, x1 = self.x[c], self.x[c + 1]
h = x1 - x0
ke = [[0.0] * (p + 1) for _ in range(p + 1)]
fe = [0.0] * (p + 1)
for s0, s1 in self.subcells(x0, x1):
for t, w in zip(gx, gw): # @line L3
x = 0.5 * (s0 + s1) + 0.5 * (s1 - s0) * t
wt = 0.5 * (s1 - s0) * w
xi = 2 * (x - x0) / h - 1
val, der = shapes(xi, p)
dN = [d * 2 / h for d in der]
k = self.E if x < self.a else self.alpha * self.E # @line L4
for i in range(p + 1):
for j in range(p + 1):
ke[i][j] += k * dN[i] * dN[j] * wt # @line L5
if x < self.a:
fe[i] += self.f(x) * val[i] * wt
if x0 < self.a < x1 and self.P:
val, _ = shapes(2 * (self.a - x0) / h - 1, p)
for i in range(p + 1):
fe[i] += self.P * val[i]
dof = self.dofs(self.cells.index(c))
for i, gi in enumerate(dof): # @line L6
if gi is None:
continue # @line L7
F[gi] += fe[i]
for j, gj in enumerate(dof):
if gj is not None:
K[gi][gj] += ke[i][j]
return K, F
def solve(self) -> List[float]:
K, F = self.assemble()
self.coef = solve_dense(K, F) # @line L8
return self.coef
def value(self, x: float, nd: int = 0) -> float:
"""u_h(x) (nd = 0) or u_h'(x) (nd = 1) for x in the active cells."""
for idx, c in enumerate(self.cells):
x0, x1 = self.x[c], self.x[c + 1]
if x0 <= x <= x1:
h = x1 - x0
val, der = shapes(2 * (x - x0) / h - 1, self.p)
row = val if nd == 0 else [d * 2 / h for d in der]
return sum(r * self.coef[g] for r, g in zip(row, self.dofs(idx)) if g is not None)
raise ValueError("x is outside the active cells")
def errors(self, exact: Callable, dexact: Callable, samples: int = 400) -> Tuple[float, float]:
"""(largest |u_h - u| on [0, a], energy norm error on (0, a)); measured, not proved."""
a = self.a
emax = max(abs(self.value(a * k / samples) - exact(a * k / samples)) for k in range(samples + 1))
gx, gw = gauss_legendre(12)
en = 0.0
pts = sorted({min(xc, a) for xc in self.x} | {a})
for s0, s1 in zip(pts, pts[1:]):
for t, w in zip(gx, gw):
x = 0.5 * (s0 + s1) + 0.5 * (s1 - s0) * t
en += self.E * (self.value(x, 1) - dexact(x)) ** 2 * 0.5 * (s1 - s0) * w
return emax, en**0.5
def stiffness_parts(bar: FiniteCellBar) -> Tuple[List[List[float]], List[List[float]]]:
"""(K0, K1) with K(alpha) = K0 + alpha K1: the physical and the fictitious stiffness."""
keep = bar.alpha
bar.alpha = 0.0
K0, _ = bar.assemble()
bar.alpha = 1.0
Kt, _ = bar.assemble()
bar.alpha = keep
K1 = [[t - s for t, s in zip(rt, r0)] for rt, r0 in zip(Kt, K0)]
return K0, K1
def extension_constant(bar: FiniteCellBar, iters: int = 300) -> float:
"""C_ext = max over the discrete space of a1(v, v) / a0(v, v), the largest eigenvalue of K0^-1 K1."""
K0, K1 = stiffness_parts(bar)
n = len(K0)
v = [1.0 + 0.01 * i for i in range(n)]
lam = 0.0
for _ in range(iters):
w = solve_dense(K0, [sum(K1[i][j] * v[j] for j in range(n)) for i in range(n)])
nw = max(abs(t) for t in w)
lam = nw / max(abs(t) for t in v)
v = [t / nw for t in w]
return lam
def condition_estimate(K: List[List[float]], iters: int = 200) -> float:
"""Ratio of the largest to the smallest eigenvalue of an SPD matrix by power and inverse iteration."""
n = len(K)
def norm(v):
return sum(t * t for t in v) ** 0.5
v = [1.0 + 0.1 * i for i in range(n)]
lmax = 0.0
for _ in range(iters):
w = [sum(K[i][j] * v[j] for j in range(n)) for i in range(n)]
lmax = norm(w) / norm(v)
v = [t / norm(w) for t in w]
v = [1.0 + 0.1 * i for i in range(n)]
lmin_inv = 0.0
for _ in range(iters):
w = solve_dense(K, v)
lmin_inv = norm(w) / norm(v)
v = [t / norm(w) for t in w]
return lmax * lmin_inv
ig2kit.py 165 lines
# SPDX-License-Identifier: MIT
# Shared helper of the ig2 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small numerical helpers: B-spline basis with derivatives, Greville points,
Gauss-Legendre points and a dense linear solver.
Every function works with float, and the spline and solver functions also work
with fractions.Fraction, so that a test can check an exact identity.
"""
from __future__ import annotations
import math
from typing import List, Sequence, Tuple
def open_uniform_knots(p: int, ne: int, a=0, b=1) -> List:
"""Open knot vector of degree p with ne equal elements on [a, b].
The ends have multiplicity p + 1 and the interior knots are simple.
With Fraction inputs the knots are Fractions.
"""
inner = [a + (b - a) * k / ne for k in range(1, ne)]
return [a] * (p + 1) + inner + [b] * (p + 1)
def find_span(knots: Sequence, p: int, x) -> int:
"""Index s with knots[s] <= x < knots[s + 1], and the last non-empty span for x = knots[-1]."""
n = len(knots) - p - 1 # number of basis functions
if x >= knots[n]:
s = n - 1
while knots[s] == knots[s + 1]:
s -= 1
return s
lo, hi = p, n
while hi - lo > 1:
mid = (lo + hi) // 2
if x < knots[mid]:
hi = mid
else:
lo = mid
return lo
def basis_ders(knots: Sequence, p: int, s: int, x, nd: int) -> List[List]:
"""Values and derivatives of the p + 1 B-splines that are non-zero on span s.
Returns d with d[k][j] = the k-th derivative of N_{s - p + j} at x, for
k = 0..nd. This is algorithm A2.3 of Piegl and Tiller.
"""
one = x - x + 1
zero = x - x
ndu = [[zero] * (p + 1) for _ in range(p + 1)]
ndu[0][0] = one
left = [zero] * (p + 1)
right = [zero] * (p + 1)
for j in range(1, p + 1):
left[j] = x - knots[s + 1 - j]
right[j] = knots[s + j] - x
saved = zero
for r in range(j):
ndu[j][r] = right[r + 1] + left[j - r]
temp = ndu[r][j - 1] / ndu[j][r]
ndu[r][j] = saved + right[r + 1] * temp
saved = left[j - r] * temp
ndu[j][j] = saved
ders = [[zero] * (p + 1) for _ in range(nd + 1)]
for j in range(p + 1):
ders[0][j] = ndu[j][p]
for r in range(p + 1):
s1, s2 = 0, 1
a = [[zero] * (p + 1) for _ in range(2)]
a[0][0] = one
for k in range(1, nd + 1):
dval = zero
rk, pk = r - k, p - k
if r >= k:
a[s2][0] = a[s1][0] / ndu[pk + 1][rk]
dval = a[s2][0] * ndu[rk][pk]
j1 = 1 if rk >= -1 else -rk
j2 = k - 1 if r - 1 <= pk else p - r
for j in range(j1, j2 + 1):
a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][rk + j]
dval += a[s2][j] * ndu[rk + j][pk]
if r <= pk:
a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r]
dval += a[s2][k] * ndu[r][pk]
ders[k][r] = dval
s1, s2 = s2, s1
fac = p
for k in range(1, nd + 1):
for j in range(p + 1):
ders[k][j] = ders[k][j] * fac
fac *= p - k
return ders
def all_basis(knots: Sequence, p: int, x, nd: int = 0) -> List[List]:
"""Full rows: out[k][i] = k-th derivative of N_i at x, for all n basis functions."""
n = len(knots) - p - 1
s = find_span(knots, p, x)
d = basis_ders(knots, p, s, x, nd)
zero = x - x
out = [[zero] * n for _ in range(nd + 1)]
for k in range(nd + 1):
for j in range(p + 1):
out[k][s - p + j] = d[k][j]
return out
def greville(knots: Sequence, p: int) -> List:
"""Greville abscissae tau_i = (knots[i+1] + ... + knots[i+p]) / p."""
n = len(knots) - p - 1
return [sum(knots[i + 1 : i + p + 1]) / p for i in range(n)]
def solve_dense(a: List[List], b: List) -> List:
"""Solve a x = b by Gaussian elimination with partial pivoting.
Works with float and with Fraction (then the result is exact).
Raises ValueError if the matrix is singular (an exact zero pivot).
Cost O(n^3) operations.
"""
n = len(a)
m = [list(row) + [bi] for row, bi in zip(a, b)]
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[piv][c] == 0:
raise ValueError("singular matrix")
m[c], m[piv] = m[piv], m[c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
if f != 0:
row_r, row_c = m[r], m[c]
for k in range(c, n + 1):
row_r[k] -= f * row_c[k]
x = [0] * n
for r in range(n - 1, -1, -1):
acc = m[r][n]
for k in range(r + 1, n):
acc -= m[r][k] * x[k]
x[r] = acc / m[r][r]
return x
def gauss_legendre(n: int) -> Tuple[List[float], List[float]]:
"""Nodes and weights of the n-point Gauss-Legendre rule on [-1, 1]."""
xs, ws = [], []
for i in range(1, n + 1):
x = math.cos(math.pi * (i - 0.25) / (n + 0.5))
for _ in range(100):
p0, p1 = 1.0, x
for k in range(2, n + 1):
p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
dp = n * (x * p1 - p0) / (x * x - 1)
dx = p1 / dp
x -= dx
if abs(dx) < 1e-16:
break
p0, p1 = 1.0, x
for k in range(2, n + 1):
p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
dp = n * (x * p1 - p0) / (x * x - 1)
xs.append(x)
ws.append(2.0 / ((1 - x * x) * dp * dp))
return xs, ws
test_finite_cell_method.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/finite-cell-method/. The authors are listed in prov/DX2BFW.jsonl.
import math
import random
from finite_cell_method import (
FiniteCellBar,
condition_estimate,
extension_constant,
shapes,
stiffness_parts,
)
A = 0.6
K = math.pi / (2 * A)
EXACT = lambda x: math.sin(K * x)
DEXACT = lambda x: K * math.cos(K * x)
LOAD = lambda x: K * K * math.sin(K * x)
def energy(M, c):
n = len(c)
return math.sqrt(max(0.0, sum(c[i] * M[i][j] * c[j] for i in range(n) for j in range(n))))
def test_shape_functions() -> None:
rng = random.Random(11)
for p in range(1, 9):
for _ in range(20):
xi = rng.uniform(-1, 1)
val, der = shapes(xi, p)
assert abs(val[0] + val[1] - 1) < 1e-15
# the inner modes vanish at both ends
for e in (-1.0, 1.0):
v, _ = shapes(e, p)
assert all(abs(t) < 1e-14 for t in v[2:])
# derivative check by central differences
h = 1e-6
vp, _ = shapes(xi + h, p)
vm, _ = shapes(xi - h, p)
assert all(abs((s - t) / (2 * h) - d) < 1e-6 for s, t, d in zip(vp, vm, der))
def test_one_cell_closed_form() -> None:
"""One cell (0, 1), p = 2, a = 1/2, f = 1: u_h(a) - u(a) = alpha (1 - alpha) / (8 (1 + 14 alpha + alpha^2))."""
for alpha in (0.0, 1e-6, 1e-3, 0.01, 0.1, 0.5, 1.0):
bar = FiniteCellBar(1.0, 1, 2, 0.5, alpha, lambda x: 1.0)
bar.solve()
expect = alpha * (1 - alpha) / (8 * (1 + 14 * alpha + alpha * alpha))
assert abs(bar.value(0.5) - 0.125 - expect) < 1e-14
def test_exact_in_space_and_linear_in_alpha() -> None:
"""u = a x - x^2 / 2 is in the space restricted to (0, a): alpha = 0 is exact, and the error is O(alpha)."""
exact = lambda x: A * x - x * x / 2
dexact = lambda x: A - x
bar = FiniteCellBar(1.0, 4, 2, A, 0.0, lambda x: 1.0)
bar.solve()
assert max(bar.errors(exact, dexact)) < 1e-12
errs = []
for alpha in (1e-4, 1e-5, 1e-6):
bar = FiniteCellBar(1.0, 4, 2, A, alpha, lambda x: 1.0)
bar.solve()
errs.append(bar.errors(exact, dexact)[1])
assert 9 < errs[0] / errs[1] < 11 and 9 < errs[1] / errs[2] < 11
def test_alpha_bounds() -> None:
"""||u_alpha - u_0||_E <= min(alpha C_ext ||u_0||_E, sqrt(alpha)/2 ||u_0||_{E, fictitious})."""
for p in (2, 4, 6):
b0 = FiniteCellBar(1.0, 4, p, A, 0.0, LOAD)
c0 = b0.solve()
K0, K1 = stiffness_parts(b0)
cext = extension_constant(b0)
for alpha in (1e-2, 1e-4, 1e-6, 1e-8):
c = FiniteCellBar(1.0, 4, p, A, alpha, LOAD).solve()
e = energy(K0, [s - t for s, t in zip(c, c0)])
bound = min(alpha * cext * energy(K0, c0), math.sqrt(alpha) / 2 * energy(K1, c0))
assert e <= bound * (1 + 1e-6) + 1e-12, (p, alpha, e, bound)
def test_p_convergence_against_exact() -> None:
prev = None
for p in range(2, 9, 2):
bar = FiniteCellBar(1.0, 4, p, A, 0.0, LOAD)
bar.solve()
_, en = bar.errors(EXACT, DEXACT)
if prev is not None:
assert en < prev / 15
prev = en
assert prev < 1e-9
def test_error_as_alpha_goes_to_zero() -> None:
bar = FiniteCellBar(1.0, 4, 4, A, 0.0, LOAD)
bar.solve()
base = bar.errors(EXACT, DEXACT)[1]
errs = []
for alpha in (1e-2, 1e-4, 1e-6, 1e-8, 1e-10):
bar = FiniteCellBar(1.0, 4, 4, A, alpha, LOAD)
bar.solve()
errs.append(bar.errors(EXACT, DEXACT)[1])
assert errs[-1] < 1.01 * base + 1e-9
assert errs[0] > 10 * base
def test_bisection_quadrature_converges() -> None:
errs = {}
for depth in (None, 4, 8, 16):
bar = FiniteCellBar(1.0, 4, 4, A, 1e-8, LOAD, depth=depth)
bar.solve()
errs[depth] = bar.errors(EXACT, DEXACT)[0]
assert errs[8] < errs[4] / 8
assert abs(errs[16] - errs[None]) < 1e-7
def test_conditioning_and_alpha() -> None:
k0, _ = FiniteCellBar(1.0, 4, 8, A, 0.0, LOAD).assemble()
k8, _ = FiniteCellBar(1.0, 4, 8, A, 1e-8, LOAD).assemble()
c0, c8 = condition_estimate(k0, 80), condition_estimate(k8, 80)
assert c0 > 1e10 and c8 < c0 / 100
History
Fictitious domain methods, which extend a problem to a simple domain, go back to the 1960s. Parvizian, Düster and Rank (2007) combined the idea with the p-version of the finite element method, a small stiffness in the fictitious part and adaptive integration of the cut cells, and named it the finite cell method. Düster, Parvizian, Yang and Rank (2008) extended it to 3D solids. Later work used B-spline and hierarchical spline bases, weak boundary conditions, and CAD and image data, as reviewed by Schillinger and Ruess (2015), and Dauge, Düster and Rank (2015) studied the error caused by .
References
- J. Parvizian, A. Düster and E. Rank, Finite cell method, h- and p-extension for embedded domain problems in solid mechanics, Computational Mechanics 41(1), 2007, 121 to 133, the whole paper (the fictitious domain with a small stiffness, the high-order cells and the adaptive integration of cut cells)
- A. Düster, J. Parvizian, Z. Yang and E. Rank, The finite cell method for three-dimensional problems of solid mechanics, Computer Methods in Applied Mechanics and Engineering 197(45-48), 2008, 3768 to 3782, the whole paper, the 3D version with octree integration of the cut cells
- D. Schillinger and M. Ruess, The finite cell method, a review in the context of higher-order structural analysis of CAD and image-based geometric models, Archives of Computational Methods in Engineering 22(3), 2015, 391 to 455, the whole review (cut cell integration, boundary conditions by Nitsche's method, conditioning, CAD and image data)
- M. Dauge, A. Düster and E. Rank, Theoretical and numerical investigation of the finite cell method, Journal of Scientific Computing 65(3), 2015, 1039 to 1064, the whole paper, the analysis of the error caused by the fictitious stiffness alpha
Where this leads
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 DX2BFW Edit this page History Report an error Markdown