---
title: "Lab: elimination and LU in code"
heading: Writing the solver that circuit simulators are built on
eyebrow: A7 · Lesson 13 · Lab: elimination and LU in code
xp: 60
---

::: hook
`np.linalg.solve` hides a few dozen lines of code that every circuit simulator, finite-element program and control design tool depends on. In this lab you'll write those lines yourself: elimination with row exchanges, the LU factorization, and forward and back substitution. Then you'll use them the way simulators do, factoring once and solving for many source values, and finally solve a twenty-node ladder whose voltages fall by the same ratio at every node.
:::

::: play
- The curves count multiply-adds for solving an $n$-node circuit with $k$ different right-hand sides.
- The upper curve factors from scratch each time: $k\left(\frac{n^3}{3} + n^2\right)$. The lower one factors once and reuses $L$ and $U$: $\frac{n^3}{3} + kn^2$.
- Raise $n$. The gap widens, because factoring grows like $n^3$ and each extra solve only like $n^2$.
:::

```sim plot
view: graph
x: k = 1..1000
y: ops = 1e3..1e12 log
slider: n = 10..1000 step 10 = 500
plot: k*(n^3/3 + n^2) | label: factor every time
plot: n^3/3 + k*n^2 | color: ch2 | label: factor once
readout: speedup for 1000 solves = 1000*(n^3/3 + n^2)/(n^3/3 + 1000*n^2) | digits: 3
```

::: predict
## A 500-node circuit must be solved for 1000 different source values. How much faster is factoring once than factoring every time?

- [ ] About 2 times
- [ ] About 10 times
- [x] About 140 times
- [ ] About 1000 times

::: reveal
About 140 times. Factoring costs $\frac{500^3}{3} = 4.2 \times 10^7$ multiply-adds, and each solve with the factors costs $500^2 = 2.5 \times 10^5$. Every time: $1000 \times 4.19 \times 10^7 = 4.2 \times 10^{10}$. Once: $4.2 \times 10^7 + 2.5 \times 10^8 = 2.9 \times 10^8$. A frequency sweep or a transient run reuses the factors the same way whenever the matrix doesn't change.
:::
:::

::: nameit
## Elimination with partial pivoting

For each column $k$:
1. find the row at or below $k$ with the largest $|a_{ik}|$, and swap it into row $k$;
2. for each row $i$ below, subtract $\ell_{ik} = a_{ik}/a_{kk}$ times row $k$.

Choosing the largest pivot keeps every multiplier at most 1 in size, which stops rounding errors from being magnified. Without it, a tiny pivot can wreck an answer even when the matrix is well conditioned.

## LU and substitution

Storing the multipliers in a unit lower-triangular $L$ gives $A = LU$ (or $PA = LU$ with row exchanges). Then $A\mathbf{x} = \mathbf{b}$ is two triangular solves:
- **forward:** $L\mathbf{y} = \mathbf{b}$, top to bottom, $y_i = b_i - \sum_{j<i}\ell_{ij}y_j$;
- **back:** $U\mathbf{x} = \mathbf{y}$, bottom to top, $x_i = \left(y_i - \sum_{j>i}u_{ij}x_j\right)/u_{ii}$.

## Cost

Factoring an $n \times n$ matrix takes about $\frac{n^3}{3}$ multiply-adds; each pair of triangular solves takes about $n^2$. A banded matrix, like a ladder's tridiagonal one, needs only about $n$ of each, which is why simulators exploit sparsity.
:::

::: example
## How long does factoring a 1000 × 1000 matrix take, and each solve after it?

::: solution
1. **Count the work.** Factoring takes
   $$\frac{1000^3}{3} = 3.3 \times 10^8$$
   multiply-adds, and each solve $1000^2 = 10^6$.
2. **Convert to time.** At a billion multiply-adds a second (a modest rate for a laptop core running plain loops in a compiled language), that's about 0.3 s to factor and 1 ms per solve.
3. **In pure Python.** Pure Python loops run about 100 times slower, which is why NumPy hands the work to compiled LAPACK routines.

**Answer:** about 0.3 s to factor and 1 ms for each solve, at a billion multiply-adds a second.
:::
:::

::: example
## Solve $\begin{bmatrix}10^{-20} & 1\\1 & 1\end{bmatrix}\mathbf{x} = \begin{bmatrix}1\\2\end{bmatrix}$ in double precision, without and with pivoting.

::: solution
1. **The true answer.** It is very close to $(1, 1)$.
2. **Eliminate without pivoting.** The multiplier is $10^{20}$, $u_{22} = 1 - 10^{20}$ rounds to $-10^{20}$, and the right side becomes $2 - 10^{20} \approx -10^{20}$.
3. **Back-substitute.**
   $$x_2 = 1$$
   $$\begin{aligned} x_1 &= \frac{1 - 1}{10^{-20}} \\ &= 0 \end{aligned}$$
   completely wrong.
4. **With pivoting.** The rows swap so the pivot is 1, the multiplier is $10^{-20}$, and the answer comes out $(1, 1)$ to full precision.
5. **Where the fault lies.** The matrix is perfectly well conditioned; only the unpivoted algorithm was unstable.

