Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

14. Percolation: critical thresholds and cluster connectivity

School of Engineering, Nazarbayev University

Why can a small increase in the fraction of conductive carbon black in a battery cathode raise its electrical conductivity by many orders of magnitude? Why does flow through a rock stop below a critical fraction of open pore throats, and why does a fire in a lattice model of a forest cross the whole forest once the tree density exceeds 59.3 %59.3\,\%? The linear intuition that 1 % more material gives 1 % more flow fails near such a geometrical phase transition (Mental Move #23: Locate Critical Thresholds Before Micro-Detailing). In this lecture, you will simulate 2-D square-lattice site percolation (emergence_verification.site_percolation_2d), reveal universal finite-size sharpening around pc≈0.592746p_c \approx 0.592746, measure how shortest-path fractal tortuosity (greedy_heuristic_search.grid_shortest_path_search) spikes right at pcp_c, benchmark path-compressed Union-Find against Hoshen-Kopelman raster labeling, and solve Kirchhoff resistor networks to show that dead-end branches carry no current.

Learning objectives

  1. Simulate 2-D 4-connected site percolation (emergence_verification.site_percolation_2d) across subcritical (p<pcp < p_c), critical (p≈0.5927p \approx 0.5927), and supercritical (p>pcp > p_c) regimes.

  2. Quantify finite-size scaling of spanning probability Pspan(p;L)P_{\mathrm{span}}(p; L) and giant-component order parameter P∞(p;L)P_\infty(p; L) across lattice sizes L∈{16,32,64}L \in \{16, 32, 64\}.

  3. Compute percolating shortest-path tortuosity τ(p)=Lmin⁡(p)/L\tau(p) = L_{\min}(p)/L via greedy_heuristic_search.grid_shortest_path_search and explain why transport paths become maximally winding at pcp_c.

  4. Implement single-pass Hoshen-Kopelman cluster labeling and Kirchhoff nodal conductance solvers to distinguish the current-carrying backbone from zero-current dangling mass.

Time: about 60 min

1. 2-D Site Percolation (site_percolation_2d): Islands, Fractals & Giant Clusters

Consider an L×LL \times L square lattice where each site (r,c)(r, c) is independently occupied (conductive particle / open pore / live tree) with probability p∈[0,1]p \in [0, 1] and vacant (insulator / solid grain) with probability 1−p1 - p. Two occupied sites belong to the same cluster if connected by a chain of 4-nearest neighbors (up, down, left, right).

On an infinite square lattice (L→∞L \to \infty), 2-D site percolation has a sharp continuous phase transition at the critical threshold (Jacobsen 2015 gives the value to 14 digits):

pcsite,4≈0.59274605(1.1)p_c^{\mathrm{site,4}} \approx 0.59274605 \tag{1.1}
  • Subcritical (p<pcp < p_c): All clusters are finite islands with exponentially decaying radius ξ(p)∼∣p−pc∣−ν\xi(p) \sim |p - p_c|^{-\nu} (ν=4/3\nu = 4/3); macroscopic top-to-bottom conductivity is identically zero.

  • Critical (p=pcp = p_c): Correlation length diverges (ξ→∞\xi \to \infty), producing a scale-free fractal spanning cluster of fractal dimension df=91/48≈1.896d_f = 91/48 \approx 1.896.

  • Supercritical (p>pcp > p_c): A unique macroscopic giant cluster spans the domain with density P∞(p)∼(p−pc)βP_\infty(p) \sim (p - p_c)^\beta (β=5/36≈0.139\beta = 5/36 \approx 0.139).


Demonstration 1: Subcritical (p=0.45), critical (p=0.593) and supercritical (p=0.72) cluster maps
=================================================================================================
p = 0.450: percolates = False | clusters = 366 | largest cluster =   1.8%
p = 0.593: percolates = True  | clusters = 111 | largest cluster =  22.8%
p = 0.720: percolates = True  | clusters =  25 | largest cluster =  70.5%
<Figure size 968x946 with 4 Axes>

Figure 14.1. Site percolation on a 64 × 64 lattice. (a)–(c) Clusters at p=0.45p = 0.45, 0.593 and 0.72; finite clusters are blue, the spanning cluster red. (d) Fraction of sites in the largest cluster of one lattice against pp (seed 14); it rises steeply near pcp_c (dotted). The red points mark the three maps; map (b) uses another seed and lies off the curve.

What Demonstration 1 shows. The change across Δp=0.27\Delta p = 0.27 is qualitative. At p=0.45p = 0.45, 45 %45\,\% of the sites are occupied (in a cathode, by carbon black), yet the largest cluster covers 1.8 %1.8\,\% of the domain and none spans it. At p=0.593p = 0.593 a thin, branched cluster connects top and bottom; at p=0.72p = 0.72 most occupied sites belong to one cluster, 70.5 %70.5\,\% of all lattice sites.


2. Finite-Size Scaling: Why Phase Transitions Sharpen as L→∞L \to \infty

On a finite L×LL \times L sample, statistical fluctuations smooth the step function Θ(p−pc)\Theta(p - p_c) over a transition width Δp(L)∼L−1/ν=L−3/4\Delta p(L) \sim L^{-1/\nu} = L^{-3/4}. Plotting the ensemble spanning probability Pspan(p;L)P_{\mathrm{span}}(p; L) for L∈{16,32,64}L \in \{16, 32, 64\} reveals two universal signatures of criticality:

  1. The S-curves steepen systematically with LL, and

  2. All curves cross almost at a single scale-invariant fixed point right at pc≈0.5927p_c \approx 0.5927.


Demonstration 2: Finite-size scaling of P_span(p; L) and order parameter P_inf(p; L)
====================================================================================
Finite-size transition slope dP_span/dp near p_c: {16: 7.5, 32: 9.58, 64: 15.83}
At p = 0.590 (~p_c): P_span = [0.46, 0.55, 0.53]
<Figure size 1254x451 with 2 Axes>

Figure 14.2. Finite-size scaling for L=16L = 16, 32 and 64. (a) Spanning probability, whose slope at pcp_c grows with LL. (b) Fraction of sites in the largest cluster.

What Demonstration 2 shows. Using common random numbers (seed = Lv * 10000 + tr, independent of pv) makes every finite-size curve monotonically non-decreasing. The maximum slope dPspan/dp\mathrm{d}P_{\mathrm{span}}/\mathrm{d}p rises from 7.5 at L=16L = 16 to 15.8 at L=64L = 64, a factor of 2.1 (the scaling L1/νL^{1/\nu} predicts 43/4=2.84^{3/4} = 2.8); in the limit L→∞L \to \infty the curve becomes a step at pc=0.5927p_c = 0.5927.


In porous battery electrodes, catalytic packed beds, and fractured aquifers, transport resistance depends not only on whether a pore network percolates, but on its hydraulic/diffusive tortuosity:

τ(p)=Lmin⁡(p)L≥1(3.1)\tau(p) = \frac{L_{\min}(p)}{L} \ge 1 \tag{3.1}

where Lmin⁡(p)L_{\min}(p) is the chemical (graph-geodesic) shortest path from the top boundary to the bottom boundary through open pores (greedy_heuristic_search.grid_shortest_path_search with method="bfs"). Right at p=pcp = p_c, blocked cul-de-sacs force diffusing ions along a self-similar fractal detour of length Lmin⁡∼Ldmin⁡L_{\min} \sim L^{d_{\min}} (dmin⁡≈1.1307>1d_{\min} \approx 1.1307 > 1), causing tortuosity τ(p)\tau(p) to spike sharply near pcp_c before relaxing toward 1.00 as p→1p \to 1.


Demonstration 3: Percolating geodesic tortuosity peak near p_c via BFS shortest path
====================================================================================
Supercritical tortuosity tau(p) = L_min / L across p: {0.595: 1.458, 0.62: 1.405, 0.66: 1.268, 0.72: 1.141, 0.8: 1.065, 0.9: 1.016, 0.98: 1.0}
<Figure size 1254x451 with 2 Axes>

Figure 14.3. Tortuosity of the shortest spanning path. (a) The shortest top-to-bottom path through open sites on a 36 × 36 lattice at p=0.595p = 0.595. (b) Ensemble tortuosity against pp: 1.46 just above pcp_c, falling to 1 as p→1p \to 1.

What Demonstration 3 shows. Effective porous diffusivity scales as Deff∝ετ2D0D_{\mathrm{eff}} \propto \frac{\varepsilon}{\tau^2} D_0. Just above pcp_c, not only is the connected pore fraction small, its path tortuosity τ≈1.45\tau \approx 1.45 reduces the diffusive flux by a further factor τ2≈2.1\tau^2 \approx 2.1, because the path winds sideways and even locally upward around dead ends.


4. Union-Find Path Compression vs. Naive Relabeling & Recursive Flood-Fill Pitfalls

How should we label connected components on a 1000×10001000 \times 1000 micrograph (N=106N = 10^6 pixels)?

  1. Naive Python Recursive DFS Flood-Fill: On a cluster of more than about 1,000 pixels, recursive dfs(r, c) can exceed Python’s default recursion limit (sys.getrecursionlimit() == 1000) and stop with RecursionError.

  2. Naive Global Label-Relabeling (labels[labels == old_id] = new_id on every merge): Costs O(N)\mathcal{O}(N) per cross-cluster bridge ⇒O(N2)=O(L4)\Rightarrow \mathcal{O}(N^2) = \mathcal{O}(L^4).

  3. Disjoint-Set Union-Find with Path Compression (site_percolation_2d): Every _find(x) flattens parent pointers directly toward the root (parent[x] = parent[parent[x]]), running in O(N α(N))\mathcal{O}(N\,\alpha(N)), which is linear in N=L2N = L^2 for all practical sizes.


Demonstration 4: Path-compressed union-find O(N) against naive equivalence-scan relabeling O(N^2)
=================================================================================================
Path-compressed Union-Find : empirical exponent p = 1.029 (O(N)), ops at L=76 = 19,949
Naive array relabeling     : empirical exponent p = 1.924 (O(N^2)), ops at L=76 = 1,181,023 (59.2x more ops)
<Figure size 825x451 with 1 Axes>

Figure 14.4. Operations of cluster labelling against the number of sites. Path-compressed union-find grows with exponent 1.03, global relabelling with exponent 1.92.

Inside the algorithm

For very large lattices the N=L2N = L^2 parent pointers may not fit in memory. Hoshen and Kopelman (1976) noticed that a raster scan from top to bottom only needs the current row and the row above it (an active frontier of size O(L)\mathcal{O}(L)), with cluster-label aliases kept on the fly. We inspect emergence_verification.site_percolation_2d and verify exact cluster-size multiset equivalence against a standalone hoshen_kopelman_single_pass implementation.

Check against the library


Inside the algorithm: Union-find percolation and standalone Hoshen-Kopelman raster labeler
==========================================================================================
def site_percolation_2d(L: int, p_occupy: float, seed: int = 42) -> dict:
    """Generate an L x L 2-D site percolation lattice and label 4-connected clusters via Union-Find."""
    n = int(L)
    if n < 2 or not (0.0 <= p_occupy <= 1.0):
        raise ValueError("Require L >= 2 and p_occupy in [0, 1].")
    rng = np.random.default_rng(seed)
    grid = rng.random((n, n)) < float(p_occupy)

    parent = list(range(n * n))

    def _find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    def _union(a: int, b: int) -> None:
        ra, rb = _find(a), _find(b)
        if ra != rb:
            if ra < rb:
                parent[rb] = ra
            else:
                parent[ra] = rb

    for r in range(n):
        for c in range(n):
            if not grid[r, c]:
                continue
            idx = r * n + c
            if r > 0 and grid[r - 1, c]:
                _union(idx, (r - 1) * n + c)
            if c > 0 and grid[r, c - 1]:
                _union(idx, r * n + (c - 1))

    labels = np.zeros((n, n), dtype=int)
    root_to_id: dict[int, int] = {}
    sizes: list[int] = []
    for r in range(n):
        for c in range(n):
            if grid[r, c]:
                rt = _find(r * n + c)
                cid = root_to_id.get(rt)
                if cid is None:
                    cid = len(sizes) + 1
                    root_to_id[rt] = cid
                    sizes.append(0)
                labels[r, c] = cid
                sizes[cid - 1] += 1

    top_ids = set(labels[0, labels[0, :] > 0].tolist())
    bot_ids = set(labels[-1, labels[-1, :] > 0].tolist())
    spanning = top_ids & bot_ids
    max_sz = max(sizes) if sizes else 0
    return {
        "grid": grid,
        "cluster_labels": labels,
        "percolates_top_to_bottom": len(spanning) > 0,
        "spanning_cluster_ids": sorted(spanning),
        "largest_cluster_fraction": max_sz / float(n * n),
        "n_clusters": len(sizes),
    }

p=0.420: exact multiset match across 339 clusters (top-3 sizes = [58, 40, 28], HK aliases = 468 << 3136)
p=0.593: exact multiset match across 110 clusters (top-3 sizes = [384, 308, 270], HK aliases = 327 << 3136)
p=0.740: exact multiset match across 19 clusters (top-3 sizes = [2264, 9, 6], HK aliases = 173 << 3136)

Exercises

Worked solutions are in 14_solutions.ipynb. The cell below the list is a short self-check to start from.

  1. Verify a result. Generate an ensemble of M=150M = 150 fixed uniform threshold fields U = rng.random((150, 50, 50)) (L=50L = 50). Prove that pixelwise coupling grid = (U[k] < p) makes the ensemble spanning probability P^span(p)\hat{P}_{\mathrm{span}}(p) strictly non-decreasing in pp, then pass predicate = lambda p: ensemble_p_span(p) >= 0.5 into divide_spatial.parametric_binary_search_min(predicate, lo=0.45, hi=0.75, tol=1e-4) to locate pc(50)p_c(50) automatically and compare against pc∞=0.592746p_c^\infty = 0.592746.

  2. Find how it fails. Audit the 4-Connectivity vs. 8-Connectivity Lattice Stencil Trap: implement 8-connected (Moore neighborhood: orthogonal + diagonal) percolation alongside 4-connected percolation on L=48L = 48. Verify exact matching-lattice topological duality across 200 random realizations (top-to-bottom 4-connected occupied path exists   ⟺  \iff NO left-to-right 8-connected vacant path exists), proving pc,8=1−pc,4≈0.4073p_{c,8} = 1 - p_{c,4} \approx 0.4073 and exposing the 18.5 percentage-point prediction error at p=0.50p = 0.50.

  3. Implement it yourself. Implement random_resistor_network_conductance(perc_grid) in NumPy solving Kirchhoff’s current law ∑v∼uguv(Vu−Vv)=0\sum_{v \sim u} g_{uv}(V_u - V_v) = 0 on interior occupied sites of an L×LL \times L lattice with V=1 VV = 1\ \mathrm{V} on occupied top-row sites, V=0 VV = 0\ \mathrm{V} on occupied bottom-row sites, and unit conductance guv=1 Sg_{uv} = 1\ \mathrm{S} between 4-connected occupied neighbors. Verify exact current conservation Itop,in==Ibottom,outI_{\mathrm{top,in}} == I_{\mathrm{bottom,out}}, separate the spanning cluster into the current-carrying backbone (Inode>10−8I_{\mathrm{node}} > 10^{-8}) vs. dead-end dangling mass (Inode≤10−8I_{\mathrm{node}} \le 10^{-8}), and verify that near p≈0.605p \approx 0.605 more than half of the spanning cluster carries no current.


Self-check for the exercises
============================
All checks passed.