Algorithm Search⌘K

Algorithmadvanced

Gilbert-Peierls sparse LU

Also called left-looking sparse LU, Gilbert-Peierls algorithm.

Sparse LU with partial pivoting that builds each column of L and U from the earlier columns, finding its pattern by depth-first search, in time proportional to the arithmetic.

Time
O(n + a + f) worst
Space
O(n + s) extra
Where
a = the number of nonzeros of A; f = the number of multiply and subtract operations of the factorization; n = the order of the matrix; s = the number of nonzeros of L and U
Properties
deterministicexactiterative
Origin
John R. Gilbert, Tim Peierls, 1988

Gilbert-Peierls LU is a sparse LU factorization with partial pivoting. It computes the factors one column at a time: column kk of LL and UU is the solution of one sparse triangular system with the columns of LL already found. Before the arithmetic it finds the nonzero pattern of that solution by a depth-first search in the graph of LL, so the total time is proportional to the number of arithmetic operations plus the size of the matrix. It is a general method of sparse linear algebra; on this page it is framed for the circuit simulation half of the logic and circuit simulation sub-area, where it factors the modified nodal analysis matrices of KLU.

In plain words

Elimination on a matrix that is almost all zeros wastes time if it looks at the zeros. This method builds the answer column by column. For each new column it first works out which positions can become nonzero, by following links from the known nonzeros through the part of the factor already built. Then it does arithmetic only on those positions, in an order where every value is final before it is used.

The search costs no more than the arithmetic it prepares. So the method never spends much time on bookkeeping, even when each column has only a few nonzeros, which is the usual case for circuits. It also swaps rows during the work to keep the numbers stable.

The problem

Given a nonsingular n×nn \times n sparse matrix AA, find a row permutation PP, a unit lower triangular LL and an upper triangular UU with PA=LUPA = LU, and use them to solve Ax=bAx = b. In a circuit simulator AA is the MNA matrix MM of the system Mx=zMx = z, or the Jacobian of the nonlinear MNA equations at one Newton iteration. The column order is fixed in advance by a fill-reducing order such as minimum degree; the row order is chosen during the factorization.

The algorithm

Write π(j)\pi(j) for the row of AA chosen as pivot jj. A row is pivotal once it is some π(j)\pi(j). The graph of LL has the rows as nodes and an edge π(j)→r\pi(j) \to r for each nonzero L(r,j)L(r, j).

  1. GP-LU(A)
  2. 1for k ← 1 to n do
  3. 2X ← REACH(L, rows of the nonzeros of A(:, k)) ▷ in topological order
  4. 3x ← A(:, k), scattered on the rows of X (zero where A has no entry)
  5. 4for each row i in X, in order do
  6. 5if i = π(j) for some j < k then
  7. 6for each r with L(r, j) ≠ 0 do x_r ← x_r − L(r, j) · x_i
  8. 7p ← the non-pivotal row of X with the largest |x_p|; if x_p = 0 then return "singular"
  9. 8U(π(j), k) ← x_π(j) for the pivotal rows of X; U(k, k) ← x_p; L(r, k) ← x_r / x_p for the other non-pivotal rows of X
  10. 9π(k) ← p
  11. 10return π, L, U
  12. REACH(L, B)
  13. R1 for each s in B not yet marked do DFS(s)
  14. R2 DFS(i): mark i; if i = π(j) then for each r with L(r, j) ≠ 0, r not marked do DFS(r)
  15. R3 append i to the postorder
  16. R4 return the postorder reversed

Lines L3 to L6 are a column-oriented triangular solve Lx=A(:,k)L x = A(:, k) that touches only the rows in XX. The reverse postorder of the search is a topological order of the graph of LL, so each xπ(j)x_{\pi(j)} is final before line L6 uses it. To solve Ax=bAx = b, run forward substitution with LL on PbPb and back substitution with UU.

Example

Take the matrix below. It has a zero in each position where a new nonzero will appear, so the trace shows both pivoting and fill-in.