**Answer:** without pivoting the answer comes out $(0, 1)$, completely wrong; with pivoting it's $(1, 1)$ to full precision.
:::
:::

::: check
given: n = 100 | 300 | 3000
answer: n^3/3
tolerance: 1%

## About how many multiply-adds does factoring an {n} × {n} matrix take?

::: right
Right. About $\frac{n^3}{3}$ = {answer}.
:::

::: misses
- [n^2] That's one pair of triangular solves after the factoring.
- [n^3] Elimination works on a shrinking corner of the matrix, which brings in the factor $\frac13$.
- [any] Not yet. The cost of LU is about $\frac{n^3}{3}$.
:::
:::

::: check
given: n = 100 | 1000; k = 10 | 100
answer: k*(n^3/3 + n^2)/(n^3/3 + k*n^2)
tolerance: 1%

## An {n}-node circuit is solved for {k} source values. How many times faster is factoring once than factoring each time?

::: right
Right. $\frac{k(n^3/3 + n^2)}{n^3/3 + kn^2}$ = {answer}.
:::

::: misses
- [k] That ignores the cost of the solves, which grows with $k$ too.
- [any] Not yet. Compare $k\left(\frac{n^3}{3} + n^2\right)$ with $\frac{n^3}{3} + kn^2$.
:::
:::

::: check
kind: python

## Write `gauss_solve(A, b)`: Gaussian elimination with partial pivoting, then back substitution. Don't call `np.linalg`. Set `x = gauss_solve(A, b)` for the system with the $10^{-20}$ pivot.

```python starter
import numpy as np

def gauss_solve(A, b):
    A = np.array(A, dtype=float)
    b = np.array(b, dtype=float)
    return b / np.diag(A)

A = [[1e-20, 1], [1, 1]]
b = [1, 2]
x = gauss_solve(A, b)
print(x)
```

```python solution
import numpy as np

def gauss_solve(A, b):
    A = np.array(A, dtype=float)
    b = np.array(b, dtype=float)
    n = len(b)
    for k in range(n):
        p = k + np.argmax(np.abs(A[k:, k]))
        A[[k, p]] = A[[p, k]]
        b[[k, p]] = b[[p, k]]
        for i in range(k + 1, n):
            m = A[i, k] / A[k, k]
            A[i, k:] -= m * A[k, k:]
            b[i] -= m * b[k]
    x = np.zeros(n)
    for i in range(n - 1, -1, -1):
        x[i] = (b[i] - A[i, i + 1:] @ x[i + 1:]) / A[i, i]
    return x

A = [[1e-20, 1], [1, 1]]
b = [1, 2]
x = gauss_solve(A, b)
print(x)
```

```python tests
import numpy as np
assert np.allclose(x, [1, 1]), f"With pivoting, the tiny-pivot system gives (1, 1); got {x}."
assert np.allclose(gauss_solve([[0, 2], [3, 1]], [4, 5]), [1, 2]), "A zero first pivot needs a row exchange: (x, y) = (1, 2)."
rng = np.random.default_rng(7)
M = rng.normal(size=(6, 6)); r = rng.normal(size=6)
assert np.allclose(gauss_solve(M, r), np.linalg.solve(M, r)), "On a random 6 x 6 system it should match np.linalg.solve."
```

::: right
Right. Choosing the largest pivot in each column is all it takes to make elimination reliable on any nonsingular matrix.
:::
:::

::: check
kind: python

## Write `lu(A)` returning `L` and `U` with no row exchanges (assume the pivots are nonzero). Factor the matrix from lesson 9.

```python starter
import numpy as np

def lu(A):
    A = np.array(A, dtype=float)
    return np.eye(len(A)), A

L, U = lu([[2, 1, 1], [4, 3, 3], [8, 7, 9]])
print(L, U, sep="\n")
```

```python solution
import numpy as np

def lu(A):
    U = np.array(A, dtype=float)
    n = len(U)
    L = np.eye(n)
    for k in range(n):
        for i in range(k + 1, n):
            L[i, k] = U[i, k] / U[k, k]
            U[i, k:] -= L[i, k] * U[k, k:]
    return L, U

L, U = lu([[2, 1, 1], [4, 3, 3], [8, 7, 9]])
print(L, U, sep="\n")
```

```python tests
import numpy as np
A = np.array([[2, 1, 1], [4, 3, 3], [8, 7, 9]], dtype=float)
assert np.allclose(L @ U, A), "L @ U should rebuild A."
assert np.allclose(L, [[1, 0, 0], [2, 1, 0], [4, 3, 1]]), f"L holds the multipliers 2, 4 and 3; got {L}."
assert np.allclose(U, np.triu(U)) and np.allclose(np.diag(U), [2, 1, 2]), "U is upper triangular with pivots 2, 1, 2."
```

::: right
Right. $L$ records the elimination and $U$ is its result: nothing is thrown away.
:::
:::

