---
title: Nodal solver lab
heading: Build a circuit solver in NumPy from a netlist
eyebrow: C1 · Lesson 25 · Nodal solver lab
xp: 50
---

::: hook
Every circuit simulator, from SPICE to the sims in this course, does what you did by hand in lesson 9: write KCL at every node and solve the linear equations. The difference is that it builds the equations automatically from a list of parts. Each resistor adds the same small pattern of four numbers to a matrix, a "stamp", wherever its two nodes are. In this lab you'll write that stamping loop, handle current sources and then voltage sources, and use the solver to find a resistance that no series-parallel trick can.
:::

::: play
- A divider driving a load from a 12 V source, solved by the course's own circuit engine, which builds and solves exactly the matrix you'll build.
- Every slider change rebuilds the conductance matrix and solves it again, in microseconds.
- Predict the output for a 20 kΩ load before checking the meter.
:::
:::

```sim circuit
V1 in 0 12          @ 0,0 down
R1 in out 10k       @ 0,0 right
R2 out 0 20k        @ 2,0 down
RL out 0 20k        @ 4,0 down
slider: RL 1k..1M log
meter: v(out), i(RL)
```

::: predict
## Nodal analysis of a circuit with 50 nodes (plus ground) and only resistors and current sources. How big is its conductance matrix?

- [ ] 51 × 51
- [x] 50 × 50
- [ ] 50 × 1
- [ ] 2500 × 2500

::: reveal
50 × 50: one row (one KCL equation) and one column (one unknown voltage) per node other than ground, whose voltage is fixed at zero. Most entries are zero, since each node connects to only a few others, so large simulators store only the nonzero ones.
:::
:::

::: nameit
## The stamp

Number the nodes 1 to $n$, with 0 for ground. KCL at every node is $\mathbf{G}\mathbf{v} = \mathbf{i}$ (lesson 9). A resistor of conductance $g = 1/R$ between nodes $a$ and $b$ adds to $\mathbf G$:

| | column $a$ | column $b$ |
|---|---|---|
| row $a$ | $+g$ | $-g$ |
| row $b$ | $-g$ | $+g$ |

leaving out any row or column for ground. A current source of $I$ flowing from $a$ through the source into $b$ subtracts $I$ from $i_a$ and adds it to $i_b$. Add every part's stamp and solve.

## Voltage sources: modified nodal analysis

A voltage source fixes a voltage difference but its current is unknown, so it needs a new unknown, its current, and a new equation, $v_a - v_b = V$. **Modified nodal analysis** (MNA) grows the matrix by one row and column per source:

$$\begin{bmatrix}\mathbf G & \mathbf B\\ \mathbf B^T & 0\end{bmatrix}\begin{bmatrix}\mathbf v\\ \mathbf j\end{bmatrix} = \begin{bmatrix}\mathbf i\\ \mathbf V\end{bmatrix}$$

where column $k$ of $\mathbf B$ has +1 in row $a$ and −1 in row $b$ for source $k$. Each $j_k$ comes out as the current flowing into the source's + terminal from the circuit; a negative value means the source is delivering power. SPICE builds exactly this.

## Equivalent resistance

To find the resistance between two nodes, inject 1 A in at one and out at the other and solve: the voltage difference, in volts, is the resistance in ohms. This works for any network, bridges included (lesson 11).

## In NumPy

```python
import numpy as np
G = np.zeros((n, n))      # n × n of zeros
G[a - 1, b - 1] += -g     # node a is row a - 1: Python counts from 0
v = np.linalg.solve(G, i) # solve G v = i
```
:::

::: example
## Write the conductance matrix for a 2 mA current source into node 1, with 1 kΩ from node 1 to ground, 1 kΩ from node 1 to node 2, and 2 kΩ from node 2 to ground.

::: solution
1. **Node 1's row.** In mS, node 1 has $1 + 1 = 2$ on the diagonal and $-1$ to node 2.
2. **Node 2's row.** Node 2 has $1 + 0.5 = 1.5$ on the diagonal.
3. **The system.** In mA:
   $$\begin{bmatrix}2 & -1\\ -1 & 1.5\end{bmatrix}\mathbf v = \begin{bmatrix}2\\0\end{bmatrix}$$
