Graphs as Resistor Networks
Replace every edge of a graph by a resistor, connect a battery between two vertices, and the currents that flow are the solution of a linear system in the Laplacian. This physical picture is the starting point of the second half of the course. Electrical flows are smooth (they spread over many paths), they are optimal for a quadratic energy, and they can be computed by solving , which is possible in nearly linear time. Modern algorithms for cuts, flows and sampling use them as a primitive. This lesson sets up the dictionary between circuits and linear algebra; Resistor Networks in the linear-algebra course is the elementary version.
Ohm, Kirchhoff and the Laplacian
Give edge a resistance and conductance (the edge weight). Inject an external current at each vertex (positive: current enters, negative: leaves), with . The unknowns are potentials (voltages) and currents on edges, oriented so that .
- Ohm's law: : current flows from high to low potential.
- Kirchhoff's current law: the current leaving through edges equals the current injected: .
Substituting the first into the second,
In matrix form with the signed incidence matrix and : currents are , Kirchhoff's law is , and .
Existence and uniqueness. For a connected graph, , so is solvable iff (total injection zero), and the solution is unique up to adding a constant: potentials are only defined relative to a reference. The canonical choice is , where is the pseudoinverse (), giving the solution with . In practice one grounds a vertex: set and solve the reduced system with row and column deleted, which is positive definite for a connected graph.
The program sends 1 ampere from to in a small network, solves by grounding , and checks both laws.
import numpy as np
names = ["s", "a", "b", "c", "t"]
# (u, v, resistance in ohms)
resistors = [("s", "a", 1), ("s", "b", 2), ("a", "b", 1), ("a", "c", 2), ("b", "c", 1), ("c", "t", 1), ("b", "t", 3)]
idx = {v: i for i, v in enumerate(names)}
n = len(names)
L = np.zeros((n, n))
for u, v, r in resistors:
i, j, w = idx[u], idx[v], 1 / r
L[i, i] += w; L[j, j] += w; L[i, j] -= w; L[j, i] -= w
b = np.zeros(n); b[idx["s"]], b[idx["t"]] = 1, -1 # 1 A in at s, out at t
keep = [i for i in range(n) if i != idx["t"]] # ground t: x_t = 0
x = np.zeros(n)
x[keep] = np.linalg.solve(L[np.ix_(keep, keep)], b[keep])
print("potentials:", {v: round(float(x[idx[v]]), 4) for v in names})
for u, v, r in resistors:
print(f" current {u}->{v}: {(x[idx[u]] - x[idx[v]]) / r:+.4f} A")
print("Kirchhoff residual L x - b:", np.round(L @ x - b, 12) + 0.0)
xp = np.linalg.pinv(L) @ b
print("pinv solution minus grounded solution is constant:", np.round(xp - x, 6) + 0.0)
energy = sum((x[idx[u]] - x[idx[v]]) ** 2 / r for u, v, r in resistors)
print(f"energy sum r_e f_e^2 = {energy:.4f} = x^T L x = {float(x @ L @ x):.4f} = x_s - x_t = {float(x[idx['s']]):.4f}")potentials: {'s': 1.8592, 'a': 1.2817, 'b': 1.0141, 'c': 0.662, 't': 0.0}
current s->a: +0.5775 A
current s->b: +0.4225 A
current a->b: +0.2676 A
current a->c: +0.3099 A
current b->c: +0.3521 A
current c->t: +0.6620 A
current b->t: +0.3380 A
Kirchhoff residual L x - b: [0. 0. 0. 0. 0.]
pinv solution minus grounded solution is constant: [-0.96338 -0.96338 -0.96338 -0.96338 -0.96338]
energy sum r_e f_e^2 = 1.8592 = x^T L x = 1.8592 = x_s - x_t = 1.8592
The energy dissipated equals the potential difference because the current is 1: in general , power = voltage times current.
Harmonic functions and random walks
At a vertex with no external current (), Kirchhoff's law says : the potential is the weighted average of its neighbours'. Such a function is harmonic at . Harmonic functions obey the maximum principle (maximum and minimum are attained on the boundary, where current is injected) and are determined uniquely by their boundary values.
That gives a probabilistic reading. Fix , (a battery instead of a current source) and let be the probability that the random walk from (step to with probability ) reaches before . Then , , and conditioning on the first step shows is harmonic everywhere else. By uniqueness, : voltages are hitting probabilities (Kakutani, 1945; developed in Doyle and Snell's Random Walks and Electric Networks, 1984).
import random
import numpy as np
names = ["s", "a", "b", "c", "t"]
resistors = [("s", "a", 1), ("s", "b", 2), ("a", "b", 1), ("a", "c", 2), ("b", "c", 1), ("c", "t", 1), ("b", "t", 3)]
idx = {v: i for i, v in enumerate(names)}
n = len(names)
W = np.zeros((n, n))
for u, v, r in resistors:
W[idx[u], idx[v]] = W[idx[v], idx[u]] = 1 / r
L = np.diag(W.sum(axis=1)) - W
# battery: x_s = 1, x_t = 0; solve for the interior vertices
inner = [idx[v] for v in "abc"]
rhs = W[np.ix_(inner, [idx["s"]])].ravel() * 1.0
x_inner = np.linalg.solve(L[np.ix_(inner, inner)], rhs)
rng = random.Random(1945)
def hits_s_first(start):
u = start
while u not in (idx["s"], idx["t"]):
u = rng.choices(range(n), weights=W[u])[0]
return u == idx["s"]
trials = 10000
for v, xv in zip("abc", x_inner):
est = sum(hits_s_first(idx[v]) for _ in range(trials)) / trials
print(f"vertex {v}: potential {xv:.4f} walk reaches s before t in {est:.4f} of {trials} walks")vertex a: potential 0.6894 walk reaches s before t in 0.6852 of 10000 walks
vertex b: potential 0.5455 walk reaches s before t in 0.5493 of 10000 walks
vertex c: potential 0.3561 walk reaches s before t in 0.3608 of 10000 walks
Thomson's principle
Among all flows that satisfy the demands (), the electrical flow minimizes the energy .
Proof. Any feasible is with (a circulation). Then , and the middle term is by Ohm's law . So , with equality only for .
This variational form is what makes electrical flows useful in optimization: the max-flow algorithm of Christiano et al. minimizes a weighted energy as a smooth proxy for congestion. It also gives Rayleigh's monotonicity law: increasing any resistance cannot decrease the energy of the optimal flow, so effective resistances can only grow.
In C++
Gauss-Seidel solves by sweeping over the vertices and setting each potential to the value that satisfies its own Kirchhoff equation, , using the newest values. For a grounded Laplacian (positive definite) it always converges, but slowly on large grids: the error shrinks by about per sweep. The program solves the battery problem on a grid with on the left column and on the right column.
#include <cmath>
#include <cstdio>
#include <vector>
int main() {
const int R = 20, C = 20;
auto id = [&](int i, int j) { return i * C + j; };
std::vector<double> x(R * C, 0.0);
for (int i = 0; i < R; ++i) x[id(i, 0)] = 1.0; // left column held at 1 V, right at 0 V
for (int sweep = 1; sweep <= 2000; ++sweep) {
double change = 0;
for (int i = 0; i < R; ++i)
for (int j = 1; j + 1 < C; ++j) { // interior columns are free
double s = 0;
int deg = 0;
if (i > 0) { s += x[id(i - 1, j)]; ++deg; }
if (i + 1 < R) { s += x[id(i + 1, j)]; ++deg; }
s += x[id(i, j - 1)] + x[id(i, j + 1)];
deg += 2;
double nx = s / deg; // harmonic: average of the neighbours
change = std::fmax(change, std::fabs(nx - x[id(i, j)]));
x[id(i, j)] = nx;
}
if (sweep == 10 || sweep == 100 || sweep == 1000 || change < 1e-12) {
std::printf("sweep %4d: largest update %.2e, x at row 0: %.4f %.4f %.4f\n",
sweep, change, x[id(0, 5)], x[id(0, 10)], x[id(0, 15)]);
if (change < 1e-12) break;
}
}
double current = 0; // current leaving the left column
for (int i = 0; i < R; ++i) current += x[id(i, 0)] - x[id(i, 1)];
std::printf("total current %.6f A, so the effective resistance is %.6f ohm\n", current, 1.0 / current);
}sweep 10: largest update 2.36e-02, x at row 0: 0.1494 0.0089 0.0003
sweep 100: largest update 2.13e-03, x at row 0: 0.6200 0.3225 0.1213
sweep 1000: largest update 7.17e-09, x at row 0: 0.7368 0.4737 0.2105
sweep 1633: largest update 9.97e-13, x at row 0: 0.7368 0.4737 0.2105
total current 1.052632 A, so the effective resistance is 0.950000 ohm
With no vertical current at all (by symmetry every row is the same), the potential falls linearly, , and the network is 20 parallel chains of 19 one-ohm resistors: ohm. Gauss-Seidel needs hundreds of sweeps to get there; conjugate gradient and the solvers after it do much better.
Test yourself
Ohm's and Kirchhoff's laws together give which equation for the potentials with injected currents ?
- with (edge weights = conductances)
When does have a solution for a connected graph?
- Always
- Exactly when
- When
- When is invertible
With and , what is the potential of another vertex?
- The distance from to
- The probability that a random walk from hits before
- The degree of
- The expected time to reach
What does Thomson's principle say?
- The electrical flow maximizes the flow value
- Among all flows meeting the demands, the electrical flow has the least energy
- Currents are integers
- Potentials are unique