Algorithm Search⌘K

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.

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
Properties
deterministicexact with exact quadraturekeeps symmetry
Origin
M. J. Turner, Ray W. Clough, H. C. Martin, L. J. Topp, 1956

Finite element assembly builds the global stiffness matrix AA and load vector bb of a finite element method cell by cell: it computes a small element matrix AKA_K and vector bKb_K on each cell KK and adds their entries into AA and bb at the rows and columns that the local-to-global map of degrees of freedom gives. This works because every entry Aij=a(ϕj,ϕi)A_{ij} = a(\phi_j, \phi_i) 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 hkh^k 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 Th\mathcal{T}_h with cells KK, and for each cell a finite element with local basis ϕ1K,…,ϕnK\phi^K_1, \ldots, \phi^K_n and a one-to-one local-to-global map gK:{1,…,n}→{1,…,N}g_K : \{1, \ldots, n\} \to \{1, \ldots, N\}, so that ϕgK(r)∣K=ϕrK\phi_{g_K(r)}|_K = \phi^K_r. A bilinear form and a linear form that split into cell integrals, a=∑KaKa = \sum_K a_K and l=∑KlKl = \sum_K l_K, for the model problem a(u,v)=∫Ωκ∇u⋅∇va(u, v) = \int_\Omega \kappa\nabla u\cdot\nabla v and l(v)=∫Ωfvl(v) = \int_\Omega fv. A set DD of Dirichlet degrees of freedom with values gjg_j.

Output. The sparse matrix AA with Aij=a(ϕj,ϕi)A_{ij} = a(\phi_j, \phi_i) and the vector bb with bi=l(ϕi)b_i = l(\phi_i), where row ii belongs to the test function ϕi\phi_i, modified so that the solution of AU=bAU = b has Uj=gjU_j = g_j for j∈Dj \in D and satisfies the Galerkin equations a(uh,ϕi)=l(ϕi)a(u_h, \phi_i) = l(\phi_i) for all other ii.

The algorithm

The element routine computes AK[r,s]=aK(ϕsK,ϕrK)A_K[r, s] = a_K(\phi^K_s, \phi^K_r) and bK[r]=lK(ϕrK)b_K[r] = l_K(\phi^K_r) by quadrature on the cell, usually through a map from a reference cell. The assembly itself does not depend on the element.

  1. ASSEMBLE(N, cells, ELEMENT) ▷ each cell is (g, data); g maps local to global dofs
  2. 1A <- empty sparse N by N matrix; b <- zero vector of length N
  3. 2for each cell in cells do
  4. 3(g, data) <- cell
  5. 4(A_K, b_K) <- ELEMENT(data) ▷ quadrature on the cell
  6. 5for i <- 1 to |g| do
  7. 6b[g[i]] <- b[g[i]] + b_K[i]
  8. 7for j <- 1 to |g| do
  9. 8A[g[i], g[j]] <- A[g[i], g[j]] + A_K[i, j] ▷ add, never overwrite
  10. 9return A, b
  11. APPLY-DIRICHLET(A, b, D) ▷ D maps each Dirichlet dof j to its value g_j
  12. 10for each j in D do
  13. 11for each row i not in D with A[i, j] != 0 do b[i] <- b[i] - A[i, j] g_j
  14. 12for each i in D do clear row i and column i of A, set A[i, i] <- 1 and b[i] <- g_i
  15. 13return A, b

The P1 triangle element. For a triangle with vertices p0,p1,p2p_0, p_1, p_2 let B=[ p1−p0, p2−p0 ]B = [\,p_1 - p_0,\ p_2 - p_0\,], so that FK(x^)=p0+Bx^F_K(\hat x) = p_0 + B\hat x maps the reference triangle onto KK and ∣K∣=∣det⁡B∣/2|K| = |\det B|/2. The reference gradients of the basis 1−x^−y^1 - \hat x - \hat y, x^\hat x, y^\hat y are the columns of G^=(−110−101)\hat G = \begin{pmatrix} -1 & 1 & 0 \\ -1 & 0 & 1\end{pmatrix}. The physical gradients are G=B−⊤G^G = B^{-\top}\hat G, and for constant κ\kappa

