Techniquecore
Static condensation
Eliminates the interior degrees of freedom of each element before assembly by a Schur complement, leaving a smaller system on element boundaries.
Static condensation solves a finite element system in two levels. Each element has interior unknowns, which belong to that element only, and boundary unknowns, which it shares with its neighbors. Because the interior unknowns of one element do not couple to any other element, they can be eliminated element by element before assembly: the element matrix is replaced by its Schur complement on the boundary unknowns. The global system then has only the boundary unknowns. After it is solved, each element recovers its interior values from its own small system. The result is exactly the solution of the full system, because static condensation is block Gaussian elimination in a good order. It is not an approximation. For high degree elements most unknowns are interior, so the global system becomes much smaller.
In plain words
Some unknowns live inside one element and talk only to the other unknowns of the same element. You can solve for them in terms of the unknowns on the element's edges before you build the big system. Each element then gives a smaller matrix that only connects edge unknowns. You build and solve the big system for the edge unknowns only. At the end, go back to each element and compute its inside unknowns from the edge values you now know. Nothing is lost: the answer is the same as when you solve the whole system at once. It is just a way to do the elimination in pieces.
When it applies
- The interior unknowns are private. An unknown can be condensed on element only if no other element uses it. This holds for the interior nodes or bubble functions of elements, for the cell unknowns of hybridized mixed and HDG methods, and for the interior of a subdomain in domain decomposition.
- The interior block is invertible. must be nonsingular. For a symmetric positive definite element matrix it is: a principal submatrix of an SPD matrix is SPD. For a singular element matrix, like a pure Neumann element stiffness, the interior block is still SPD as long as the interior functions do not include a constant.
- A linear static problem. For the method is exact. For a dynamic problem the interior unknowns have inertia too, and eliminating them with the stiffness alone, as Guyan did, is an approximation.
The template
CONDENSE(K, F, I) ▷ one element; I = its interior local unknowns- 1
B <- the local unknowns that are not in I - 2
factor K_II = L L^T; X_K <- K_II^{-1} K_IB; X_F <- K_II^{-1} F_I - 3
S <- K_BB - K_BI X_K; g <- F_B - K_BI X_F ▷ the Schur complement and the condensed load - 4
return S, g, X_K, X_F SOLVE-CONDENSED(elements)- 5
for each element: (S, g, X_K, X_F) <- CONDENSE(K, F, I); add S and g into the global boundary system - 6
apply the boundary conditions and solve the global boundary system for u_B - 7
for each element: u_I <- X_F - X_K u_B ▷ local recovery - 8
return u
Why it is exact. Write the full system with all interior unknowns first:
The first block row gives . Put it into the second row: . Because the interior unknowns of different elements do not couple, the global is block diagonal with one block per element. So its inverse is the block diagonal of the element inverses, and the global Schur complement is the sum of the element Schur complements, assembled like ordinary element matrices. Line L5 does exactly that, and line L7 is the first block row.
Energy view. For an SPD element matrix, , and the minimizer is the recovered when the load is 0. So is SPD, and the condensed element gives the response of least energy of the element to given boundary values.
Classic examples
The P2 element in 1D condenses to P1. For , the P2 element on of length with unknowns (left, right, middle) has
Condense the middle unknown. and for both ends, so has all four entries , and
That is the P1 element matrix with the P1 load. So the vertex values of P2 are the P1 vertex values, which in 1D are exact. The recovery gives , which is the exact value of the quadratic solution at the midpoint. The test file checks this, and it checks that the condensed solve and the full solve agree on P2 meshes and on chains of random SPD elements.
High degree quadrilaterals. A element has unknowns, of which are interior and are on the boundary. For that is 49 interior and 32 boundary unknowns out of 81. In the hp finite element method and the spectral element method, condensation removes most of the unknowns from the global system, and the boundary system has a much smaller bandwidth.
Hybridization. In HDG and hybridized mixed methods, all cell unknowns are interior, and the only global unknowns are on the faces. Condensation is what makes these methods competitive: the global system is a sparse system for a single face function.
Substructuring. Treat a whole subdomain as one element. Its interior is condensed, and the interface problem with the Schur complement is the starting point of the iterative substructuring methods of domain decomposition.
Variations
- Condense, then solve iteratively. The Schur complement system is better conditioned than the full system for many problems, and it can be solved by the conjugate gradient method without forming , using one interior solve per element in each product.
- Static condensation in parallel. The condensation of all elements is independent, so it runs in parallel with no communication.
- Recursive condensation. Condense the element interiors, then group elements into patches and condense the patch interiors, and so on. This is the nested dissection idea, and it is how multifrontal direct solvers work.
- Guyan reduction. Apply the transformation also to the mass matrix. This gives a smaller eigenvalue problem that is accurate for the low frequencies, but it is no longer exact.
- Condensation of a nonlinear problem. In Newton's method, condense the tangent matrix in each step. The interior residual must then be part of the condensed load.
Pitfalls
- Shared unknowns. Condensing an unknown that another element also uses gives a wrong answer. The interior set must be private to the element.
- Do not form the inverse. Compute with one Cholesky factorization and several triangular solves, as the code does. An explicit inverse costs more and loses accuracy.
- Storage for the recovery. The recovery needs and , or the factorization of , for every element. Keep them, or recompute the element matrices after the global solve.
- Fill in the boundary system. The Schur complement of an element is dense on its boundary unknowns. For a low degree element with few interior unknowns, this can make the global matrix denser than it was, with little gain. Use condensation when the interior is large.
- Dynamics. The Schur complement of the stiffness alone does not give the right inertia. Do not treat Guyan reduction as exact.
- Boundary conditions on interior unknowns. If a Dirichlet condition fixes an interior unknown, move it to the right side before condensation.
Code
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
# 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)]
static_condensation.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/static-condensation/. The authors are listed in prov/G6BEQJ.jsonl.
"""Static condensation of element interior unknowns.
An element has a symmetric positive definite stiffness K and a load F on
its local unknowns, split into interior ones I (used by this element only)
and boundary ones B (shared with neighbors). Static condensation replaces
the element by the Schur complement
S = K_BB - K_BI K_II^{-1} K_IB, g = F_B - K_BI K_II^{-1} F_I,
assembles only S and g, solves for the boundary unknowns u_B, and then
recovers u_I = K_II^{-1} (F_I - K_IB u_B) element by element. The result is
exactly the solution of the full system: this is block Gaussian elimination
in a chosen order, not an approximation.
Cost per element with i interior and b boundary unknowns: O(i^3 + i^2 b + i b^2)
(dense Cholesky of K_II and b + 1 solves).
"""
import scimat
def condense(K, F, interior):
"""Return (boundary, S, g, XK, XF) for the local interior index list.
boundary lists the other local indices in order. XK = K_II^{-1} K_IB and
XF = K_II^{-1} F_I are kept for the recovery.
"""
n = len(K)
inner = list(interior)
boundary = [r for r in range(n) if r not in set(inner)] # @line L1
if not inner:
return boundary, [[K[r][s] for s in boundary] for r in boundary], [F[r] for r in boundary], [], []
Kii = [[K[r][s] for s in inner] for r in inner]
low = scimat.cholesky(Kii) # one factorization, b + 1 right sides
cols = [scimat.cholesky_solve(low, [K[r][s] for r in inner]) for s in boundary] # @line L2
XK = [[cols[c][a] for c in range(len(boundary))] for a in range(len(inner))]
XF = scimat.cholesky_solve(low, [F[r] for r in inner])
S = [[K[r][s] - sum(K[r][inner[a]] * XK[a][c] for a in range(len(inner))) # @line L3
for c, s in enumerate(boundary)] for r in boundary]
g = [F[r] - sum(K[r][inner[a]] * XF[a] for a in range(len(inner))) for r in boundary]
return boundary, S, g, XK, XF # @line L4
def recover(XK, XF, uB):
"""Return the interior values u_I = XF - XK u_B."""
return [XF[a] - sum(XK[a][c] * uB[c] for c in range(len(uB))) for a in range(len(XF))] # @line L7
def solve_condensed(ndof, elements, fixed):
"""Solve the assembled problem by static condensation.
elements: list of (dofs, K, F, interior) with dofs the global numbers of
the local unknowns and interior the local indices to condense (their
global numbers must not appear in any other element). fixed: dict of
global unknown -> prescribed value. Return the full global solution.
"""
data = []
S_glob = scimat.zeros(ndof)
g_glob = [0.0] * ndof
used = set()
for dofs, K, F, interior in elements:
boundary, S, g, XK, XF = condense(K, F, interior)
gb = [dofs[r] for r in boundary]
for a, r in enumerate(gb): # @line L5
g_glob[r] += g[a]
used.add(r)
for c, s in enumerate(gb):
S_glob[r][s] += S[a][c]
data.append((dofs, interior, gb, XK, XF))
free = sorted(r for r in used if r not in fixed)
rhs = [g_glob[r] - sum(S_glob[r][s] * v for s, v in fixed.items()) for r in free]
x = scimat.solve([[S_glob[r][s] for s in free] for r in free], rhs) if free else [] # @line L6
u = [0.0] * ndof
for r, v in fixed.items():
u[r] = v
for r, v in zip(free, x):
u[r] = v
for dofs, interior, gb, XK, XF in data:
uI = recover(XK, XF, [u[r] for r in gb])
for a, r in enumerate(interior):
u[dofs[r]] = uI[a]
return u # @line L8
def solve_full(ndof, elements, fixed):
"""Solve the same problem by assembling every unknown (the reference)."""
A = scimat.zeros(ndof)
b = [0.0] * ndof
for dofs, K, F, _ in elements:
for r, gr in enumerate(dofs):
b[gr] += F[r]
for s, gs in enumerate(dofs):
A[gr][gs] += K[r][s]
free = [r for r in range(ndof) if r not in fixed]
rhs = [b[r] - sum(A[r][s] * v for s, v in fixed.items()) for r in free]
x = scimat.solve([[A[r][s] for s in free] for r in free], rhs)
u = [0.0] * ndof
for r, v in fixed.items():
u[r] = v
for r, v in zip(free, x):
u[r] = v
return u
def p2_element(h, f=1.0):
"""Return (K, F) of the 1D P2 element for -u'' = f (f constant), unknowns (left, right, middle)."""
K = [[7 / (3 * h), 1 / (3 * h), -8 / (3 * h)],
[1 / (3 * h), 7 / (3 * h), -8 / (3 * h)],
[-8 / (3 * h), -8 / (3 * h), 16 / (3 * h)]]
F = [f * h / 6, f * h / 6, 2 * f * h / 3]
return K, F
def p2_mesh(n, f=1.0):
"""Return (ndof, elements) for n equal P2 elements on [0, 1]; vertices 0..n, midpoints n+1..2n."""
h = 1.0 / n
elements = []
for e in range(n):
K, F = p2_element(h, f)
elements.append(([e, e + 1, n + 1 + e], K, F, [2]))
return 2 * n + 1, elements
test_static_condensation.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/static-condensation/. The authors are listed in prov/G6BEQJ.jsonl.
import random
import scimat
import static_condensation as SC
def random_spd(n, rng):
a = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
m = scimat.matmul(scimat.transpose(a), a)
for i in range(n):
m[i][i] += 0.5
return m
def test_hand_example_p2_condenses_to_p1():
h = 0.25
K, F = SC.p2_element(h)
boundary, S, g, XK, XF = SC.condense(K, F, [2])
assert boundary == [0, 1]
want = [[1 / h, -1 / h], [-1 / h, 1 / h]]
assert max(abs(S[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-12
assert max(abs(v - h / 2) for v in g) < 1e-15
# the middle value is the mean of the ends plus h^2 f / 8
assert abs(SC.recover(XK, XF, [1.0, 3.0])[0] - (2.0 + h * h / 8)) < 1e-14
def test_p2_mesh_matches_full_solve_and_exact_solution():
for n in (1, 3, 8):
ndof, elements = SC.p2_mesh(n)
fixed = {0: 0.0, n: 0.0}
a = SC.solve_condensed(ndof, elements, fixed)
b = SC.solve_full(ndof, elements, fixed)
assert max(abs(x - y) for x, y in zip(a, b)) < 1e-12
for e in range(n + 1): # vertices
x = e / n
assert abs(a[e] - x * (1 - x) / 2) < 1e-12
for e in range(n): # midpoints: P2 is exact for the quadratic solution
x = (e + 0.5) / n
assert abs(a[n + 1 + e] - x * (1 - x) / 2) < 1e-12
def test_random_elements_match_full_solve():
rng = random.Random(7)
for _ in range(20):
ne = rng.randint(1, 5)
# a chain: element e has boundary unknowns e and e + 1 and its own interior ones
ndof = ne + 1
elements = []
for e in range(ne):
ni = rng.randint(0, 4)
dofs = [e, e + 1] + list(range(ndof, ndof + ni))
ndof += ni
K = random_spd(2 + ni, rng)
F = [rng.uniform(-1, 1) for _ in range(2 + ni)]
elements.append((dofs, K, F, list(range(2, 2 + ni))))
fixed = {0: rng.uniform(-1, 1)}
a = SC.solve_condensed(ndof, elements, fixed)
b = SC.solve_full(ndof, elements, fixed)
assert max(abs(x - y) for x, y in zip(a, b)) < 1e-9
def test_schur_complement_is_spd_and_minimizes_energy():
rng = random.Random(1)
K = random_spd(6, rng)
F = [0.0] * 6
boundary, S, _, XK, XF = SC.condense(K, F, [3, 4, 5])
scimat.cholesky(S) # raises if S is not positive definite
uB = [rng.uniform(-1, 1) for _ in boundary]
uI = SC.recover(XK, XF, uB)
u = uB + uI # boundary = [0, 1, 2], interior = [3, 4, 5]
def energy(v):
return scimat.dot(v, scimat.matvec(K, v))
sb = scimat.dot(uB, scimat.matvec(S, uB))
assert abs(energy(u) - sb) < 1e-12
for _ in range(20): # any other interior values give a larger energy
other = uB + [x + rng.uniform(-0.1, 0.1) for x in uI]
assert energy(other) > sb
Exercises
- Show that is symmetric positive definite when is. Answer: for , let . Then , and the left side is positive because .
- Count the operations of condensing one element with interior and boundary unknowns by Cholesky. Answer: for the factorization, for the solves, and for , so .
- For the 1D P2 element with the load constant, find the recovered midpoint value. Answer: .
- Why does condensation of all unknowns except one give the exact value of that unknown? Answer: it is Gaussian elimination of all other unknowns, and the last equation is with a Schur complement.
References
- Edward L. Wilson, The static condensation algorithm, International Journal for Numerical Methods in Engineering 8(1) (1974) 198-203, the element level elimination of internal unknowns and its operation count
- Robert J. Guyan, Reduction of stiffness and mass matrices, AIAA Journal 3(2) (1965) 380, elimination of unloaded coordinates from the stiffness, and its use for the mass
- George Em Karniadakis and Spencer J. Sherwin, Spectral/hp Element Methods for Computational Fluid Dynamics, 2nd edition, Oxford University Press (2005), static condensation of the interior modes and the boundary system for high degree elements
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag G6BEQJ Edit this page History Report an error Markdown