---
title: "Project: a circuit solver in Python"
heading: Build the core of SPICE in forty lines
eyebrow: A7 · Lesson 53 · Project
xp: 80
---

::: hook
Every circuit simulator, from SPICE to the one running the sims in this course, starts the same way: read a list of parts, turn each part into a few entries of a matrix, and solve. In this project you'll write that core yourself. Your solver will read a netlist of resistors, current sources and voltage sources, assemble the equations with the "stamps" that make nodal analysis mechanical, and solve circuits too tangled to do by hand. Along the way, every idea from this course shows up: the incidence matrix, symmetry, positive definiteness, and the null space you remove by grounding a node.
:::

::: predict
## Your solver builds the conductance matrix $G$ for a circuit and forgets to ground any node. What will the solver do?

- [ ] Solve it normally
- [x] Fail: $G$ is singular, because raising every node by 1 V changes no current
- [ ] Return all zeros
- [ ] Give voltages relative to the average node

::: reveal
It fails. Without a ground, the vector of all ones is in the null space of $G$ (lesson 19), so $G$ is singular and has no inverse. Numbering nodes from 1 and leaving out node 0, the ground, removes that null space.
:::
:::

::: nameit
## Stamps

Number the nodes 1 to $N$, with 0 for ground. Each part adds a small pattern, its **stamp**, to the system $G\mathbf{v} = \mathbf{i}$:

**A resistor $R$ between nodes $a$ and $b$** (conductance $g = 1/R$):

$$G_{aa} \mathrel{+}= g \quad G_{bb} \mathrel{+}= g \quad G_{ab} \mathrel{-}= g \quad G_{ba} \mathrel{-}= g$$

skipping any entry for node 0. This is $A^TCA$ assembled one branch at a time.

**A current source** pushing current $I$ from node $a$ through itself to node $b$: $i_a \mathrel{-}= I$ and $i_b \mathrel{+}= I$.

## Voltage sources: modified nodal analysis

A voltage source fixes $v_a - v_b = E$ and carries an unknown current $j$. Add $j$ as an extra unknown and the constraint as an extra equation:

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

where column $k$ of $B$ has $+1$ at row $a$ and $-1$ at row $b$ for the $k$th source. This is **modified nodal analysis** (MNA), what SPICE does. The matrix is still symmetric, but no longer positive definite: the zero block makes it indefinite, so the solver needs pivoting.

## The netlist

One part per line: a kind, two nodes, a value in SI units.

```
V 1 0 10
R 1 2 1000
R 2 0 1000
```
:::

::: example
## By hand: a 1 mA source into node 1, with 1 kΩ from node 1 to ground, 1 kΩ from node 1 to node 2, and 1 kΩ from node 2 to ground.

::: solution
1. **Stamp the resistors.** In siemens:
   $$G = \begin{bmatrix}0.002 & -0.001\\-0.001 & 0.002\end{bmatrix}$$
   $$\mathbf{i} = \begin{bmatrix}0.001\\0\end{bmatrix}$$
2. **Solve.**
   $$\begin{aligned} \mathbf{v} &= G^{-1}\mathbf{i} \\ &= (0.667, 0.333)\ \text{V} \end{aligned}$$
   Your solver should reproduce this exactly.

**Answer:** $v_1$ = 0.667 V and $v_2$ = 0.333 V.
:::
:::

::: example
## By hand: a 10 V source from node 1 to ground feeding two 1 kΩ resistors in series to ground.

::: solution
1. **Unknowns.** $v_1$, $v_2$ and the source current $j$.
2. **The pieces.** The resistors give
   $$G = \begin{bmatrix}0.001 & -0.001\\-0.001 & 0.002\end{bmatrix}$$
   and $B = (1, 0)$.
3. **The full system.**
   $$A = \begin{bmatrix}0.001 & -0.001 & 1\\-0.001 & 0.002 & 0\\1 & 0 & 0\end{bmatrix}$$
   $$A\begin{bmatrix}v_1\\v_2\\j\end{bmatrix} = \begin{bmatrix}0\\0\\10\end{bmatrix}$$
4. **Solve.** It gives $v_1 = 10$, $v_2 = 5$ and $j = -5$ mA.
5. **The sign of $j$.** The current $j$ is defined as flowing into the source's positive end, so $-5$ mA means 5 mA flowing out to the circuit.

**Answer:** $v_1$ = 10 V and $v_2$ = 5 V, and the source supplies 5 mA ($j = -5$ mA).
:::
:::

::: check
kind: python

## Step 1. Write `stamp_resistor(G, a, b, R)`, adding a resistor's stamp to the NumPy array `G` in place. Nodes are numbered from 1, node 0 is ground and gets no row or column, and node $k$ uses index $k - 1$.

```python starter
import numpy as np

def stamp_resistor(G, a, b, R):
    g = 1 / R
    # add g on the diagonal for a and b, subtract it off the diagonal; skip node 0
    pass

G = np.zeros((2, 2))
stamp_resistor(G, 1, 0, 1000)
stamp_resistor(G, 1, 2, 1000)
stamp_resistor(G, 2, 0, 1000)
print(G)
```

