Algorithm Search⌘K

Algorithmcore

Spectral partitioning

Also called spectral bisection, Fiedler vector partitioning.

Splits a graph by the signs or the median of the eigenvector of the second smallest Laplacian eigenvalue, the Fiedler vector, as in Hall and in Pothen and coauthors.

Time
Θ(t (n + m) + n log n) worst · averageΘ(n + m + n log n) best
Space
Θ(n + m) extra
Where
m = the number of edges; n = the number of vertices; t = the number of power iteration steps
Properties
randomizednot exactiterative
Origin
Kenneth M. Hall, Miroslav Fiedler, Alex Pothen, Horst D. Simon, Kang Pu Liou, Lars Hagen, Andrew B. Kahng, 1970

Spectral partitioning splits a graph into two parts by one eigenvector of its Laplacian: the eigenvector of the second smallest eigenvalue λ2\lambda_2, called the Fiedler vector. Sort the vertices by their entries in this vector, then cut the sorted list at the median for a bisection, or at the best prefix for a ratio cut. The method is a relaxation of graph bisection: it solves the problem exactly when the entries may be any real numbers, and then rounds. It is a heuristic with no constant-factor guarantee, but λ2\lambda_2 gives a lower bound that sometimes proves the result optimal.

In plain words

Think of the vertices as beads and the edges as springs. Pull the beads apart along a line, but keep their center fixed and their total spread fixed. The springs pull linked beads together. In the position with the least spring energy, groups of beads with many springs between them stay close together, and groups with few springs between them drift apart.

That position is the Fiedler vector. So you sort the beads by their place on the line and cut the line in the middle. Beads on the same side are mostly linked to each other. The cut is often good, but it is not always the best, and on some graphs it is far from the best.

The problem

The input is an undirected graph G=(V,E)G = (V, E) with n≥2n \ge 2 vertices 0,…,n−10, \ldots, n - 1, mm edges and weights w(u,v)>0w(u, v) > 0. In bisection mode the output is a split (A,B)(A, B) with ∣A∣=⌊n/2⌋|A| = \lfloor n/2 \rfloor, and the goal, which the method does not always reach, is a small cut weight cut(A,B)\mathrm{cut}(A, B). This is the bisection case of the graph partitioning problem, which is NP-hard. In ratio mode the output is any split with both parts nonempty, and the goal is a small ratio cut cut(A,B)/(∣A∣ ∣B∣)\mathrm{cut}(A, B) / (|A| \, |B|).

For a netlist, a hypergraph with nn cells, mm nets and PP pins, first replace each net by a graph with the clique net model. A net of pp pins gives (p2)\binom{p}{2} edges, so large nets make the graph dense. The cut of the graph then only approximates the number of cut nets, which is the true cost in hypergraph partitioning.

The algorithm

Let d(v)d(v) be the weighted degree of vv and L=D−AL = D - A the Laplacian, with eigenvalues 0=λ1≤λ2≤⋯≤λn0 = \lambda_1 \le \lambda_2 \le \cdots \le \lambda_n. The all-ones vector 1\mathbf 1 is an eigenvector of λ1\lambda_1. The implementation finds the Fiedler vector by power iteration on M=cI−LM = cI - L with c=2max⁡vd(v)c = 2 \max_v d(v). The eigenvalues of MM are c−λi≥0c - \lambda_i \ge 0, so after the component along 1\mathbf 1 is removed, the largest one is c−λ2c - \lambda_2, and power iteration finds its eigenvector. The tolerance τ\tau bounds the residual of the unit vector xx.

  1. SPECTRAL-PARTITION(G, mode, τ)
  2. 1build L = D − A and set c ← 2 · max_v d(v)
  3. 2x ← a random vector; x ← x − mean(x) · 1; x ← x / ‖x‖
  4. 3loop
  5. 4ρ ← xᵀ L x ▷ the Rayleigh quotient
  6. 5if ‖L x − ρ x‖ ≤ τ then leave the loop
  7. 6x ← (c I − L) x; x ← x − mean(x) · 1; x ← x / ‖x‖
  8. 7sort the vertices by x_v, ties by the vertex number
  9. 8if mode = bisection then return (the first ⌊n/2⌋ vertices, the rest)
  10. 9for k ← 1 to n − 1: R_k ← cut(first k, rest) / (k (n − k))
  11. 10return the split at the k with the least R_k

Line L6 uses one product with LL, which costs O(n+m)O(n + m) with adjacency lists. Removing the mean in lines L2 and L6 keeps xx orthogonal to 1\mathbf 1, both in exact arithmetic and against the drift of rounding errors. Line L9 moves the vertices to the first part one at a time and updates the cut from the edges of the moved vertex, so the whole sweep costs O(n+m)O(n + m).

The sign split is the other common rounding: put the vertices with xv<0x_v < 0 on one side. It does not control the sizes of the parts. In practice the eigenvector is computed by the Lanczos method, which needs far fewer products than power iteration when λ2\lambda_2 and λ3\lambda_3 are close. Power iteration is used here because it is short and its stopping rule is easy to check.

Example

Take the graph of the graph partitioning page: two triangles a,b,ca, b, c and d,e,fd, e, f, joined by the edges cdcd and bebe, all of weight 1. The Laplacian has eigenvalues 0,1,3,3,4,50, 1, 3, 3, 4, 5, and the Fiedler vector for λ2=1\lambda_2 = 1 is

