---
title: "Project: a nonlinear circuit simulator"
heading: Nodal analysis, Newton's method and implicit time steps, assembled into a small SPICE
eyebrow: "A13 · Lesson 53 · Project: a nonlinear circuit simulator"
xp: 80
---

::: hook
Every method in the second half of this course meets in a circuit simulator. Nodal analysis turns a circuit into a sparse linear system. Diodes make it nonlinear, so each solve becomes a Newton iteration with companion models and step limiting. Capacitors make it dynamic, and because real circuits are stiff, time steps are implicit: backward Euler turns each capacitor into another companion model. In this project you'll build all three layers in a hundred lines of Python and use them to simulate a half-wave rectifier with a smoothing capacitor, the first circuit in most power supplies.
:::

::: predict
## A 5 V, 50 Hz sine drives a diode through 10 Ω into 100 µF in parallel with 1 kΩ. About what's the capacitor's peak voltage once it has charged?

- [ ] 5 V
- [x] About 4.1 V: the peak, less the diode's drop and a little resistor drop
- [ ] About 2.5 V
- [ ] 0 V

::: reveal
About 4.1 V. The capacitor charges near each peak through the diode and 10 Ω, so it reaches the 5 V peak less about 0.7 V across the diode and a little across the resistor, then sags through the 1 kΩ load until the next peak. Your simulator gives 4.07 V with 0.64 V of ripple. With 100 Ω in place of 10 Ω the diode conducts so briefly that the capacitor settles near 2.9 V: the source's resistance matters as much as the diode's drop.
:::
:::

::: nameit
## Layer 1: linear nodal analysis