```python solution
import numpy as np

def stamp_resistor(G, a, b, R):
    g = 1 / R
    if a:
        G[a - 1, a - 1] += g
    if b:
        G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g

G = np.zeros((2, 2))
stamp_resistor(G, 1, 0, 1000)
stamp_resistor(G, 1, 2, 1000)
stamp_resistor(G, 2, 0, 1000)
print(G)
```

```python tests
import numpy as np
G = np.zeros((2, 2))
stamp_resistor(G, 1, 0, 1000)
stamp_resistor(G, 1, 2, 1000)
stamp_resistor(G, 2, 0, 1000)
assert np.allclose(G, [[0.002, -0.001], [-0.001, 0.002]]), f"Expected [[0.002, -0.001], [-0.001, 0.002]], got {G.tolist()}."
G = np.zeros((3, 3))
stamp_resistor(G, 3, 1, 500)
assert np.allclose(G, [[0.002, 0, -0.002], [0, 0, 0], [-0.002, 0, 0.002]]), "A resistor between nodes 3 and 1 touches entries (0,0), (2,2), (0,2) and (2,0)."
```

::: right
Right. Notice the result is always symmetric, and each stamp's rows add to zero before grounding: that's the incidence matrix at work.
:::
:::

::: check
kind: python

## Step 2. Write `solve_ri(lines)` for netlists of resistors (`R a b ohms`) and current sources (`I a b amps`, pushing current from `a` to `b` through the source). Return the node voltages as a NumPy array, node 1 first. Use `stamp_resistor` (included).

```python starter
import numpy as np

def stamp_resistor(G, a, b, R):
    g = 1 / R
    if a:
        G[a - 1, a - 1] += g
    if b:
        G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g

def solve_ri(lines):
    parts = [l.split() for l in lines]
    n = max(max(int(p[1]), int(p[2])) for p in parts)
    G = np.zeros((n, n))
    i = np.zeros(n)
    # stamp each part, then solve
    return np.zeros(n)

print(solve_ri(["I 0 1 1e-3", "R 1 0 1000", "R 1 2 1000", "R 2 0 1000"]))
```

```python solution
import numpy as np

def stamp_resistor(G, a, b, R):
    g = 1 / R
    if a:
        G[a - 1, a - 1] += g
    if b:
        G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g

def solve_ri(lines):
    parts = [l.split() for l in lines]
    n = max(max(int(p[1]), int(p[2])) for p in parts)
    G = np.zeros((n, n))
    i = np.zeros(n)
    for kind, a, b, val in parts:
        a, b, val = int(a), int(b), float(val)
        if kind == "R":
            stamp_resistor(G, a, b, val)
        elif kind == "I":
            if a:
                i[a - 1] -= val
            if b:
                i[b - 1] += val
    return np.linalg.solve(G, i)

print(solve_ri(["I 0 1 1e-3", "R 1 0 1000", "R 1 2 1000", "R 2 0 1000"]))
```

```python tests
import numpy as np
v = solve_ri(["I 0 1 1e-3", "R 1 0 1000", "R 1 2 1000", "R 2 0 1000"])
assert np.allclose(v, [2/3, 1/3]), f"The worked example gives (0.667, 0.333) V; got {v}."
v = solve_ri(["I 1 0 2e-3", "R 1 0 500"])
assert np.allclose(v, [-1.0]), "A source pushing 2 mA out of node 1 through 500 Ω gives −1 V: check the source's direction."
v = solve_ri(["I 0 1 1e-3", "R 1 2 1000", "R 2 3 1000", "R 3 0 1000", "R 1 3 2000"])
G = np.array([[1/1000 + 1/2000, -1/1000, -1/2000], [-1/1000, 2/1000, -1/1000], [-1/2000, -1/1000, 1/1000 + 1/1000 + 1/2000]])
assert np.allclose(v, np.linalg.solve(G, [1e-3, 0, 0])), "Check a three-node circuit with a loop."
```

::: right
Right. That's nodal analysis for any network of resistors and current sources, of any size.
:::
:::

::: check
kind: python

## Step 3. Write `solve_mna(lines)` that also handles voltage sources (`V a b volts`, meaning $v_a - v_b$ = volts), using modified nodal analysis. Return only the node voltages.

```python starter
import numpy as np

def stamp_resistor(G, a, b, R):
    g = 1 / R
    if a:
        G[a - 1, a - 1] += g
    if b:
        G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g

def solve_mna(lines):
    parts = [l.split() for l in lines]
    n = max(max(int(p[1]), int(p[2])) for p in parts)
    vs = [p for p in parts if p[0] == "V"]
    m = len(vs)
    M = np.zeros((n + m, n + m))
    rhs = np.zeros(n + m)
    # stamp R and I into the top-left n x n block and rhs[:n];
    # for the k-th V source, put +1/-1 in column n + k and row n + k, and its value in rhs[n + k]
    return np.zeros(n)

print(solve_mna(["V 1 0 10", "R 1 2 1000", "R 2 0 1000"]))
```