AK=κ ∣K∣ G⊤G,MK=∣K∣12(211121112).A_K = \kappa\,|K|\,G^\top G, \qquad M_K = \frac{|K|}{12}\begin{pmatrix} 2 & 1 & 1 \\ 1 & 2 & 1 \\ 1 & 1 & 2\end{pmatrix}.

On the reference triangle itself AK=12(2−1−1−110−101)A_K = \tfrac12\begin{pmatrix} 2 & -1 & -1 \\ -1 & 1 & 0 \\ -1 & 0 & 1\end{pmatrix}. Its rows add up to zero, because the three basis functions add up to 11 and a constant has no gradient. The off-diagonal entries equal −12cot⁡θ-\tfrac12\cot\theta for the angle θ\theta opposite the edge, which is the cotangent formula of mesh processing. For curved or quadrilateral cells the isoparametric mapping replaces BB by a Jacobian that changes from point to point.

Example

Two triangles on the unit square. Number the corners v0=(0,0)v_0 = (0,0), v1=(1,0)v_1 = (1,0), v2=(1,1)v_2 = (1,1), v3=(0,1)v_3 = (0,1) and split the square along the diagonal v0v2v_0v_2 into T1=(v0,v1,v2)T_1 = (v_0, v_1, v_2) and T2=(v0,v2,v3)T_2 = (v_0, v_2, v_3), with κ=1\kappa = 1. On T1T_1 the basis is 1−x1 - x, x−yx - y, yy with gradients (−1,0)(-1, 0), (1,−1)(1, -1), (0,1)(0, 1), and on T2T_2 it is 1−y1 - y, xx, y−xy - x with gradients (0,−1)(0, -1), (1,0)(1, 0), (−1,1)(-1, 1). Both areas are 12\tfrac12, so

AT1=12(1−10−12−10−11) on (0,1,2),AT2=12(10−101−1−1−12) on (0,2,3).A_{T_1} = \frac12\begin{pmatrix} 1 & -1 & 0 \\ -1 & 2 & -1 \\ 0 & -1 & 1\end{pmatrix} \text{ on } (0, 1, 2), \qquad A_{T_2} = \frac12\begin{pmatrix} 1 & 0 & -1 \\ 0 & 1 & -1 \\ -1 & -1 & 2\end{pmatrix} \text{ on } (0, 2, 3).

Line L8 adds them at the global positions. The diagonal entries for v0v_0 and v2v_2 get a contribution from both triangles, and the result is

A=(1−120−12−121−1200−121−12−120−121).A = \begin{pmatrix} 1 & -\tfrac12 & 0 & -\tfrac12 \\ -\tfrac12 & 1 & -\tfrac12 & 0 \\ 0 & -\tfrac12 & 1 & -\tfrac12 \\ -\tfrac12 & 0 & -\tfrac12 & 1\end{pmatrix}.

The entry A02A_{02} is 00 although v0v_0 and v2v_2 share an edge: both angles opposite the diagonal are right angles, and cot⁡(π/2)=0\cot(\pi/2) = 0. Every row adds up to 00, so AA is singular until boundary conditions are imposed.

A Dirichlet step in one dimension. Take −u′′=1-u'' = 1 on (0,1)(0, 1) with u(0)=0u(0) = 0 and u(1)=1u(1) = 1, and three P1 cells with h=13h = \tfrac13. Each cell gives AK=3(1−1−11)A_K = 3\begin{pmatrix} 1 & -1 \\ -1 & 1\end{pmatrix} and bK=(16,16)b_K = (\tfrac16, \tfrac16), so ASSEMBLE returns

