---
title: "Lab: circuit graphs in code"
heading: Kirchhoff's laws as matrices you can compute with
eyebrow: A7 · Lesson 21 · Lab: circuit graphs in code
xp: 60
---

::: hook
Lessons 19 and 20 turned a circuit's wiring into an incidence matrix and read Kirchhoff's laws off its four subspaces. In this lab you'll compute with that structure: build the incidence matrix from a list of branches, find a basis of loop currents from the SVD, assemble the conductance matrix as $A^TCA$ and solve the circuit, then check Tellegen's theorem, that the power the source delivers equals the power every resistor takes. The circuit is the one below: four nodes counting ground, five resistors and a current source.
:::

::: play
- A 1 mA source feeds node n1 of a two-section ladder. The meters read the three node voltages.
- Change $R_1$, the resistor between n1 and n2. The voltages beyond it fall as it grows, and n1's rises.
- With every part at its starting value, the meters should match what your code computes: 0.636, 0.273 and 0.182 V.
:::

```sim circuit
I1 0 n1 1m          @ 0,2 up
R3 n1 0 1k          @ 2,0 down
R1 n1 n2 1k         @ 2,0 right
R4 n2 0 1k          @ 4,0 down
R2 n2 n3 1k         @ 4,0 right
R5 n3 0 2k          @ 6,0 down
slider: R1 100..10k log
scope: v(n1), v(n3)
time: 0..1m s
meter: v(n1), v(n2), v(n3)
```

::: predict
## This circuit has 4 nodes counting ground and 5 resistors. How many independent loop currents does it have?

- [ ] 1
- [x] 2
- [ ] 4
- [ ] 5

::: reveal
Two: $b - n + 1 = 5 - 4 + 1$. They're the two meshes, one through $R_3$, $R_1$ and $R_4$, the other through $R_4$, $R_2$ and $R_5$. The current source is left out of the graph and enters as a current injected at n1; it doesn't add a loop.
:::
:::

::: nameit
## The incidence matrix in code

Number the nodes from 0, with ground last, and list each branch as a pair (from, to). The incidence matrix has one row per branch, with $-1$ in the from column and $+1$ in the to column. For a connected circuit, $A\mathbf{1} = \mathbf{0}$ and the rank is $n - 1$.

## Null spaces from the SVD

The rows of $V^T$ in an SVD whose singular values are (numerically) zero span the null space. In NumPy:

```python
u, s, vt = np.linalg.svd(M)
r = np.sum(s > 1e-10 * s[0])
basis = vt[r:].T          # columns span the null space of M
```

The null space of $A^T$ holds the branch-current patterns that satisfy KCL with no sources, the loop currents.

## Assembling and solving

Drop the ground column to get $A_r$. With the branch conductances on the diagonal of $C$, the conductance matrix is $G = A_r^TCA_r$, and $G\mathbf{v} = \mathbf{f}$ gives the node voltages for injected currents $\mathbf{f}$. This is exactly what a simulator does, one branch at a time.

## Tellegen's theorem

With ground at 0 V appended to $\mathbf{v}$, the branch voltages are $\mathbf{e} = A\mathbf{u}$ and the branch currents $\mathbf{w} = C\mathbf{e}$. Then $\mathbf{e}\cdot\mathbf{w} = \mathbf{u}^TA^TCA\mathbf{u} = \mathbf{v}^T\mathbf{f}$: the power taken by the branches equals the power the sources put in.
:::

::: example
## Write the incidence matrix of the lab circuit.

::: solution
1. **Number the nodes and branches.** With nodes n1, n2, n3 and ground numbered 0 to 3, and branches $R_1$ (0→1), $R_2$ (1→2), $R_3$ (0→3), $R_4$ (1→3) and $R_5$ (2→3):
   $$A = \begin{bmatrix}-1 & 1 & 0 & 0\\0 & -1 & 1 & 0\\-1 & 0 & 0 & 1\\0 & -1 & 0 & 1\\0 & 0 & -1 & 1\end{bmatrix}$$
2. **Row sums.** Each row sums to zero, so $A\mathbf{1} = \mathbf{0}$.
3. **Rank.** The first three columns are independent, so the rank is 3.

**Answer:** $A$ is the 5 × 4 matrix above, one row per branch with $-1$ at the node it leaves and $+1$ at the node it enters, and its rank is 3.
:::
:::

::: example
## Solve the lab circuit by hand from $G = A_r^TCA_r$.

::: solution
1. **Conductance matrix.** In millisiemens, $C = \text{diag}(1, 1, 1, 1, 0.5)$, and
   $$G = \begin{bmatrix}2 & -1 & 0\\-1 & 3 & -1\\0 & -1 & 1.5\end{bmatrix}$$
   each diagonal entry being the total conductance at a node.