A=(10024200011000−11)A = \begin{pmatrix} 1 & 0 & 0 & 2 \\ 4 & 2 & 0 & 0 \\ 0 & 1 & 1 & 0 \\ 0 & 0 & -1 & 1 \end{pmatrix}

Rows are numbered 1 to 4.

column kk start rows BB reach XX (in order) values after line L6 pivot new L(:,k)L(:, k) new U(:,k)U(:, k)
1 1, 2 1, 2 x1=1x_1 = 1, x2=4x_2 = 4 row 2 L(1,1)=1/4L(1,1) = 1/4 U(1,1)=4U(1,1) = 4
2 2, 3 2, 1, 3 x2=2x_2 = 2, x1=0−14⋅2=−12x_1 = 0 - \tfrac14 \cdot 2 = -\tfrac12, x3=1x_3 = 1 row 3 L(1,2)=−12L(1,2) = -\tfrac12 U(1,2)=2U(1,2) = 2, U(2,2)=1U(2,2) = 1
3 3, 4 3, 1, 4 x3=1x_3 = 1, x1=0+12⋅1=12x_1 = 0 + \tfrac12 \cdot 1 = \tfrac12, x4=−1x_4 = -1 row 4 L(1,3)=−12L(1,3) = -\tfrac12 U(2,3)=1U(2,3) = 1, U(3,3)=−1U(3,3) = -1
4 1, 4 4, 1 x4=1x_4 = 1, x1=2+12⋅1=52x_1 = 2 + \tfrac12 \cdot 1 = \tfrac52 row 1 none U(3,4)=1U(3,4) = 1, U(4,4)=52U(4,4) = \tfrac52

In column 2 the search goes from row 2, which is pivot 1, along the edge to row 1, because L(1,1)≠0L(1, 1) \ne 0. Row 1 has a zero in A(:,2)A(:, 2), so L(1,2)L(1, 2) is a fill entry, found by the search before any arithmetic. In column 4 the search starts at rows 1 and 4, follows the edge from row 4 (pivot 3) to row 1, and never visits rows 2 and 3, because no path leads there. The pivot order is π=(2,3,4,1)\pi = (2, 3, 4, 1). The factorization does 3 multiply and subtract operations, and the four searches visit 10 nodes and traverse 3 edges. With b=(3,6,2,0)b = (3, 6, 2, 0) the solution is x=(1,1,1,1)x = (1, 1, 1, 1).

Correctness

The column solve of lines L3 to L6 is forward substitution with the columns of LL found so far, and it is correct when each pivotal row is visited before every row it updates. The search gives that order: along each edge of the graph of LL the pivot step grows, so the graph has no cycle, and the reverse postorder of a depth-first search of a graph with no cycle is a topological order. The rows where xx is structurally nonzero are exactly the rows reachable from the nonzeros of A(:,k)A(:, k), so the search misses no nonzero. The patterns of LL and UU equal those of symbolic Gaussian elimination on PAPA. The full proofs are in the correctness proof.

Proof: Gilbert-Peierls LU computes P A = L U, finds each column pattern by search, and runs in time proportional to arithmeticfull

We use the notation of the page. AA is n×nn \times n. After step k−1k - 1 the columns 1,…,k−11, \ldots, k - 1 of LL and UU exist, and π(j)\pi(j) is the row of AA chosen as pivot jj. A row ii is pivotal after step k−1k - 1 when i=π(j)i = \pi(j) for some j<kj < k. The graph GkG_k has the rows of AA as nodes and an edge π(j)→r\pi(j) \to r for each j<kj < k and each rr with L(r,j)≠0L(r, j) \ne 0. We count an entry as nonzero when it is stored, so all statements are about structural patterns: an entry is structurally nonzero when it is stored by the algorithm, even if its value cancels to zero.