4. **Solve.**
   $$\begin{aligned} v_1 &= 1.5\ \text{V} \\ v_2 &= 1.0\ \text{V} \end{aligned}$$

**Answer:** the conductance matrix is $\begin{bmatrix}2 & -1\\ -1 & 1.5\end{bmatrix}$ mS, giving $v_1$ = 1.5 V and $v_2$ = 1.0 V.
:::
:::

::: example
## Lesson 11's bridge, driven by 10 V at its input, solved by MNA. What are the node voltages and the source's current?

::: solution
1. **Node voltages.** With nodes 1 (input), 2 ($a$) and 3 ($b$), the solver gives
   $$\begin{aligned} v_1 &= 10\ \text{V} \\ v_2 &= 7.869\ \text{V} \\ v_3 &= 7.377\ \text{V} \end{aligned}$$
2. **Source current.** The solver gives −0.34426 A: 0.344 A flows out of its + terminal.
3. **Input resistance.**
   $$\begin{aligned} R_\text{in} &= \frac{10}{0.34426} \\ &= 29.05\ \Omega \end{aligned}$$
   matching the delta-wye calculation.

**Answer:** the nodes sit at 10 V, 7.869 V and 7.377 V, and the source current is −0.344 A, which makes the input resistance 29.05 Ω.
:::
:::

::: check
given: n = 5 | 50 | 1000
answer: n^2
tolerance: 0.1%

## A circuit has {n} nodes besides ground. How many entries does its full conductance matrix have?

::: right
Right. $n \times n$ = {answer}.
:::

::: misses
- [(n + 1)^2] Ground has no row or column: its voltage is known.
- [any] Not yet. One row and one column per non-ground node.
:::
:::

::: check
given: R = 1 | 2.2 | 10
answer: -1/R
unit: mS
tolerance: 0.5%

## A {R} kΩ resistor joins nodes 2 and 3. What does it add to the entry in row 2, column 3?

::: right
Right. $-1/R$ = {answer}.
:::

::: misses
- [1/R] Off-diagonal entries get $-g$; the diagonal ones get $+g$.
- [any] Not yet. The stamp's off-diagonal entries.
:::
:::

::: check
given: n = 10 | 20; m = 1 | 3
answer: n + m
tolerance: 0.1%

## A circuit has {n} non-ground nodes and {m} voltage sources. How many unknowns does modified nodal analysis solve for?

::: right
Right. One per node voltage and one per source current: {answer}.
:::

::: misses
- [n] Each voltage source adds its current as an unknown.
- [any] Not yet. Node voltages plus source currents.
:::
:::

::: check
given: g1 = 1 | 2; g2 = 0.5 | 1; I = 1 | 3
answer: I/(g1 + g2)
unit: V
tolerance: 0.5%

## A node connects to ground through {g1} mS and {g2} mS, and a {I} mA source feeds it. What is its voltage?

::: right
Right. A 1 × 1 nodal equation: $(g_1 + g_2)v = I$, so {answer}.
:::

::: misses
- [I/g1] Both conductances connect the node to ground.
- [any] Not yet. Solve $(g_1 + g_2)v = I$.
:::
:::

::: check
kind: python

## Write `nodal(netlist, n)`: each entry is `('R', a, b, ohms)` or `('I', a, b, amps)` (current flowing from node `a` through the source into node `b`), with node 0 as ground. Build $\mathbf G$ and $\mathbf i$ and return the voltages of nodes 1 to `n` as an array.

```python starter
import numpy as np

def nodal(netlist, n):
    G = np.eye(n)
    i = np.zeros(n)
    return np.linalg.solve(G, i)

print(nodal([('I', 0, 1, 2e-3), ('R', 1, 0, 1e3), ('R', 1, 2, 1e3), ('R', 2, 0, 2e3)], 2))
```

```python solution
import numpy as np

def nodal(netlist, n):
    G = np.zeros((n, n))
    i = np.zeros(n)
    for kind, a, b, val in netlist:
        if kind == 'R':
            g = 1 / val
            for x, y, s in ((a, a, 1), (b, b, 1), (a, b, -1), (b, a, -1)):
                if x and y:
                    G[x - 1, y - 1] += s * g
        elif kind == 'I':
            if a:
                i[a - 1] -= val
            if b:
                i[b - 1] += val
    return np.linalg.solve(G, i)

print(nodal([('I', 0, 1, 2e-3), ('R', 1, 0, 1e3), ('R', 1, 2, 1e3), ('R', 2, 0, 2e3)], 2))
```

