Algorithmadvanced
KLU
Also called Clark Kent LU, KLU sparse solver.
Davis and Palamadai Natarajan's sparse LU for circuit matrices, using block triangular form, AMD ordering of each block and Gilbert-Peierls factorization with fast refactoring.
- Time
- O(n a + f) worst
- Space
- O(n + a + s) extra
- Where
- a = the number of nonzeros of A; f = the multiply and subtract operations of the block factorizations; n = the order of the matrix; s = the number of nonzeros of the block factors
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Timothy A. Davis, Ekanathan Palamadai Natarajan, 2010
KLU is a sparse direct solver for the matrices of circuit simulation, by Davis and Palamadai Natarajan (2010). It permutes the matrix to block upper triangular form, orders each diagonal block to reduce fill-in, factors only the diagonal blocks with Gilbert-Peierls LU, and solves by block back substitution. When only the values change, as from one Newton iteration to the next, it refactors with the same pivots and patterns and skips all symbolic work. It belongs to the circuit simulation half of the logic and circuit simulation sub-area, where it solves the modified nodal analysis systems of DC, transient and AC analysis.
In plain words
A circuit often splits into parts where signals pass one way only. An amplifier stage drives the next stage, but the next stage does not change the first. The equations of such a circuit can be put in an order where each group of equations needs only the answers of the groups after it. Then the groups can be solved one at a time, from the last to the first, and each group is a small separate problem.
KLU finds this order automatically from the positions of the nonzero coefficients. It then solves each group with sparse elimination, in an order that keeps the work small. A simulator solves the same pattern thousands of times with new numbers, so KLU does the planning once and repeats only the arithmetic.
The problem
Solve for a nonsingular sparse matrix , many times, where the pattern of stays fixed and the values change. In a circuit simulator is the MNA matrix of (or the Jacobian of the nonlinear MNA equations, or in AC analysis). Circuit matrices have few nonzeros per row, unsymmetric values and often unsymmetric patterns (controlled sources), zeros on the diagonal (rows of voltage sources and inductors), and little fill after a good ordering.
The algorithm
The graph of a matrix with a zero-free diagonal has a node per index and an edge for each off-diagonal nonzero .
KLU(A, b)- 1
Q ← a maximum transversal of A: AQ has a zero-free diagonal - 2
the strongly connected components of the graph of AQ, in reverse of Tarjan's output order, give a symmetric permutation P; T = P A Q Pᵀ is block upper triangular with blocks T_11, ..., T_mm - 3
inside each block, apply a symmetric fill-reducing order of the pattern of T_KK + T_KKᵀ - 4
for K ← 1 to m do - 5
P_K T_KK = L_K U_K by Gilbert-Peierls LU, threshold partial pivoting, diagonal preferred - 6
for K ← m downto 1 do - 7
c_K ← (P b)_K − Σ_{J > K} T_KJ y_J - 8
y_K ← U_K⁻¹ L_K⁻¹ P_K c_K - 9
return x ← Q Pᵀ y
Lines L1 to L3 are the symbolic analysis and depend only on the pattern. Line L1 is the transversal step of the Dulmage-Mendelsohn decomposition, found with augmenting paths of bipartite matching. Line L2 uses Tarjan's algorithm. Lines L4 and L5 are the numerical factorization. Refactorization repeats lines L4 and L5 with the pivot rows fixed and no search for patterns. Lines L6 to L8 solve; a block needs one division.
The real KLU orders each block with approximate minimum degree on , the alias of minimum degree ordering, or with COLAMD, and accepts the diagonal entry at line L5 when its magnitude is at least times the largest candidate. The code of this page uses the exact minimum degree rule, which is slower on large blocks but has the same purpose.
Example
Two stages joined by a voltage-controlled current source. Node 1 is held at V by a voltage source with current . Conductances of S join node 1 to ground, nodes 1 and 2, node 2 to ground, node 3 to ground, nodes 3 and 4, and node 4 to ground. A source draws amperes out of node 3 to ground. With the MNA system is
| step | result |
|---|---|
| L1, transversal | row 5 (the source row) is matched to column , row 1 to column , rows 2, 3, 4 to their own columns |
| L2, components | rows 3, 4 (stage 2) is one component; rows 1, 2 and 5 are three singletons, because once row 5 owns the first stage has no cycle |
| L2, block order | rows , columns |
| L5, factor | only the block of stage 2 needs elimination: |
| L6 to L8, block 4 | row 5: |
| block 3 | row 2: , so |
| block 2 | row 1: |
| block 1 | stage 2 with right side : , |
The coupling entry in row 3 lies in an off-diagonal block. It is used once, at line L7, and it never enters a factor. The determinant is the product of the block determinants with the signs of the permutations, here .
Correctness
Line L1 finds a transversal of size whenever is nonsingular, because a nonzero determinant needs at least one nonzero product . Tarjan's algorithm emits a component only after all components reachable from it, so the reversed order puts every nonzero at or above the diagonal blocks. For a block upper triangular matrix , so each diagonal block is nonsingular, and the block rows solved from the last to the first give the exact solution. Each block factorization is correct by the theorem of Gilbert-Peierls LU. The full proofs are in the correctness proof.
Proof: KLU's block triangular form is valid, and factoring only the diagonal blocks solves the systemfull
We use the notation of the page. is . The bipartite graph of has a row node for each row, a column node for each column, and an edge for each structural nonzero . A transversal is a set of nonzeros, no two in the same row or column; it is a matching of the bipartite graph.
Lemma 1 (a nonsingular matrix has a full transversal). If , then has a transversal of size .
Proof. By the Leibniz formula, . If no permutation has all , every term is zero and . So some has all its entries nonzero, and is a transversal of size .
Lemma 2 (the transversal step). Line L1 returns a transversal of size when one exists, and reports structural singularity otherwise.
Proof. The step processes the columns in turn and searches, by depth-first search, for an alternating path from the new column to an unmatched row: an edge to a row, the matching edge from that row to its column, an edge to another row, and so on. Flipping such a path increases the matching by one. By Berge's theorem, a matching is maximum if and only if it has no augmenting path, see bipartite matching. When the search from a column fails, the rows it reached and the columns it reached form a set of columns whose nonzeros lie in at most rows, so by Hall's theorem no matching covers all columns.
Let be the column permutation that puts the matched column of row in place . Then has a zero-free diagonal. The graph of has a node per index and an edge for each off-diagonal nonzero .
Lemma 3 (the strongly connected components give block upper triangular form). Order the strongly connected components of the graph of in reverse of the order in which Tarjan's algorithm emits them, and number the indices block by block. With the resulting symmetric permutation, is block upper triangular, and each diagonal block has a zero-free diagonal.
Proof. Tarjan's algorithm emits a component only after it has emitted every component reachable from it, see Tarjan's algorithm. So an edge with and in different components has the component of emitted before that of , and after the reversal the component of comes first. A nonzero therefore lies in a block row that is at or before its block column: the matrix is block upper triangular. A symmetric permutation moves diagonal entries to diagonal places, so the diagonal stays zero-free.
The orders inside each block (the fill-reducing order of line L3) are symmetric permutations inside the block, so they keep both properties. Write for the final matrix, with diagonal blocks and blocks with above them.
Theorem 1 (only the diagonal blocks need factors). . So is nonsingular if and only if each is nonsingular. In that case, with split into the blocks and split the same way, the system is equivalent to
which lines L6 to L8 solve in this order.
Proof. The determinant of a block upper triangular matrix is the product of the determinants of its diagonal blocks (apply with and use induction on the number of blocks). The permutations change only the sign. For the system: block row of reads , because the blocks below the diagonal are zero. When block is processed, all with are already known, so the equation for is the one displayed, with a nonsingular matrix. By induction from down to all blocks are found.
Corollary (fill is confined to the diagonal blocks). The LU factors that KLU computes are those of the diagonal blocks. The blocks with are used as they are in the products of line L7, and the zero blocks below the diagonal are never touched. So no fill-in can appear outside the diagonal blocks, and a block needs only a division.
Theorem 2 (each block is factored correctly). Each is factored by the Gilbert-Peierls method with threshold pivoting, which returns , and the block solve of line L8 is exact in exact arithmetic.
Proof. This is the correctness theorem of Gilbert-Peierls LU applied to the block. The threshold test only changes which non-pivotal row is chosen among those with ; the proof of that theorem holds for any choice of a nonzero pivot, and the multipliers are bounded by instead of 1.
Theorem 3 (refactorization). If a new matrix has the same pattern as and the reused pivots are nonzero, the refactorization returns factors with .
Proof. The block form depends only on the pattern, so it is the same for . With the pivot rows fixed, the Gilbert-Peierls column solve computes the same quantities as before, with the new values, and a nonzero pivot gives a valid column of and . Nothing in the proof of Theorem 2 depends on how the pivot row was chosen.
Not proved here: that the irreducible blocks found are the finest possible block triangular form, and that this form is unique up to the order of independent blocks and the permutations inside blocks. Duff, Erisman and Reid prove these facts in their chapter on reduction to block triangular form; they rest on the Dulmage-Mendelsohn decomposition. Also not proved: that the minimum degree order gives little fill. That is an empirical property of the heuristic, measured on circuit matrices by Davis and Palamadai Natarajan.
Complexity
Line L1 with depth-first augmenting paths costs in the worst case, where , and is usually far faster on circuit matrices; Hopcroft-Karp gives . Line L2 is . The ordering of line L3 has no useful worst case bound for the approximate minimum degree of the real KLU beyond , and is close to linear in practice. Lines L4 and L5 cost , where is the arithmetic of the block factorizations, by the theorem of Gilbert-Peierls LU. A solve costs , where is the number of nonzeros of the block factors. Refactorization costs with a smaller constant, because it does no search.
The gain from the block form is that fill and arithmetic stay inside the diagonal blocks. A chain of stages coupled one way, each a pair of nodes, gives blocks of size 2, and the factorization is linear in . On a circuit with global feedback, or on a power grid, the whole matrix is one block and the block step gains nothing. Davis and Palamadai Natarajan report that the block step pays off on many of the circuit matrices of their test set, and that KLU was faster than SuperLU and UMFPACK on most of their circuit matrices; those are their measurements, not proved bounds.
Properties
- Built for refactorization. The symbolic analysis is done once. Newton iterations and time steps then call only the numerical factorization, and most calls reuse the pivots.
- No dense kernels. KLU does not use supernodes or the BLAS. On circuit matrices, which have very little fill, dense kernels do not pay off.
- Partial pivoting inside blocks. Pivots are chosen only inside the diagonal blocks, which keeps the block form and limits the fill to the blocks.
- Determinant and condition estimates. The determinant is a product over the blocks; KLU also gives a cheap estimate of the condition number and of the pivot growth, which a simulator can use to decide when to refactor with new pivots.
Variants and improvements
- Without the block step. For matrices that are known to be irreducible, skip lines L1 and L2.
- Ordering choices. Approximate minimum degree on , COLAMD on , or an order supplied by the user.
- Row scaling. KLU can scale each row by its largest entry or by its sum before the threshold test, which makes the test independent of the units of each equation.
When to use it
Use KLU for repeated solves of sparse circuit matrices in a SPICE-type simulator, for DC, transient and AC analysis, and for other matrices with the same features: very sparse, unsymmetric, with low fill. For large 2D or 3D mesh problems with high fill, supernodal or multifrontal solvers are faster. For a symmetric positive definite matrix, such as the conductance matrix of a resistor network or a power grid without sources, use Cholesky.
Pitfalls
- Reusing pivots too long. Refactorization does not check the pivot sizes against a threshold. If a pivot becomes small, the solution is inaccurate without an error. Check the growth or the condition estimate, and run a full factorization when it is bad.
- Pattern changes. A device model that drops a stamp entry when its value is zero changes the pattern, and the symbolic analysis becomes invalid. Keep explicit zeros in the pattern.
- Structural singularity. A floating node or a loop of voltage sources makes the matrix structurally singular, and line L1 fails. This is a fault in the netlist, not in the solver; DC operating point analysis codes usually add gmin conductances to avoid it.
- Expecting gains on one block. When the whole circuit is one strongly connected block, KLU is only a well-tuned Gilbert-Peierls LU with a fill-reducing order.
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/klu-solver/. The authors are listed in prov/SR6DG7.jsonl.
"""A small KLU-style sparse solver: BTF, a fill-reducing order per block,
Gilbert-Peierls LU per block, block back substitution and refactorization.
The matrix is a list of rows; a zero is a structural zero.
analyze(a) does the symbolic work:
1. a maximum transversal (augmenting paths, as in MC21) gives a column
permutation with a zero-free diagonal;
2. Tarjan's strongly connected components of the graph of the permuted
matrix give a symmetric permutation to block upper triangular form;
3. each diagonal block gets a minimum degree order of the pattern of
B + B^T. This is the exact minimum degree rule on the elimination graph,
not the approximate minimum degree (AMD) of the real KLU.
factor(a, sym) does the numerical work: Gilbert-Peierls LU with threshold
partial pivoting on each diagonal block, preferring the diagonal entry.
refactor(a, num) reuses the pivots and patterns for new values.
solve(num, b) does block back substitution.
The returned permutations satisfy: row k of the permuted matrix is row
sym.prow[k] of A and column k is column sym.pcol[k] of A.
"""
from dataclasses import dataclass, field
class SingularMatrixError(ValueError):
"""The matrix is structurally or numerically singular."""
# ---------------------------------------------------------------- symbolic
def max_transversal(rows, n):
"""match[j] = the row matched to column j, by augmenting paths from each column.
rows[i] is the set of columns of row i. Raises SingularMatrixError when
the structural rank is less than n.
"""
cols = [[] for _ in range(n)]
for i in range(n):
for j in sorted(rows[i]):
cols[j].append(i)
rmatch = [-1] * n # rmatch[i] = column matched to row i
cmatch = [-1] * n
def look_ahead(j): # free rows first, as in the cheap assignment of MC21
return iter(sorted(cols[j], key=lambda i: (rmatch[i] >= 0, i)))
for j0 in range(n):
# iterative DFS for an augmenting path from column j0
seen = set()
parent = {}
stack = [(j0, look_ahead(j0))]
found = -1
while stack and found < 0:
j, it = stack[-1]
for i in it:
if i in seen:
continue
seen.add(i)
parent[i] = j
if rmatch[i] < 0:
found = i
break
stack.append((rmatch[i], look_ahead(rmatch[i])))
break
else:
stack.pop()
if found < 0:
raise SingularMatrixError(f"structurally singular: column {j0} cannot be matched")
i = found
while True: # flip the path
j = parent[i]
prev = cmatch[j]
cmatch[j], rmatch[i] = i, j
if j == j0:
break
i = prev
return cmatch
def tarjan_scc(adj, n):
"""Strongly connected components in the order Tarjan's algorithm emits them."""
index, low, on, stack, comps = [-1] * n, [0] * n, [False] * n, [], []
counter = 0
for s in range(n):
if index[s] >= 0:
continue
work = [(s, iter(adj[s]))]
index[s] = low[s] = counter
counter += 1
stack.append(s)
on[s] = True
while work:
v, it = work[-1]
advanced = False
for w in it:
if index[w] < 0:
index[w] = low[w] = counter
counter += 1
stack.append(w)
on[w] = True
work.append((w, iter(adj[w])))
advanced = True
break
if on[w]:
low[v] = min(low[v], index[w])
if advanced:
continue
work.pop()
if work:
u = work[-1][0]
low[u] = min(low[u], low[v])
if low[v] == index[v]:
comp = []
while True:
w = stack.pop()
on[w] = False
comp.append(w)
if w == v:
break
comps.append(sorted(comp))
return comps
def minimum_degree(adj):
"""Exact minimum degree order of an undirected graph (dict node -> set)."""
g = {v: set(nb) - {v} for v, nb in adj.items()}
order = []
while g:
v = min(g, key=lambda x: (len(g[x]), x))
nb = g.pop(v)
for a in nb:
g[a].discard(v)
g[a] |= nb - {a}
order.append(v)
return order
@dataclass
class Symbolic:
n: int
prow: list
pcol: list
blocks: list # list of (start, end) in the permuted numbering
def analyze(a):
n = len(a)
rows = [{j for j in range(n) if a[i][j] != 0} for i in range(n)]
match = max_transversal(rows, n) # @line L1
# In A(:, match^-1) the entry (i, i) is nonzero: column j moves to place match[j].
colof = [0] * n
for j in range(n):
colof[match[j]] = j # column of A placed at position i has its match in row i
adj = [sorted({match[j] for j in rows[i]} - {i}) for i in range(n)]
comps = tarjan_scc(adj, n) # @line L2
comps.reverse() # upper block triangular: an edge i -> j goes to the same or a later block
prow, pcol, blocks = [], [], []
for comp in comps: # @line L3
start = len(prow)
sub = {v: {w for w in adj[v] if w in comp} for v in comp}
for v in comp:
for w in list(sub[v]):
sub[w].add(v)
for v in minimum_degree(sub):
prow.append(v)
pcol.append(colof[v])
blocks.append((start, len(prow)))
return Symbolic(n, prow, pcol, blocks)
# ---------------------------------------------------------------- numerical
@dataclass
class Numeric:
sym: Symbolic
lu: list = field(default_factory=list) # per block: (pivrow, lcols, ucols)
offdiag: list = field(default_factory=list) # per block: list of (local row, global col, value)
a: list = None
def _gp_block(cols, m, u, tol, pivrow_fixed=None):
"""Gilbert-Peierls LU of one block given as column dicts {local row: value}.
With pivrow_fixed, reuse that row order (refactorization).
"""
lcols, ucols, pivrow, pivstep = [], [], [], {}
for k in range(m):
mark, post = set(), []
for s in cols[k]:
if s in mark:
continue
mark.add(s)
stack = [(s, iter(lcols[pivstep[s]]) if s in pivstep else iter(()))]
while stack:
i, it = stack[-1]
for r in it:
if r not in mark:
mark.add(r)
stack.append((r, iter(lcols[pivstep[r]]) if r in pivstep else iter(())))
break
else:
stack.pop()
post.append(i)
post.reverse()
x = {i: 0 for i in post}
for i, v in cols[k].items():
x[i] = v
for i in post:
if i in pivstep:
xi = x[i]
for r, l in lcols[pivstep[i]].items():
x[r] -= l * xi
cand = [i for i in post if i not in pivstep]
if pivrow_fixed is not None:
p = pivrow_fixed[k]
if p not in x or abs(x[p]) <= tol:
raise SingularMatrixError("refactorization met a zero pivot")
else:
if not cand:
raise SingularMatrixError("numerically singular block")
big = max(abs(x[i]) for i in cand)
if big <= tol:
raise SingularMatrixError("numerically singular block")
if k in x and k not in pivstep and abs(x[k]) >= u * big:
p = k # the diagonal entry of the ordered block passes the threshold
else:
p = max(cand, key=lambda i: (abs(x[i]), -i))
piv = x[p]
uc = {pivstep[i]: x[i] for i in post if i in pivstep}
uc[k] = piv
lc = {i: x[i] / piv for i in cand if i != p}
lcols.append(lc)
ucols.append(uc)
pivrow.append(p)
pivstep[p] = k
return pivrow, lcols, ucols
def _split(a, sym):
"""Diagonal blocks as local column dicts, and the off-diagonal entries."""
pos_c = {c: k for k, c in enumerate(sym.pcol)}
blocks, off = [], []
for s, e in sym.blocks:
cols = [{} for _ in range(e - s)]
rest = []
for k in range(s, e):
r = sym.prow[k]
for c, v in enumerate(a[r]):
if v == 0:
continue
kc = pos_c[c]
if s <= kc < e:
cols[kc - s][k - s] = v
elif kc < s:
raise AssertionError("entry below the block diagonal")
else:
rest.append((k - s, kc, v))
blocks.append(cols)
off.append(rest)
return blocks, off
def factor(a, sym, u=0.001, tol=0):
num = Numeric(sym, a=a)
blocks, num.offdiag = _split(a, sym)
for (s, e), cols in zip(sym.blocks, blocks): # @line L4
num.lu.append(_gp_block(cols, e - s, u, tol)) # @line L5
return num
def refactor(a, num, tol=0):
"""New values on the same pattern: reuse the pivot rows and the order."""
sym = num.sym
new = Numeric(sym, a=a)
blocks, new.offdiag = _split(a, sym)
for (s, e), cols, old in zip(sym.blocks, blocks, num.lu):
new.lu.append(_gp_block(cols, e - s, 0, tol, pivrow_fixed=old[0]))
return new
def _block_solve(lu, rhs):
pivrow, lcols, ucols = lu
m = len(pivrow)
y = list(rhs)
z = [None] * m
for k in range(m):
zk = y[pivrow[k]]
z[k] = zk
for r, l in lcols[k].items():
y[r] = y[r] - l * zk
x = [None] * m
for k in range(m - 1, -1, -1):
xk = z[k] / ucols[k][k]
x[k] = xk
for j, v in ucols[k].items():
if j != k:
z[j] = z[j] - v * xk
return x
def solve(num, b):
sym = num.sym
n = sym.n
xp = [None] * n # solution in the permuted column numbering
for bi in range(len(sym.blocks) - 1, -1, -1): # @line L6
s, e = sym.blocks[bi]
rhs = [b[sym.prow[k]] for k in range(s, e)]
for lr, kc, v in num.offdiag[bi]: # @line L7
rhs[lr] = rhs[lr] - v * xp[kc]
xb = _block_solve(num.lu[bi], rhs) # @line L8
for t, v in enumerate(xb):
xp[s + t] = v
x = [None] * n
for k, c in enumerate(sym.pcol):
x[c] = xp[k]
return x # @line L9
def klu_solve(a, b, u=0.001, tol=0):
return solve(factor(a, analyze(a), u, tol), b)
def determinant(num):
"""det A as the product of the block determinants, with the permutation signs."""
def sign(perm):
seen, s = set(), 1
for i in range(len(perm)):
if i in seen:
continue
j, length = i, 0
while j not in seen:
seen.add(j)
j = perm[j]
length += 1
if length % 2 == 0:
s = -s
return s
d = sign(num.sym.prow) * sign(num.sym.pcol)
for pivrow, _, ucols in num.lu:
d *= sign(pivrow)
for k, uc in enumerate(ucols):
d *= uc[k]
return d
sim3dense.py 70 lines
# SPDX-License-Identifier: MIT
# Shared helper of the sim3 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for Fraction, float or complex entries.
The circuit pages of group sim3 use this module as a reference solver and for
the small dense systems inside their tests. It holds no sparse method and no
circuit method. Matrices are lists of rows.
"""
from fractions import Fraction
class SingularMatrixError(ValueError):
"""The matrix has no inverse (a zero pivot in exact arithmetic)."""
def _exact(x):
return Fraction(x) if isinstance(x, int) else x
def solve(a, b, tol=0.0):
"""Solve a x = b by Gaussian elimination with partial pivoting.
With Fraction entries the result is exact. b is a vector or a matrix
(a list of rows); the result has the same shape.
"""
n = len(a)
m = [[_exact(x) for x in row] for row in a]
vec = not (b and isinstance(b[0], list))
rhs = [[_exact(x)] for x in b] if vec else [[_exact(x) for x in row] for row in b]
for k in range(n):
p = max(range(k, n), key=lambda i: abs(m[i][k]))
if abs(m[p][k]) <= tol:
raise SingularMatrixError(f"zero pivot in column {k}")
m[k], m[p] = m[p], m[k]
rhs[k], rhs[p] = rhs[p], rhs[k]
for i in range(k + 1, n):
if m[i][k] != 0:
f = m[i][k] / m[k][k]
for j in range(k, n):
m[i][j] -= f * m[k][j]
for j in range(len(rhs[i])):
rhs[i][j] -= f * rhs[k][j]
x = [[0] * len(rhs[0]) for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(len(rhs[0])):
s = rhs[i][j] - sum(m[i][k] * x[k][j] for k in range(i + 1, n))
x[i][j] = s / m[i][i]
return [r[0] for r in x] if vec else x
def transpose(a):
return [list(r) for r in zip(*a)]
def matvec(a, x):
return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]
def matmul(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 identity(n, one=1):
return [[one if i == j else 0 * one for j in range(n)] for i in range(n)]
def inverse(a):
return solve(a, identity(len(a)))
test_klu_solver.py 216 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/klu-solver/. The authors are listed in prov/SR6DG7.jsonl.
import itertools
import random
from fractions import Fraction as F
import pytest
from klu_solver import (
SingularMatrixError,
analyze,
determinant,
factor,
klu_solve,
max_transversal,
minimum_degree,
refactor,
solve,
tarjan_scc,
)
from sim3dense import solve as dense_solve
# Two stages joined by a voltage-controlled current source: a 1 V source at
# node 1, unit conductances 1-gnd, 1-2, 2-gnd, 3-gnd, 3-4, 4-gnd, and a VCCS
# of 2 S from node 3 to ground controlled by the voltage of node 2.
# Unknowns (e1, e2, e3, e4, j).
TWO_STAGE = [
[2, -1, 0, 0, 1],
[-1, 2, 0, 0, 0],
[0, 2, 2, -1, 0],
[0, 0, -1, 2, 0],
[1, 0, 0, 0, 0],
]
def exact(a):
return [[F(x) for x in row] for row in a]
def closure(adj, n):
reach = [[i == j for j in range(n)] for i in range(n)]
for i in range(n):
for j in adj[i]:
reach[i][j] = True
for k in range(n):
for i in range(n):
if reach[i][k]:
for j in range(n):
if reach[k][j]:
reach[i][j] = True
return reach
def brute_det(a):
n = len(a)
total = F(0)
for perm in itertools.permutations(range(n)):
inv = sum(1 for i in range(n) for j in range(i + 1, n) if perm[i] > perm[j])
prod = F(1)
for i in range(n):
prod *= a[i][perm[i]]
if prod == 0:
break
total += -prod if inv % 2 else prod
return total
def structural_rank_full(a):
n = len(a)
return any(all(a[i][p[i]] != 0 for i in range(n)) for p in itertools.permutations(range(n)))
def random_btf_matrix(rng, n):
"""A random sparse matrix, often reducible, with a nonzero determinant."""
while True:
a = [[F(0)] * n for _ in range(n)]
perm = list(range(n))
rng.shuffle(perm)
for i in range(n):
a[i][perm[i]] = F(rng.choice([-3, -2, -1, 1, 2, 3, 5]))
for _ in range(rng.randint(0, 2 * n)):
a[rng.randrange(n)][rng.randrange(n)] = F(rng.randint(-4, 4))
if brute_det(a) != 0 if n <= 6 else True:
try:
dense_solve(a, [F(1)] * n)
return a
except ValueError:
continue
def check_btf(a, sym):
n = len(a)
pos_c = {c: k for k, c in enumerate(sym.pcol)}
block_of = [0] * n
for b, (s, e) in enumerate(sym.blocks):
for k in range(s, e):
block_of[k] = b
for k, r in enumerate(sym.prow):
for c in range(n):
if a[r][c] != 0:
assert block_of[k] <= block_of[pos_c[c]], "entry below the diagonal blocks"
for k in range(n):
assert a[sym.prow[k]][sym.pcol[k]] != 0, "zero on the permuted diagonal"
# each diagonal block is irreducible: strongly connected
for s, e in sym.blocks:
m = e - s
adj = [[t - s for t in range(s, e) if t != k and a[sym.prow[k]][sym.pcol[t]] != 0] for k in range(s, e)]
reach = closure(adj, m)
assert all(all(row) for row in reach)
return block_of
def test_two_stage_example():
a = exact(TWO_STAGE)
sym = analyze(a)
assert sym.prow == [2, 3, 0, 1, 4]
assert sym.pcol == [2, 3, 4, 1, 0]
assert sym.blocks == [(0, 2), (2, 3), (3, 4), (4, 5)]
num = factor(a, sym)
x = solve(num, [F(0), F(0), F(0), F(0), F(1)])
assert x == [F(1), F(1, 2), F(-2, 3), F(-1, 3), F(-3, 2)]
assert determinant(num) == brute_det(a) == F(-6)
def test_tarjan_against_closure():
rng = random.Random(31)
for _ in range(200):
n = rng.randint(1, 9)
adj = [sorted({rng.randrange(n) for _ in range(rng.randint(0, 3))} - {i}) for i in range(n)]
comps = tarjan_scc(adj, n)
reach = closure(adj, n)
brute = {}
for i in range(n):
key = frozenset(j for j in range(n) if reach[i][j] and reach[j][i])
brute[key] = True
assert {frozenset(c) for c in comps} == set(brute)
# emitted in reverse topological order: an edge goes to the same or an earlier component
where = {v: k for k, c in enumerate(comps) for v in c}
for i in range(n):
for j in adj[i]:
assert where[j] <= where[i]
def test_transversal_against_permutations():
rng = random.Random(32)
for _ in range(300):
n = rng.randint(1, 6)
a = [[1 if rng.random() < 0.35 else 0 for _ in range(n)] for _ in range(n)]
rows = [{j for j in range(n) if a[i][j]} for i in range(n)]
full = structural_rank_full(a)
if full:
match = max_transversal(rows, n)
assert sorted(match) == list(range(n))
assert all(a[match[j]][j] for j in range(n))
else:
with pytest.raises(SingularMatrixError):
max_transversal(rows, n)
def test_minimum_degree_is_greedy():
g = {0: {1, 2, 3}, 1: {0}, 2: {0}, 3: {0}}
# leaves first; after two leaves the hub and the last leaf tie at degree 1
assert minimum_degree(g) == [1, 2, 0, 3]
# a path 0-1-2-3-4: ends first, never a middle node of degree 2
path = {0: {1}, 1: {0, 2}, 2: {1, 3}, 3: {2, 4}, 4: {3}}
assert minimum_degree(path) == [0, 1, 2, 3, 4]
def test_btf_solve_det_refactor():
rng = random.Random(33)
for _ in range(150):
n = rng.randint(1, 6)
a = random_btf_matrix(rng, n)
sym = analyze(a)
check_btf(a, sym)
num = factor(a, sym)
b = [F(rng.randint(-5, 5)) for _ in range(n)]
assert solve(num, b) == dense_solve(a, b)
assert determinant(num) == brute_det(a)
# same pattern, new values: refactorization reuses the pivots
a2 = [[x * F(rng.randint(1, 3), rng.randint(1, 3)) if x != 0 else F(0) for x in row] for row in a]
try:
num2 = refactor(a2, num)
except SingularMatrixError:
continue
assert solve(num2, b) == dense_solve(a2, b)
def test_float_circuit_chain():
# A chain of 40 amplifier stages, each a grounded RC-like node pair, one-way coupled.
rng = random.Random(34)
stages, n = 40, 80
a = [[0.0] * n for _ in range(n)]
for s in range(stages):
i, j = 2 * s, 2 * s + 1
g1, g2, g3 = (rng.uniform(0.5, 2.0) for _ in range(3))
a[i][i] += g1 + g2
a[j][j] += g2 + g3
a[i][j] -= g2
a[j][i] -= g2
if s > 0:
a[i][2 * s - 1] += rng.uniform(1.0, 5.0) # transconductance from the previous stage
b = [rng.uniform(-1, 1) for _ in range(n)]
sym = analyze(a)
assert len(sym.blocks) == stages
x = klu_solve(a, b)
r = max(abs(sum(a[i][k] * x[k] for k in range(n)) - b[i]) for i in range(n))
assert r < 1e-9
def test_singular():
with pytest.raises(SingularMatrixError):
analyze([[F(1), F(1)], [F(0), F(0)]])
with pytest.raises(SingularMatrixError):
klu_solve([[F(1), F(2)], [F(2), F(4)]], [F(1), F(1)])
History
Davis and Palamadai Natarajan developed KLU for circuit simulation and published it in 2010 as ACM TOMS Algorithm 907. It combines the block triangular form, whose algorithms Duff, Reid and others developed in the 1970s, with the factorization of Gilbert and Peierls (1988). It is the default solver of Xyce and is used in other simulators, among them NGSPICE, where it is an option that replaces the older Sparse 1.3 package.
References
- Timothy A. Davis and Ekanathan Palamadai Natarajan, Algorithm 907, KLU, a direct sparse solver for circuit simulation problems, ACM Transactions on Mathematical Software 37(3), article 36, 2010, the whole paper (the BTF step, the ordering of each block, the factorization with threshold partial pivoting, refactorization, and the comparison with SuperLU, UMFPACK and Sparse 1.3 on circuit matrices)
- John R. Gilbert and Tim Peierls, Sparse partial pivoting in time proportional to arithmetic operations, SIAM Journal on Scientific and Statistical Computing 9(5), 862 to 874, 1988, the factorization kernel used on each diagonal block
- Iain S. Duff, Albert M. Erisman and John K. Reid, Direct Methods for Sparse Matrices, second edition, Oxford University Press, 2017, the chapter on reduction to block triangular form (the transversal, the strong components and the uniqueness of the form)
- Timothy A. Davis, Direct Methods for Sparse Linear Systems, SIAM, 2006, the chapter on fill-reducing orderings, with the maximum transversal and the block triangular form
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 SR6DG7 Edit this page History Report an error Markdown