x=112(2,1,1,−1,−1,−2)≈(0.577,0.289,0.289,−0.289,−0.289,−0.577)x = \tfrac{1}{\sqrt{12}} (2, 1, 1, -1, -1, -2) \approx (0.577, 0.289, 0.289, -0.289, -0.289, -0.577)

in the order a,…,fa, \ldots, f. Check at aa with the unscaled vector (2,1,1,−1,−1,−2)(2, 1, 1, -1, -1, -2): aa has degree 2 and the neighbors b,cb, c, so (Lx)a=2⋅2−1−1=2=λ2⋅2(Lx)_a = 2 \cdot 2 - 1 - 1 = 2 = \lambda_2 \cdot 2.

The largest degree is 3, so c=6c = 6. Start from eae_a, the unit vector at aa, after line L2 removes its mean.

step xx (rounded) ρ\rho residual
0 (0.913,−0.183,−0.183,−0.183,−0.183,−0.183)(0.913, -0.183, -0.183, -0.183, -0.183, -0.183) 2.4 1.20
1 (0.866,0,0,−0.289,−0.289,−0.289)(0.866, 0, 0, -0.289, -0.289, -0.289) 1.6667 1.03
2 (0.778,0.130,0.130,−0.324,−0.324,−0.389)(0.778, 0.130, 0.130, -0.324, -0.324, -0.389) 1.2605 0.698
3 (0.704,0.203,0.203,−0.325,−0.325,−0.460)(0.704, 0.203, 0.203, -0.325, -0.325, -0.460) 1.0948 0.432
5 (0.623,0.262,0.262,−0.307,−0.307,−0.534)(0.623, 0.262, 0.262, -0.307, -0.307, -0.534) 1.0122 0.156
10 1.0001 1.21⋅10−21.21 \cdot 10^{-2}
20 1.0000 7.31⋅10−57.31 \cdot 10^{-5}
30 1.0000 4.42⋅10−74.42 \cdot 10^{-7}

The residual falls by a factor of about 3/53/5 per step, which is (c−λ3)/(c−λ2)=3/5(c - \lambda_3)/(c - \lambda_2) = 3/5. The sorted order a,b,c,d,e,fa, b, c, d, e, f is already right at step 2, long before the residual is small. Line L8 returns {a,b,c}∣{d,e,f}\{a, b, c\} \mid \{d, e, f\} with cut 2. Every bisection has cut at least nλ2/4=1.5n \lambda_2 / 4 = 1.5, so at least 2, and this split is optimal. In ratio mode, line L9 finds R3=2/9R_3 = 2/9 as the least value, which is the minimum ratio cut; the bound of Hagen and Kahng gives only λ2/n=1/6\lambda_2 / n = 1/6.

A graph where the median fails. The roach graph of Guattery and Miller has two paths of 2k2k vertices each, the upper and the lower path, with a rung between the ii-th vertices of the two paths for i=1,…,ki = 1, \ldots, k. The other kk vertices of each path form an "antenna". Guattery and Miller show that the Fiedler vector is odd under the swap of the two paths, so the median split puts the upper path on one side and the lower path on the other and cuts all kk rungs. The minimum bisection cuts each path in its middle, 2 edges. With the implementation (seed 1), k=3k = 3 and k=4k = 4 give cuts 3 and 4 against the optimum 2, checked by brute force, and k=8k = 8 and k=12k = 12 give cuts 8 and 12. The ratio sweep does better here: it cuts off one antenna with a single edge.

Correctness