A=3(1−100−12−100−12−100−11),b=(16,13,13,16).A = 3\begin{pmatrix} 1 & -1 & 0 & 0 \\ -1 & 2 & -1 & 0 \\ 0 & -1 & 2 & -1 \\ 0 & 0 & -1 & 1\end{pmatrix}, \qquad b = \bigl(\tfrac16, \tfrac13, \tfrac13, \tfrac16\bigr).

Line L11 for j=3j = 3 with g3=1g_3 = 1 changes b2b_2 to 13−(−3)(1)=103\tfrac13 - (-3)(1) = \tfrac{10}3. Line L12 replaces rows and columns 00 and 33 by those of the identity. The free equations are 3(2U1−U2)=133(2U_1 - U_2) = \tfrac13 and 3(−U1+2U2)=1033(-U_1 + 2U_2) = \tfrac{10}3, with the solution U1=49U_1 = \tfrac49 and U2=79U_2 = \tfrac79. These are the exact values of u=x(1−x)/2+xu = x(1-x)/2 + x at x=13x = \tfrac13 and 23\tfrac23, because P1 elements are exact at the nodes for this one-dimensional problem. The final matrix is still symmetric.

Sparsity. On the uniform m×mm \times m square mesh with two triangles per square, the assembled P1 matrix has (m+1)2+2(3m2+2m)(m+1)^2 + 2(3m^2 + 2m) stored entries: one per node and two per edge. For m=32m = 32 that is 73617361 entries for 10891089 unknowns, about 6.8 per row. Only 53135313 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 A[i,j]A[i, j] is the sum over the cells of aK(ϕj∣K,ϕi∣K)a_K(\phi_j|_K, \phi_i|_K), which is a(ϕj,ϕi)a(\phi_j, \phi_i) because the map gKg_K 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 (AFF00I)\begin{pmatrix} A_{FF} & 0 \\ 0 & I\end{pmatrix} with right side (bF−AFDg, g)(b_F - A_{FD}g,\ g) for the free indices FF and the Dirichlet indices DD. 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 aa is symmetric and coercive.

Proof: Assembly computes the Galerkin matrix and the Dirichlet step keeps it symmetricfull

Setting. The mesh has cells K1,…,KEK_1, \ldots, K_E and the global space VhV_h has the basis ϕ1,…,ϕN\phi_1, \ldots, \phi_N. Each cell KK has local basis functions ϕ1K,…,ϕnK\phi^K_1, \ldots, \phi^K_n and a local-to-global map g=gKg = g_K from {1,…,n}\{1, \ldots, n\} to {1,…,N}\{1, \ldots, N\}. We assume:

  1. (Map.) gKg_K is one to one, and for every ii the restriction ϕi∣K\phi_i|_K is ϕrK\phi^K_r if gK(r)=ig_K(r) = i and is 00 if ii is not in the image of gKg_K.
  2. (Forms.) a(u,v)=∑KaK(u∣K,v∣K)a(u, v) = \sum_K a_K(u|_K, v|_K) and l(v)=∑KlK(v∣K)l(v) = \sum_K l_K(v|_K), as for forms that are integrals over Ω\Omega split into cells.
  3. (Element.) For the cell data of KK, ELEMENT returns AK[r,s]=aK(ϕsK,ϕrK)A_K[r, s] = a_K(\phi^K_s, \phi^K_r) and bK[r]=lK(ϕrK)b_K[r] = l_K(\phi^K_r).

A missing entry of the sparse matrix stands for 00.

Lemma 1 (assembly). After line L9, A[i,j]=a(ϕj,ϕi)A[i, j] = a(\phi_j, \phi_i) and b[i]=l(ϕi)b[i] = l(\phi_i) for all i,ji, j.

Proof. We show the invariant: after the loop of line L2 has processed the cells K1,…,KmK_1, \ldots, K_m,