Lemma 1 (the column solve). Let b=A(:,k)b = A(:, k). Lines L3 to L6 compute the vector xx with xπ(j)=U(j,k)x_{\pi(j)} = U(j, k) for j<kj < k and, for a row rr that is not pivotal, xr=br−∑j<kL(r,j) U(j,k)x_r = b_r - \sum_{j < k} L(r, j)\, U(j, k), provided that the rows are visited in an order where π(j)\pi(j) comes before every rr with L(r,j)≠0L(r, j) \ne 0.

Proof. This is forward substitution with the unit lower triangular matrix whose columns are L(:,1),…,L(:,k−1)L(:, 1), \ldots, L(:, k - 1), written column by column: when row π(j)\pi(j) is visited, xπ(j)x_{\pi(j)} already has all its updates, because each update to it comes from some π(j′)\pi(j') with L(π(j),j′)≠0L(\pi(j), j') \ne 0, and the visiting order puts π(j′)\pi(j') first. Line L6 then subtracts L(r,j) xπ(j)L(r, j)\, x_{\pi(j)} from every xrx_r. By induction over the visiting order, xπ(j)=bπ(j)−∑j′<jL(π(j),j′)xπ(j′)x_{\pi(j)} = b_{\pi(j)} - \sum_{j' < j} L(\pi(j), j') x_{\pi(j')}, which is the definition of U(j,k)U(j, k) in the factorization PA=LUPA = LU restricted to the first kk columns, and the non-pivotal rows hold the stated sums. □\square

Lemma 2 (the pattern is a reach set). Let BB be the set of nonzero rows of A(:,k)A(:, k). In exact structural terms, xr≠0x_r \ne 0 if and only if rr is reachable in GkG_k from some node of BB.

Proof. If r∈Br \in B, then xrx_r starts nonzero. If r∉Br \notin B, then xrx_r starts at zero and changes only at line L6, from some pivotal i=π(j)i = \pi(j) with L(r,j)≠0L(r, j) \ne 0 and xi≠0x_i \ne 0, that is, along an edge i→ri \to r of GkG_k from a node with xi≠0x_i \ne 0. By induction on the visiting order, every nonzero xrx_r is reachable from BB. Conversely, if rr is reachable from BB by the path s=i0→i1→⋯→it=rs = i_0 \to i_1 \to \cdots \to i_t = r, then each ximx_{i_m} receives a structural update from xim−1x_{i_{m-1}}, so by induction on mm each is structurally nonzero. □\square

Lemma 3 (the order is topological). The graph GkG_k has no cycle, and the reverse postorder of a depth-first search of GkG_k from BB visits π(j)\pi(j) before every rr with L(r,j)≠0L(r, j) \ne 0.

