Techniquecore
Markowitz pivoting
Also called Markowitz criterion, Markowitz ordering.
Chooses as pivot the entry that minimizes (r - 1)(c - 1), with r and c its row and column counts, subject to a size threshold, to limit fill-in in sparse LU.
Markowitz pivoting is a rule for choosing the pivots of a sparse LU factorization. At each elimination step it takes, among the entries of the remaining submatrix that are large enough to be stable, the one with the least Markowitz count , where and are the numbers of nonzeros in its row and its column. The count is an upper bound on the fill-in that the step creates, so the rule is a greedy way to keep the factors sparse. It is a general method of sparse linear algebra, proposed by Markowitz in 1957 for linear programming, and this page frames it for the circuit simulation half of the logic and circuit simulation sub-area, where every Newton iteration of a simulator solves one modified nodal analysis system with it.
In plain words
To solve a system of equations by elimination, you pick one equation and one unknown, use that equation to remove the unknown from all the other equations, and repeat. When most coefficients are zero, as in a circuit, the order of these choices matters a lot. A bad choice spreads nonzero coefficients over many equations that had none, and the later work grows.
The rule counts, for a candidate coefficient, the other nonzeros in its equation and the other equations that hold its unknown. Their product is the most new nonzeros the step can create. The rule picks the candidate with the smallest product. It skips a candidate that is tiny compared with the other coefficients of its unknown, because dividing by a tiny number magnifies rounding errors.
When it applies
Use it to factor an unsymmetric sparse matrix when the pivot order is chosen during the numerical factorization, so that sparsity and numerical size are judged together. Circuit matrices fit this well: the MNA matrix of a transistor circuit is unsymmetric because of the transconductances, it has zero diagonal entries in the rows of voltage sources, and its values change from one Newton iteration to the next. For a symmetric positive definite matrix, such as the nodal matrix of a resistor network, no numerical pivoting is needed, and a symbolic order such as minimum degree is cheaper. When the same pattern is factored many times, a simulator chooses the pivots once with this rule and reuses the order, see Variations.
The template
Notation. At step the active submatrix is what remains of after eliminations, with the pivot rows and columns removed. In , is the number of nonzeros in row and the number in column . The threshold is a number with . An entry is acceptable when , the maximum taken over the active rows .
MARKOWITZ-LU(A, u)- 1
build the row and column patterns of A; all rows and columns are active - 2
for k ← 1 to n do - 3
for each active column j: m_j ← max over active rows t of |a_tj|; if m_j = 0 then return "singular" - 4
(p, q) ← the acceptable entry (|a_pq| ≥ u · m_q) with the least (r_p − 1)(c_q − 1) - 5
pivot k is (p, q); row k of U ← the active part of row p - 6
for each active row i ≠ p with a_iq ≠ 0 do - 7
l_ik ← a_iq / a_pq - 8
for each active column j ≠ q with a_pj ≠ 0 do - 9
a_ij ← a_ij − l_ik · a_pj ▷ if a_ij was 0, this is a fill entry - 10
deactivate row p and column q - 11
return the row order p_1, ..., p_n, the column order q_1, ..., q_n, L and U
The result satisfies , where puts row in place , puts column in place , is unit lower triangular with the multipliers , and is upper triangular. Ties at line L4 can go to the larger , and then to the lower index.
Theorem (the count bounds the fill of one step). If step pivots on , the number of entries of that are zero before the step and nonzero after it is at most . The step does exactly multiply and subtract operations and divisions.
Proof. Let , the other nonzero columns of the pivot row, so , and let , so . Line L7 runs once for each , which gives the divisions. Line L9 runs once for each pair , which gives the multiply and subtract operations. An entry with is not changed, because its row is not touched; and an entry with in a row is not changed, because line L9 runs only for . Row and column leave the active submatrix. So every entry that changes from zero to nonzero lies in , a set of positions.
The bound is reached when all positions of are zero before the step and no update cancels to zero. It is an upper bound because some of these positions can already be nonzero. With or the step creates no fill at all, so the rule first takes singleton rows and columns, which is exactly what a triangular part of the matrix needs.
Theorem (threshold and growth). With threshold , every multiplier has . If is the largest magnitude in , then , so all entries of are at most times the largest entry of .
Proof. The pivot is acceptable, so for every active row , and . Line L9 gives . Apply this times.
With only the largest entry of a column is acceptable, as in partial pivoting with a free choice of the column. A smaller admits more candidates and so gives sparser factors, at the price of a weaker bound on the growth factor. The bound is a worst case; in practice the growth is usually far smaller, which is a measured fact and not a theorem.
Worked example. A hub node joined by S to each of three leaf nodes, with S from each leaf to ground, has the nodal matrix below (hub first). Take .
| step | candidate | choice and effect | |
|---|---|---|---|
| 1 | hub diagonal | not chosen | |
| 1 | leaf diagonal | chosen; the update hits only , which is already nonzero: no fill | |
| 1 | entry | not acceptable: | |
| 2 | leaf diagonal | chosen; no fill | |
| 3 | leaf diagonal | chosen; no fill | |
| 4 | hub diagonal | chosen; its value is now |
The factors have no fill. In the natural order, the first step pivots on the hub, and its update writes all 6 off-diagonal positions of the leaf block, which were zero. With A injected into the hub, both orders give the hub voltage V and the leaf voltages V. The same contrast holds for a hub with leaves: Markowitz gives no fill and the natural order gives fill entries.
On larger circuit-like matrices the rule does not reach zero fill, and the gain is a measured one. On the nodal matrices of square resistor grids with a conductance to ground at every node (row-major numbering, , exact arithmetic, the code of this page), the measured fill is:
| grid | unknowns | nonzeros of | fill, natural order | fill, Markowitz |
|---|---|---|---|---|
| 25 | 105 | 128 | 82 | |
| 36 | 156 | 250 | 142 | |
| 64 | 288 | 686 | 346 |
These are toy inputs, not benchmark results.
Cost. The arithmetic of step is operations by the theorem, so the total arithmetic is the sum of the chosen counts plus the divisions. The search of lines L3 and L4 is the expensive part when it is done as written: it looks at every active entry, which costs per step and up to in total on a matrix that fills in. Practical codes keep the rows and the columns in lists by their counts and look only at a few rows and columns of least count, which makes the search cheap in practice but no longer guarantees the least count. Finding an order with the least total fill is NP-hard already for symmetric matrices with diagonal pivots (Yannakakis 1981), so the greedy rule has no guarantee of optimal fill, and none is known for any fixed ratio.
Classic examples
- SPICE and its descendants. Kundert's Sparse package, the solver of Berkeley SPICE3, factors the MNA matrix with Markowitz pivoting and a relative threshold. It chooses the order at the first factorization and reuses it in the later Newton iterations until a pivot becomes too small.
- Linear programming. Markowitz introduced the rule to keep the elimination form of the basis inverse sparse in the simplex method, which is still where it is used most in optimization codes.
- Power network equations. Tinney and Walker (1967) ordered the nodal equations of power systems by fewest connections. For a symmetric matrix with diagonal pivots the Markowitz count of the diagonal entry of a node of degree is , so the rule becomes minimum degree.
- Unsymmetric multifrontal and supernodal codes. They choose pivots inside dense frontal matrices with a threshold test and Markowitz-like counts, see multifrontal method.
Markowitz described the rule in 1957 in a paper on the elimination form of the inverse for linear programming, and Tinney and Walker (1967) used related orders for the nodal equations of power networks. Threshold pivoting, the Markowitz count together with a relative size test, is the form that Duff, Erisman and Reid present as standard. Kundert's Sparse package brought it to Berkeley SPICE3. Later circuit solvers such as KLU replaced the run-time search by a symbolic order and a column pivot test.
Variations
- Symbolic order, then numerical check. Order the pattern once, for example by minimum degree on the pattern of , and during the factorization accept the planned diagonal pivot when it passes the threshold, else pivot inside its column. This is the approach of KLU with Gilbert-Peierls LU, which does no Markowitz search at run time.
- Reuse of the order. In a transient simulation the pattern never changes and the values change slowly. The simulator keeps the pivot sequence and repeats only the arithmetic, and it falls back to a new Markowitz search when a reused pivot fails the threshold.
- Restricted search. Search only the rows and the columns with the fewest nonzeros. Duff, Erisman and Reid discuss searches limited to a few rows and columns of least count, which in their reported experience give orders close to those of the full search.
- Rook and complete pivoting. Complete pivoting takes the largest entry of the whole active matrix and ignores sparsity. Threshold rook pivoting asks that the pivot pass the threshold in its row and in its column.
- Local minimum fill. Count the exact fill of each candidate instead of the bound. This costs more and gives slightly better orders on some matrices; it is still greedy.
Pitfalls
- Using the counts of the original matrix. The counts must be those of the active submatrix at each step. Counts from alone give a static order that ignores the fill created so far.
- Forgetting the threshold. The least count alone can pick a tiny pivot, and the factors then have huge entries and large rounding error. In a circuit this happens with a small conductance next to a large one, or with a gmin conductance of S.
- A zero diagonal is not a zero pivot. The row of a voltage source has a zero diagonal in MNA, but the matrix is usually nonsingular. The rule handles it by choosing an off-diagonal pivot; a code that only looks at diagonal entries fails.
- Cancellation. The count bounds the structural fill. An update can cancel to an exact zero; a code that stores it keeps a structural nonzero, and a code that drops it must update the counts. The code of this page keeps it.
- Reusing an order after the values change. A pivot that passed the threshold in one Newton iteration can fail it in the next. Check the threshold during the refactorization, not only at the first factorization.
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
# Part of https://algorithm.tamnd.com/markowitz-pivoting/. The authors are listed in prov/RPNJK6.jsonl.
"""Sparse LU factorization with Markowitz pivoting and a threshold test.
The input is a square matrix as a list of rows; a zero entry is a structural
zero. Entries are Fraction (exact) or float. At each step the pivot is the
active entry a_ij that passes the threshold test |a_ij| >= u * max_k |a_kj|
(the largest entry of its active column) and has the least Markowitz count
(r_i - 1)(c_j - 1), where r_i and c_j count the nonzeros of row i and column
j in the active submatrix. Ties go to the larger |a_ij|, then to the smaller
row and column index.
An entry that becomes zero by cancellation is kept as a stored zero, so the
pattern of the factors is the structural pattern and the fill counts are
structural counts.
markowitz_lu returns a Factor with:
- prow[k], pcol[k]: the row and the column of A that hold pivot k, so
P A Q = L U with (P A Q)[k][m] = A[prow[k]][pcol[m]];
- lower[k]: a dict {i: l_ik} over the rows i of A eliminated later (unit
diagonal not stored);
- upper[k]: a dict {j: u_kj} over the columns j of A, including the pivot;
- steps[k]: (count, fill) of step k, the Markowitz count of the chosen pivot
and the number of new nonzeros that step created.
"""
from dataclasses import dataclass, field
class SingularMatrixError(ValueError):
"""An active column has no nonzero entry, so A is singular."""
@dataclass
class Factor:
n: int
prow: list = field(default_factory=list)
pcol: list = field(default_factory=list)
lower: list = field(default_factory=list)
upper: list = field(default_factory=list)
steps: list = field(default_factory=list)
@property
def fill(self):
return sum(f for _, f in self.steps)
def markowitz_lu(a, u=1, tol=0):
"""Factor the square matrix a (a list of rows) with Markowitz pivoting.
u is the threshold, 0 < u <= 1. tol is the magnitude at or below which a
column maximum counts as zero (0 for exact Fraction input).
"""
n = len(a)
rows = {i: {j: v for j, v in enumerate(a[i]) if v != 0} for i in range(n)} # @line L1
cols = {j: set() for j in range(n)}
for i, r in rows.items():
for j in r:
cols[j].add(i)
f = Factor(n)
for _ in range(n): # @line L2
best = None
for j, cj in cols.items(): # @line L3
m = max((abs(rows[i][j]) for i in cj), default=0)
if m <= tol:
raise SingularMatrixError(f"column {j} has no usable pivot")
for i in cj: # @line L4
v = rows[i][j]
if abs(v) >= u * m:
key = ((len(rows[i]) - 1) * (len(cj) - 1), -abs(v), i, j)
if best is None or key < best:
best = key
count, _, p, q = best
piv = rows[p][q]
prow = rows.pop(p) # @line L5
f.prow.append(p)
f.pcol.append(q)
f.upper.append(dict(prow))
low, made = {}, 0
for i in cols[q] - {p}: # @line L6
ri = rows[i]
l = ri.pop(q) / piv # @line L7
low[i] = l
for j, v in prow.items(): # @line L8
if j == q:
continue
if j in ri:
ri[j] -= l * v # @line L9
else:
ri[j] = -l * v
cols[j].add(i)
made += 1
for j in prow: # @line L10
cols[j].discard(p)
del cols[q]
f.lower.append(low)
f.steps.append((count, made))
return f # @line L11
def lu_solve(f, b):
"""Solve A x = b with the factors of markowitz_lu."""
n = f.n
pos = {r: k for k, r in enumerate(f.prow)}
y = [None] * n
for k in range(n): # forward: L y = P b, column by column
s = b[f.prow[k]] if y[k] is None else b[f.prow[k]] - y[k]
y[k] = s
for i, l in f.lower[k].items():
m = pos[i]
y[m] = (0 if y[m] is None else y[m]) + l * s
x = [0] * n
for k in range(n - 1, -1, -1): # backward: U z = y, x = Q z
s = y[k]
for j, v in f.upper[k].items():
if j != f.pcol[k]:
s -= v * x[j]
x[f.pcol[k]] = s / f.upper[k][f.pcol[k]]
return x
def markowitz_solve(a, b, u=1, tol=0):
return lu_solve(markowitz_lu(a, u, 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_markowitz_pivoting.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/markowitz-pivoting/. The authors are listed in prov/RPNJK6.jsonl.
import random
from fractions import Fraction as F
import pytest
from markowitz_pivoting import SingularMatrixError, markowitz_lu, markowitz_solve
from sim3dense import solve
def star(leaves):
"""Grounded conductance matrix of a hub node 0 joined by 1 S to each leaf, each leaf 1 S to ground."""
n = leaves + 1
a = [[F(0)] * n for _ in range(n)]
a[0][0] = F(leaves)
for k in range(1, n):
a[0][k] = a[k][0] = F(-1)
a[k][k] = F(2)
return a
def symbolic_fill(pattern, order):
"""Brute force: dense symbolic elimination along the pivot order; returns fill per step."""
n = len(pattern)
s = [row[:] for row in pattern]
done_r, done_c, out = set(), set(), []
for p, q in order:
rs = [i for i in range(n) if i not in done_r and i != p and s[i][q]]
cs = [j for j in range(n) if j not in done_c and j != q and s[p][j]]
made = 0
for i in rs:
for j in cs:
if not s[i][j]:
s[i][j] = True
made += 1
done_r.add(p)
done_c.add(q)
out.append(made)
return out
def reconstruct(f):
n = f.n
pos = {r: k for k, r in enumerate(f.prow)}
lo = [[F(0)] * n for _ in range(n)]
up = [[F(0)] * n for _ in range(n)]
cpos = {c: k for k, c in enumerate(f.pcol)}
for k in range(n):
lo[k][k] = F(1)
for i, l in f.lower[k].items():
lo[pos[i]][k] = l
for j, v in f.upper[k].items():
up[k][cpos[j]] = v
return [[sum(lo[i][t] * up[t][j] for t in range(n)) for j in range(n)] for i in range(n)]
def random_sparse(rng, n, density):
while True:
a = [[F(rng.randint(-9, 9)) if rng.random() < density else F(0) for _ in range(n)] for _ in range(n)]
try:
solve(a, [F(1)] * n)
return a
except ValueError:
continue
def test_star_example():
a = star(3)
f = markowitz_lu(a)
assert f.fill == 0
assert [c for c, _ in f.steps] == [1, 1, 1, 0]
pattern = [[x != 0 for x in row] for row in a]
assert sum(symbolic_fill(pattern, [(k, k) for k in range(4)])) == 6
x = markowitz_solve(a, [F(1), F(0), F(0), F(0)])
assert x == solve(a, [F(1), F(0), F(0), F(0)]) == [F(2, 3), F(1, 3), F(1, 3), F(1, 3)]
def test_factors_exact_and_fill_bound():
rng = random.Random(11)
for _ in range(150):
n = rng.randint(1, 7)
a = random_sparse(rng, n, rng.choice([0.3, 0.5, 0.8]))
for u in (F(1), F(1, 10)):
f = markowitz_lu(a, u)
pa = [[a[f.prow[i]][f.pcol[j]] for j in range(n)] for i in range(n)]
assert reconstruct(f) == pa
for count, made in f.steps:
assert made <= count
pattern = [[x != 0 for x in row] for row in a]
assert symbolic_fill(pattern, list(zip(f.prow, f.pcol))) == [m for _, m in f.steps]
for low in f.lower:
for l in low.values():
assert abs(l) <= 1 / u
b = [F(rng.randint(-5, 5)) for _ in range(n)]
assert markowitz_solve(a, b, u) == solve(a, b)
def test_pivot_has_least_count():
rng = random.Random(12)
for _ in range(80):
n = rng.randint(2, 6)
a = random_sparse(rng, n, 0.5)
u = F(1, 4)
f = markowitz_lu(a, u)
m = [row[:] for row in a]
pat = [[x != 0 for x in row] for row in a]
act_r, act_c = set(range(n)), set(range(n))
for k in range(n):
best = None
for j in act_c:
mx = max(abs(m[i][j]) for i in act_r if pat[i][j])
for i in act_r:
if pat[i][j] and abs(m[i][j]) >= u * mx:
r = sum(1 for c in act_c if pat[i][c])
c = sum(1 for t in act_r if pat[t][j])
best = min(best, (r - 1) * (c - 1)) if best is not None else (r - 1) * (c - 1)
p, q = f.prow[k], f.pcol[k]
assert f.steps[k][0] == best
for i in act_r - {p}:
if pat[i][q]:
l = m[i][q] / m[p][q]
for j in act_c:
if pat[p][j]:
m[i][j] -= l * m[p][j]
pat[i][j] = True
act_r.discard(p)
act_c.discard(q)
def test_mna_matrix_with_zero_diagonal():
# 6 V source at node 1, 2 ohm from 1 to 2, 3 ohm from 2 to ground, 1 A into node 2.
a = [[F(1, 2), F(-1, 2), F(1)], [F(-1, 2), F(5, 6), F(0)], [F(1), F(0), F(0)]]
b = [F(0), F(1), F(6)]
assert markowitz_solve(a, b) == [F(6), F(24, 5), F(-3, 5)]
def test_singular():
with pytest.raises(SingularMatrixError):
markowitz_lu([[F(1), F(2)], [F(2), F(4)]])
with pytest.raises(SingularMatrixError):
markowitz_lu([[F(1), F(0)], [F(1), F(0)]])
def test_float_ladder():
rng = random.Random(13)
n = 30
a = [[0.0] * n for _ in range(n)]
for i in range(n):
g = rng.uniform(0.5, 2.0)
a[i][i] += g
if i + 1 < n:
h = rng.uniform(0.5, 2.0)
a[i][i] += h
a[i + 1][i + 1] += h
a[i][i + 1] -= h
a[i + 1][i] -= h
b = [rng.uniform(-1, 1) for _ in range(n)]
f = markowitz_lu(a, 0.1)
assert f.fill == 0
x = markowitz_solve(a, b, 0.1)
y = solve(a, b)
assert max(abs(p - q) for p, q in zip(x, y)) < 1e-12
Exercises
- Show that a matrix whose pattern is upper triangular after a row and column permutation is factored by Markowitz pivoting with no fill, for every threshold for which the diagonal entries pass the test.
- For the arrow matrix with a full first row and column and a nonzero diagonal, of order , count the fill of the natural order and of the reverse order. (Answer: and 0.)
- Give a matrix where the entry of least Markowitz count fails the threshold , and find the pivot that the rule takes instead.
- Prove that for a symmetric pattern with diagonal pivots, the fill of eliminating a node of degree is at most entries, that is symmetric pairs, and compare with the Markowitz count .
- Find a matrix on which the greedy rule gives more total fill than the best order.
References
- Harry M. Markowitz, The elimination form of the inverse and its application to linear programming, Management Science 3(3), 255 to 269, 1957, the pivot rule that takes the nonzero with the least product (r - 1)(c - 1) of the other entries in its row and column
- Iain S. Duff, Albert M. Erisman and John K. Reid, Direct Methods for Sparse Matrices, second edition, Oxford University Press, 2017, Chapter 7, local pivotal strategies for sparse matrices (the Markowitz count, threshold pivoting and its stability bound, and the search for the pivot)
- Kenneth S. Kundert, Sparse matrix techniques, in A. E. Ruehli (editor), Circuit Analysis, Simulation and Design, North-Holland, 1986, the chapter on sparse LU for circuit matrices, with Markowitz pivoting, the threshold test and the data structures of the Sparse package
- Farid N. Najm, Circuit Simulation, Wiley-IEEE Press, 2010, Chapter 3, solution of linear algebraic circuit equations (Gaussian elimination, sparse matrices, fill-in and pivot ordering)
- Mihalis Yannakakis, Computing the minimum fill-in is NP-complete, SIAM Journal on Algebraic and Discrete Methods 2(1), 77 to 79, 1981, the NP-completeness of minimum fill for symmetric elimination
- William F. Tinney and John W. Walker, Direct solutions of sparse network equations by optimally ordered triangular factorization, Proceedings of the IEEE 55(11), 1801 to 1809, 1967, the ordering schemes for sparse network matrices, among them the scheme that takes the node with the fewest connections
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 | W3 standard |
|
Tag RPNJK6 Edit this page History Report an error Markdown