::: check
kind: python

## Write `lu_solve(L, U, b)` by forward and back substitution. Factor the ladder $G = \begin{bmatrix}2 & -1 & 0\\-1 & 2 & -1\\0 & -1 & 2\end{bmatrix}$ mS once with your `lu` (in the starter), then set `volts` to node 3's voltage for currents of 1, 2, 3, 4 and 5 mA into node 1.

```python starter
import numpy as np

def lu(A):
    U = np.array(A, dtype=float)
    n = len(U)
    L = np.eye(n)
    for k in range(n):
        for i in range(k + 1, n):
            L[i, k] = U[i, k] / U[k, k]
            U[i, k:] -= L[i, k] * U[k, k:]
    return L, U

def lu_solve(L, U, b):
    return np.zeros(len(b))

G = [[2, -1, 0], [-1, 2, -1], [0, -1, 2]]
volts = []
print(volts)
```

```python solution
import numpy as np

def lu(A):
    U = np.array(A, dtype=float)
    n = len(U)
    L = np.eye(n)
    for k in range(n):
        for i in range(k + 1, n):
            L[i, k] = U[i, k] / U[k, k]
            U[i, k:] -= L[i, k] * U[k, k:]
    return L, U

def lu_solve(L, U, b):
    n = len(b)
    y = np.zeros(n)
    for i in range(n):
        y[i] = b[i] - L[i, :i] @ y[:i]
    x = np.zeros(n)
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - U[i, i + 1:] @ x[i + 1:]) / U[i, i]
    return x

G = [[2, -1, 0], [-1, 2, -1], [0, -1, 2]]
L, U = lu(G)
volts = [lu_solve(L, U, np.array([s, 0, 0]))[2] for s in (1, 2, 3, 4, 5)]
print(volts)
```

```python tests
import numpy as np
assert len(volts) == 5 and np.allclose(volts, [0.25, 0.5, 0.75, 1.0, 1.25]), f"Node 3 sits at a quarter volt per milliamp; got {volts}."
L, U = lu([[4, 3], [6, 3]])
assert np.allclose(lu_solve(L, U, np.array([10.0, 12.0])), [1, 2]), "lu_solve should solve [[4, 3], [6, 3]] x = (10, 12) as (1, 2)."
```

::: right
Right. One factoring, five cheap solves, and the answers scale with the source exactly as linearity says.
:::
:::

::: check
kind: python
given: n = 20 | 30 | 40

## Build the conductance matrix of an $n$-node ladder, $n$ = {n}: 1 mS between neighboring nodes and 1 mS from every node to ground, so interior diagonal entries are 3 and the two end ones are 2. Inject 1 mA at node 1, solve, and set `ratio` to $v_{n/2 + 1}/v_{n/2}$ (with nodes counted from 1).

```python starter
import numpy as np

v = np.ones(n)
ratio = 1.0
print(ratio)
```

```python solution
import numpy as np

G = 3 * np.eye(n) - np.eye(n, k=1) - np.eye(n, k=-1)
G[0, 0] = G[-1, -1] = 2
i = np.zeros(n)
i[0] = 1
v = np.linalg.solve(G, i)
ratio = v[n // 2] / v[n // 2 - 1]
print(ratio)
```

```python tests
import math
import numpy as np
assert abs(ratio - (3 - math.sqrt(5)) / 2) < 1e-6, f"Deep in a long ladder each node sits at 0.381966 of the one before; got {ratio}."
assert abs(v[0] - 0.618034) < 1e-5, f"Node 1 sits at about 0.618 V for 1 mA; got {v[0]}."
```

::: right
Right. The ratio $r$ satisfies $r + \frac1r = 3$, so $r = \frac{3 - \sqrt5}{2}$: the reciprocal of the golden ratio squared.
:::
:::

::: explain
## A circuit simulator runs a transient analysis of a linear circuit with a fixed time step. Why does it factor the matrix once instead of solving from scratch at every step?

::: model
With a fixed step and fixed parts, the matrix in each step's equations is the same; only the right-hand side changes, as sources and the stored charges and currents of capacitors and inductors evolve. Factoring costs about $\frac{n^3}{3}$ operations and each solve with the factors about $n^2$, so for a circuit of a few hundred nodes run for thousands of steps, factoring once is a hundred or more times faster. When the step size changes or a nonlinear part's operating point moves, the matrix changes and must be refactored, which is why simulators try to keep the step constant and reuse factors whenever they can.
:::
:::

::: practice

::: check
given: n = 10..10000
answer: n^3/3
tolerance: 1%

## Multiply-adds to factor an {n} × {n} matrix?

::: misses
- [any] About $\frac{n^3}{3}$.
:::
:::

::: check
given: n = 10..1000; k = 1..1000
answer: k*(n^3/3 + n^2)/(n^3/3 + k*n^2)
tolerance: 1%

## Speedup from factoring once, {n} nodes and {k} solves?

::: misses
- [any] $\frac{k(n^3/3 + n^2)}{n^3/3 + kn^2}$.
:::
:::
:::
