Algorithmintro
Finite element assembly
Also called stiffness matrix assembly, direct stiffness method.
Computes small element matrices by quadrature and adds them into the global sparse matrix through the local-to-global map of degrees of freedom.
- Solves
- Poisson equation
- Time
- Θ(E q n^2) average
- Space
- Θ(N + E n^2) extra
- Where
- E = the number of cells; N = the number of global degrees of freedom; n = the number of local degrees of freedom per cell; q = the number of quadrature points per cell
- Model
- Real RAM
- Properties
- deterministicexact with exact quadraturekeeps symmetry
- Evidence
- Proof sketchCode in 1 languages
- Origin
- M. J. Turner, Ray W. Clough, H. C. Martin, L. J. Topp, 1956
Finite element assembly builds the global stiffness matrix and load vector of a finite element method cell by cell: it computes a small element matrix and vector on each cell and adds their entries into and at the rows and columns that the local-to-global map of degrees of freedom gives. This works because every entry is an integral over the domain, so it is the sum of the integrals over the cells, and only the few cells where both basis functions are nonzero contribute. Graphics simulators use the same loop with linear triangles or tetrahedra, one integration point and lumped masses, and the accurate method adds quadrature that integrates the element integrals exactly, elements of higher degree, consistent mass and load vectors, and boundary conditions imposed so that the matrix stays symmetric, which together give a proved error bound of order in the energy norm. The output is a sparse symmetric matrix that a sparse solver or conjugate gradients can handle.
In plain words
A large structure is hard to analyze as a whole, but each small piece of it is easy. Assembly first works out how each piece responds when its corner points move, which gives a small table of numbers for that piece. Then it adds every small table into one big table for the whole structure. Each corner point has one place in the big table, and a short list for each piece says where its corners go. Where two pieces share a corner, both add their numbers into the same place. At the end, the points where the structure is held fixed get special treatment. Their known values move to the other side of the equations, so that the big table keeps its balanced, mirror-image form.
The problem
Input. A mesh with cells , and for each cell a finite element with local basis and a one-to-one local-to-global map , so that . A bilinear form and a linear form that split into cell integrals, and , for the model problem and . A set of Dirichlet degrees of freedom with values .
Output. The sparse matrix with and the vector with , where row belongs to the test function , modified so that the solution of has for and satisfies the Galerkin equations for all other .
The algorithm
The element routine computes and by quadrature on the cell, usually through a map from a reference cell. The assembly itself does not depend on the element.
ASSEMBLE(N, cells, ELEMENT) ▷ each cell is (g, data); g maps local to global dofs- 1
A <- empty sparse N by N matrix; b <- zero vector of length N - 2
for each cell in cells do - 3
(g, data) <- cell - 4
(A_K, b_K) <- ELEMENT(data) ▷ quadrature on the cell - 5
for i <- 1 to |g| do - 6
b[g[i]] <- b[g[i]] + b_K[i] - 7
for j <- 1 to |g| do - 8
A[g[i], g[j]] <- A[g[i], g[j]] + A_K[i, j] ▷ add, never overwrite - 9
return A, b APPLY-DIRICHLET(A, b, D) ▷ D maps each Dirichlet dof j to its value g_j- 10
for each j in D do - 11
for each row i not in D with A[i, j] != 0 do b[i] <- b[i] - A[i, j] g_j - 12
for each i in D do clear row i and column i of A, set A[i, i] <- 1 and b[i] <- g_i - 13
return A, b
The P1 triangle element. For a triangle with vertices let , so that maps the reference triangle onto and . The reference gradients of the basis , , are the columns of . The physical gradients are , and for constant
On the reference triangle itself . Its rows add up to zero, because the three basis functions add up to and a constant has no gradient. The off-diagonal entries equal for the angle opposite the edge, which is the cotangent formula of mesh processing. For curved or quadrilateral cells the isoparametric mapping replaces by a Jacobian that changes from point to point.
Example
Two triangles on the unit square. Number the corners , , , and split the square along the diagonal into and , with . On the basis is , , with gradients , , , and on it is , , with gradients , , . Both areas are , so
Line L8 adds them at the global positions. The diagonal entries for and get a contribution from both triangles, and the result is
The entry is although and share an edge: both angles opposite the diagonal are right angles, and . Every row adds up to , so is singular until boundary conditions are imposed.
A Dirichlet step in one dimension. Take on with and , and three P1 cells with . Each cell gives and , so ASSEMBLE returns
Line L11 for with changes to . Line L12 replaces rows and columns and by those of the identity. The free equations are and , with the solution and . These are the exact values of at and , because P1 elements are exact at the nodes for this one-dimensional problem. The final matrix is still symmetric.
Sparsity. On the uniform square mesh with two triangles per square, the assembled P1 matrix has stored entries: one per node and two per edge. For that is entries for unknowns, about 6.8 per row. Only of them are nonzero in value, because the diagonal edges give zeros as in the example, and the remaining entries form the 5-point stencil of the finite difference method.
Correctness
The full proof is in the correctness proof. A loop invariant for lines L2 to L8 shows that after line L9 each is the sum over the cells of , which is because the map is one to one and the basis functions vanish on cells outside their support. Lines L10 to L12 turn the system into the block form with right side for the free indices and the Dirichlet indices . So the solution takes the prescribed values and satisfies the Galerkin equations of the free rows, and the matrix stays symmetric and positive definite when is symmetric and coercive.
Proof: Assembly computes the Galerkin matrix and the Dirichlet step keeps it symmetricfull
Setting. The mesh has cells and the global space has the basis . Each cell has local basis functions and a local-to-global map from to . We assume:
- (Map.) is one to one, and for every the restriction is if and is if is not in the image of .
- (Forms.) and , as for forms that are integrals over split into cells.
- (Element.) For the cell data of , ELEMENT returns and .
A missing entry of the sparse matrix stands for .
Lemma 1 (assembly). After line L9, and for all .
Proof. We show the invariant: after the loop of line L2 has processed the cells ,
For both sides are by line L1. Assume it for and process . Line L3 takes its map and line L4 computes and . For each pair the loops of lines L5 and L7 visit it exactly once, and line L8 adds to . No other entry of changes. In the same way line L6 adds to once for each . So the invariant holds for .
At the end . Fix and and a cell . Because is one to one, the inner sum for has at most one term. If both and are in the image of , with and , the term is by assumptions 3 and 1. If one of them is not in the image, the sum is empty, and by assumption 1 one of the restrictions is , so again the sum equals . By assumption 2 the sum over all cells is . The argument for is the same.
Lemma 2 (Dirichlet step). Let be the set of Dirichlet indices with prescribed values , , and let be the other indices. Let and be the result of lines L10 to L13 applied to and . Then:
- holds if and only if for all and for all ;
- if is symmetric, so is ;
- if , the submatrix on the free indices, is positive definite, so is .
Proof. Lines L10 and L11 finish before line L12 starts, so they read the original . For they give , and they do not change for or any entry of . Line L12 then makes row of the unit row for every , sets , and removes column from every other row. (The code reaches those rows through the pattern of row . The pattern of is symmetric, because line L8 visits and for the same cell, so this removes every nonzero of the column.) In block form, with the free indices first,
So means and , that is, , which is part 1. Part 2 holds because is a principal submatrix of a symmetric matrix and the off-diagonal blocks are zero. For part 3, for .
Theorem. Under the assumptions above, ASSEMBLE followed by APPLY-DIRICHLET returns a system whose solution gives with at the Dirichlet nodes and for every free basis function . This is the Galerkin method on with the Dirichlet values imposed by nodal interpolation. If is symmetric and coercive on the functions of that vanish at the Dirichlet nodes, the system matrix is symmetric positive definite.
Proof. By Lemma 1, and . Lemma 2, part 1, gives the two conditions. For part 3 of Lemma 2, let and . Then vanishes at the Dirichlet nodes and .
Remark (quadrature). Assumption 3 holds exactly when the quadrature rule in ELEMENT integrates the element integrands exactly. The reference code uses Boole's rule on each 1D cell, which is exact for polynomials of degree 5, so the P1 and P2 stiffness and mass matrices for a constant are exact. With a weaker rule, Lemma 1 still holds with replaced by its quadrature approximation, and the method is a Galerkin method for a perturbed form.
Complexity
The element routine does work per entry, so it costs per cell for a fixed dimension, and the scatter of lines L5 to L8 costs updates per cell. With a hash map per row, as in the reference code, an update takes expected constant time, and the total is on average. With a sparsity pattern computed in advance (compressed sparse row storage), each update is a search in a short row, and the bound holds in the worst case. The matrix has at most stored entries before duplicates merge, and after, for a mesh whose node degrees stay bounded. The Dirichlet step touches each stored entry of the Dirichlet rows and columns once. Assembly is linear in the size of the mesh. The solve that follows usually costs more.
Properties
- Symmetry. If every is symmetric, so is , and lines L10 to L12 keep it symmetric.
- Semidefiniteness. For a symmetric form with , each is positive semidefinite, and a sum of such matrices is positive semidefinite.
- Zero row sums. For and Lagrange elements, gives before boundary conditions.
- Mass. The entries of the assembled mass matrix add up to , which is the starting point of mass lumping.
- Locality. only if and are both nonzero on some cell, so the pattern is the graph of the mesh.
- Exactness. The result is the exact Galerkin matrix when the quadrature in ELEMENT is exact for the integrands. The reference code uses Boole's rule, exact for degree 5, which covers P1 and P2 stiffness and mass matrices in 1D.
Variants and improvements
- Triplet assembly. Store the triples of all cells, then sort and add duplicates in one pass. This is the vectorized method of Alberty, Carstensen and Funken, with the sparse matrix constructor doing the sums.
- Pattern first. Build the compressed sparse row pattern from the mesh graph, then fill values. Codes that assemble many times, such as Newton or time stepping, reuse the pattern.
- Parallel assembly. Color the cells so that no two cells of one color share a degree of freedom and process each color in parallel, or use atomic additions, or give each process its own cells plus ghost entries.
- Static condensation. Eliminate interior degrees of freedom of each cell from before the scatter, which shrinks the global system for high order.
- Matrix-free operation. Never form . Compute by the same loop over cells applied to vectors. For high degree on tensor-product cells, sum factorization makes this cheaper than storing .
- Other Dirichlet methods. Penalty terms, Lagrange multipliers or Nitsche's method impose the values weakly, and a lifting function moves them into the right side before assembly.
- Graphics practice. Deformable-body codes such as corotational FEM assemble linear tetrahedra with one-point integration and diagonal masses, and they often apply constraints by projection inside the solver.
When to use it
Use assembly when an implicit method needs the matrix: sparse direct solvers, algebraic multigrid and incomplete factorizations all need the entries. For low-order elements the stored matrix is also the fastest way to apply the operator many times. For high-order elements, or on GPUs where memory bandwidth limits the speed, matrix-free application often wins, and assembly is only needed for a coarse level or a preconditioner.
Pitfalls
- Overwriting instead of adding. Line L8 must add. With an assignment, the two-triangle example gives in place of , and the solution is wrong without any error message.
- Nonsymmetric Dirichlet rows. Replacing only the Dirichlet rows by unit rows, without line L11 and without clearing the columns, gives a nonsymmetric matrix, and conjugate gradients may then fail.
- Orientation of cells. A clockwise triangle has . Use for the area, and check the sign when an inverted cell would mean a bad mesh.
- Orientation of shared degrees of freedom. For P3 and higher, or for edge elements, two cells may order the nodes on a shared edge in opposite directions. The map must agree on both sides, or the global function is not continuous.
- Weak quadrature for data. A rule that is exact for the stiffness matrix can be too weak for a variable or a rough , and the convergence order drops.
- Dense storage. An dense matrix is numbers. For that is bytes, while the sparse matrix needs about .
- Races in parallel. Two threads that add into the same entry at the same time lose one of the updates unless the cells are colored or the additions are atomic.
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-element-assembly/. The authors are listed in prov/AW3E0H.jsonl.
"""Finite element assembly for -(kappa u')' = f in 1D (P1, P2) and -div grad u = f in 2D (P1).
The global matrix is sparse: a list of dicts, one dict {column: value} per row.
Element matrices are computed by quadrature on the reference element. With
Fraction coordinates and the default rational rules, the element matrices and
the assembled matrix are exact.
"""
from fractions import Fraction as F
import scimat
# Quadrature rules on [0, 1]: lists of (point, weight).
# Boole's rule (closed Newton-Cotes, 5 points) is exact for degree <= 5 and rational.
BOOLE = [(F(0), F(7, 90)), (F(1, 4), F(32, 90)), (F(1, 2), F(12, 90)), (F(3, 4), F(32, 90)), (F(1), F(7, 90))]
_G5 = [(-0.9061798459386640, 0.2369268850561891), (-0.5384693101056831, 0.4786286704993665),
(0.0, 0.5688888888888889), (0.5384693101056831, 0.4786286704993665),
(0.9061798459386640, 0.2369268850561891)]
# 5-point Gauss-Legendre rule mapped to [0, 1], exact for degree <= 9.
GAUSS5 = [((1.0 + x) / 2.0, w / 2.0) for x, w in _G5]
def lagrange_basis_1d(k):
"""Return (phi, dphi): the Lagrange basis of degree k = 1 or 2 on [0, 1].
The local nodes are in order along the interval: (0, 1) for k = 1 and
(0, 1/2, 1) for k = 2.
"""
if k == 1:
phi = [lambda s: 1 - s, lambda s: s]
dphi = [lambda s: -1, lambda s: 1]
elif k == 2:
phi = [lambda s: (1 - s) * (1 - 2 * s), lambda s: 4 * s * (1 - s), lambda s: s * (2 * s - 1)]
dphi = [lambda s: 4 * s - 3, lambda s: 4 - 8 * s, lambda s: 4 * s - 1]
else:
raise ValueError("k must be 1 or 2")
return phi, dphi
def element_1d(xl, xr, k, f=None, kappa=1, rule=BOOLE, load_rule=GAUSS5):
"""Return (A_K, M_K, b_K) on the interval [xl, xr] for Lagrange elements of degree k.
A_K[i][j] = integral of kappa phi_j' phi_i', M_K[i][j] = integral of phi_j phi_i,
b_K[i] = integral of f phi_i. A_K and M_K use `rule`; b_K uses `load_rule`
(b_K is zero if f is None). kappa is a constant on the element.
"""
h = xr - xl
phi, dphi = lagrange_basis_1d(k)
n = k + 1
a = [[sum(w * kappa * dphi[j](s) * dphi[i](s) for s, w in rule) / h for j in range(n)] for i in range(n)]
m = [[sum(w * phi[j](s) * phi[i](s) for s, w in rule) * h for j in range(n)] for i in range(n)]
if f is None:
b = [0] * n
else:
b = [sum(w * f(xl + s * h) * phi[i](s) for s, w in load_rule) * h for i in range(n)]
return a, m, b
def mesh_1d(x, k):
"""Return (cells, coords) for the 1D mesh with vertices x[0] < ... < x[E] and degree k.
Global dofs are numbered along the line: element e has the dofs
k e, ..., k e + k. Each cell is (g, (xl, xr)) with g the local-to-global map.
"""
cells = []
coords = []
for e in range(len(x) - 1):
xl, xr = x[e], x[e + 1]
g = tuple(k * e + i for i in range(k + 1))
cells.append((g, (xl, xr)))
coords.append(xl)
if k == 2:
coords.append((xl + xr) / 2)
coords.append(x[-1])
return cells, coords
def assemble(n, cells, element):
"""Assemble the global sparse matrix and load vector.
n is the number of global dofs. cells is a list of (g, data), where g is the
local-to-global map of the element (g[i] is the global index of local dof i).
element(data) returns (A_K, b_K). Return (A, b) with A a list of n dicts.
"""
a = [dict() for _ in range(n)] # @line L1
b = [0] * n # @line L1
for cell in cells: # @line L2
g, data = cell # @line L3
a_k, b_k = element(data) # @line L4
for i in range(len(g)): # @line L5
b[g[i]] += b_k[i] # @line L6
row = a[g[i]]
for j in range(len(g)): # @line L7
row[g[j]] = row.get(g[j], 0) + a_k[i][j] # @line L8
return a, b # @line L9
def apply_dirichlet(a, b, values):
"""Impose u[j] = values[j] for the dofs j in values, keeping the matrix symmetric.
The known values move to the right side (lines L10 and L11); then the row
and the column of each Dirichlet dof become those of the identity (line L12).
a and b are changed in place and returned.
"""
for j, gj in values.items(): # @line L10
for i in range(len(a)): # @line L11
if i not in values and j in a[i]: # @line L11
b[i] -= a[i][j] * gj # @line L11
for i, gi in values.items(): # @line L12
for j in list(a[i]): # @line L12
if j != i:
a[j].pop(i, None)
a[i] = {i: 1} # @line L12
b[i] = gi # @line L12
return a, b # @line L13
def to_dense(a):
"""Return the sparse matrix a (list of dicts) as a dense list of rows."""
n = len(a)
out = scimat.zeros(n, n)
for i, row in enumerate(a):
for j, v in row.items():
out[i][j] = v
return out
def solve_poisson_1d(x, k, f, g_left, g_right, kappa=1, rule=BOOLE, load_rule=GAUSS5):
"""Solve -(kappa u')' = f on [x[0], x[-1]] with u = g_left, g_right at the ends.
Return (coords, U): the dof coordinates and the nodal values of u_h.
"""
cells, coords = mesh_1d(x, k)
n = len(coords)
def element(data):
a_k, _, b_k = element_1d(data[0], data[1], k, f, kappa, rule, load_rule)
return a_k, b_k
a, b = assemble(n, cells, element)
apply_dirichlet(a, b, {0: g_left, n - 1: g_right})
return coords, scimat.solve(to_dense(a), b)
def errors_1d(x, k, u_h, u, du):
"""Return (L2 error, H1 seminorm error) of the P_k solution u_h against u, u'.
Both are computed with the 5-point Gauss rule on each element.
"""
phi, dphi = lagrange_basis_1d(k)
e0 = 0.0
e1 = 0.0
for e in range(len(x) - 1):
xl, xr = float(x[e]), float(x[e + 1])
h = xr - xl
loc = [float(u_h[k * e + i]) for i in range(k + 1)]
for s, w in GAUSS5:
xs = xl + s * h
uh = sum(loc[i] * phi[i](s) for i in range(k + 1))
duh = sum(loc[i] * dphi[i](s) for i in range(k + 1)) / h
e0 += w * h * (u(xs) - uh) ** 2
e1 += w * h * (du(xs) - duh) ** 2
return e0 ** 0.5, e1 ** 0.5
# ---------------------------------------------------------------- P1 on triangles
def p1_triangle(p0, p1, p2, f=None):
"""Return (A_K, M_K, b_K) for P1 on the triangle with vertices p0, p1, p2.
The affine map is F_K(xhat) = p0 + B xhat with B = [p1 - p0, p2 - p0]. The
reference gradients are (-1, -1), (1, 0), (0, 1), and grad phi_i = B^(-T)
grad phihat_i. The load uses the edge midpoint rule (exact for degree 2).
"""
b11, b12 = p1[0] - p0[0], p2[0] - p0[0]
b21, b22 = p1[1] - p0[1], p2[1] - p0[1]
det = b11 * b22 - b12 * b21
if det == 0:
raise ValueError("degenerate triangle")
area = abs(det) / 2
# B^(-T) = (1/det) [[b22, -b21], [-b12, b11]]
grads = []
for gx, gy in ((-1, -1), (1, 0), (0, 1)):
grads.append(((b22 * gx - b21 * gy) / det, (-b12 * gx + b11 * gy) / det))
a = [[area * (grads[i][0] * grads[j][0] + grads[i][1] * grads[j][1]) for j in range(3)] for i in range(3)]
m = [[area * (F(2, 12) if i == j else F(1, 12)) for j in range(3)] for i in range(3)]
if f is None:
b = [0, 0, 0]
else:
pts = (p0, p1, p2)
b = [0, 0, 0]
for i in range(3):
for j in range(3):
if i != j:
# midpoint of edge (i, j): phi_i = 1/2 there; each midpoint has weight area / 3
mid = ((pts[i][0] + pts[j][0]) / 2, (pts[i][1] + pts[j][1]) / 2)
b[i] += area / 3 * f(mid[0], mid[1]) / 2
return a, m, b
def square_mesh(m, perturb=None):
"""Return (points, triangles) for the unit square cut into m by m cells.
Each cell is cut by its diagonal from the lower left to the upper right
corner. Point (i, j) has index j (m + 1) + i. perturb(i, j) may return a
shift (dx, dy) for interior points.
"""
pts = []
for j in range(m + 1):
for i in range(m + 1):
x, y = F(i, m), F(j, m)
if perturb is not None and 0 < i < m and 0 < j < m:
dx, dy = perturb(i, j)
x, y = x + dx, y + dy
pts.append((x, y))
tris = []
for j in range(m):
for i in range(m):
v00 = j * (m + 1) + i
v10, v01, v11 = v00 + 1, v00 + m + 1, v00 + m + 2
tris.append((v00, v10, v11))
tris.append((v00, v11, v01))
return pts, tris
def boundary_points(m):
"""Return the indices of the points of square_mesh(m) on the boundary."""
out = []
for j in range(m + 1):
for i in range(m + 1):
if i in (0, m) or j in (0, m):
out.append(j * (m + 1) + i)
return out
def solve_poisson_2d(pts, tris, boundary, f, g):
"""Solve -div grad u = f with u = g on the boundary points, by P1 elements.
Return the nodal values of u_h.
"""
cells = [(t, t) for t in tris]
def element(t):
a_k, _, b_k = p1_triangle(pts[t[0]], pts[t[1]], pts[t[2]], f)
return a_k, b_k
a, b = assemble(len(pts), cells, element)
apply_dirichlet(a, b, {v: g(*pts[v]) for v in boundary})
return scimat.solve(to_dense(a), b)
def errors_2d(pts, tris, u_h, u, grad_u):
"""Return (L2 error, H1 seminorm error) of the P1 solution, by a collapsed Gauss rule.
The rule maps the square [0, 1]^2 to the reference triangle by
(s, t) -> (s, t (1 - s)), with the factor (1 - s), and uses 5 by 5 Gauss points.
"""
e0 = 0.0
e1 = 0.0
for t in tris:
p0, p1, p2 = (tuple(float(c) for c in pts[v]) for v in t)
b11, b12 = p1[0] - p0[0], p2[0] - p0[0]
b21, b22 = p1[1] - p0[1], p2[1] - p0[1]
det = b11 * b22 - b12 * b21
loc = [float(u_h[v]) for v in t]
# constant gradient of u_h on the triangle
gx = sum(loc[i] * (b22 * gxh - b21 * gyh) / det for i, (gxh, gyh) in enumerate(((-1, -1), (1, 0), (0, 1))))
gy = sum(loc[i] * (-b12 * gxh + b11 * gyh) / det for i, (gxh, gyh) in enumerate(((-1, -1), (1, 0), (0, 1))))
for s, ws in GAUSS5:
for r, wr in GAUSS5:
xh, yh = s, r * (1 - s)
w = ws * wr * (1 - s) * abs(det)
x = p0[0] + b11 * xh + b12 * yh
y = p0[1] + b21 * xh + b22 * yh
uh = loc[0] * (1 - xh - yh) + loc[1] * xh + loc[2] * yh
ux, uy = grad_u(x, y)
e0 += w * (u(x, y) - uh) ** 2
e1 += w * ((ux - gx) ** 2 + (uy - gy) ** 2)
return e0 ** 0.5, e1 ** 0.5
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_finite_element_assembly.py 346 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/finite-element-assembly/. The authors are listed in prov/AW3E0H.jsonl.
import math
import random
from fractions import Fraction as F
import scimat
from finite_element_assembly import (
apply_dirichlet,
assemble,
boundary_points,
element_1d,
errors_1d,
errors_2d,
lagrange_basis_1d,
mesh_1d,
p1_triangle,
solve_poisson_1d,
solve_poisson_2d,
square_mesh,
to_dense,
)
# Tests of the shared helper scimat.py.
def test_scimat_solve_fraction_exact() -> None:
a = [[F(2), F(1), F(1)], [F(4), F(-6), F(0)], [F(-2), F(7), F(2)]]
b = [F(5), F(-2), F(9)]
x = scimat.solve(a, b)
assert x == [F(1), F(1), F(2)]
assert scimat.matvec(a, x) == b
assert all(isinstance(v, F) for v in x)
def test_scimat_inv_det() -> None:
a = [[F(2), F(1), F(1)], [F(4), F(-6), F(0)], [F(-2), F(7), F(2)]]
assert scimat.det(a) == F(-16)
assert scimat.matmul(a, scimat.inv(a)) == scimat.eye(3)
assert scimat.det([[1, 2], [2, 4]]) == 0
assert scimat.det([[0, 1], [1, 0]]) == -1
try:
scimat.solve([[1, 2], [2, 4]], [1, 1])
except ValueError:
pass
else:
raise AssertionError("singular matrix not detected")
def test_scimat_solve_matrix_rhs_and_pivoting() -> None:
a = [[0, 1], [1, 0]]
assert scimat.solve(a, [3, 4]) == [4, 3]
x = scimat.solve([[F(1), F(2)], [F(3), F(4)]], [[F(1), F(0)], [F(0), F(1)]])
assert x == [[F(-2), F(1)], [F(3, 2), F(-1, 2)]]
def test_scimat_cholesky_known_factor() -> None:
low = [[2.0, 0.0, 0.0], [6.0, 1.0, 0.0], [-8.0, 5.0, 3.0]]
a = scimat.matmul(low, scimat.transpose(low))
assert a == [[4.0, 12.0, -16.0], [12.0, 37.0, -43.0], [-16.0, -43.0, 98.0]]
got = scimat.cholesky(a)
for i in range(3):
for j in range(3):
assert abs(got[i][j] - low[i][j]) < 1e-12
x = scimat.cholesky_solve(got, [1.0, 2.0, 3.0])
r = scimat.sub(scimat.matvec(a, x), [1.0, 2.0, 3.0])
assert scimat.norm2(r) < 1e-10
try:
scimat.cholesky([[1.0, 2.0], [2.0, 1.0]])
except ValueError:
pass
else:
raise AssertionError("indefinite matrix not detected")
def test_scimat_random_float_solve() -> None:
rng = random.Random(7)
for n in range(1, 8):
a = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
for i in range(n):
a[i][i] += n
x = [rng.uniform(-1, 1) for _ in range(n)]
b = scimat.matvec(a, x)
y = scimat.solve(a, b)
assert scimat.norm2(scimat.sub(x, y)) < 1e-12
def test_scimat_small_ops() -> None:
assert scimat.zeros(2, 3) == [[0, 0, 0], [0, 0, 0]]
assert scimat.zeros(2) == [[0, 0], [0, 0]]
assert scimat.add([1, 2], [3, 4]) == [4, 6]
assert scimat.sub([[1, 2]], [[3, 5]]) == [[-2, -3]]
assert scimat.scale(F(1, 2), [[2, 4]]) == [[1, 2]]
assert scimat.dot([1, 2, 3], [4, 5, 6]) == 32
assert scimat.outer([1, 2], [3, 4, 5]) == [[3, 4, 5], [6, 8, 10]]
assert scimat.transpose([[1, 2, 3]]) == [[1], [2], [3]]
assert scimat.norm2([3, 4]) == 5.0
def test_scimat_error_norms_and_order() -> None:
e = [F(1, 2), F(-1, 4), F(1, 4)]
assert scimat.err_l1(e, F(1, 2)) == F(1, 2)
assert abs(scimat.err_l2(e, F(1, 2)) - math.sqrt(0.1875)) < 1e-15
assert scimat.err_linf(e) == F(1, 2)
errors = [3 * (1 / 2**k) ** 2 for k in range(1, 6)]
orders = scimat.observed_order(errors)
assert len(orders) == 4
assert all(abs(p - 2.0) < 1e-12 for p in orders)
# Tests of the assembly.
BOOLE_RULE = [(F(0), F(7, 90)), (F(1, 4), F(32, 90)), (F(1, 2), F(12, 90)), (F(3, 4), F(32, 90)), (F(1), F(7, 90))]
def _pmul(p, q):
out = [F(0)] * (len(p) + len(q) - 1)
for i, a in enumerate(p):
for j, b in enumerate(q):
out[i + j] += a * b
return out
def _pint01(p):
return sum(c / (n + 1) for n, c in enumerate(p))
def _pder(p):
return [n * p[n] for n in range(1, len(p))] or [F(0)]
# Lagrange bases on [0, 1] as coefficient lists in s (constant term first).
_P1 = [[F(1), F(-1)], [F(0), F(1)]]
_P2 = [[F(1), F(-3), F(2)], [F(0), F(4), F(-4)], [F(0), F(-1), F(2)]]
def test_element_1d_exact_integrals() -> None:
for k, basis in ((1, _P1), (2, _P2)):
for h in (F(1), F(1, 3), F(2, 7)):
a, m, _ = element_1d(F(5, 11), F(5, 11) + h, k)
n = k + 1
for i in range(n):
for j in range(n):
want_a = _pint01(_pmul(_pder(basis[i]), _pder(basis[j]))) / h
want_m = _pint01(_pmul(basis[i], basis[j])) * h
assert a[i][j] == want_a
assert m[i][j] == want_m
a, m, _ = element_1d(F(0), F(1), 2)
assert a == scimat.scale(F(1, 3), [[7, -8, 1], [-8, 16, -8], [1, -8, 7]])
assert m == scimat.scale(F(1, 30), [[4, 2, -1], [2, 16, 2], [-1, 2, 4]])
a, m, _ = element_1d(F(0), F(1, 4), 1)
assert a == [[4, -4], [-4, 4]]
assert m == [[F(1, 12), F(1, 24)], [F(1, 24), F(1, 12)]]
def test_basis_is_nodal() -> None:
nodes = {1: [F(0), F(1)], 2: [F(0), F(1, 2), F(1)]}
for k in (1, 2):
phi, _ = lagrange_basis_1d(k)
for i in range(k + 1):
for j in range(k + 1):
assert phi[i](nodes[k][j]) == (1 if i == j else 0)
def _p1_by_vandermonde(p):
"""Gradients of the P1 basis from the 3 by 3 system phi_i(p_j) = delta_ij."""
v = [[F(1), F(q[0]), F(q[1])] for q in p]
c = scimat.inv(v) # column i holds the coefficients of phi_i
return [(c[1][i], c[2][i]) for i in range(3)]
def test_reference_triangle_stiffness() -> None:
a, m, _ = p1_triangle((F(0), F(0)), (F(1), F(0)), (F(0), F(1)))
assert a == scimat.scale(F(1, 2), [[2, -1, -1], [-1, 1, 0], [-1, 0, 1]])
# Mass matrix against exact monomial integrals on the reference triangle:
# the integral of x^a y^b is a! b! / (a + b + 2)!.
fact = [1, 1, 2, 6, 24]
phis = [{(0, 0): 1, (1, 0): -1, (0, 1): -1}, {(1, 0): 1}, {(0, 1): 1}]
for i in range(3):
for j in range(3):
total = F(0)
for (a1, b1), c1 in phis[i].items():
for (a2, b2), c2 in phis[j].items():
aa, bb = a1 + a2, b1 + b2
total += c1 * c2 * F(fact[aa] * fact[bb], fact[aa + bb + 2])
assert m[i][j] == total
def test_triangle_stiffness_random() -> None:
rng = random.Random(3)
for _ in range(40):
p = [(F(rng.randint(-9, 9), 4), F(rng.randint(-9, 9), 4)) for _ in range(3)]
det = (p[1][0] - p[0][0]) * (p[2][1] - p[0][1]) - (p[2][0] - p[0][0]) * (p[1][1] - p[0][1])
if det == 0:
continue
a, m, _ = p1_triangle(*p)
grads = _p1_by_vandermonde(p)
area = abs(det) / 2
for i in range(3):
assert sum(a[i]) == 0
for j in range(3):
assert a[i][j] == area * (grads[i][0] * grads[j][0] + grads[i][1] * grads[j][1])
assert sum(sum(r) for r in m) == area
def test_two_triangles_by_hand() -> None:
pts = [(F(0), F(0)), (F(1), F(0)), (F(1), F(1)), (F(0), F(1))]
tris = [(0, 1, 2), (0, 2, 3)]
a, _ = assemble(4, [(t, t) for t in tris], lambda t: (p1_triangle(*(pts[v] for v in t))[0], [0, 0, 0]))
h = F(1, 2)
assert to_dense(a) == [[1, -h, 0, -h], [-h, 1, -h, 0], [0, -h, 1, -h], [-h, 0, -h, 1]]
def _random_mesh_1d(rng, n):
x = [F(0)]
for _ in range(n):
x.append(x[-1] + F(rng.randint(1, 9), 10))
return x
def test_assembly_against_brute_force_1d() -> None:
rng = random.Random(5)
for _ in range(10):
x = _random_mesh_1d(rng, rng.randint(1, 8))
n = len(x)
cells, _ = mesh_1d(x, 1)
a, b = assemble(n, cells, lambda d: (element_1d(d[0], d[1], 1)[0], element_1d(d[0], d[1], 1)[1][0]))
dense = to_dense(a)
def dhat(i, e):
# derivative of the global hat function i on element e = [x_e, x_(e+1)]
h = x[e + 1] - x[e]
if i == e:
return -1 / h
if i == e + 1:
return 1 / h
return 0
for i in range(n):
for j in range(n):
want = sum(dhat(i, e) * dhat(j, e) * (x[e + 1] - x[e]) for e in range(n - 1))
assert dense[i][j] == want
assert sum(dense[i]) == 0
def test_row_sums_zero_and_symmetry_2d() -> None:
rng = random.Random(11)
def shift(i, j):
return (F(rng.randint(-2, 2), 40), F(rng.randint(-2, 2), 40))
pts, tris = square_mesh(4, shift)
a, _ = assemble(len(pts), [(t, t) for t in tris], lambda t: (p1_triangle(*(pts[v] for v in t))[0], [0, 0, 0]))
dense = to_dense(a)
assert all(sum(row) == 0 for row in dense)
assert dense == scimat.transpose(dense)
def test_patch_test_2d_exact() -> None:
rng = random.Random(13)
def shift(i, j):
return (F(rng.randint(-3, 3), 50), F(rng.randint(-3, 3), 50))
pts, tris = square_mesh(4, shift)
g = lambda x, y: 1 + 2 * x - 3 * y # noqa: E731
u = solve_poisson_2d(pts, tris, boundary_points(4), None, g)
assert u == [g(*p) for p in pts]
def test_patch_test_1d_p2_exact() -> None:
rng = random.Random(17)
x = _random_mesh_1d(rng, 5)
coords, u = solve_poisson_1d(x, 2, lambda s: -2, x[0] ** 2, x[-1] ** 2, load_rule=BOOLE_RULE)
assert u == [c * c for c in coords]
def test_hand_example_1d() -> None:
x = [F(0), F(1, 3), F(2, 3), F(1)]
# Boundary values are Fractions: an int divided by an int in the solve would give a float.
_, u = solve_poisson_1d(x, 1, lambda s: 1, F(0), F(0), load_rule=BOOLE_RULE)
assert u == [0, F(1, 9), F(1, 9), 0]
assert all(isinstance(v, F) for v in u)
pts, tris = square_mesh(2)
u = solve_poisson_2d(pts, tris, boundary_points(2), lambda x, y: 1, lambda x, y: F(0))
assert u[4] == F(1, 16) and isinstance(u[4], F)
def test_dirichlet_keeps_symmetry_and_solution() -> None:
rng = random.Random(19)
x = _random_mesh_1d(rng, 6)
cells, coords = mesh_1d(x, 2)
n = len(coords)
f = lambda s: 1 + s # noqa: E731
def element(d):
a_k, _, b_k = element_1d(d[0], d[1], 2, f, 1, BOOLE_RULE, BOOLE_RULE)
return a_k, b_k
a, b = assemble(n, cells, element)
full = to_dense(a)
rhs = list(b)
apply_dirichlet(a, b, {0: F(1), n - 1: F(-2)})
dense = to_dense(a)
assert dense == scimat.transpose(dense)
u = scimat.solve(dense, b)
assert u[0] == 1 and u[-1] == -2
# the interior equations of the original system hold
for i in range(1, n - 1):
assert sum(full[i][j] * u[j] for j in range(n)) == rhs[i]
def test_rates_1d_p1_p2() -> None:
pi = math.pi
u = lambda s: math.sin(pi * s) + s # noqa: E731
du = lambda s: pi * math.cos(pi * s) + 1 # noqa: E731
f = lambda s: pi * pi * math.sin(pi * s) # noqa: E731
for k, p0, p1 in ((1, 2, 1), (2, 3, 2)):
e0, e1 = [], []
for n in (4, 8, 16, 32):
x = [i / n for i in range(n + 1)]
_, uh = solve_poisson_1d(x, k, f, 0.0, 1.0)
a, b = errors_1d(x, k, uh, u, du)
e0.append(a)
e1.append(b)
assert all(abs(q - p0) < 0.2 for q in scimat.observed_order(e0))
assert all(abs(q - p1) < 0.2 for q in scimat.observed_order(e1))
def test_rates_2d_p1() -> None:
pi = math.pi
u = lambda x, y: math.sin(pi * x) * math.sin(pi * y) # noqa: E731
gu = lambda x, y: (pi * math.cos(pi * x) * math.sin(pi * y), pi * math.sin(pi * x) * math.cos(pi * y)) # noqa: E731
f = lambda x, y: 2 * pi * pi * u(x, y) # noqa: E731
e0, e1 = [], []
for m in (4, 8, 16):
pts, tris = square_mesh(m)
pts = [(float(p[0]), float(p[1])) for p in pts]
uh = solve_poisson_2d(pts, tris, boundary_points(m), f, lambda x, y: 0.0)
a, b = errors_2d(pts, tris, uh, u, gu)
e0.append(a)
e1.append(b)
assert all(abs(q - 2) < 0.2 for q in scimat.observed_order(e0))
assert all(abs(q - 1) < 0.2 for q in scimat.observed_order(e1))
History
M. J. Turner, Ray Clough, H. C. Martin and L. J. Topp published the direct stiffness method in 1956 for aircraft structures at Boeing. They computed stiffness matrices of triangular plate pieces and added them into the global matrix by node numbers, which is the loop above. Clough named the method the finite element method in 1960. Bruce Irons published the frontal solver in 1970, which interleaves assembly with Gaussian elimination so that only a small front of the matrix is in memory. The short vectorized implementations of the 1990s, such as the 50 lines of Matlab of Alberty, Carstensen and Funken, made the algorithm a standard part of teaching.
References
- M. J. Turner, R. W. Clough, H. C. Martin and L. J. Topp, Stiffness and deflection analysis of complex structures, Journal of the Aeronautical Sciences 23(9) (1956) 805-823, element stiffness matrices and the direct stiffness assembly
- J. Alberty, C. Carstensen and S. A. Funken, Remarks around 50 lines of Matlab, short finite element implementation, Numerical Algorithms 20 (1999) 117-137, element stiffness of P1 triangles and assembly with Dirichlet and Neumann data
- Thomas J. R. Hughes, The Finite Element Method, Linear Static and Dynamic Finite Element Analysis, Dover, 2000, Chapters 1 and 2 (element point of view, location matrix and the assembly operator)
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 AW3E0H Edit this page History Report an error Markdown