```python solution
import numpy as np

def stamp_resistor(G, a, b, R):
    g = 1 / R
    if a:
        G[a - 1, a - 1] += g
    if b:
        G[b - 1, b - 1] += g
    if a and b:
        G[a - 1, b - 1] -= g
        G[b - 1, a - 1] -= g

def solve_mna(lines):
    parts = [l.split() for l in lines]
    n = max(max(int(p[1]), int(p[2])) for p in parts)
    vs = [p for p in parts if p[0] == "V"]
    m = len(vs)
    M = np.zeros((n + m, n + m))
    rhs = np.zeros(n + m)
    k = 0
    for kind, a, b, val in parts:
        a, b, val = int(a), int(b), float(val)
        if kind == "R":
            stamp_resistor(M, a, b, val)
        elif kind == "I":
            if a:
                rhs[a - 1] -= val
            if b:
                rhs[b - 1] += val
        elif kind == "V":
            if a:
                M[a - 1, n + k] += 1
                M[n + k, a - 1] += 1
            if b:
                M[b - 1, n + k] -= 1
                M[n + k, b - 1] -= 1
            rhs[n + k] = val
            k += 1
    return np.linalg.solve(M, rhs)[:n]

print(solve_mna(["V 1 0 10", "R 1 2 1000", "R 2 0 1000"]))
```

```python tests
import numpy as np
v = solve_mna(["V 1 0 10", "R 1 2 1000", "R 2 0 1000"])
assert np.allclose(v, [10, 5]), f"A 10 V source on two equal resistors: expected (10, 5), got {v}."
net = ["V 1 0 10", "R 1 2 1000", "R 2 0 2000", "R 1 3 2000", "R 3 0 1000", "R 2 3 5000"]
v = solve_mna(net)
G = np.array([[1/1000 + 1/2000, -1/1000, -1/2000], [-1/1000, 1/1000 + 1/2000 + 1/5000, -1/5000], [-1/2000, -1/5000, 1/2000 + 1/1000 + 1/5000]])
M = np.block([[G, np.array([[1], [0], [0]])], [np.array([[1, 0, 0, 0]])]])
ref = np.linalg.solve(M, [0, 0, 0, 10])[:3]
assert np.allclose(v, ref), f"The bridge: expected {ref}, got {v}."
v = solve_mna(["V 2 1 3", "R 1 0 1000", "R 2 0 1000"])
assert np.allclose(v, [-1.5, 1.5]), "A floating 3 V source across two equal resistors to ground gives −1.5 V and +1.5 V."
```

::: right
Right. With R, I and V stamps you have the linear core of SPICE. Capacitors and inductors add stamps that depend on frequency (lesson 50) or time step; diodes and transistors add Newton's method on top.
:::
:::

::: check
given: R1 = 1 | 2.2; R2 = 2 | 4.7; R3 = 3.3 | 10
answer: R2*R3/R1
unit: kΩ
tolerance: 0.5%

## Step 4. A bridge has $R_1$ = {R1} kΩ from the top to node 2, $R_2$ = {R2} kΩ from node 2 to ground, $R_3$ = {R3} kΩ from the top to node 3, and $R_4$ from node 3 to ground. What $R_4$ balances it ($v_2 = v_3$)? Check your answer with your solver.

::: right
Right. Balance needs equal dividers, $\frac{R_2}{R_1 + R_2} = \frac{R_4}{R_3 + R_4}$, which gives $R_4 = \frac{R_2R_3}{R_1}$ = {answer}.
:::

::: misses
- [R1*R3/R2] Each side is a divider: node 3 must divide like node 2, so $R_4/R_3 = R_2/R_1$.
- [any] Not yet. Make the two dividers' ratios equal.
:::
:::

::: explain
## Why does the conductance matrix you assemble from resistor stamps always come out symmetric?

::: model
Each resistor joins two nodes and adds the same $-g$ to both entry $(a, b)$ and entry $(b, a)$, plus $+g$ on the two diagonal entries. Every stamp is symmetric on its own, and adding symmetric matrices gives a symmetric matrix. Physically, a resistor conducts equally in both directions, which is the reciprocity of lesson 11; in matrix terms, $G = A^TCA$ is symmetric for any incidence matrix $A$ and diagonal $C$.
:::
:::

::: practice

::: check
given: R = 1 | 4.7; k = 2 | 3
answer: k/R
unit: mS

## {k} resistors of {R} kΩ each connect node 1 to other places. What is $G_{11}$, in mS?

::: misses
- [R/k] Conductances add: each contributes $1/R$.
- [any] Add the conductances touching node 1.
:::
:::

::: check
given: n = 4 | 10; m = 1 | 3
answer: n + m

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

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

::: check
given: I = 1 | 5; R = 2 | 3
answer: -I*R
unit: V

## A current source pushes {I} mA out of node 1 (to ground) through itself, and {R} kΩ connects node 1 to ground. What is $v_1$?

::: misses
- [I*R] The source pulls current out of node 1, so the resistor's current flows up from ground.
- [any] KCL at node 1.
:::
:::
:::