Number the nodes 1 to n, with 0 as ground. A resistor R between a and b adds $1/R$ to $G_{aa}$ and $G_{bb}$ and subtracts it from $G_{ab}$ and $G_{ba}$ (skipping ground's row and column). A current source pushing I into node a adds I to $i_a$. Solve $Gv = i$. A voltage source with a series resistor is entered as its Norton equivalent: a current $V/R$ into its node and R to ground.

## Layer 2: diodes by Newton's method

A diode from a to b with voltage $V = v_a - v_b$ carries $I_s(e^{V/nV_T} - 1)$. Linearized at the current guess, it's a conductance $g_d$ in parallel with a current source $I_{eq} = I_d - g_dV$ (lesson 34). Each iteration stamps the resistors, sources and the diodes' companion models, solves, and repeats until the change is below a tolerance. To keep the exponential from overflowing, limit each iteration's change of every node voltage to 0.1 V.

## Layer 3: transients by backward Euler

A capacitor C between a and b, with step h and previous voltage $V_n$, becomes a conductance $C/h$ in parallel with a current source $CV_n/h$ pushing current toward a (lesson 43). At each time step, update the sources to $t_{n+1}$, run the Newton loop of layer 2 with the capacitors' companion models included, and store the result.

## Data used in the tests

$I_s = 10^{-14}$ A, $nV_T$ = 0.02585 V. The two-diode circuit of lesson 34 settles at $V_1 = 0.691903$ V, $V_2 = 0.594530$ V.
:::

::: example
## Write the nodal matrix for 1 kΩ from node 1 to ground, 2 kΩ from node 1 to node 2, and 3 kΩ from node 2 to ground.

::: solution
1. **Stamp each resistor.** Each resistor contributes to the diagonal of each node it touches and to the off-diagonals between them; ground's row and column are left out.
2. **The matrix.**
   $$G = \begin{pmatrix}\frac{1}{1000} + \frac{1}{2000} & -\frac{1}{2000}\\ -\frac{1}{2000} & \frac{1}{2000} + \frac{1}{3000}\end{pmatrix}$$

**Answer:** the diagonal entries are $\frac{1}{1000} + \frac{1}{2000}$ and $\frac{1}{2000} + \frac{1}{3000}$ S, and both off-diagonal entries are $-\frac{1}{2000}$ S.
:::
:::

::: example
## A capacitor of 100 µF at 4 V is simulated with h = 0.1 ms. What's its companion model?

::: solution
1. **The conductance.**
   $$\begin{aligned} C/h &= 10^{-4}/10^{-4} \\ &= 1\ \text{S} \end{aligned}$$
2. **The current source.** In parallel sits a source of
   $$CV_n/h = 4\ \text{A}$$
   into the node at its positive end.
3. **Check.** With nothing else attached, the next solve gives back 4 V, as it should for an isolated capacitor.

**Answer:** a 1 S conductance in parallel with a 4 A current source into the capacitor's positive node.
:::
:::

::: check
kind: python

## Step 1. Write `solve_linear(n, resistors, sources)`: `resistors` is a list of `(a, b, R)`, `sources` a list of `(node, current_in)`, node 0 is ground. Return the node voltages as a NumPy array `v` with `v[0]` for node 1.

```python starter
import numpy as np

def stamp_r(G, a, b, R):
    g = 1 / R
    # add g to (a, a) and (b, b), subtract from (a, b) and (b, a); skip node 0
    pass

def solve_linear(n, resistors, sources):
    G = np.zeros((n, n))
    i = np.zeros(n)
    return np.zeros(n)

print(solve_linear(1, [(1, 0, 1000), (1, 0, 2000)], [(1, 0.01)]))
```

```python solution
import numpy as np

def stamp_r(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_linear(n, resistors, sources):
    G = np.zeros((n, n))
    i = np.zeros(n)
    for a, b, R in resistors:
        stamp_r(G, a, b, R)
    for node, cur in sources:
        if node: i[node - 1] += cur
    return np.linalg.solve(G, i)

print(solve_linear(1, [(1, 0, 1000), (1, 0, 2000)], [(1, 0.01)]))
```

```python tests
import numpy as np
v = solve_linear(1, [(1, 0, 1000), (1, 0, 2000)], [(1, 0.01)])
assert abs(v[0] - 20 / 3) < 1e-9, f"10 mA into 1 kΩ ∥ 2 kΩ gives 6.667 V; got {v[0]}."
v = solve_linear(2, [(1, 0, 1000), (1, 2, 2000), (2, 0, 3000)], [(1, 0.005), (2, -0.001)])
G = np.array([[1/1000 + 1/2000, -1/2000], [-1/2000, 1/2000 + 1/3000]])
ref = np.linalg.solve(G, np.array([0.005, -0.001]))
assert np.allclose(v, ref, atol=1e-12), f"Expected {ref}, got {v}: check the off-diagonal stamps."
```

::: right
Right. Each resistor adds the same four entries wherever it appears, so building any network's matrix is a loop over its parts.
:::
:::

::: check
kind: python

## Step 2. Write `solve_dc(n, resistors, sources, diodes)` with Newton's method: `diodes` is a list of `(a, b)` (anode, cathode). Start from all zeros, limit each node's change to 0.1 V per iteration, stop when the largest change is below $10^{-12}$ V. Return `(v, iterations)`. `stamp_r` is included.

```python starter
import math
import numpy as np
IS, NVT = 1e-14, 0.02585

def stamp_r(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_dc(n, resistors, sources, diodes):
    v = np.zeros(n)
    iterations = 0
    # each iteration: stamp resistors, sources and each diode's g_d and I_eq; solve; limit; repeat
    return v, iterations

R = [(1, 0, 1000), (1, 2, 1000)]
print(solve_dc(2, R, [(1, 0.005)], [(1, 0), (2, 0)]))
```

```python solution
import math
import numpy as np
IS, NVT = 1e-14, 0.02585

def stamp_r(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 node_v(v, k):
    return v[k - 1] if k else 0.0

def stamp_diodes(G, i, v, diodes):
    for a, b in diodes:
        vd = node_v(v, a) - node_v(v, b)
        e = math.exp(vd / NVT)
        gd = IS / NVT * e
        ieq = IS * (e - 1) - gd * vd
        stamp_r(G, a, b, 1 / gd)
        if a: i[a - 1] -= ieq
        if b: i[b - 1] += ieq

def solve_dc(n, resistors, sources, diodes, v=None, extra=None):
    v = np.zeros(n) if v is None else v.copy()
    for it in range(1, 500):
        G = np.zeros((n, n))
        i = np.zeros(n)
        for a, b, R in resistors:
            stamp_r(G, a, b, R)
        for node, cur in sources:
            if node: i[node - 1] += cur
        if extra:
            extra(G, i)
        stamp_diodes(G, i, v, diodes)
        new = np.linalg.solve(G, i)
        step = np.clip(new - v, -0.1, 0.1)
        v = v + step
        if np.max(np.abs(step)) < 1e-12:
            return v, it
    return v, it

R = [(1, 0, 1000), (1, 2, 1000)]
print(solve_dc(2, R, [(1, 0.005)], [(1, 0), (2, 0)]))
```

```python tests
import numpy as np
R = [(1, 0, 1000), (1, 2, 1000)]
v, n = solve_dc(2, R, [(1, 0.005)], [(1, 0), (2, 0)])
assert abs(v[0] - 0.691903) < 2e-6 and abs(v[1] - 0.594530) < 2e-6, f"Expected V1 = 0.691903 and V2 = 0.594530 V; got {v}."
assert n < 60, f"Newton with 0.1 V limiting should settle in well under 60 iterations; it took {n}."
v, n = solve_dc(1, [(1, 0, 1000)], [(1, -0.005)], [(1, 0)])
assert abs(v[0] + 5) < 1e-6, f"A reverse-biased diode carries almost nothing, so the node sits at −5 V; got {v[0]}."
```

::: right
Right. From zero the limiter walks the voltages up 0.1 V at a time, then Newton converges quadratically to six digits and beyond.
:::
:::

::: check
kind: python

## Step 3. Write `rectifier(h, t_end)`: a 5 V, 50 Hz sine through 10 Ω (as its Norton equivalent into node 1), a diode from node 1 to node 2, and 100 µF and 1 kΩ from node 2 to ground. Use backward Euler with step h, starting from rest, and the Newton loop of step 2 at every step (starting from the previous solution). Return the lists `ts` and `v2s` (node 2's voltage). `solve_dc` is included and accepts `v=` (a start) and `extra=` (a function that stamps more into G and i).

```python starter
import math
import numpy as np
IS, NVT = 1e-14, 0.02585

def stamp_r(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 node_v(v, k):
    return v[k - 1] if k else 0.0

def stamp_diodes(G, i, v, diodes):
    for a, b in diodes:
        vd = node_v(v, a) - node_v(v, b)
        e = math.exp(vd / NVT)
        gd = IS / NVT * e
        ieq = IS * (e - 1) - gd * vd
        stamp_r(G, a, b, 1 / gd)
        if a: i[a - 1] -= ieq
        if b: i[b - 1] += ieq

def solve_dc(n, resistors, sources, diodes, v=None, extra=None):
    v = np.zeros(n) if v is None else v.copy()
    for it in range(1, 500):
        G = np.zeros((n, n))
        i = np.zeros(n)
        for a, b, R in resistors:
            stamp_r(G, a, b, R)
        for node, cur in sources:
            if node: i[node - 1] += cur
        if extra:
            extra(G, i)
        stamp_diodes(G, i, v, diodes)
        new = np.linalg.solve(G, i)
        step = np.clip(new - v, -0.1, 0.1)
        v = v + step
        if np.max(np.abs(step)) < 1e-12:
            return v, it
    return v, it

def rectifier(h, t_end):
    ts, v2s = [0.0], [0.0]
    # each step: source current 5 sin(2π 50 t)/10 into node 1; capacitor companion C/h with C*v2/h into node 2
    return ts, v2s

ts, v2 = rectifier(1e-4, 0.06)
print(max(v2), v2[-1])
```

```python solution
import math
import numpy as np
IS, NVT = 1e-14, 0.02585

def stamp_r(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 node_v(v, k):
    return v[k - 1] if k else 0.0

def stamp_diodes(G, i, v, diodes):
    for a, b in diodes:
        vd = node_v(v, a) - node_v(v, b)
        e = math.exp(vd / NVT)
        gd = IS / NVT * e
        ieq = IS * (e - 1) - gd * vd
        stamp_r(G, a, b, 1 / gd)
        if a: i[a - 1] -= ieq
        if b: i[b - 1] += ieq

def solve_dc(n, resistors, sources, diodes, v=None, extra=None):
    v = np.zeros(n) if v is None else v.copy()
    for it in range(1, 500):
        G = np.zeros((n, n))
        i = np.zeros(n)
        for a, b, R in resistors:
            stamp_r(G, a, b, R)
        for node, cur in sources:
            if node: i[node - 1] += cur
        if extra:
            extra(G, i)
        stamp_diodes(G, i, v, diodes)
        new = np.linalg.solve(G, i)
        step = np.clip(new - v, -0.1, 0.1)
        v = v + step
        if np.max(np.abs(step)) < 1e-12:
            return v, it
    return v, it

def rectifier(h, t_end):
    C = 100e-6
    ts, v2s = [0.0], [0.0]
    v = np.zeros(2)
    t = 0.0
    for k in range(int(round(t_end / h))):
        t = (k + 1) * h
        vin = 5 * math.sin(2 * math.pi * 50 * t)
        prev = v[1]
        def cap(G, i):
            G[1, 1] += C / h
            i[1] += C * prev / h
        v, _ = solve_dc(2, [(1, 0, 10), (2, 0, 1000)], [(1, vin / 10)], [(1, 2)], v=v, extra=cap)
        ts.append(t)
        v2s.append(v[1])
    return ts, v2s

ts, v2 = rectifier(1e-4, 0.06)
print(max(v2), v2[-1])
```

```python tests
import math
import numpy as np
ts, v2 = rectifier(1e-4, 0.06)
assert len(ts) == 601 and abs(ts[-1] - 0.06) < 1e-12, "There should be 601 points from 0 to 60 ms at h = 0.1 ms."
peak = max(v2[400:])
assert 4.0 < peak < 4.15, f"The capacitor should peak near 4.07 V; got {peak:.3f} V."
tail = v2[400:]
ripple = max(tail) - min(tail)
assert 0.55 < ripple < 0.75, f"The ripple should be about 0.64 V; got {ripple:.3f} V."
ts2, v2b = rectifier(5e-5, 0.06)
assert abs(max(v2b[800:]) - peak) < 0.02, "Halving h should change the peak by only a little: backward Euler is first-order."
print(f"peak {peak:.4f} V, ripple {ripple:.4f} V")
```

::: right
Right. The capacitor charges over the first few cycles, then each peak tops it up through the diode and it sags through the load in between: a small SPICE, built from the pieces of this course.
:::
:::

::: check
given: C = 10 | 100 | 470; h = 20 | 50
answer: C/h
unit: S
tolerance: 0.5%

## What conductance stands for a {C} µF capacitor with a {h} µs backward-Euler step?

::: right
Right. $C/h$ = {answer} S.
:::

::: misses
- [h/C] Conductance is $C/h$.
- [any] Not yet. $i = C\frac{v_{n+1} - v_n}{h}$.
:::
:::

::: check
given: R1 = 1000 | 2200; R2 = 2000 | 4700; I = 5 | 10
answer: I*R1*R2/(R1 + R2)/1000
unit: V
tolerance: 0.1%

## A current of {I} mA flows into a node with {R1} Ω and {R2} Ω to ground. What's the node voltage?

::: right
Right. $I(R_1 \parallel R_2)$ = {answer} V.
:::

::: misses
- [I*(R1 + R2)/1000] The resistors are in parallel, both from the node to ground.
- [any] Not yet. $G = \frac{1}{R_1} + \frac{1}{R_2}$, $v = I/G$.
:::
:::

::: explain
## Why do circuit simulators solve each time step with Newton's method on a linear "companion" circuit?

::: model
Stiff circuits need implicit time steps, and an implicit step requires solving the circuit's equations at the new time, which are nonlinear because of diodes and transistors. Newton's method linearizes those equations at a guess. In circuit terms, linearizing a device replaces it by a conductance and a current source, and the backward-Euler formula replaces each capacitor by a conductance C/h and a current source carrying its previous charge. Every element then looks like a resistor or a source, so each Newton iteration is just nodal analysis of a linear circuit: one sparse linear solve. Repeating that until the voltages stop changing gives the solution at the new time, and the next time step starts from it.
:::
:::

::: practice

::: check
given: C = 1 | 22; h = 0.5 | 2
answer: C/h
unit: S
tolerance: 0.5%

## Companion conductance, {C} µF, {h} µs?

::: misses
- [any] $C/h$.
:::
:::

::: check
given: R1 = 470 | 3300; R2 = 1000 | 10000; I = 2 | 20
answer: I*R1*R2/(R1 + R2)/1000
unit: V
tolerance: 0.1%

## Node voltage: {I} mA into {R1} Ω ∥ {R2} Ω?

::: misses
- [any] $I(R_1 \parallel R_2)$.
:::
:::

::: check
given: V = 0.55 | 0.6 | 0.65 | 0.68 | 0.72 | 0.75
answer: 1e-14/0.02585*exp(V/0.02585)*1000
unit: mS
tolerance: 0.5%

## Diode companion conductance at {V} V?

::: misses
- [any] $\frac{I_s}{nV_T}e^{V/nV_T}$.
:::
:::
:::