A[i,j]=∑t=1m∑r,s: gKt(r)=i,gKt(s)=jAKt[r,s],b[i]=∑t=1m∑r: gKt(r)=ibKt[r].A[i, j] = \sum_{t=1}^m \sum_{\substack{r, s:\ g_{K_t}(r) = i,\\ g_{K_t}(s) = j}} A_{K_t}[r, s], \qquad b[i] = \sum_{t=1}^m \sum_{r:\ g_{K_t}(r) = i} b_{K_t}[r].

For m=0m = 0 both sides are 00 by line L1. Assume it for m−1m - 1 and process K=KmK = K_m. Line L3 takes its map gg and line L4 computes AKA_K and bKb_K. For each pair (r,s)(r, s) the loops of lines L5 and L7 visit it exactly once, and line L8 adds AK[r,s]A_K[r, s] to A[g(r),g(s)]A[g(r), g(s)]. No other entry of AA changes. In the same way line L6 adds bK[r]b_K[r] to b[g(r)]b[g(r)] once for each rr. So the invariant holds for mm.

At the end m=Em = E. Fix ii and jj and a cell KK. Because gKg_K is one to one, the inner sum for KK has at most one term. If both ii and jj are in the image of gKg_K, with gK(r)=ig_K(r) = i and gK(s)=jg_K(s) = j, the term is AK[r,s]=aK(ϕsK,ϕrK)=aK(ϕj∣K,ϕi∣K)A_K[r, s] = a_K(\phi^K_s, \phi^K_r) = a_K(\phi_j|_K, \phi_i|_K) 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 00, so again the sum equals aK(ϕj∣K,ϕi∣K)=0a_K(\phi_j|_K, \phi_i|_K) = 0. By assumption 2 the sum over all cells is a(ϕj,ϕi)a(\phi_j, \phi_i). The argument for bb is the same. □\square

Lemma 2 (Dirichlet step). Let DD be the set of Dirichlet indices with prescribed values gjg_j, j∈Dj \in D, and let FF be the other indices. Let A′A' and b′b' be the result of lines L10 to L13 applied to AA and bb. Then:

  1. A′U=b′A'U = b' holds if and only if Uj=gjU_j = g_j for all j∈Dj \in D and ∑kA[i,k]Uk=b[i]\sum_k A[i, k]U_k = b[i] for all i∈Fi \in F;
  2. if AA is symmetric, so is A′A';
  3. if AFFA_{FF}, the submatrix on the free indices, is positive definite, so is A′A'.

Proof. Lines L10 and L11 finish before line L12 starts, so they read the original AA. For i∈Fi \in F they give b′[i]=b[i]−∑j∈DA[i,j]gjb'[i] = b[i] - \sum_{j \in D}A[i, j]g_j, and they do not change b[i]b[i] for i∈Di \in D or any entry of AA. Line L12 then makes row ii of AA the unit row ei⊤e_i^\top for every i∈Di \in D, sets b′[i]=gib'[i] = g_i, and removes column ii from every other row. (The code reaches those rows through the pattern of row ii. The pattern of AA is symmetric, because line L8 visits (g(r),g(s))(g(r), g(s)) and (g(s),g(r))(g(s), g(r)) for the same cell, so this removes every nonzero of the column.) In block form, with the free indices first,

A′=(AFF00I),b′=(bF−AFD gg).A' = \begin{pmatrix} A_{FF} & 0 \\ 0 & I\end{pmatrix}, \qquad b' = \begin{pmatrix} b_F - A_{FD}\,g \\ g\end{pmatrix}.

So A′U=b′A'U = b' means UD=gU_D = g and AFFUF=bF−AFDgA_{FF}U_F = b_F - A_{FD}g, that is, AFFUF+AFDUD=bFA_{FF}U_F + A_{FD}U_D = b_F, which is part 1. Part 2 holds because AFFA_{FF} is a principal submatrix of a symmetric matrix and the off-diagonal blocks are zero. For part 3, x⊤A′x=xF⊤AFFxF+∣xD∣2>0x^\top A'x = x_F^\top A_{FF}x_F + |x_D|^2 > 0 for x≠0x \ne 0. □\square

