TExcelTAD
Home › Spectral Graph Theory & Modern Graph Algorithms › Nearly-Linear-Time Laplacian Solvers

Nearly-Linear-Time Laplacian Solvers

In 2004 Spielman and Teng proved that a Laplacian system Lx=bLx = b with mm nonzeros can be solved to accuracy ε\varepsilon in time O(mlog⁡cnlog⁡(1/ε))O(m\log^c n\log(1/\varepsilon)) for a constant cc: 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 b⊥1b \perp \mathbf{1}, an ε\varepsilon-approximate solution is an xx with

∥x−L+b∥L≤ε ∥L+b∥L,∥y∥L=yTLy.\lVert x - L^+ b \rVert_L \le \varepsilon\, \lVert L^+ b \rVert_L, \qquad \lVert y \rVert_L = \sqrt{y^{\mathsf{T}} L y} .

The LL-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

  1. Preconditioned iterative methods (Conjugate Gradient and Tree Preconditioners): with a preconditioner BB, the number of iterations is O(κ(L,B)log⁡(1/ε))O(\sqrt{\kappa(L, B)}\log(1/\varepsilon)), each costing one multiplication by LL and one solve with BB.
  2. Low-stretch spanning trees: a tree TT with total stretch st⁡T(G)=O(mlog⁡nlog⁡log⁡n)\operatorname{st}_T(G) = O(m\log n\log\log n), so κ(L,LT)≤st⁡T(G)\kappa(L, L_T) \le \operatorname{st}_T(G).
  3. Ultra-sparsifiers: add back to TT a few edges (sampled by stretch, or found via sparsification) to get H=T+O(m/k)H = T + O(m/k) edges with κ(LG,LH)=O~(k)\kappa(L_G, L_H) = \tilde O(k). A graph that is a tree plus ss extra edges can be shrunk, by eliminating degree-1 and degree-2 vertices (Schur complements, no fill), to a graph with O(s)O(s) vertices and edges.
  4. Recursion: solving with LHL_H means solving a Laplacian system on a graph kk times smaller, which is done by the same algorithm. With the right kk the total work is a geometric series, nearly linear in mm.

The results

Year Authors Running time for an ε\varepsilon-approximate solution Main new idea
2004 Spielman and Teng O(mlog⁡cnlog⁡(1/ε))O(m\log^{c} n\log(1/\varepsilon)) for a (large) constant cc ultra-sparsifiers from low-stretch trees and spectral sparsification via local clustering; recursive preconditioning
2010 Koutis, Miller and Peng O~(mlog⁡2nlog⁡(1/ε))\tilde O(m\log^2 n\log(1/\varepsilon)) sparsify by sampling edges with probabilities from the tree's stretch (an upper bound on effective resistance)
2011 Koutis, Miller and Peng O(mlog⁡n (log⁡log⁡n)2log⁡(1/ε))O(m\log n\,(\log\log n)^2\log(1/\varepsilon)), i.e. O~(mlog⁡n)\tilde O(m\log n) better low-stretch trees and a sharper sampling analysis
2013 Kelner, Orecchia, Sidford and Zhu O(mlog⁡2nlog⁡log⁡nlog⁡(n/ε))O(m\log^2 n\log\log n\log(n/\varepsilon)) no recursion: randomized cycle toggling on a tree (below)
2014 Cohen, Kyng, Miller, Pachocki, Peng, Rao and Xu O(mlog⁡n poly⁡(log⁡log⁡n)log⁡(1/ε))O(m\sqrt{\log n}\,\operatorname{poly}(\log\log n)\log(1/\varepsilon)) low-stretch subgraphs and preconditioners with a better stretch-to-size tradeoff
2016 Kyng and Sachdeva O(mlog⁡3nlog⁡(1/ε))O(m\log^3 n\log(1/\varepsilon)) 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 O~(mlog⁡n)\tilde O(m\log n) form of Koutis, Miller and Peng is the one usually quoted as "nearly mlog⁡nm\log n". 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 ff meeting the demands bb (BTf=bB^{\mathsf{T}} f = b) whose potential drops refer_e f_e sum to zero around every cycle (Kirchhoff's voltage law). The algorithm:

text
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 x

Each step fixes one cycle exactly and may break others slightly. The analysis shows that the energy gap shrinks by a factor 1−1/τ1 - 1/\tau in expectation per step, where τ=∑e∉TRe/re=st⁡T(G)+m−2n+2\tau = \sum_{e \notin T} R_e/r_e = \operatorname{st}_T(G) + m - 2n + 2 (each off-tree edge contributes its stretch plus one; the n−1n - 1 tree edges, of stretch 1 each, are not counted). The starting tree flow has energy at most st⁡T(G)\operatorname{st}_T(G) times the optimum, so ⌈τln⁡(st⁡T(G) τ/ε)⌉=O(τlog⁡(n/ε))\lceil \tau\ln(\operatorname{st}_T(G)\,\tau/\varepsilon) \rceil = O(\tau\log(n/\varepsilon)) steps suffice. With a low-stretch tree, τ=O(mlog⁡nlog⁡log⁡n)\tau = O(m\log n\log\log n), and with a data structure that updates a tree path in O(log⁡n)O(\log n) time, the total is O(mlog⁡2nlog⁡log⁡nlog⁡(n/ε))O(m\log^2 n\log\log n\log(n/\varepsilon)). The implementation below walks the tree path explicitly, which costs O(n)O(n) per step but is enough to see the convergence.

python · try it yourself
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 (1−1/τ)t≈e−t/τ(1 - 1/\tau)^t \approx e^{-t/\tau} on the energy promises a factor of only about e−1000/(2τ)≈0.013e^{-1000/(2\tau)} \approx 0.013 in the norm per 1000 toggles here, while the measured factor is far smaller. τ\tau 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.

cpp · try it yourself
#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 τ\tau 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 ε\varepsilon-dependence): computing electrical flows and potentials; approximating all effective resistances at once (Spielman and Srivastava, 2008: O(log⁡n/ε2)O(\log n/\varepsilon^2) 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 ε\varepsilon-approximately solving a Laplacian system with mm nonzeros?

  1. O(n3)O(n^3)
  2. O(mlog⁡cnlog⁡(1/ε))O(m\log^c n\log(1/\varepsilon)) for a constant cc
  3. O(mn)O(m\sqrt n)
  4. O(m2)O(m^2)

In which norm is the error of an approximate Laplacian solution measured?

  1. The maximum norm
  2. The energy norm ∥y∥L=yTLy\lVert y \rVert_L = \sqrt{y^{\mathsf{T}} L y}, relative to ∥L+b∥L\lVert L^+ b \rVert_L
  3. The number of correct digits of x1x_1
  4. The ℓ1\ell_1 norm of the residual

What does one step of the cycle-toggling solver (Kelner, Orecchia, Sidford and Zhu) do?

  1. Eliminates a vertex
  2. Picks an off-tree edge and pushes flow around its tree cycle so that the voltage drop around that cycle becomes zero
  3. Doubles all resistances
  4. Computes an eigenvector

How many toggles does the cycle-toggling solver need, in terms of τ=∑e∉TRe/re\tau = \sum_{e \notin T} R_e/r_e?

  1. O(log⁡n)O(\log n)
  2. O(τlog⁡(n/ε))O(\tau\log(n/\varepsilon))
  3. O(τ2)O(\tau^2)
  4. O(n3)O(n^3)