```python tests
import numpy as np
v = nodal([('I', 0, 1, 2e-3), ('R', 1, 0, 1e3), ('R', 1, 2, 1e3), ('R', 2, 0, 2e3)], 2)
assert np.allclose(v, [1.5, 1.0]), f"The two-node example should give 1.5 V and 1.0 V; got {v}."
v = nodal([('I', 1, 0, 1e-3), ('R', 1, 0, 1e3)], 1)
assert np.allclose(v, [-1.0]), f"Current flowing out of node 1 through the source should pull it to -1 V; got {v}."
v = nodal([('I', 0, 2, 1.0), ('R', 1, 2, 10), ('R', 1, 3, 20), ('R', 2, 3, 30), ('R', 2, 0, 40), ('R', 3, 0, 50)], 3)
assert np.allclose(v[1], 24.761904761904763), f"Check the stamp for resistors between two non-ground nodes; got v2 = {v[1]:.4f}."
```

::: right
Right. That loop is the heart of every circuit simulator; the rest is more kinds of stamp.
:::
:::

::: check
kind: python

## Write `mna(netlist, n)`, accepting `('V', a, b, volts)` (with `a` the + terminal) as well as resistors and current sources. Return `(v, j)`: the node voltages and the voltage sources' currents, in the order the sources appear.

```python starter
import numpy as np

def mna(netlist, n):
    return np.zeros(n), np.zeros(0)

print(mna([('V', 1, 0, 12), ('R', 1, 2, 10e3), ('R', 2, 0, 20e3)], 2))
```

```python solution
import numpy as np

def mna(netlist, n):
    vs = [e for e in netlist if e[0] == 'V']
    m = len(vs)
    A = np.zeros((n + m, n + m))
    z = np.zeros(n + m)
    for kind, a, b, val in netlist:
        if kind == 'R':
            g = 1 / val
            for x, y, s in ((a, a, 1), (b, b, 1), (a, b, -1), (b, a, -1)):
                if x and y:
                    A[x - 1, y - 1] += s * g
        elif kind == 'I':
            if a:
                z[a - 1] -= val
            if b:
                z[b - 1] += val
    for k, (_, a, b, val) in enumerate(vs):
        r = n + k
        if a:
            A[a - 1, r] += 1
            A[r, a - 1] += 1
        if b:
            A[b - 1, r] -= 1
            A[r, b - 1] -= 1
        z[r] = val
    x = np.linalg.solve(A, z)
    return x[:n], x[n:]

print(mna([('V', 1, 0, 12), ('R', 1, 2, 10e3), ('R', 2, 0, 20e3)], 2))
```

```python tests
import numpy as np
v, j = mna([('V', 1, 0, 12), ('R', 1, 2, 10e3), ('R', 2, 0, 20e3)], 2)
assert np.allclose(v, [12, 8]), f"The divider should give 12 V and 8 V; got {v}."
assert np.allclose(j, [-0.4e-3]), f"0.4 mA flows out of the source's + terminal, so j = -0.4 mA; got {j}."
bridge = [('R', 1, 2, 10), ('R', 1, 3, 20), ('R', 2, 3, 30), ('R', 2, 0, 40), ('R', 3, 0, 50), ('V', 1, 0, 10)]
v, j = mna(bridge, 3)
assert np.allclose(v, [10, 7.868852459016393, 7.377049180327869]), f"Bridge node voltages: got {v}."
assert np.allclose(j, [-0.3442622950819672]), f"Bridge source current: got {j}."
v, j = mna([('V', 1, 2, 5), ('R', 1, 0, 1e3), ('R', 2, 0, 1e3)], 2)
assert np.allclose(v, [2.5, -2.5]), f"A floating 5 V source between two 1 kΩ resistors to ground should give +2.5 and -2.5 V; got {v}."
```

::: right
Right. Notice the floating source between nodes 1 and 2: plain nodal analysis needs a supernode for that, and MNA handles it without any special case.
:::
:::

::: check
kind: python

## Write `req(netlist, n, a, b=0)`: the resistance between nodes `a` and `b` of a resistor network, found by injecting 1 A into `a` and out of `b` with your `nodal`.

