Electrical Flows and Almost-Linear Maximum Flow
Maximum flow is the textbook problem of combinatorial optimization, and for decades its fastest algorithms were combinatorial: augmenting paths, blocking flows, push-relabel (Graph Algorithms). The breakthrough of the last fifteen years came from continuous optimization and Laplacian solvers. Christiano, Kelner, Mądry, Spielman and Teng (2011) showed that a sequence of electrical flows, reweighted by multiplicative weights, approximates the maximum flow in an undirected graph faster than any combinatorial method. A line of work through interior-point methods ended in 2022 with Chen, Kyng, Liu, Peng, Probst Gutenberg and Sachdeva's almost-linear-time algorithm for exact maximum flow and minimum-cost flow on directed graphs. This lesson implements the electrical-flow idea and states the modern results carefully.
Why electrical flows?
Augmenting-path algorithms push flow along one path at a time. An electrical flow spreads the flow over all paths at once, in proportion to how "easy" they are. For an undirected graph with capacities , set resistances and send units from to electrically. By Thomson's principle (Graphs as Resistor Networks) the result minimizes , the sum of squared congestions, among all - flows of value . If a flow with all congestions at most 1 exists (that is, max flow), its energy is at most , so the electrical flow's energy is at most too: on average the congestion is at most 1, though a few edges may be overloaded by up to a factor . One Laplacian solve, nearly linear time, computes it.
Compare it with a maximum flow found by augmenting paths on the network below.
import numpy as np
names = ["s", "a", "b", "c", "d", "t"]
caps = [("s", "a", 4), ("s", "b", 3), ("a", "b", 2), ("a", "c", 3), ("b", "d", 4), ("c", "d", 2), ("c", "t", 3), ("d", "t", 4)]
idx = {v: i for i, v in enumerate(names)}
n = len(names)
F = 7.0 # the maximum flow value of this network
L = np.zeros((n, n))
for u, v, c in caps:
i, j, g = idx[u], idx[v], c * c # conductance 1/r_e = u_e^2
L[i, i] += g; L[j, j] += g; L[i, j] -= g; L[j, i] -= g
b = np.zeros(n); b[idx["s"]], b[idx["t"]] = F, -F
x = np.zeros(n)
x[:-1] = np.linalg.solve(L[:-1, :-1], b[:-1]) # ground t
print("edge capacity electrical flow congestion")
for u, v, c in caps:
f = c * c * (x[idx[u]] - x[idx[v]])
print(f"{u}-{v} {c:8} {f:15.4f} {abs(f) / c:10.4f}")
cong = max(abs(c * c * (x[idx[u]] - x[idx[v]])) / c for u, v, c in caps)
print(f"max congestion {cong:.4f}: scaling down gives a feasible flow of value {F / cong:.4f} (optimum {F:.0f})")edge capacity electrical flow congestion
s-a 4 3.6364 0.9091
s-b 3 3.3636 1.1212
a-b 2 0.5858 0.2929
a-c 3 3.0505 1.0168
b-d 4 3.9495 0.9874
c-d 2 0.2174 0.1087
c-t 3 2.8331 0.9444
d-t 4 4.1669 1.0417
max congestion 1.1212: scaling down gives a feasible flow of value 6.2433 (optimum 7)
One electrical flow already routes most of the optimum feasibly. The overloaded edges are the ones a multiplicative-weights loop must fix.
The Christiano-Kelner-Mądry-Spielman-Teng algorithm (the idea)
Combine electrical flows with the multiplicative weights framework of Approximately Solving LPs and Flows with MWU:
electrical_mwu(G, u, s, t, F, ε, iterations)
1 w_e ← 1 for every edge
2 repeat iterations times
3 r_e ← (w_e + ε·Σw / (3m)) / u_e² (resistances from the current weights)
4 f ← electrical s-t flow of value F with resistances r (one Laplacian solve)
5 w_e ← w_e · (1 + ε·|f_e| / (ρ u_e)) (penalize congested edges)
6 add f to the running sum
7 return the average flow (value F; its congestion → 1 + O(ε) if F ≤ max flow)The energy argument above shows that the weighted average congestion of each electrical flow is at most , which is exactly the "oracle" guarantee MWU needs; the width (the largest congestion an oracle answer can have) is by the energy bound. MWU then needs iterations of one nearly-linear Laplacian solve each: time. Christiano et al. improved this to by removing edges whose congestion is too high (there cannot be many, and removing them barely changes the effective resistance between and ), which lowers the width to . Running this on a cut sparsifier of the graph gives their headline bound . A binary search over finds the max flow value, and a dual version of the method, which reads cuts off the potentials of electrical flows, finds a -approximate minimum cut in time.
The program runs the loop on a random undirected network with integer capacities (with the aggressive practical choice instead of the worst-case width) and compares with the exact maximum flow from Edmonds-Karp.
import random
from collections import deque
import numpy as np
r = random.Random(2011)
n = 24
edges = [(u, v, r.randint(1, 10)) for u in range(n) for v in range(u + 1, n) if r.random() < 0.2]
m, s, t = len(edges), 0, n - 1
def max_flow():
cap, adj = {}, [[] for _ in range(n)]
for u, v, c in edges:
for a, b in ((u, v), (v, u)):
if (a, b) not in cap:
adj[a].append(b); cap[(a, b)] = 0
cap[(a, b)] += c
flow = 0
while True:
prev, q = {s: None}, deque([s])
while q and t not in prev:
a = q.popleft()
for b in adj[a]:
if b not in prev and cap[(a, b)] > 0:
prev[b] = a; q.append(b)
if t not in prev:
return flow
path, b = [], t
while prev[b] is not None:
path.append((prev[b], b)); b = prev[b]
push = min(cap[e] for e in path)
for a, b in path:
cap[(a, b)] -= push; cap[(b, a)] += push
flow += push
def electrical(res, F):
L = np.zeros((n, n))
for (u, v, c), re in zip(edges, res):
L[u, u] += 1 / re; L[v, v] += 1 / re; L[u, v] -= 1 / re; L[v, u] -= 1 / re
b = np.zeros(n); b[s], b[t] = F, -F
x = np.zeros(n)
x[:-1] = np.linalg.solve(L[:-1, :-1], b[:-1]) # ground t = n - 1
return np.array([(x[u] - x[v]) / re for (u, v, c), re in zip(edges, res)]), x
opt = max_flow()
cap = np.array([c for _, _, c in edges], dtype=float)
print(f"{n} vertices, {m} edges, exact maximum flow {opt} (Edmonds-Karp)")
eps, rho = 0.1, 1.0
w, total = np.ones(m), np.zeros(m)
for it in range(1, 501):
res = (w + eps * w.sum() / (3 * m)) / cap ** 2
f, x = electrical(res, opt)
w *= 1 + eps * np.abs(f) / (rho * cap)
total += f
if it in (1, 5, 20, 100, 500):
cong = float(np.abs(total / it / cap).max())
print(f"after {it:3} electrical flows: max congestion of the average {cong:.4f}, "
f"feasible value {opt / cong:.3f} = {opt / cong / opt:.1%} of the optimum")
# an approximate minimum cut from the last potentials: sweep the threshold over x
order = np.argsort(-x, kind="stable")
best = min(sum(c for u, v, c in edges if (u in set(order[:k].tolist())) != (v in set(order[:k].tolist())))
for k in range(1, n) if s in order[:k] and t not in order[:k])
print(f"best threshold cut of the electrical potentials: capacity {best} (minimum cut = {opt})")24 vertices, 46 edges, exact maximum flow 22 (Edmonds-Karp)
after 1 electrical flows: max congestion of the average 1.2039, feasible value 18.274 = 83.1% of the optimum
after 5 electrical flows: max congestion of the average 1.1950, feasible value 18.410 = 83.7% of the optimum
after 20 electrical flows: max congestion of the average 1.1396, feasible value 19.305 = 87.7% of the optimum
after 100 electrical flows: max congestion of the average 1.0258, feasible value 21.447 = 97.5% of the optimum
after 500 electrical flows: max congestion of the average 1.0049, feasible value 21.893 = 99.5% of the optimum
best threshold cut of the electrical potentials: capacity 22 (minimum cut = 22)
The averaged flow approaches the optimum, and a sweep over the potentials of the last electrical flow finds a cut whose capacity certifies optimality (by max-flow min-cut duality, no flow can exceed it).
In C++
The same loop with the Laplacian solves done by conjugate gradient, on a grid with random capacities from = corner to = opposite corner, against Edmonds-Karp.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <queue>
#include <random>
#include <vector>
struct E { int u, v; double cap; };
int n;
std::vector<E> edges;
int max_flow(int s, int t) { // Edmonds-Karp on the undirected network
std::vector<std::vector<double>> c(n, std::vector<double>(n, 0.0));
for (auto& e : edges) { c[e.u][e.v] += e.cap; c[e.v][e.u] += e.cap; }
double flow = 0;
while (true) {
std::vector<int> prev(n, -1);
prev[s] = s;
std::queue<int> q;
q.push(s);
while (!q.empty() && prev[t] < 0) {
int a = q.front(); q.pop();
for (int b = 0; b < n; ++b)
if (prev[b] < 0 && c[a][b] > 1e-12) { prev[b] = a; q.push(b); }
}
if (prev[t] < 0) return int(flow + 0.5);
double push = 1e18;
for (int b = t; b != s; b = prev[b]) push = std::min(push, c[prev[b]][b]);
for (int b = t; b != s; b = prev[b]) { c[prev[b]][b] -= push; c[b][prev[b]] += push; }
flow += push;
}
}
// electrical flow of value F from s to t with conductances g: CG on L x = b, then f_e = g_e (x_u - x_v)
std::vector<double> electrical(const std::vector<double>& g, int s, int t, double F) {
auto mulL = [&](const std::vector<double>& x, std::vector<double>& y) {
std::fill(y.begin(), y.end(), 0.0);
for (std::size_t i = 0; i < edges.size(); ++i) {
double d = g[i] * (x[edges[i].u] - x[edges[i].v]);
y[edges[i].u] += d; y[edges[i].v] -= d;
}
};
std::vector<double> x(n, 0.0), r(n, 0.0), p, q(n);
r[s] = F; r[t] = -F;
p = r;
double rr = F * F * 2;
for (int it = 0; it < 10 * n && rr > 1e-24; ++it) {
mulL(p, q);
double pq = 0;
for (int i = 0; i < n; ++i) pq += p[i] * q[i];
double a = rr / pq, rr2 = 0;
for (int i = 0; i < n; ++i) { x[i] += a * p[i]; r[i] -= a * q[i]; rr2 += r[i] * r[i]; }
for (int i = 0; i < n; ++i) p[i] = r[i] + rr2 / rr * p[i];
rr = rr2;
}
std::vector<double> f(edges.size());
for (std::size_t i = 0; i < edges.size(); ++i) f[i] = g[i] * (x[edges[i].u] - x[edges[i].v]);
return f;
}
int main() {
const int K = 6;
n = K * K;
std::mt19937_64 rng(2022);
for (int i = 0; i < K; ++i)
for (int j = 0; j < K; ++j) {
if (j + 1 < K) edges.push_back({i * K + j, i * K + j + 1, double(1 + rng() % 9)});
if (i + 1 < K) edges.push_back({i * K + j, (i + 1) * K + j, double(1 + rng() % 9)});
}
const int s = 0, t = n - 1;
const std::size_t m = edges.size();
int opt = max_flow(s, t);
std::printf("%d vertices, %zu edges, maximum flow %d\n", n, m, opt);
const double eps = 0.1;
std::vector<double> w(m, 1.0), total(m, 0.0), g(m);
for (int it = 1; it <= 400; ++it) {
double W = 0;
for (double v : w) W += v;
for (std::size_t e = 0; e < m; ++e) g[e] = edges[e].cap * edges[e].cap / (w[e] + eps * W / (3.0 * m));
auto f = electrical(g, s, t, opt);
for (std::size_t e = 0; e < m; ++e) { w[e] *= 1 + eps * std::fabs(f[e]) / edges[e].cap; total[e] += f[e]; }
if (it == 1 || it == 10 || it == 100 || it == 400) {
double cong = 0;
for (std::size_t e = 0; e < m; ++e) cong = std::max(cong, std::fabs(total[e] / it) / edges[e].cap);
std::printf("after %3d flows: feasible value %.3f (%.1f%% of the optimum)\n", it, opt / cong, 100.0 / cong);
}
}
}36 vertices, 60 edges, maximum flow 4
after 1 flows: feasible value 3.419 (85.5% of the optimum)
after 10 flows: feasible value 3.508 (87.7% of the optimum)
after 100 flows: feasible value 3.884 (97.1% of the optimum)
after 400 flows: feasible value 3.970 (99.3% of the optimum)
From approximate to exact, and to almost-linear time
The electrical-flow line of work developed in two directions.
Approximate undirected max flow in nearly linear time. Sherman (2013) and Kelner, Lee, Orecchia and Sidford (2014) replaced the electrical flows by congestion approximators and gradient descent on a smoothed objective (an "oblivious routing" preconditioner), reaching time; Peng (2016) brought it to for constant .
Exact max flow through interior-point methods. An interior-point method (Interior-Point Methods) for the flow LP takes steps, and each step is a weighted Laplacian solve (an electrical flow). Mądry (2013) took fewer steps on unit-capacity graphs, ; Lee and Sidford (2014) gave for general capacities; van den Brand et al. (2021) reached by maintaining the IPM's Laplacian systems with data structures.
Theorem (Chen, Kyng, Liu, Peng, Probst Gutenberg and Sachdeva, 2022; stated). There is a randomized algorithm that computes exact maximum flows and minimum-cost flows on directed graphs with edges and integral demands, costs and capacities bounded by in time, with high probability.
How it works (idea only). The algorithm is an interior-point method on the min-cost flow LP, driven by an -type potential function, with iterations, each needing only an approximate min-ratio cycle: a cycle minimizing for the current gradient and lengths . Because consecutive iterations change the gradients and lengths only slightly, these cycles are maintained by a dynamic data structure built from low-stretch spanning trees (the same trees as in conjugate gradient) and a recursive hierarchy of shrinking graphs, in amortized time per iteration. A deterministic version followed (van den Brand, Chen, Kyng, Liu, Peng, Probst Gutenberg, Sachdeva and Sidford, 2023). The factor is subpolynomial but large in practice; the result settles the asymptotic complexity of max flow up to it, and it shows how far ideas from spectral graph theory (low-stretch trees, electrical flows, dynamic graph sparsification) now reach.
Test yourself
With resistances , what does the electrical - flow of value minimize?
- The maximum congestion
- The sum of squared congestions
- The number of paths used
- The cost of the flow
If is at most the maximum flow, why is the electrical flow's energy at most ?
- Because
- Because a feasible flow of value has every congestion at most 1, hence energy at most , and the electrical flow has the least energy
- Because the graph is undirected
- Because resistances are at most 1
What running time did Christiano, Kelner, Mądry, Spielman and Teng (2011) achieve for -approximate undirected max flow, before running it on a sparsifier?
- exactly
Which statement matches the result of Chen, Kyng, Liu, Peng, Probst Gutenberg and Sachdeva (2022)?
- Approximate max flow on undirected graphs in
- Exact max flow and min-cost flow on directed graphs with polynomially bounded integer data in time
- A deterministic max flow
- Max flow is NP-hard on directed graphs