Proof. An edge π(j)→r\pi(j) \to r has L(r,j)≠0L(r, j) \ne 0, so rr is not pivotal at step jj: either rr never becomes pivotal before step kk, or r=π(j′)r = \pi(j') with j′>jj' > j. So along each edge the pivot step strictly grows, and a node that is not pivotal has no outgoing edge. There is no cycle. In a depth-first search of a graph with no cycle, each edge i→ri \to r has rr finished before ii; so ii comes before rr in the reverse postorder. This is the standard proof of topological sort by depth-first search. □\square

Theorem 1 (correctness). If every step finds a nonzero pivot, the algorithm returns a row order π\pi, a unit lower triangular LL and an upper triangular UU with PA=LUPA = LU, where row kk of PAPA is row π(k)\pi(k) of AA, and every multiplier has ∣L(r,k)∣≤1|L(r, k)| \le 1. If AA is nonsingular, in exact arithmetic every step finds a nonzero pivot.

Proof. By Lemmas 2 and 3 the rows of line L2 contain every row where xx is nonzero, in an order valid for Lemma 1. So line L8 sets U(j,k)=xπ(j)U(j, k) = x_{\pi(j)} for j<kj < k and U(k,k)=xpU(k, k) = x_p with p=π(k)p = \pi(k), and L(r,k)=xr/xpL(r, k) = x_r / x_p for the other non-pivotal rows. For a non-pivotal row rr, Lemma 1 gives A(r,k)=∑j<kL(r,j)U(j,k)+xr=∑j≤kL(r,j)U(j,k)A(r, k) = \sum_{j < k} L(r, j) U(j, k) + x_r = \sum_{j \le k} L(r, j) U(j, k), with L(p,k)=1L(p, k) = 1. For a pivotal row π(j)\pi(j) the same identity holds by the definition of U(j,k)U(j, k). Together these are column kk of PA=LUPA = LU. Line L7 takes the largest ∣xr∣|x_r|, so ∣L(r,k)∣≤1|L(r, k)| \le 1.

If all non-pivotal xrx_r are zero at step kk, then A(:,k)A(:, k) is a combination of the first k−1k - 1 columns of LL with coefficients U(1:k−1,k)U(1{:}k{-}1, k). The first k−1k - 1 columns of AA span the same space as these columns of LL, because the leading k−1k - 1 columns of UU form a nonsingular triangle. So the first kk columns of AA are dependent and AA is singular. □\square

Theorem 2 (time proportional to arithmetic). Let fkf_k be the number of multiply and subtract operations of line L6 in step kk, and f=∑kfkf = \sum_k f_k. The depth-first search of step kk visits at most ∣B∣+fk|B| + f_k nodes and traverses exactly fkf_k edges. The whole factorization runs in O(n+nnz(A)+f)O(n + \mathrm{nnz}(A) + f) time.

Proof. The search traverses each out-edge of each visited pivotal node once. The out-edges of π(j)\pi(j) are the nonzeros of L(:,j)L(:, j), and line L6 does one operation for each of them for each visited pivotal node, so the edge count equals fkf_k. Each visited node is either a start node in BB or is reached by a traversed edge, so the node count is at most ∣B∣+fk|B| + f_k. Lines L3, L7 and L8 cost O(1)O(1) per visited node, and the divisions are at most the visited nodes. With a mark array that is reset only for the visited nodes, nothing costs time proportional to nn inside a step. Summing over kk, ∑k∣B∣=nnz(A)\sum_k |B| = \mathrm{nnz}(A), which gives O(n+nnz(A)+f)O(n + \mathrm{nnz}(A) + f). □\square

The count ff is the same arithmetic that a column-oriented dense code would do with the same pivots if it skipped all zero operands. So the theorem says that the sparse overhead (the search and the bookkeeping) is never more than a constant times the useful arithmetic plus the size of the input.

Theorem 3 (the pattern equals symbolic elimination). The stored patterns of LL and UU are the patterns that symbolic Gaussian elimination without pivoting produces on PAPA, where symbolic elimination makes position (i,j)(i, j) nonzero when it is nonzero in PAPA or when (i,t)(i, t) and (t,j)(t, j) are nonzero for some t<min⁡(i,j)t < \min(i, j).

Proof. Renumber the rows by PP. Then Lemma 2 says that (i,k)(i, k) is in the pattern of column kk of L+UL + U if and only if (i,k)(i, k) is nonzero in PAPA or there is a t<kt < k with (i,t)(i, t) in the pattern of LL, t<it < i, and (t,k)(t, k) in the pattern of column kk of UU. This is the same recurrence as symbolic elimination, column by column, with the same base case. Both define the smallest set closed under the rule, so they agree. □\square

What is proved here is exact for exact arithmetic and for the structural patterns. In floating point the pivot choice of line L7 can differ from the exact one when two candidates have nearly equal size, and the stability of partial pivoting is the usual worst case bound 2n−12^{n-1} on the growth factor, which is rarely approached in practice; that last point is an empirical observation, not a theorem.

Complexity

Theorem. In step kk the search traverses exactly fkf_k edges and visits at most ∣B∣+fk|B| + f_k nodes, where fkf_k is the number of multiply and subtract operations of line L6 and ∣B∣|B| the number of nonzeros of A(:,k)A(:, k). The whole factorization takes O(n+nnz(A)+f)O(n + \mathrm{nnz}(A) + f) time, where f=∑kfkf = \sum_k f_k.

The proof is short: the out-edges of row π(j)\pi(j) are the nonzeros of L(:,j)L(:, j), and line L6 does one operation for each of them. This is the result of the title of the 1988 paper. Earlier sparse codes with partial pivoting either scanned a dense work vector of length nn per column, which costs Θ(n2)\Theta(n^2) in total even for a diagonal matrix, or needed a symbolic analysis that assumed a fixed pivot order. Space is O(n)O(n) for the work vector and the marks plus the storage of LL and UU.

The bound does not say that ff is small. ff depends on the column order and on the pivots. With a poor column order, ff grows fast: on the nodal matrices of k×kk \times k resistor grids in row-major order (a conductance of 1/101/10 S to ground at every node, floats, the code of this page), the measured counts are:

grid nn nnz(A)\mathrm{nnz}(A) ff nodes visited edges traversed
10×1010 \times 10 100 460 8769 1918 8769
20×2020 \times 20 400 1920 149739 15638 149739
30×3030 \times 30 900 4380 774909 53158 774909

The edge count equals ff, as the theorem says. For an n×nn \times n tridiagonal matrix the measured counts are f=n−1f = n - 1 and 3n−23n - 2 visited nodes, so the total work is linear. These are toy inputs, not benchmark results.

Properties

  • Exact patterns, no symbolic phase. The pattern of each column is found during the factorization, so partial pivoting can choose any row. No estimate of the fill is needed in advance.
  • Stable as partial pivoting. Every multiplier has ∣L(r,k)∣≤1|L(r, k)| \le 1, so the backward error bound is that of dense partial pivoting.
  • Column by column. Each step reads only the columns of LL already built and writes one new column of LL and of UU. Memory can grow as the factorization proceeds.
  • Good for very sparse matrices. Circuit matrices have few nonzeros per column and little fill after ordering, so the dense kernels of supernodal and multifrontal codes have little work to speed up. This method has no dense kernel and no overhead per column beyond the search.

Variants and improvements

  • Symmetric pruning. Eisenstat and Liu showed that edges of the graph of LL can be removed without changing the reach sets, once a symmetric pair L(r,j)≠0L(r, j) \ne 0 and U(j,r)≠0U(j, r) \ne 0 is found. This makes the searches faster. KLU uses it (Davis and Palamadai Natarajan 2010).
  • Threshold pivoting with a preferred diagonal. Accept the planned diagonal entry when ∣xdiag∣≥umax⁡∣xr∣|x_{\text{diag}}| \ge u \max |x_r|, which keeps the fill-reducing order. KLU does this with u=10−3u = 10^{-3} by default.
  • Refactorization. When only the values change, as in Newton iterations, keep π\pi and the patterns and repeat lines L3 to L8 without the search and without pivot choice.
  • Sparse right-hand side. The same search solves Lx=bLx = b for a sparse bb in time proportional to the arithmetic, which is useful for a few entries of A−1A^{-1} or for the adjoint solves of noise analysis.
  • Supernodes. SuperLU groups columns with the same pattern to use dense kernels; this pays off when fill is high, which is rare for circuits.

When to use it

Use it to factor sparse unsymmetric matrices with low fill after ordering, such as circuit matrices, when partial pivoting is needed for stability. Combine it with a fill-reducing column order and, for circuits, with the block triangular form of KLU. For matrices from 2D and 3D meshes, where the factors become dense, supernodal or multifrontal codes are faster. For symmetric positive definite matrices, use Cholesky with an elimination tree, which needs no pivoting.

Pitfalls

  • Scanning the work vector. Clearing or scanning a dense vector of length nn in each column brings back the Θ(n2)\Theta(n^2) term that the method avoids. Clear only the rows in XX.
  • Recursive search. A recursive depth-first search can overflow the stack on a long path in the graph of LL. Use an explicit stack, as the code of this page does.
  • Wrong visiting order. Visiting the rows of XX in index order instead of topological order uses values that are not final. The result is wrong without any error message.
  • No column order. The method does not reduce fill by itself. Without a fill-reducing column order, the arithmetic ff can be much larger than needed.
  • Structural versus numerical zeros. An entry that cancels to zero still lies in the pattern. A code that drops it changes the graph of LL, which is allowed, but it must then drop it consistently in the later searches.

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.

gilbert_peierls_lu.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gilbert-peierls-lu/. The authors are listed in prov/6ASGQ9.jsonl.
"""Gilbert-Peierls sparse LU factorization with partial pivoting.

The matrix is factored column by column. Column k of L and U comes from one
sparse triangular solve L x = A(:, k) with the columns of L found so far. The
nonzero pattern of x is found first, by a depth-first search in the graph of
L from the nonzero rows of A(:, k); the numerical solve then visits only
those rows, in a topological order given by the reverse postorder of the
search. The pivot of column k is the largest |x_i| over the rows i that are
not yet pivot rows.

Rows keep their original numbers inside the factorization. L(:, k) is a dict
{row of A: multiplier} without the unit diagonal; U(:, k) is a dict
{pivot step j: u_jk}, with u_kk the pivot. pivrow[k] is the row of A chosen
as pivot k, so (P A)[k] = A[pivrow[k]] and P A = L U.

An entry that cancels to zero is kept as a stored zero, so the patterns are
structural. The counters flops (multiply and subtract operations of the
triangular solves), divs, dfs_nodes and dfs_edges measure the work.
"""

from dataclasses import dataclass, field


class SingularMatrixError(ValueError):
    """Column k has no usable pivot."""


@dataclass
class Factor:
    n: int
    lcols: list = field(default_factory=list)
    ucols: list = field(default_factory=list)
    pivrow: list = field(default_factory=list)
    flops: int = 0
    divs: int = 0
    dfs_nodes: int = 0
    dfs_edges: int = 0
    reach_per_column: list = field(default_factory=list)


def columns_of(a):
    """Columns of a dense list-of-rows matrix as dicts {row: value} of the nonzeros."""
    n = len(a)
    return [{i: a[i][j] for i in range(n) if a[i][j] != 0} for j in range(n)]


def reach(f, pivstep, start):
    """Rows reachable from start in the graph of L, in topological order.

    The graph has an edge i -> r when row i is the pivot row of step j and
    L(r, j) is nonzero. Returns the reverse postorder of an iterative DFS.
    """
    mark, post = set(), []
    for s in start:  # @line R1
        if s in mark:
            continue
        mark.add(s)
        f.dfs_nodes += 1
        stack = [(s, iter(f.lcols[pivstep[s]]) if s in pivstep else iter(()))]
        while stack:
            i, it = stack[-1]
            for r in it:  # @line R2
                f.dfs_edges += 1
                if r not in mark:
                    mark.add(r)
                    f.dfs_nodes += 1
                    stack.append((r, iter(f.lcols[pivstep[r]]) if r in pivstep else iter(())))
                    break
            else:
                stack.pop()
                post.append(i)  # @line R3
    post.reverse()
    return post  # @line R4


def gp_lu(a, tol=0):
    """Factor the square matrix a (a list of rows, or a list of column dicts).

    tol is the magnitude at or below which a pivot counts as zero.
    """
    cols = a if a and isinstance(a[0], dict) else columns_of(a)
    n = len(cols)
    f = Factor(n)
    pivstep = {}  # row of A -> the step at which it became a pivot row
    for k in range(n):  # @line L1
        order = reach(f, pivstep, cols[k].keys())  # @line L2
        f.reach_per_column.append(len(order))
        x = {i: 0 for i in order}  # @line L3
        for i, v in cols[k].items():
            x[i] = v
        for i in order:  # @line L4
            if i in pivstep:  # @line L5
                xi = x[i]
                for r, l in f.lcols[pivstep[i]].items():  # @line L6
                    x[r] -= l * xi
                    f.flops += 1
        cand = [i for i in order if i not in pivstep]
        p = max(cand, key=lambda i: (abs(x[i]), -i), default=None)  # @line L7
        if p is None or abs(x[p]) <= tol:
            raise SingularMatrixError(f"no usable pivot in column {k}")
        piv = x[p]
        u = {pivstep[i]: x[i] for i in order if i in pivstep}  # @line L8
        u[k] = piv
        low = {}
        for i in cand:
            if i != p:
                low[i] = x[i] / piv
                f.divs += 1
        f.ucols.append(u)
        f.lcols.append(low)
        f.pivrow.append(p)
        pivstep[p] = k  # @line L9
    return f  # @line L10


def lu_solve(f, b):
    """Solve A x = b with the factors of gp_lu (column-oriented solves)."""
    n = f.n
    y = list(b)  # y holds P b in original row numbering, updated in place
    z = [None] * n
    for k in range(n):  # L z = P b: z_k sits in the pivot row of step k
        zk = y[f.pivrow[k]]
        z[k] = zk
        for r, l in f.lcols[k].items():
            y[r] = y[r] - l * zk
    x = [None] * n
    for k in range(n - 1, -1, -1):  # U x = z, column-oriented
        xk = z[k] / f.ucols[k][k]
        x[k] = xk
        for j, v in f.ucols[k].items():
            if j != k:
                z[j] = z[j] - v * xk
    return x


def gp_solve(a, b, tol=0):
    return lu_solve(gp_lu(a, tol), b)
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_gilbert_peierls_lu.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gilbert-peierls-lu/. The authors are listed in prov/6ASGQ9.jsonl.

import random
from fractions import Fraction as F

import pytest

from gilbert_peierls_lu import SingularMatrixError, gp_lu, gp_solve
from sim3dense import solve

EXAMPLE = [
    [F(1), F(0), F(0), F(2)],
    [F(4), F(2), F(0), F(0)],
    [F(0), F(1), F(1), F(0)],
    [F(0), F(0), F(-1), F(1)],
]


def random_matrix(rng, n, density, exact=True):
    while True:
        a = [[0] * n for _ in range(n)]
        for i in range(n):
            for j in range(n):
                if i == j or rng.random() < density:
                    v = rng.randint(-9, 9)
                    a[i][j] = F(v) if exact else float(v) + rng.random()
        try:
            solve([[F(x) for x in row] for row in a], [F(1)] * n)
            return a
        except ValueError:
            continue


def dense_factors(f):
    n = f.n
    pos = {r: k for k, r in enumerate(f.pivrow)}
    lo = [[F(int(i == j)) for j in range(n)] for i in range(n)]
    up = [[F(0)] * n for _ in range(n)]
    for k in range(n):
        for r, l in f.lcols[k].items():
            lo[pos[r]][k] = l
        for j, v in f.ucols[k].items():
            up[j][k] = v
    return lo, up


def symbolic_lu(pattern):
    """Brute force: dense symbolic elimination without pivoting; returns (L set, U set)."""
    n = len(pattern)
    m = [row[:] for row in pattern]
    for k in range(n):
        for i in range(k + 1, n):
            if m[i][k]:
                for j in range(k + 1, n):
                    if m[k][j]:
                        m[i][j] = True
    lset = {(i, k) for k in range(n) for i in range(k + 1, n) if m[i][k]}
    uset = {(k, j) for k in range(n) for j in range(k, n) if m[k][j]}
    return lset, uset


def test_example_trace():
    f = gp_lu(EXAMPLE)
    assert f.pivrow == [1, 2, 3, 0]
    assert f.lcols == [{0: F(1, 4)}, {0: F(-1, 2)}, {0: F(-1, 2)}, {}]
    assert f.ucols == [{0: F(4)}, {0: F(2), 1: F(1)}, {1: F(1), 2: F(-1)}, {2: F(1), 3: F(5, 2)}]
    assert f.reach_per_column == [2, 3, 3, 2]
    assert (f.flops, f.dfs_edges, f.dfs_nodes) == (3, 3, 10)
    b = [F(3), F(6), F(2), F(0)]
    assert gp_solve(EXAMPLE, b) == solve(EXAMPLE, b) == [F(1)] * 4


def test_exact_factors_patterns_and_work():
    rng = random.Random(21)
    for _ in range(200):
        n = rng.randint(1, 8)
        a = random_matrix(rng, n, rng.choice([0.15, 0.3, 0.6]))
        f = gp_lu(a)
        lo, up = dense_factors(f)
        pa = [a[r] for r in f.pivrow]
        assert [[sum(lo[i][t] * up[t][j] for t in range(n)) for j in range(n)] for i in range(n)] == pa
        lset, uset = symbolic_lu([[x != 0 for x in row] for row in pa])
        pos = {r: k for k, r in enumerate(f.pivrow)}
        assert {(pos[r], k) for k in range(n) for r in f.lcols[k]} == lset
        assert {(j, k) for k in range(n) for j in f.ucols[k]} == uset
        for k in range(n):
            for l in f.lcols[k].values():
                assert abs(l) <= 1
        nnz = sum(1 for row in a for x in row if x != 0)
        assert f.dfs_edges == f.flops
        assert f.dfs_nodes <= nnz + f.flops
        b = [F(rng.randint(-5, 5)) for _ in range(n)]
        assert gp_solve(a, b) == solve(a, b)


def test_float_matrices():
    rng = random.Random(22)
    for n in (20, 60):
        a = random_matrix(rng, n, 3 / n, exact=False)
        b = [rng.uniform(-1, 1) for _ in range(n)]
        x = gp_solve(a, b, tol=1e-14)
        r = max(abs(sum(a[i][j] * x[j] for j in range(n)) - b[i]) for i in range(n))
        assert r < 1e-9


def test_mna_zero_diagonal_needs_pivoting():
    # 6 V source at node 1, 2 ohm from 1 to 2, 3 ohm from 2 to ground, 1 A into node 2.
    # Unknowns (e1, e2, j); the source row has a zero diagonal.
    a = [[F(1, 2), F(-1, 2), F(1)], [F(-1, 2), F(5, 6), F(0)], [F(1), F(0), F(0)]]
    assert gp_solve(a, [F(0), F(1), F(6)]) == [F(6), F(24, 5), F(-3, 5)]


def test_work_is_linear_on_tridiagonal():
    for n in (500, 1000, 2000):
        a = [{} for _ in range(n)]
        for j in range(n):
            a[j][j] = 4.0
            if j > 0:
                a[j][j - 1] = -1.0
            if j + 1 < n:
                a[j][j + 1] = -1.0
        f = gp_lu(a)
        assert f.flops == n - 1
        assert f.dfs_edges == n - 1
        assert f.dfs_nodes == 3 * n - 2


def test_singular():
    with pytest.raises(SingularMatrixError):
        gp_lu([[F(1), F(2)], [F(2), F(4)]])
    with pytest.raises(SingularMatrixError):
        gp_lu([[F(1), F(0)], [F(1), F(0)]])

History

Gilbert and Peierls published the method in 1988, with the title result that sparse partial pivoting can run in time proportional to the arithmetic. Davis gave a compact implementation in the CSparse package and in his 2006 book. Davis and Palamadai Natarajan built KLU on it for circuit simulation, and KLU became the default sparse solver of the Xyce circuit simulator (Davis and Palamadai Natarajan 2010).

References

  1. 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 column algorithm, the reach of the column pattern by depth-first search, and the time bound
  2. Timothy A. Davis, Direct Methods for Sparse Linear Systems, SIAM, 2006, the chapter on solving triangular systems (the sparse triangular solve with a sparse right-hand side) and the chapter on LU factorization (the column method with partial pivoting)
  3. 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 use of the method on the diagonal blocks of circuit matrices and the symmetric pruning of Eisenstat and Liu
  4. Farid N. Najm, Circuit Simulation, Wiley-IEEE Press, 2010, Chapter 3, solution of linear algebraic circuit equations (LU factorization, pivoting and sparse matrices)

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.worst
  • 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