2. **Determinant.**
   $$\begin{aligned} \det G &= 2(4.5 - 1) - 1(1.5) \\ &= 5.5 \end{aligned}$$
3. **Cramer's rule.** With 1 mA into n1:
   $$\begin{aligned} v_1 &= \frac{3.5}{5.5} \\ &= 0.636\ \text{V} \\ v_2 &= \frac{1.5}{5.5} \\ &= 0.273\ \text{V} \\ v_3 &= \frac{1}{5.5} \\ &= 0.182\ \text{V} \end{aligned}$$
4. **Source power.**
   $$0.636 \times 1 = 0.636\ \text{mW}$$

**Answer:** $v_1$ = 0.636 V, $v_2$ = 0.273 V and $v_3$ = 0.182 V, and the source delivers 0.636 mW.
:::
:::

::: check
given: n = 6 | 8; b = 11 | 13
answer: b - n + 1
tolerance: 0

## A connected circuit graph has {n} nodes and {b} branches. How many columns does a basis of the null space of $A^T$ have?

::: right
Right. $b - n + 1$ = {answer}: one per independent loop.
:::

::: misses
- [n - 1] That's the rank.
- [b - n] One more: the rank is $n - 1$.
- [any] Not yet. $A^T$ is $n \times b$ with rank $n - 1$.
:::
:::

::: check
given: g1 = 1 | 2; g2 = 0.5 | 3; g3 = 1.5 | 4
answer: g1 + g2 + g3
unit: mS
tolerance: 0.5%

## A node has branches of {g1}, {g2} and {g3} mS to other nodes. What is its diagonal entry in $G = A^TCA$?

::: right
Right. The sum of the conductances at the node: {answer}.
:::

::: misses
- [-(g1 + g2 + g3)] Diagonal entries are positive; the off-diagonal ones carry the minus signs.
- [any] Not yet. Each branch at the node adds its conductance to the diagonal.
:::
:::

::: check
kind: python

## Write `incidence(edges, n)` returning the $b \times n$ incidence matrix. Build it for the lab circuit and set `rank` with `np.linalg.matrix_rank`.

```python starter
import numpy as np

edges = [(0, 1), (1, 2), (0, 3), (1, 3), (2, 3)]

def incidence(edges, n):
    return np.zeros((len(edges), n))

A = incidence(edges, 4)
rank = np.linalg.matrix_rank(A)
print(A, rank)
```

```python solution
import numpy as np

edges = [(0, 1), (1, 2), (0, 3), (1, 3), (2, 3)]

def incidence(edges, n):
    A = np.zeros((len(edges), n))
    for k, (a, b) in enumerate(edges):
        A[k, a] = -1
        A[k, b] = 1
    return A

A = incidence(edges, 4)
rank = np.linalg.matrix_rank(A)
print(A, rank)
```

```python tests
import numpy as np
assert A.shape == (5, 4), f"Five branches and four nodes give a 5 x 4 matrix; got {A.shape}."
assert np.allclose(A @ np.ones(4), 0), "Each row should hold one -1 and one +1."
assert rank == 3, f"A connected graph's incidence matrix has rank n - 1 = 3; got {rank}."
assert A[2, 0] == -1 and A[2, 3] == 1, "Branch (0, 3) has -1 in column 0 and +1 in column 3."
```

::: right
Right. The constant vector is in the null space, so the rank is one less than the number of nodes.
:::
:::

::: check
kind: python

## Write `null_space(M)` from the SVD, and set `loops = null_space(A.T)` for the lab circuit (its incidence matrix is in the starter).

```python starter
import numpy as np

A = np.array([[-1, 1, 0, 0], [0, -1, 1, 0], [-1, 0, 0, 1], [0, -1, 0, 1], [0, 0, -1, 1]], dtype=float)

def null_space(M):
    return np.zeros((M.shape[1], 1))

loops = null_space(A.T)
print(loops)
```

```python solution
import numpy as np

A = np.array([[-1, 1, 0, 0], [0, -1, 1, 0], [-1, 0, 0, 1], [0, -1, 0, 1], [0, 0, -1, 1]], dtype=float)

def null_space(M):
    u, s, vt = np.linalg.svd(M)
    r = np.sum(s > 1e-10 * s[0])
    return vt[r:].T

loops = null_space(A.T)
print(loops)
```

