Nearly-Linear-Time Laplacian Solvers
In 2004 Spielman and Teng proved that a Laplacian system with nonzeros can be solved to accuracy in time for a constant : essentially the time it takes to read the input. Every dense or iterative method before had a worse exponent on general graphs. The result launched what Teng called the Laplacian paradigm: reduce a graph problem to a sequence of Laplacian solves and inherit nearly linear running time. This lesson explains the ingredients, states the main results with their exact forms, and implements one of the simplest nearly-linear solvers, the cycle-toggling algorithm of Kelner, Orecchia, Sidford and Zhu (2013).
What "solving" means
For a connected graph and , an -approximate solution is an with
The -norm is the energy norm: the error is measured in the units of the electrical problem. All the running times below are for this guarantee (randomized algorithms: with high probability), and they extend to every symmetric diagonally dominant (SDD) system, which reduces to a Laplacian of twice the size (Gremban, 1996).
The ingredients
- Preconditioned iterative methods (Conjugate Gradient and Tree Preconditioners): with a preconditioner , the number of iterations is , each costing one multiplication by and one solve with .
- Low-stretch spanning trees: a tree with total stretch , so .
- Ultra-sparsifiers: add back to a few edges (sampled by stretch, or found via sparsification) to get edges with . A graph that is a tree plus extra edges can be shrunk, by eliminating degree-1 and degree-2 vertices (Schur complements, no fill), to a graph with vertices and edges.
- Recursion: solving with means solving a Laplacian system on a graph times smaller, which is done by the same algorithm. With the right the total work is a geometric series, nearly linear in .
The results
| Year | Authors | Running time for an -approximate solution | Main new idea |
|---|---|---|---|
| 2004 | Spielman and Teng | for a (large) constant | ultra-sparsifiers from low-stretch trees and spectral sparsification via local clustering; recursive preconditioning |
| 2010 | Koutis, Miller and Peng | sparsify by sampling edges with probabilities from the tree's stretch (an upper bound on effective resistance) | |
| 2011 | Koutis, Miller and Peng | , i.e. | better low-stretch trees and a sharper sampling analysis |
| 2013 | Kelner, Orecchia, Sidford and Zhu | no recursion: randomized cycle toggling on a tree (below) | |
| 2014 | Cohen, Kyng, Miller, Pachocki, Peng, Rao and Xu | low-stretch subgraphs and preconditioners with a better stretch-to-size tradeoff | |
| 2016 | Kyng and Sachdeva | approximate Gaussian elimination with sampled cliques; very simple |
The Spielman-Teng paper appeared at STOC 2004; its journal version, split into three papers (on sparsification, on local clustering, and on the solver itself, the last in SIAM J. Matrix Analysis and Applications, 2014), contains the full proofs. The form of Koutis, Miller and Peng is the one usually quoted as "nearly ". In practice, combinatorial multigrid, algebraic multigrid and approximate Cholesky (for example the Laplacians.jl package) are the methods of choice; the theoretical algorithms explain why such methods can work on every graph.
Cycle toggling: a simple nearly-linear solver
Kelner, Orecchia, Sidford and Zhu work with flows instead of potentials. The electrical flow is the unique flow meeting the demands () whose potential drops sum to zero around every cycle (Kirchhoff's voltage law). The algorithm:
cycle_toggling(G, r, b, T, iterations)
1 f ← the unique flow on the spanning tree T meeting the demands b
2 for each off-tree edge e = (u, v): R_e ← r_e + (tree resistance between v and u) (cycle resistance)
3 repeat iterations times
4 pick an off-tree edge e with probability proportional to R_e / r_e
5 Δ ← sum of r_c f_c around the cycle C_e = e + tree path (oriented along e)
6 push −Δ / R_e units of flow around C_e (now the voltage drop around C_e is 0)
7 potentials x: x_root ← 0, then x_v from x_parent and r f along tree edges
8 return xEach step fixes one cycle exactly and may break others slightly. The analysis shows that the energy gap shrinks by a factor in expectation per step, where (each off-tree edge contributes its stretch plus one; the tree edges, of stretch 1 each, are not counted). The starting tree flow has energy at most times the optimum, so steps suffice. With a low-stretch tree, , and with a data structure that updates a tree path in time, the total is . The implementation below walks the tree path explicitly, which costs per step but is enough to see the convergence.
import numpy as np
k = 8
n = k * k
edges = [(i * k + j, i * k + j + 1) for i in range(k) for j in range(k - 1)] + \
[(i * k + j, (i + 1) * k + j) for i in range(k - 1) for j in range(k)]
rng = np.random.default_rng(2013)
r = 10.0 ** rng.uniform(-1, 1, len(edges)) # resistances between 0.1 and 10
# spanning tree: Kruskal by increasing resistance (= maximum conductance), rooted at 0
parent_uf = list(range(n))
def find(a):
while parent_uf[a] != a:
parent_uf[a] = parent_uf[parent_uf[a]]; a = parent_uf[a]
return a
tree = []
for e in np.argsort(r, kind="stable"):
a, b2 = find(edges[e][0]), find(edges[e][1])
if a != b2:
parent_uf[a] = b2; tree.append(int(e))
adj = [[] for _ in range(n)]
for e in tree:
u, v = edges[e]; adj[u].append((v, e)); adj[v].append((u, e))
par, pedge, depth, order = [-1] * n, [-1] * n, [0] * n, [0]
for u in order: # BFS order from the root 0
for v, e in adj[u]:
if v != par[u]:
par[v], pedge[v], depth[v] = u, e, depth[u] + 1; order.append(v)
def tree_path(u, v):
"""Edges of the tree path from u to v, each with the direction it is traversed (+1 along edges[e])."""
up, down = [], []
while u != v:
if depth[u] >= depth[v]:
e = pedge[u]; up.append((e, 1 if edges[e][0] == u else -1)); u = par[u]
else:
e = pedge[v]; down.append((e, 1 if edges[e][1] == v else -1)); v = par[v]
return up + down[::-1]
b = np.zeros(n); b[0], b[n - 1] = 1.0, -1.0 # unit current between opposite corners
f = np.zeros(len(edges))
excess = b.copy()
for v in reversed(order[1:]): # route the demands up the tree
e = pedge[v]
sign = 1 if edges[e][0] == v else -1 # flow along edges[e] leaves v when sign = +1
f[e] += sign * excess[v]; excess[par[v]] += excess[v]
off = [e for e in range(len(edges)) if e not in set(tree)]
cycles = {e: [(e, 1)] + tree_path(edges[e][1], edges[e][0]) for e in off}
R = {e: sum(r[c] for c, _ in cycles[e]) for e in off}
tau = sum(R[e] / r[e] for e in off)
probs = np.array([R[e] / r[e] for e in off]) / tau
W = np.diag(1 / r)
Bm = np.zeros((len(edges), n))
for i, (u, v) in enumerate(edges):
Bm[i, u], Bm[i, v] = 1, -1
L = Bm.T @ W @ Bm
xstar = np.linalg.pinv(L) @ b
def potentials(f):
x = np.zeros(n)
for v in order[1:]:
e = pedge[v]
drop = r[e] * f[e] # x_tail - x_head along edges[e]
x[v] = x[par[v]] - drop if edges[e][0] == par[v] else x[par[v]] + drop
return x - x.mean()
def rel_error(x):
d = x - xstar
return float(np.sqrt(d @ L @ d / (xstar @ L @ xstar)))
print(f"{n} vertices, {len(edges)} edges, {len(off)} off-tree edges, tau = {tau:.1f}")
picks = rng.choice(len(off), size=2000, p=probs)
for it, i in enumerate(picks, start=1):
e = off[i]
delta = sum(s * r[c] * f[c] for c, s in cycles[e])
for c, s in cycles[e]:
f[c] -= s * delta / R[e]
if it in (100, 500, 1000, 2000):
print(f"after {it:4} toggles: relative error in the L-norm {rel_error(potentials(f)):.2e}")
print(f"R_eff(corner, corner) = {float(xstar[0] - xstar[-1]):.6f}, from the toggled flow {float(potentials(f)[0] - potentials(f)[-1]):.6f}")64 vertices, 112 edges, 49 off-tree edges, tau = 114.7
after 100 toggles: relative error in the L-norm 2.30e-01
after 500 toggles: relative error in the L-norm 7.62e-03
after 1000 toggles: relative error in the L-norm 1.93e-04
after 2000 toggles: relative error in the L-norm 4.26e-08
R_eff(corner, corner) = 3.450736, from the toggled flow 3.450736
The error falls geometrically. It falls faster than the guarantee: the bound on the energy promises a factor of only about in the norm per 1000 toggles here, while the measured factor is far smaller. is a worst-case quantity.
In C++
The same algorithm in C++ on a larger weighted grid. Off-tree edges are sampled with a cumulative table and binary search; the tree path is found with parent pointers and depths.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <numeric>
#include <random>
#include <vector>
struct Edge { int u, v; double r; };
int main() {
const int K = 20, n = K * K;
std::mt19937_64 rng(2013);
std::vector<Edge> E;
for (int i = 0; i < K; ++i)
for (int j = 0; j < K; ++j) {
double a = double(rng() >> 11) * 0x1.0p-53, c = double(rng() >> 11) * 0x1.0p-53;
if (j + 1 < K) E.push_back({i * K + j, i * K + j + 1, std::pow(10.0, 2 * a - 1)});
if (i + 1 < K) E.push_back({i * K + j, (i + 1) * K + j, std::pow(10.0, 2 * c - 1)});
}
int m = (int)E.size();
// maximum-conductance spanning tree (Kruskal), then root it at 0
std::vector<int> idx(m), uf(n);
std::iota(idx.begin(), idx.end(), 0);
std::iota(uf.begin(), uf.end(), 0);
std::stable_sort(idx.begin(), idx.end(), [&](int a, int b) { return E[a].r < E[b].r; });
auto find = [&](int a) { while (uf[a] != a) a = uf[a] = uf[uf[a]]; return a; };
std::vector<char> in_tree(m, 0);
std::vector<std::vector<int>> adj(n);
for (int e : idx) {
int a = find(E[e].u), b = find(E[e].v);
if (a != b) { uf[a] = b; in_tree[e] = 1; adj[E[e].u].push_back(e); adj[E[e].v].push_back(e); }
}
std::vector<int> par(n, -1), pe(n, -1), dep(n, 0), order{0};
std::vector<char> seen(n, 0);
seen[0] = 1;
for (std::size_t q = 0; q < order.size(); ++q) {
int u = order[q];
for (int e : adj[u]) {
int v = E[e].u == u ? E[e].v : E[e].u;
if (!seen[v]) { seen[v] = 1; par[v] = u; pe[v] = e; dep[v] = dep[u] + 1; order.push_back(v); }
}
}
// cycle of off-tree edge e: (edge, sign) pairs, sign +1 when traversed from E[c].u to E[c].v
auto cycle = [&](int e) {
std::vector<std::pair<int, int>> up, down;
int a = E[e].v, b = E[e].u; // tree path from v back to u
while (a != b) {
if (dep[a] >= dep[b]) { int c = pe[a]; up.push_back({c, E[c].u == a ? 1 : -1}); a = par[a]; }
else { int c = pe[b]; down.push_back({c, E[c].v == b ? 1 : -1}); b = par[b]; }
}
std::vector<std::pair<int, int>> cyc{{e, 1}};
cyc.insert(cyc.end(), up.begin(), up.end());
cyc.insert(cyc.end(), down.rbegin(), down.rend());
return cyc;
};
std::vector<int> off;
std::vector<std::vector<std::pair<int, int>>> cyc;
std::vector<double> Rc, cum;
double tau = 0;
for (int e = 0; e < m; ++e)
if (!in_tree[e]) {
off.push_back(e);
cyc.push_back(cycle(e));
double R = 0;
for (auto [c, s] : cyc.back()) R += E[c].r;
Rc.push_back(R);
tau += R / E[e].r;
cum.push_back(tau);
}
// initial tree flow for a unit current from vertex 0 to vertex n-1
std::vector<double> f(m, 0.0), ex(n, 0.0);
ex[0] = 1.0; ex[n - 1] = -1.0;
for (int q = n - 1; q >= 1; --q) {
int v = order[q], e = pe[v];
f[e] += (E[e].u == v ? 1.0 : -1.0) * ex[v];
ex[par[v]] += ex[v];
}
auto reff = [&]() { // potential difference x_0 - x_{n-1}
std::vector<double> x(n, 0.0);
for (int q = 1; q < n; ++q) {
int v = order[q], e = pe[v];
double drop = E[e].r * f[e];
x[v] = E[e].u == par[v] ? x[par[v]] - drop : x[par[v]] + drop;
}
return x[0] - x[n - 1];
};
std::printf("%d vertices, %d edges, %zu off-tree edges, tau = %.1f\n", n, m, off.size(), tau);
for (int it = 1; it <= 40000; ++it) {
double pick = double(rng() >> 11) * 0x1.0p-53 * tau;
int i = int(std::upper_bound(cum.begin(), cum.end(), pick) - cum.begin());
i = std::min(i, (int)off.size() - 1);
double delta = 0;
for (auto [c, s] : cyc[i]) delta += s * E[c].r * f[c];
for (auto [c, s] : cyc[i]) f[c] -= s * delta / Rc[i];
if (it % 10000 == 0) std::printf("after %5d toggles: R_eff estimate %.8f\n", it, reff());
}
}400 vertices, 760 edges, 361 off-tree edges, tau = 982.5
after 10000 toggles: R_eff estimate 4.61260433
after 20000 toggles: R_eff estimate 4.61258785
after 30000 toggles: R_eff estimate 4.61258786
after 40000 toggles: R_eff estimate 4.61258786
The estimate stabilizes to eight digits after a few multiples of toggles. Each toggle touched only one cycle; nothing like a matrix factorization was needed.
The Laplacian paradigm
Nearly-linear solvers made the following run in nearly linear time (up to polylogarithmic factors and -dependence): computing electrical flows and potentials; approximating all effective resistances at once (Spielman and Srivastava, 2008: solves after a Johnson-Lindenstrauss projection); spectral sparsification; sampling random spanning trees faster than by random walks; approximate maximum flow in undirected graphs and, combined with interior-point methods, exact max flow and min-cost flow (the last lesson of this section); semi-supervised learning on graphs (harmonic label propagation is a Laplacian solve). Teng's survey The Laplacian Paradigm (2010) and Vishnoi's monograph Lx = b (2013) cover these reductions.
Test yourself
What running time did Spielman and Teng (2004) prove for -approximately solving a Laplacian system with nonzeros?
- for a constant
In which norm is the error of an approximate Laplacian solution measured?
- The maximum norm
- The energy norm , relative to
- The number of correct digits of
- The norm of the residual
What does one step of the cycle-toggling solver (Kelner, Orecchia, Sidford and Zhu) do?
- Eliminates a vertex
- Picks an off-tree edge and pushes flow around its tree cycle so that the voltage drop around that cycle becomes zero
- Doubles all resistances
- Computes an eigenvector
How many toggles does the cycle-toggling solver need, in terms of ?