The proof shows the following. The first three items hold for every input; the last says how good the result is, and it is only a bound.

  • Valid output. Line L8 returns parts of sizes ⌊n/2⌋\lfloor n/2 \rfloor and ⌈n/2⌉\lceil n/2 \rceil, and line L10 returns two nonempty parts. The incremental cut of line L9 equals the cut of each prefix.
  • The relaxation. Over real vectors x⊥1x \perp \mathbf 1 with x≠0x \ne 0, the Rayleigh quotient x⊤Lx/x⊤xx^{\top} L x / x^{\top} x is least, with value λ2\lambda_2, exactly at the eigenvectors of λ2\lambda_2. For a bisection with xv=±1x_v = \pm 1, x⊤Lx=4 cutx^{\top} L x = 4 \, \mathrm{cut}, so the method minimizes the relaxed cut and rounds.
  • Convergence. With c=2max⁡vd(v)c = 2 \max_v d(v), every eigenvalue of cI−LcI - L is nonnegative. If the start has a nonzero component in the eigenspace of λ2\lambda_2, which happens with probability 1 for a continuous random start, the residual after kk steps is at most C qkC \, q^k with q=(c−λ′)/(c−λ2)<1q = (c - \lambda')/(c - \lambda_2) < 1, where λ′\lambda' is the least eigenvalue above λ2\lambda_2 (q=0q = 0 if there is none). So the loop of line L3 stops.
  • Lower bounds. Every bisection has cut at least nλ2/4n \lambda_2 / 4, and every split has ratio cut at least λ2/n\lambda_2 / n. If the returned cut meets the bound after rounding up, it is optimal. These bounds are for the unnormalized Laplacian and for R=cut/(∣A∣∣B∣)R = \mathrm{cut}/(|A| |B|); other normalizations give other constants.
Proof: Spectral partitioning returns a valid split, its power iteration converges, and the second eigenvalue bounds every cut from belowfull

Let G=(V,E)G = (V, E) have n≥2n \ge 2 vertices, weights w(u,v)>0w(u, v) > 0 and Laplacian L=D−AL = D - A. For every real vector xx,

x⊤Lx=∑{u,v}∈Ew(u,v) (xu−xv)2≥0.x^{\top} L x = \sum_{\{u, v\} \in E} w(u, v) \, (x_u - x_v)^2 \ge 0.

So LL is symmetric and positive semidefinite. By the spectral theorem it has an orthonormal basis of eigenvectors u1,…,unu_1, \ldots, u_n with eigenvalues 0=λ1≤λ2≤⋯≤λn0 = \lambda_1 \le \lambda_2 \le \cdots \le \lambda_n, and we take u1=1/nu_1 = \mathbf 1 / \sqrt n. Let U=1⊥U = \mathbf 1^{\perp}, the vectors with sum 0. We assume exact real arithmetic; the implementation uses floating point and checks the residual in floating point.

Lemma 1 (the largest eigenvalue). λn≤2Δ\lambda_n \le 2 \Delta, where Δ=max⁡vd(v)\Delta = \max_v d(v).

Proof. Since (xu−xv)2≤2xu2+2xv2(x_u - x_v)^2 \le 2 x_u^2 + 2 x_v^2, we get x⊤Lx≤2∑{u,v}∈Ew(u,v)(xu2+xv2)=2∑vd(v)xv2≤2Δ x⊤xx^{\top} L x \le 2 \sum_{\{u,v\} \in E} w(u, v) (x_u^2 + x_v^2) = 2 \sum_v d(v) x_v^2 \le 2 \Delta \, x^{\top} x. The largest eigenvalue is the largest Rayleigh quotient, so λn≤2Δ\lambda_n \le 2 \Delta. □\square

Lemma 2 (the relaxation). For x∈Ux \in U, x≠0x \ne 0, x⊤Lx/x⊤x≥λ2x^{\top} L x / x^{\top} x \ge \lambda_2, with equality exactly when xx is an eigenvector of λ2\lambda_2.

Proof. Write x=∑i≥2αiuix = \sum_{i \ge 2} \alpha_i u_i, which is possible because x⊥u1x \perp u_1. Then x⊤Lx=∑i≥2λiαi2≥λ2∑i≥2αi2=λ2 x⊤xx^{\top} L x = \sum_{i \ge 2} \lambda_i \alpha_i^2 \ge \lambda_2 \sum_{i \ge 2} \alpha_i^2 = \lambda_2 \, x^{\top} x, with equality exactly when αi=0\alpha_i = 0 for every ii with λi>λ2\lambda_i > \lambda_2. □\square

Theorem 1 (lower bounds). If nn is even, every bisection (A,B)(A, B) has cut(A,B)≥nλ2/4\mathrm{cut}(A, B) \ge n \lambda_2 / 4. Every split with A,B≠∅A, B \ne \emptyset has cut(A,B)/(∣A∣∣B∣)≥λ2/n\mathrm{cut}(A, B) / (|A| |B|) \ge \lambda_2 / n.

Proof. For a bisection put xv=1x_v = 1 on AA and xv=−1x_v = -1 on BB. Then x∈Ux \in U, x⊤x=nx^{\top} x = n and every cut edge contributes w⋅22w \cdot 2^2, so x⊤Lx=4 cut(A,B)x^{\top} L x = 4 \, \mathrm{cut}(A, B). Lemma 2 gives 4 cut(A,B)≥λ2n4 \, \mathrm{cut}(A, B) \ge \lambda_2 n. For a general split put xv=∣B∣x_v = |B| on AA and xv=−∣A∣x_v = -|A| on BB. Then x∈Ux \in U, x⊤x=n∣A∣∣B∣x^{\top} x = n |A| |B| and each cut edge contributes w n2w \, n^2, so n2 cut(A,B)≥λ2 n∣A∣∣B∣n^2 \, \mathrm{cut}(A, B) \ge \lambda_2 \, n |A| |B|. □\square

Theorem 2 (convergence of lines L2 to L6). Let c=2Δ>0c = 2 \Delta > 0 and μi=c−λi\mu_i = c - \lambda_i. Let E2E_2 be the eigenspace of λ2\lambda_2 inside UU, let λ′\lambda' be the least eigenvalue larger than λ2\lambda_2, and q=(c−λ′)/(c−λ2)q = (c - \lambda')/(c - \lambda_2), or q=0q = 0 if there is no such eigenvalue. Let x0x_0 be the vector of line L2 and write x0=y0+z0x_0 = y_0 + z_0 with y0∈E2y_0 \in E_2 and z0⊥E2z_0 \perp E_2, z0∈Uz_0 \in U. If y0≠0y_0 \ne 0, then after kk executions of line L6,

∥Lxk−ρkxk∥≤(λn−λ2) ∥z0∥∥y0∥ qk,ρk=xk⊤Lxk.\| L x_k - \rho_k x_k \| \le (\lambda_n - \lambda_2) \, \frac{\|z_0\|}{\|y_0\|} \, q^k, \qquad \rho_k = x_k^{\top} L x_k.