```python tests
import numpy as np
assert loops.shape == (5, 2), f"There are 5 - 4 + 1 = 2 independent loops; got shape {loops.shape}."
assert np.allclose(A.T @ loops, 0), "Every loop current pattern satisfies KCL: A.T @ loops = 0."
assert np.allclose(loops.T @ loops, np.eye(2)), "The SVD gives an orthonormal basis."
mesh = np.array([1, 0, -1, 1, 0.0])
coef = loops.T @ mesh
assert np.allclose(loops @ coef, mesh), "The mesh through R3, R1 and R4 should be a combination of the basis."
```

::: right
Right. The SVD's basis is orthonormal rather than the meshes themselves, but it spans the same loops.
:::
:::

::: check
kind: python

## Assemble $G = A_r^TCA_r$ with $C$ = diag(1, 1, 1, 1, 0.5) mS, solve for 1 mA into node 0, and set `v` to the three node voltages.

```python starter
import numpy as np

A = np.array([[-1, 1, 0, 0], [0, -1, 1, 0], [-1, 0, 0, 1], [0, -1, 0, 1], [0, 0, -1, 1]], dtype=float)
C = np.diag([1, 1, 1, 1, 0.5])
v = np.zeros(3)
print(v)
```

```python solution
import numpy as np

A = np.array([[-1, 1, 0, 0], [0, -1, 1, 0], [-1, 0, 0, 1], [0, -1, 0, 1], [0, 0, -1, 1]], dtype=float)
C = np.diag([1, 1, 1, 1, 0.5])
Ar = A[:, :3]
G = Ar.T @ C @ Ar
v = np.linalg.solve(G, [1, 0, 0])
print(v)
```

```python tests
import numpy as np
assert np.allclose(v, [7 / 11, 3 / 11, 2 / 11]), f"The node voltages are 0.636, 0.273 and 0.182 V; got {v}."
```

::: right
Right. $A^TCA$ builds the same matrix you'd write by inspection, and it does so for any circuit you can list as branches.
:::
:::

::: check
kind: python

## Check Tellegen's theorem: append 0 V for ground to `v`, form the branch voltages `e = A @ u` and currents `w = C @ e`, and set `p_branches = e @ w` and `p_source` to the power the 1 mA source delivers.

```python starter
import numpy as np

A = np.array([[-1, 1, 0, 0], [0, -1, 1, 0], [-1, 0, 0, 1], [0, -1, 0, 1], [0, 0, -1, 1]], dtype=float)
C = np.diag([1, 1, 1, 1, 0.5])
v = np.linalg.solve(A[:, :3].T @ C @ A[:, :3], [1, 0, 0])
p_branches = p_source = 0
print(p_branches, p_source)
```

```python solution
import numpy as np

A = np.array([[-1, 1, 0, 0], [0, -1, 1, 0], [-1, 0, 0, 1], [0, -1, 0, 1], [0, 0, -1, 1]], dtype=float)
C = np.diag([1, 1, 1, 1, 0.5])
v = np.linalg.solve(A[:, :3].T @ C @ A[:, :3], [1, 0, 0])
u = np.append(v, 0)
e = A @ u
w = C @ e
p_branches = e @ w
p_source = v[0] * 1
print(p_branches, p_source)
```

```python tests
assert abs(p_source - 7 / 11) < 1e-12, f"The source delivers 0.636 mW; got {p_source}."
assert abs(p_branches - p_source) < 1e-12, f"The resistors take exactly what the source delivers; got {p_branches} against {p_source}."
```

::: right
Right. The balance holds to rounding error, and it would for any circuit: it's $\mathbf{u}^TA^TCA\mathbf{u} = \mathbf{v}^T\mathbf{f}$.
:::
:::

::: explain
## Why is the incidence matrix's rank always one less than the number of nodes for a connected circuit?

::: model
Each row of $A$ measures a voltage difference across a branch, so raising every node's voltage by the same amount changes no row: the constant vector is always in the null space. In a connected circuit, nothing else is. If $A\mathbf{u} = \mathbf{0}$, every branch has zero voltage across it, so neighboring nodes have equal voltages, and following branches from any node reaches all the others, forcing every voltage to be the same. The null space is exactly the line of constant vectors, dimension 1, so the rank is $n - 1$. Grounding one node removes that freedom, which is why the reduced matrix $A_r^TCA_r$ is invertible.
:::
:::

::: practice

::: check
given: n = 3..40 int; b = 41..80 int
answer: b - n + 1
tolerance: 0

## Loop basis size for {n} nodes and {b} branches?

::: misses
- [any] $b - n + 1$.
:::
:::

::: check
given: g1 = 0.1..10; g2 = 0.1..10; g3 = 0.1..10
answer: g1 + g2 + g3
tolerance: 0.5%

## Diagonal entry of $G$ for a node with {g1}, {g2} and {g3} mS?

::: misses
- [any] The sum of the conductances at the node.
:::
:::
:::