```python starter
import numpy as np

def nodal(netlist, n):
    G = np.zeros((n, n)); i = np.zeros(n)
    for kind, a, b, val in netlist:
        if kind == 'R':
            g = 1 / val
            for x, y, s in ((a, a, 1), (b, b, 1), (a, b, -1), (b, a, -1)):
                if x and y:
                    G[x - 1, y - 1] += s * g
        elif kind == 'I':
            if a: i[a - 1] -= val
            if b: i[b - 1] += val
    return np.linalg.solve(G, i)

def req(netlist, n, a, b=0):
    return sum(val for kind, x, y, val in netlist if kind == 'R')

print(req([('R', 1, 2, 10), ('R', 1, 3, 20), ('R', 2, 3, 30), ('R', 2, 0, 40), ('R', 3, 0, 50)], 3, 1))
```

```python solution
import numpy as np

def nodal(netlist, n):
    G = np.zeros((n, n)); i = np.zeros(n)
    for kind, a, b, val in netlist:
        if kind == 'R':
            g = 1 / val
            for x, y, s in ((a, a, 1), (b, b, 1), (a, b, -1), (b, a, -1)):
                if x and y:
                    G[x - 1, y - 1] += s * g
        elif kind == 'I':
            if a: i[a - 1] -= val
            if b: i[b - 1] += val
    return np.linalg.solve(G, i)

def req(netlist, n, a, b=0):
    v = nodal(netlist + [('I', b, a, 1.0)], n)
    va = v[a - 1] if a else 0.0
    vb = v[b - 1] if b else 0.0
    return va - vb

print(req([('R', 1, 2, 10), ('R', 1, 3, 20), ('R', 2, 3, 30), ('R', 2, 0, 40), ('R', 3, 0, 50)], 3, 1))
```

```python tests
import numpy as np
bridge = [('R', 1, 2, 10), ('R', 1, 3, 20), ('R', 2, 3, 30), ('R', 2, 0, 40), ('R', 3, 0, 50)]
r = req(bridge, 3, 1)
assert abs(r - 29.047619047619) < 1e-6, f"The bridge's input resistance is 29.05 Ω; got {r:.4f}."
r = req([('R', 1, 0, 1e3), ('R', 1, 0, 1e3)], 1, 1)
assert abs(r - 500) < 1e-6, f"Two 1 kΩ in parallel make 500 Ω; got {r}."
r = req(bridge, 3, 2, 3)
assert abs(r - 12.857142857142856) < 1e-6, f"Between a and b the bridge measures 12.86 Ω; got {r:.4f}."
```

::: right
Right. The same injection trick gives the resistance between any two points of any resistor network, which is how simulators find Thevenin resistances.
:::
:::

::: explain
## Why does modified nodal analysis add an unknown for each voltage source, instead of just writing KCL at every node?

::: model
KCL at a node adds up the currents leaving it, and for a resistor that current is easy to write from the node voltages, $(v_a - v_b)/R$. A voltage source has no such formula: its current can be anything, set by the rest of the circuit, while its voltage is fixed. So its current has to be treated as an extra unknown, appearing in the KCL equations at both of its nodes, and the source's own equation, $v_a - v_b = V$, is added to make up the count. That way every kind of part fits into one matrix, with no special handling for floating sources.
:::
:::

::: practice

::: check
given: Ra = 1 | 2; Rb = 1 | 4
answer: 1/Ra + 1/Rb
unit: mS
tolerance: 0.5%

## A node connects to two others through {Ra} kΩ and {Rb} kΩ. What is its diagonal entry in $\mathbf G$?

::: misses
- [any] The sum of the conductances touching it.
:::
:::

::: check
given: V = 1 | 5; I = 2 | 10
answer: V/I*1000
unit: Ω
tolerance: 0.5%

## Injecting {I} mA between two nodes makes {V} V between them. What resistance is that?

::: misses
- [any] $V/I$.
:::
:::

::: check
given: n = 3 | 4 | 5 | 6 | 7 | 9 | 10 | 12
answer: n*n - n
tolerance: 0.1%

## A {n}-node conductance matrix has how many off-diagonal entries?

::: misses
- [any] All entries minus the diagonal.
:::
:::
:::