In particular 0≤q<10 \le q < 1 and the loop stops after finitely many steps for every τ>0\tau > 0.

Proof. By Lemma 1, 0≤μn≤⋯≤μ20 \le \mu_n \le \cdots \le \mu_2 for the eigenvalues on UU, and μi≤c−λ′=qμ2\mu_i \le c - \lambda' = q \mu_2 for every ii with λi>λ2\lambda_i > \lambda_2. Line L6 multiplies by M=cI−LM = cI - L, which maps UU to UU because M1=c1M \mathbf 1 = c \mathbf 1 and MM is symmetric. So in exact arithmetic the mean removal changes nothing, and the normalization only scales. Hence xk=Mkx0/∥Mkx0∥x_k = M^k x_0 / \|M^k x_0\|. In the eigenbasis, Mky0=μ2ky0M^k y_0 = \mu_2^k y_0 and ∥Mkz0∥≤(qμ2)k∥z0∥\|M^k z_0\| \le (q \mu_2)^k \|z_0\|, since every component of z0z_0 is along some uiu_i with λi>λ2\lambda_i > \lambda_2, and 0≤μi≤qμ20 \le \mu_i \le q \mu_2 there. Write xk=yk+zkx_k = y_k + z_k in the same way. Then

∥zk∥∥yk∥=∥Mkz0∥μ2k∥y0∥≤qk∥z0∥∥y0∥,\frac{\|z_k\|}{\|y_k\|} = \frac{\|M^k z_0\|}{\mu_2^k \|y_0\|} \le q^k \frac{\|z_0\|}{\|y_0\|},

and since ∥xk∥=1\|x_k\| = 1, ∥zk∥≤∥zk∥/∥yk∥\|z_k\| \le \|z_k\| / \|y_k\| once ∥yk∥≤1\|y_k\| \le 1, which always holds. For a unit vector xx, the value σ=x⊤Lx\sigma = x^{\top} L x minimizes ∥Lx−σx∥\|L x - \sigma x\| over all real σ\sigma, because ∥Lx−σx∥2=∥Lx∥2−2σ x⊤Lx+σ2\|Lx - \sigma x\|^2 = \|Lx\|^2 - 2 \sigma \, x^{\top} L x + \sigma^2. So

∥Lxk−ρkxk∥≤∥(L−λ2I)xk∥=∥(L−λ2I)zk∥≤(λn−λ2)∥zk∥,\|L x_k - \rho_k x_k\| \le \|(L - \lambda_2 I) x_k\| = \|(L - \lambda_2 I) z_k\| \le (\lambda_n - \lambda_2) \|z_k\|,

because (L−λ2I)yk=0(L - \lambda_2 I) y_k = 0 and L−λ2IL - \lambda_2 I has norm at most λn−λ2\lambda_n - \lambda_2 on the span of the uiu_i with λi>λ2\lambda_i > \lambda_2. Combining the two bounds gives the claim. q<1q < 1 because λ′>λ2\lambda' > \lambda_2. □\square

If Δ=0\Delta = 0 there are no edges, L=0L = 0, every vector of UU is an eigenvector, and line L5 stops at once with residual 0. The set of starts with y0=0y_0 = 0 is the subspace E2⊥∩UE_2^{\perp} \cap U of dimension less than n−1n - 1; the start of line L2 is a continuous random vector projected onto UU, so y0≠0y_0 \ne 0 with probability 1.

Theorem 3 (valid output). Line L8 returns parts of sizes ⌊n/2⌋\lfloor n/2 \rfloor and ⌈n/2⌉\lceil n/2 \rceil. Line L10 returns two nonempty parts, and the value RkR_k of line L9 is the ratio cut of the split into the first kk sorted vertices and the rest.

Proof. Line L7 gives a permutation v1,…,vnv_1, \ldots, v_n of VV. Line L8 returns {v1,…,v⌊n/2⌋}\{v_1, \ldots, v_{\lfloor n/2 \rfloor}\} and its complement. In line L9, let Sk={v1,…,vk}S_k = \{v_1, \ldots, v_k\} and keep the invariant that the variable cut equals cut(Sk,V∖Sk)\mathrm{cut}(S_k, V \setminus S_k). It holds for S0=∅S_0 = \emptyset with value 0. Moving v=vkv = v_k from the second part to the first changes the side of vv only. An edge {v,u}\{v, u\} with u∉Sku \notin S_k becomes cut, and an edge {v,u}\{v, u\} with u∈Sk−1u \in S_{k-1} stops being cut. Edges without vv do not change. The implementation adds ww for the first kind and subtracts ww for the second, so the invariant holds for SkS_k. For 1≤k≤n−11 \le k \le n - 1 both SkS_k and its complement are nonempty, so Rk=cut(Sk,V∖Sk)/(k(n−k))R_k = \mathrm{cut}(S_k, V \setminus S_k)/(k(n - k)) is the ratio cut, and line L10 returns the split of least RkR_k. ■\blacksquare

