Sub topic 12
Building the Conductance Matrix in Code
This chapter assumes you can write KCL equations at a node, rewrite them as G v = i, and run basic NumPy. It turns the hand method into a program. You will see why every resistor edits the matrix in the same four places, and how to build the matrix from a list of components.
Why build the matrix by program
Writing nodal equations by hand works for two or three nodes. At ten nodes you will make a sign error somewhere. The conductance matrix has a regular structure, so a program can build it from the component list. This is called stamping: each component adds its own small, fixed pattern to G and i. Circuit simulators such as SPICE use the same idea.
The pattern comes from the KCL equation at a node. For a node k, the equation is
(sum of conductances touching k) × Vk − (sum over neighbors j of gkj × V_j) = (source current entering k)
So the diagonal entry G[k][k] is the sum of all conductances attached to node k. The off-diagonal entry G[k][j] is the negative of the total conductance directly between nodes k and j.
The stamps
Use the convention that node 0 is ground and nodes 1 to n are unknowns. Ground has no row or column, because its voltage is zero by definition. Matrix index p therefore belongs to node p+1.
| Component | Effect on G | Effect on i |
|---|---|---|
| Resistor, g = 1/R, between nodes a and b (both non-ground) | Add g to G[a][a] and G[b][b]. Subtract g from G[a][b] and G[b][a]. | None |
| Resistor from node a to ground | Add g to G[a][a] only | None |
| Current source pushing I into node b, out of node a | None | Add I to i[b]. Subtract I from i[a]. |
| Current source into node b from ground | None | Add I to i[b] only |
Two properties follow from the table:
- Contributions accumulate. Two resistors between the same pair of nodes are in parallel, and their conductances add. Your code must use
+=and never=. - G is symmetric. Every resistor writes equal values at [a][b] and [b][a]. A circuit with only resistors and independent sources always gives a symmetric G. Dependent sources break this, as the dependent sources chapter explains.
A first implementation
The code below splits stamping into small functions, so each one matches a row of the table. It also validates its input, because a wrong node number otherwise fails silently or wraps around to the wrong row.
import numpy as np
def stamp_resistor(G, a, b, ohms):
"""Add a resistor between nodes a and b. Node 0 is ground."""
if ohms <= 0:
raise ValueError(f"resistance must be positive, got {ohms}")
if a == b:
raise ValueError("a resistor cannot connect a node to itself")
g = 1.0 / ohms
for node in (a, b):
if node > 0:
G[node - 1, node - 1] += g
if a > 0 and b > 0:
G[a - 1, b - 1] -= g
G[b - 1, a - 1] -= g
def stamp_current_source(i, frm, to, amps):
"""Add a source that pushes `amps` into node `to` and out of node `frm`."""
if to > 0:
i[to - 1] += amps
if frm > 0:
i[frm - 1] -= amps
def build_nodal(n, resistors, current_sources):
for a, b, *_ in resistors + current_sources:
if not (0 <= a <= n and 0 <= b <= n):
raise ValueError(f"node out of range 0..{n}: {a}, {b}")
G = np.zeros((n, n))
i = np.zeros(n)
for a, b, ohms in resistors:
stamp_resistor(G, a, b, ohms)
for frm, to, amps in current_sources:
stamp_current_source(i, frm, to, amps)
return G, i
# Two-node circuit from earlier in the tutorial:
# 2 A into node 1, R1 = 4 ohm (1 to ground),
# R2 = 2 ohm (1 to 2), R3 = 6 ohm (2 to ground).
G, i = build_nodal(2, [(1, 0, 4), (1, 2, 2), (2, 0, 6)], [(0, 1, 2)])
print(G)
print(i)
v = np.linalg.solve(G, i)
print(v) # [5.33333333 4. ]The printed matrix is [[0.75, -0.5], [-0.5, 0.66666667]]. You can confirm the first diagonal entry by hand: 1/4 + 1/2 = 0.75.
A three-node example with a check
Larger circuits only need a longer component list. Consider this circuit:
- A 3 A source pushes current into node 1.
- R1 = 2 Ω connects node 1 to ground.
- R2 = 4 Ω connects node 1 to node 2.
- R3 = 4 Ω connects node 2 to ground.
- R4 = 2 Ω connects node 2 to node 3.
- R5 = 1 Ω connects node 3 to ground.
By hand, the conductances are 0.5, 0.25, 0.25, 0.5 and 1 S. The matrix is
- Row 1: 0.75, −0.25, 0
- Row 2: −0.25, 1.0, −0.5
- Row 3: 0, −0.5, 1.5
The right-hand side is [3, 0, 0]. Solving gives V1 = 40/9 ≈ 4.444 V, V2 = 4/3 ≈ 1.333 V and V3 = 4/9 ≈ 0.444 V. The next program reproduces this, and also runs two checks.
import numpy as np
def stamp_resistor(G, a, b, ohms):
g = 1.0 / ohms
for node in (a, b):
if node > 0:
G[node - 1, node - 1] += g
if a > 0 and b > 0:
G[a - 1, b - 1] -= g
G[b - 1, a - 1] -= g
n = 3
resistors = [(1, 0, 2), (1, 2, 4), (2, 0, 4), (2, 3, 2), (3, 0, 1)]
G = np.zeros((n, n))
i = np.array([3.0, 0.0, 0.0]) # 3 A from ground into node 1
for a, b, ohms in resistors:
stamp_resistor(G, a, b, ohms)
v = np.linalg.solve(G, i)
print(v) # approximately [4.44444444 1.33333333 0.44444444]
# Check 1: the solution must satisfy every KCL equation.
print(np.allclose(G @ v, i)) # True
# Check 2: power balance. The source supplies 3 A at V1.
volts = np.concatenate(([0.0], v)) # prepend ground so node numbers index directly
supplied = 3.0 * volts[1]
dissipated = sum((volts[a] - volts[b]) ** 2 / r for a, b, r in resistors)
print(supplied, dissipated) # both 13.333...
print(np.isclose(supplied, dissipated)) # TrueThe volts array has ground prepended at index 0. After that, a node number indexes it directly and no off-by-one arithmetic is needed.
Common errors
- Assigning instead of accumulating. Writing
G[a-1, a-1] = gkeeps only the last resistor at that node. Always use+=. - Stamping ground. Node 0 has no row, so
G[-1, -1]would silently edit the last node through Python's negative indexing. Theif node > 0guard prevents this. - Reversing a current source. The source pushes current into the
tonode. If the answer has the wrong sign everywhere, check the order offrmandto. - Mixing units. Use ohms and amps together, or kilohms and milliamps together. A kilohm value with an amp source gives voltages that are off by 1000.
- Trusting
solveblindly. If a sub-circuit has no resistive path to ground, G is singular. NumPy raisesLinAlgErrorin the exact-singular case, and in near-singular cases it can return huge, meaningless numbers. The next-but-one chapter covers this. For now, keep the residual check in your code.
Voltage sources and scale
The stamps above cover resistors and current sources only. A voltage source from a node to ground fixes that node's voltage, so one simple approach is to drop its unknown. Every conductance g that connects the known node k to an unknown node j then moves to the right-hand side as g × V_k added to i[j]. The second code example in this tutorial's plan does this for a single node. Floating voltage sources need the supernode treatment from the earlier chapter, or an extra row in the matrix, which this chapter does not cover.
For large networks, G is mostly zeros, because each node touches only a few neighbors. Storing it as a dense array wastes memory. scipy.sparse stores only the nonzero entries, and its solvers handle thousands of nodes. The stamping logic stays identical. Only the container changes.
Exercise
A circuit has two resistors that both connect node 1 to node 2, one of 3 Ω and one of 6 Ω. No other component touches node 1 or 2. What does the resistor stamping contribute to G[0][0] and G[0][1]?
Show answer
Each resistor stamps its own conductance, and the contributions add. The conductances are 1/3 S and 1/6 S, so the total is 1/2 S. G[0][0] gets +0.5 from these two resistors and G[0][1] gets −0.5. This matches the single equivalent resistor of 2 Ω (3 Ω in parallel with 6 Ω).
Exercise
In the three-node example, a 1 Ω resistor is added from node 2 to node 3, in parallel with R4. Which entries of G change, and by how much?
Show answer
The added conductance is 1 S. G[1][1] (node 2 diagonal) and G[2][2] (node 3 diagonal) each increase by 1, and G[1][2] and G[2][1] each decrease by 1. The new values are G[1][1] = 2.0, G[2][2] = 2.5 and G[1][2] = G[2][1] = −1.5. Entries involving node 1 do not change.