Theorem. Under the assumptions above, ASSEMBLE followed by APPLY-DIRICHLET returns a system whose solution UU gives uh=∑kUkϕku_h = \sum_k U_k\phi_k with uh(xj)=gju_h(x_j) = g_j at the Dirichlet nodes and a(uh,ϕi)=l(ϕi)a(u_h, \phi_i) = l(\phi_i) for every free basis function ϕi\phi_i. This is the Galerkin method on VhV_h with the Dirichlet values imposed by nodal interpolation. If aa is symmetric and coercive on the functions of VhV_h that vanish at the Dirichlet nodes, the system matrix is symmetric positive definite.

Proof. By Lemma 1, ∑kA[i,k]Uk=∑ka(ϕk,ϕi)Uk=a(uh,ϕi)\sum_k A[i, k]U_k = \sum_k a(\phi_k, \phi_i)U_k = a(u_h, \phi_i) and b[i]=l(ϕi)b[i] = l(\phi_i). Lemma 2, part 1, gives the two conditions. For part 3 of Lemma 2, let xF≠0x_F \ne 0 and v=∑k∈Fxkϕkv = \sum_{k \in F}x_k\phi_k. Then vv vanishes at the Dirichlet nodes and xF⊤AFFxF=a(v,v)>0x_F^\top A_{FF}x_F = a(v, v) > 0. □\square

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 κ\kappa are exact. With a weaker rule, Lemma 1 still holds with aKa_K replaced by its quadrature approximation, and the method is a Galerkin method for a perturbed form.

Complexity

The element routine does Θ(q)\Theta(q) work per entry, so it costs Θ(qn2)\Theta(q n^2) per cell for a fixed dimension, and the scatter of lines L5 to L8 costs Θ(n2)\Theta(n^2) updates per cell. With a hash map per row, as in the reference code, an update takes expected constant time, and the total is Θ(Eqn2)\Theta(E q n^2) 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 En2E n^2 stored entries before duplicates merge, and Θ(N)\Theta(N) 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 AKA_K is symmetric, so is AA, and lines L10 to L12 keep it symmetric.
  • Semidefiniteness. For a symmetric form with aK(v,v)≥0a_K(v, v) \ge 0, each AKA_K is positive semidefinite, and a sum of such matrices is positive semidefinite.
  • Zero row sums. For a(u,v)=∫κ∇u⋅∇va(u, v) = \int\kappa\nabla u\cdot\nabla v and Lagrange elements, ∑jϕj=1\sum_j\phi_j = 1 gives ∑jAij=a(1,ϕi)=0\sum_j A_{ij} = a(1, \phi_i) = 0 before boundary conditions.
  • Mass. The entries of the assembled mass matrix Mij=(ϕj,ϕi)M_{ij} = (\phi_j, \phi_i) add up to ∣Ω∣|\Omega|, which is the starting point of mass lumping.
  • Locality. Aij≠0A_{ij} \ne 0 only if ϕi\phi_i and ϕj\phi_j 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 (i,j,value)(i, j, value) 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 AKA_K before the scatter, which shrinks the global system for high order.
  • Matrix-free operation. Never form AA. Compute AUAU by the same loop over cells applied to vectors. For high degree on tensor-product cells, sum factorization makes this cheaper than storing AA.
  • 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 A00=12A_{00} = \tfrac12 in place of 11, 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 det⁡B<0\det B < 0. Use ∣det⁡B∣|\det B| 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 gKg_K 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 κ\kappa or a rough ff, and the convergence order drops.
  • Dense storage. An N×NN \times N dense matrix is N2N^2 numbers. For N=106N = 10^6 that is 8×10128 \times 10^{12} bytes, while the sparse matrix needs about 10810^8.
  • 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.

finite_element_assembly.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example