Running time. Building the adjacency lists, the degrees and cc takes O(n+m)O(n + m). One loop step computes LxLx from the lists in O(n+m)O(n + m) and the inner products and the mean in O(n)O(n). Line L7 sorts in O(nlog⁡n)O(n \log n). In line L9 each vertex is moved once, and the update scans its edges once, so the sweep takes O(n+m)O(n + m) in total. With tt loop steps the time is Θ(t(n+m)+nlog⁡n)\Theta(t (n + m) + n \log n) and the space is Θ(n+m)\Theta(n + m). By Theorem 2, t≤1+log⁡((λn−λ2)∥z0∥/(τ∥y0∥))/log⁡(1/q)t \le 1 + \log\big((\lambda_n - \lambda_2) \|z_0\| / (\tau \|y_0\|)\big) / \log(1/q) when q>0q > 0.

What is not proved. Nothing above says that the rounded split has a small cut compared with the optimum. The roach graphs of Guattery and Miller (1998) show that no such constant-factor statement holds for the median split.

Complexity

Let tt be the number of power steps.

  • Time. Line L1 takes O(n+m)O(n + m). Each step of lines L4 to L6 takes O(n+m)O(n + m). Line L7 takes O(nlog⁡n)O(n \log n), and lines L8 to L10 take O(n+m)O(n + m). The total is Θ(t(n+m)+nlog⁡n)\Theta(t (n + m) + n \log n).
  • Steps. By the convergence bound, t=O(log⁡(C/τ)/log⁡(1/q))t = O(\log(C/\tau) / \log(1/q)). When the gap λ′−λ2\lambda' - \lambda_2 is small compared with cc, qq is close to 1 and tt is large. In the usual analysis, the number of Lanczos steps depends on the square root of the relative gap instead of the gap itself, so it needs far fewer products, which is why production codes use it.
  • Space. The adjacency lists and a few vectors of length nn take Θ(n+m)\Theta(n + m).
  • Netlists. With the clique model, the graph of a netlist has up to ∑e(∣e∣2)\sum_e \binom{|e|}{2} edges, which can be much more than PP. A star model or a cap on net sizes keeps it at O(P)O(P).

Properties

Spectral partitioning is a heuristic for bisection and for the ratio cut. What is proved about it and what is only measured are kept apart below.

What is proved.

  • The relaxation, the convergence of the power iteration and the two lower bounds above.
  • Fiedler (1975): if GG is connected and xx is a Fiedler vector, then for every r≥0r \ge 0 the vertices with xv≥−rx_v \ge -r induce a connected subgraph, and so do the vertices with xv≤rx_v \le r. So both sides of the sign split with xv≥0x_v \ge 0 and xv≤0x_v \le 0 are connected. This page cites it and does not prove it.
  • Spielman and Teng (2007): for planar graphs of bounded degree, λ2=O(1/n)\lambda_2 = O(1/n), and a sweep of the Fiedler vector finds a split whose cut divided by the smaller part is O(1/n)O(1/\sqrt n). Applied recursively, this gives balanced separators of size O(n)O(\sqrt n), as the planar separator theorem does.
  • No constant ratio: on the roach graphs of Guattery and Miller (1998), the median split cuts Θ(n)\Theta(n) edges while the minimum bisection cuts 2. So spectral bisection has no constant approximation ratio.

What is measured. Pothen, Simon and Liou (1990) and Hagen and Kahng (1992) reported experiments on sparse matrices and on benchmark circuits, in their papers. The numbers below are from the implementation of this page, on small random graphs, and are not benchmark results. On 200 graphs G(12,0.3)G(12, 0.3) with unit weights (generator random.Random(2026), the solver of graph tt started from random.Random(t)), compared with brute force:

method optimal mean of cut / optimum worst
median split (bisection) 107 of 200 1.151 2.333
sweep (ratio cut) 191 of 200 1.003 1.257

All runs converged to residual 10−1010^{-10}. The median split is often far from the best bisection on such small graphs, which is why it is followed by a Kernighan-Lin or Fiduccia-Mattheyses refinement in practice.

Variants and improvements

  • EIG1 for ratio cut. Hagen and Kahng's sweep, lines L9 and L10, picks the best of the n−1n - 1 prefixes for the ratio cut instead of the median.
  • More eigenvectors. Hall (1970) used the eigenvectors of λ2\lambda_2 and λ3\lambda_3 as xx and yy coordinates, a quadratic placement in the plane. Spectral kk-way methods use kk eigenvectors, as in spectral clustering with kk-means.
  • Normalized Laplacian. Using D−1/2LD−1/2D^{-1/2} L D^{-1/2} relaxes the normalized cut instead of the ratio cut.
  • Recursive bisection. Bisect each part again to get 2j2^j parts. Each level needs a new eigenvector of the subgraph.
  • Refinement and multilevel use. Refine the rounded split with local moves, or use a spectral split as the start at the coarsest level of a multilevel partitioner.

When to use it

Use spectral partitioning when you need a global view of a graph that local moves do not have, for example as a starting split for refinement, or when a lower bound from λ2\lambda_2 is useful. It works well on meshes and other graphs with geometric structure, as the result of Spielman and Teng explains. For large netlists, multilevel partitioners with FM refinement are faster and give smaller cuts, and they handle nets directly.

Pitfalls

  • Forgetting to remove 1\mathbf 1. Without the mean removal, power iteration on cI−LcI - L converges to 1\mathbf 1, the eigenvector of λ1=0\lambda_1 = 0, which carries no information.
  • A shift that is too small. If c<λnc < \lambda_n, the eigenvalue c−λnc - \lambda_n of MM is negative and can be larger in absolute value than c−λ2c - \lambda_2. Then the iteration finds the wrong vector. c=2max⁡vd(v)c = 2 \max_v d(v) is safe because λn≤2max⁡vd(v)\lambda_n \le 2 \max_v d(v).
  • Stopping on ρ\rho alone. ρ\rho converges about twice as fast as xx, so ρ\rho can look exact while the order of the entries is still wrong. Stop on the residual.
  • A multiple λ2\lambda_2. If λ2=λ3\lambda_2 = \lambda_3, any vector of the eigenspace is a Fiedler vector, and different starts give different splits.
  • Disconnected graphs. Then λ2=0\lambda_2 = 0, and the Fiedler vector can be any vector that is constant on each component, so a split with cut 0 exists, but the median split need not find it.
  • Wrong cost for netlists. The cut of the clique graph is not the number of cut nets. Report the hypergraph cut of the final split, not the graph cut.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

spectral_partitioning.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spectral-partitioning/. The authors are listed in prov/VACAVK.jsonl.

import math
import random
from typing import Sequence

Edge = tuple[int, int, float]


def laplacian(n: int, edges: Sequence[Edge]) -> list[list[float]]:
    """Dense Laplacian L = D - A of a weighted undirected graph on 0 .. n-1."""
    lap = [[0.0] * n for _ in range(n)]
    for u, v, w in edges:
        if u == v:
            continue
        lap[u][u] += w
        lap[v][v] += w
        lap[u][v] -= w
        lap[v][u] -= w
    return lap


def cut_weight(edges: Sequence[Edge], side: Sequence[int]) -> float:
    """Total weight of the edges whose ends are on different sides."""
    return sum(w for u, v, w in edges if side[u] != side[v])


def _times_laplacian(adj: list[list[tuple[int, float]]], deg: list[float], x: list[float]) -> list[float]:
    return [deg[u] * x[u] - sum(w * x[v] for v, w in adj[u]) for u in range(len(x))]


def fiedler_vector(
    n: int,
    edges: Sequence[Edge],
    rng: random.Random,
    tol: float = 1e-10,
    max_iter: int = 200000,
) -> tuple[float, list[float], float]:
    """Approximate the second smallest Laplacian eigenvalue and an eigenvector.

    Power iteration on M = c I - L with c = 2 times the largest weighted
    degree, so that the eigenvalues of M are c - lambda_i >= 0. Each step
    removes the component along the all-ones vector, which is the eigenvector
    of lambda_1 = 0. The loop stops when the residual ||L x - rho x|| of the
    unit vector x is at most tol, or after max_iter steps.

    Returns (rho, x, residual), where rho = x^T L x is the Rayleigh quotient.
    Cost: O(n + m) per step for m edges, and O(n + m) space.
    """
    if n < 2:
        raise ValueError("need at least two vertices")
    adj: list[list[tuple[int, float]]] = [[] for _ in range(n)]
    deg = [0.0] * n
    for u, v, w in edges:
        if u != v:
            adj[u].append((v, w))
            adj[v].append((u, w))
            deg[u] += w
            deg[v] += w
    c = 2.0 * max(deg) if max(deg) > 0 else 1.0

    def normalize(y: list[float]) -> list[float]:
        mean = sum(y) / n
        y = [t - mean for t in y]
        norm = math.sqrt(sum(t * t for t in y))
        return [t / norm for t in y]

    x = normalize([rng.uniform(-1.0, 1.0) for _ in range(n)])  # @line L2
    rho, res = 0.0, math.inf
    for _ in range(max_iter):  # @line L3
        lx = _times_laplacian(adj, deg, x)
        rho = sum(a * b for a, b in zip(x, lx))  # @line L4
        res = math.sqrt(sum((a - rho * b) ** 2 for a, b in zip(lx, x)))
        if res <= tol:  # @line L5
            break
        x = normalize([c * a - b for a, b in zip(x, lx)])  # @line L6
    return rho, x, res


def spectral_partitioning(
    n: int,
    edges: Sequence[Edge],
    rng: random.Random,
    mode: str = "bisection",
    tol: float = 1e-10,
) -> list[int]:
    """Split a graph by the order of the entries of its Fiedler vector.

    mode "bisection": the floor(n/2) vertices with the smallest entries go to
    side 0 (a split at the median). mode "ratio": try the n - 1 splits of the
    sorted order and keep the one with the least ratio cut cut/(|A| |B|), as
    in the EIG1 method of Hagen and Kahng. Ties in the entries are broken by
    the vertex number.

    Returns side[v] in {0, 1}. The eigenvector costs O(n + m) per power step;
    the sort costs O(n log n) and the sweep O(n + m).
    """
    lap_edges = [(u, v, w) for u, v, w in edges if u != v]  # @line L1
    _, x, _ = fiedler_vector(n, lap_edges, rng, tol)
    order = sorted(range(n), key=lambda v: (x[v], v))  # @line L7
    side = [1] * n
    if mode == "bisection":
        for v in order[: n // 2]:  # @line L8
            side[v] = 0
        return side
    if mode != "ratio":
        raise ValueError("mode must be 'bisection' or 'ratio'")
    adj: list[list[tuple[int, float]]] = [[] for _ in range(n)]
    for u, v, w in lap_edges:
        adj[u].append((v, w))
        adj[v].append((u, w))
    best_k, best_ratio, cut = 1, math.inf, 0.0
    for k in range(1, n):  # @line L9
        v = order[k - 1]
        side[v] = 0
        for u, w in adj[v]:
            cut += w if side[u] == 1 else -w
        ratio = cut / (k * (n - k))
        if ratio < best_ratio - 1e-12:
            best_k, best_ratio = k, ratio
    side = [1] * n
    for v in order[:best_k]:  # @line L10
        side[v] = 0
    return side
test_spectral_partitioning.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spectral-partitioning/. The authors are listed in prov/VACAVK.jsonl.

import math
import random
from fractions import Fraction
from itertools import combinations

from spectral_partitioning import cut_weight, fiedler_vector, laplacian, spectral_partitioning

TOL = 1e-6  # tolerance for eigenvalue comparisons (the solver stops at residual 1e-10)


def jacobi_eigenvalues(a: list[list[float]]) -> list[float]:
    """All eigenvalues of a symmetric matrix by cyclic Jacobi rotations (the reference)."""
    n = len(a)
    a = [row[:] for row in a]
    for _ in range(100):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        if off < 1e-22:
            break
        for p in range(n):
            for q in range(p + 1, n):
                if abs(a[p][q]) < 1e-300:
                    continue
                theta = (a[q][q] - a[p][p]) / (2 * a[p][q])
                t = (1 if theta >= 0 else -1) / (abs(theta) + math.sqrt(theta * theta + 1))
                c = 1 / math.sqrt(t * t + 1)
                s = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - s * akq
                    a[k][q] = s * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - s * aqk
                    a[q][k] = s * apk + c * aqk
    return sorted(a[i][i] for i in range(n))


def exact_cut(edges, side) -> Fraction:
    return sum((Fraction(w) for u, v, w in edges if side[u] != side[v]), Fraction(0))


def min_bisection(n, edges) -> Fraction:
    best = None
    for s in combinations(range(n), n // 2):
        side = [1] * n
        for v in s:
            side[v] = 0
        c = exact_cut(edges, side)
        best = c if best is None or c < best else best
    return best


def min_ratio_cut(n, edges) -> Fraction:
    best = None
    for mask in range(1, (1 << n) - 1):
        if mask & 1 == 0:
            continue
        side = [0 if mask >> v & 1 else 1 for v in range(n)]
        a = side.count(0)
        r = exact_cut(edges, side) / (a * (n - a))
        best = r if best is None or r < best else best
    return best


def random_graph(rng: random.Random, n: int, p: float) -> list[tuple[int, int, int]]:
    return [(u, v, rng.randint(1, 3)) for u, v in combinations(range(n), 2) if rng.random() < p]


def two_triangles():
    a, b, c, d, e, f = range(6)
    return [(a, b, 1), (a, c, 1), (b, c, 1), (d, e, 1), (d, f, 1), (e, f, 1), (c, d, 1), (b, e, 1)]


def test_page_example():
    edges = two_triangles()
    lam, x, res = fiedler_vector(6, edges, random.Random(1))
    assert res <= 1e-10 and abs(lam - 1.0) < TOL
    side = spectral_partitioning(6, edges, random.Random(1))
    assert side[0] == side[1] == side[2] != side[3] == side[4] == side[5]
    assert exact_cut(edges, side) == 2 == min_bisection(6, edges)
    side = spectral_partitioning(6, edges, random.Random(1), mode="ratio")
    assert exact_cut(edges, side) / 9 == Fraction(2, 9) == min_ratio_cut(6, edges)


def test_path_and_cycle_eigenvalues():
    for n in range(2, 10):
        path = [(i, i + 1, 1) for i in range(n - 1)]
        lam, _, _ = fiedler_vector(n, path, random.Random(n))
        assert abs(lam - 2 * (1 - math.cos(math.pi / n))) < TOL
        side = spectral_partitioning(n, path, random.Random(n))
        assert cut_weight(path, side) == 1  # a path splits at its middle edge
    for n in range(3, 10):
        cyc = [(i, (i + 1) % n, 1) for i in range(n)]
        lam, _, _ = fiedler_vector(n, cyc, random.Random(n))
        assert abs(lam - 2 * (1 - math.cos(2 * math.pi / n))) < TOL


def test_disconnected_graph_has_zero_lambda2():
    edges = [(0, 1, 1), (1, 2, 1), (0, 2, 1), (3, 4, 1), (4, 5, 1), (3, 5, 1)]
    lam, _, _ = fiedler_vector(6, edges, random.Random(3))
    assert abs(lam) < TOL
    side = spectral_partitioning(6, edges, random.Random(3))
    assert exact_cut(edges, side) == 0


def test_small_cases():
    assert spectral_partitioning(2, [(0, 1, 1)], random.Random(0)) in ([0, 1], [1, 0])
    side = spectral_partitioning(3, [], random.Random(0))
    assert side.count(0) == 1


def roach(k: int) -> tuple[int, list[tuple[int, int, int]]]:
    """Guattery and Miller's roach graph: two paths of 2k vertices, rungs on the first k."""
    edges = []
    for i in range(2 * k - 1):
        edges.append((i, i + 1, 1))
        edges.append((2 * k + i, 2 * k + i + 1, 1))
    edges += [(i, 2 * k + i, 1) for i in range(k)]
    return 4 * k, edges


def test_roach_graph_defeats_the_median_split():
    for k in (3, 4):
        n, edges = roach(k)
        side = spectral_partitioning(n, edges, random.Random(1))
        assert exact_cut(edges, side) == k  # the rungs: upper path against lower path
        assert min_bisection(n, edges) == 2  # cut both paths in the middle
        side = spectral_partitioning(n, edges, random.Random(1), mode="ratio")
        assert exact_cut(edges, side) == 1  # the sweep cuts off one antenna


def test_random_graphs_against_brute_force():
    rng = random.Random(2026)
    for trial in range(120):
        n = rng.randint(3, 10)
        edges = random_graph(rng, n, rng.choice([0.3, 0.5, 0.8]))
        if not edges:
            continue
        lam, x, res = fiedler_vector(n, edges, random.Random(trial))
        ref = jacobi_eigenvalues(laplacian(n, edges))
        assert abs(ref[0]) < TOL
        if res <= 1e-10:
            assert abs(lam - ref[1]) < TOL
        assert lam >= ref[1] - TOL  # a unit vector orthogonal to 1 has Rayleigh quotient >= lambda2
        assert abs(sum(x)) < 1e-9 and abs(sum(t * t for t in x) - 1) < 1e-9
        # Bisection: balanced, cut computed right, never below the optimum,
        # and the optimum is at least n lambda2 / 4.
        side = spectral_partitioning(n, edges, random.Random(trial))
        assert side.count(0) == n // 2
        c = exact_cut(edges, side)
        assert abs(float(c) - cut_weight(edges, side)) < 1e-9
        best = min_bisection(n, edges)
        assert c >= best
        if n % 2 == 0:
            assert float(best) >= n * ref[1] / 4 - TOL
        # Ratio cut sweep: never below the optimum, and the optimum is at
        # least lambda2 / n (Hagen and Kahng).
        side = spectral_partitioning(n, edges, random.Random(trial), mode="ratio")
        a = side.count(0)
        assert 0 < a < n
        r = exact_cut(edges, side) / (a * (n - a))
        best_r = min_ratio_cut(n, edges)
        assert r >= best_r
        assert float(best_r) >= ref[1] / n - TOL

History

Hall (1970) placed the vertices of a graph in rr dimensions by minimizing a quadratic sum of squared edge lengths, and found that the optimum is given by eigenvectors of the Laplacian. Donath and Hoffman (1973) used eigenvectors of graph matrices for partitioning. Fiedler (1973) named λ2\lambda_2 the algebraic connectivity and in 1975 proved the connectivity property of its eigenvectors. Pothen, Simon and Liou (1990) made the median split of the Fiedler vector a standard tool for sparse matrix ordering and parallel computing. Hagen and Kahng (1992) linked λ2\lambda_2 to the ratio cut of circuits and proposed the EIG1 sweep. Guattery and Miller (1998) showed that the method can fail badly, and Spielman and Teng (1996 at FOCS, 2007 in the journal) showed why it works on planar graphs and meshes.

References

  1. Kenneth M. Hall, An r-dimensional quadratic placement algorithm, Management Science 17(3), 219 to 229, 1970, the placement of the vertices by the eigenvectors of the smallest nonzero eigenvalues of the Laplacian, under a norm constraint
  2. Miroslav Fiedler, Algebraic connectivity of graphs, Czechoslovak Mathematical Journal 23(98), 298 to 305, 1973, the second smallest Laplacian eigenvalue as the algebraic connectivity, positive exactly for connected graphs
  3. Miroslav Fiedler, A property of eigenvectors of nonnegative symmetric matrices and its application to graph theory, Czechoslovak Mathematical Journal 25(100), 619 to 633, 1975, the theorem that the vertices with entries of the Fiedler vector at least (or at most) a threshold on the right side of zero induce a connected subgraph
  4. Alex Pothen, Horst D. Simon and Kang-Pu Liou, Partitioning sparse matrices with eigenvectors of graphs, SIAM Journal on Matrix Analysis and Applications 11(3), 430 to 452, 1990, spectral bisection by the median of the Fiedler vector, computed by the Lanczos method, and the vertex separators found from it
  5. Lars Hagen and Andrew B. Kahng, New spectral methods for ratio cut partitioning and clustering, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 11(9), 1074 to 1085, 1992, the bound of the minimum ratio cut by the second eigenvalue over n, and the EIG1 sweep over the sorted eigenvector
  6. Stephen Guattery and Gary L. Miller, On the quality of spectral separators, SIAM Journal on Matrix Analysis and Applications 19(3), 701 to 719, 1998, the roach graph, a family with bisections of constant width on which the median split of the Fiedler vector cuts a linear number of edges
  7. Daniel A. Spielman and Shang-Hua Teng, Spectral partitioning works, planar graphs and finite element meshes, Linear Algebra and its Applications 421(2 to 3), 284 to 305, 2007, the bound on the Fiedler value of bounded degree planar graphs and well-shaped meshes, and the cut ratio of the sweep that follows from it
  8. Andrew B. Kahng, Jens Lienig, Igor L. Markov and Jin Hu, VLSI Physical Design, From Graph Partitioning to Timing Closure, second edition, Springer, 2022, Chapter 2, Netlist and System Partitioning (general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example