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 ? 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 , measure how shortest-path fractal tortuosity (greedy_heuristic_search.grid_shortest_path_search) spikes right at , 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¶
Simulate 2-D 4-connected site percolation (
emergence_verification.site_percolation_2d) across subcritical (), critical (), and supercritical () regimes.Quantify finite-size scaling of spanning probability and giant-component order parameter across lattice sizes .
Compute percolating shortest-path tortuosity via
greedy_heuristic_search.grid_shortest_path_searchand explain why transport paths become maximally winding at .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
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. 2-D Site Percolation (site_percolation_2d): Islands, Fractals & Giant Clusters¶
Consider an square lattice where each site is independently occupied (conductive particle / open pore / live tree) with probability and vacant (insulator / solid grain) with probability . 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 (), 2-D site percolation has a sharp continuous phase transition at the critical threshold (Jacobsen 2015 gives the value to 14 digits):
Subcritical (): All clusters are finite islands with exponentially decaying radius (); macroscopic top-to-bottom conductivity is identically zero.
Critical (): Correlation length diverges (), producing a scale-free fractal spanning cluster of fractal dimension .
Supercritical (): A unique macroscopic giant cluster spans the domain with density ().
heading("Demonstration 1: Subcritical (p=0.45), critical (p=0.593) and supercritical (p=0.72) cluster maps")
L_vis = 64
regimes = [
(0.450, 14, "Subcritical ($p = 0.45 < p_c$)"),
(0.593, 5, "Critical ($p = 0.593 \\approx p_c$)"),
(0.720, 14, "Supercritical ($p = 0.72 > p_c$)"),
]
fig, axes = plt.subplots(2, 2, figsize=(8.8, 8.6))
results_d1 = []
for ax, (pv, sd, title_s) in zip(axes.flat[:3], regimes):
res_p = emergence_verification.site_percolation_2d(L=L_vis, p_occupy=pv, seed=sd)
results_d1.append(res_p)
lbl = res_p["cluster_labels"]
# Color code: 0 = white (vacant), 1 = cool blue (isolated finite clusters), 2 = crimson (spanning giant cluster)
canvas = np.zeros((L_vis, L_vis, 3), dtype=float)
canvas[:, :] = [0.96, 0.97, 0.98]
span_set = set(res_p["spanning_cluster_ids"])
finite_mask = (lbl > 0) & (~np.isin(lbl, list(span_set)))
span_mask = np.isin(lbl, list(span_set)) if span_set else np.zeros_like(res_p["grid"])
canvas[finite_mask] = [0.129, 0.400, 0.675]
canvas[span_mask] = [0.753, 0.224, 0.169]
ax.imshow(canvas, interpolation="nearest")
ax.grid(False)
ax.set_xticks([])
ax.set_yticks([])
ax.set_title(f"{title_s}\n{'spanning' if res_p['percolates_top_to_bottom'] else 'not spanning'}, $P_\\infty={100*res_p['largest_cluster_fraction']:.1f}\\%$", fontsize=9.5)
print(f"p = {pv:.3f}: percolates = {str(res_p['percolates_top_to_bottom']):5s} | clusters = {res_p['n_clusters']:3d} | largest cluster = {100*res_p['largest_cluster_fraction']:5.1f}%")
assert not results_d1[0]["percolates_top_to_bottom"]
assert results_d1[1]["percolates_top_to_bottom"] and results_d1[2]["percolates_top_to_bottom"]
assert results_d1[0]["largest_cluster_fraction"] < 0.08 < results_d1[1]["largest_cluster_fraction"] < results_d1[2]["largest_cluster_fraction"]
# Fourth panel: the largest-cluster fraction of one lattice (seed 14) across p, with the three maps marked
p_line = np.linspace(0.30, 0.90, 25)
frac_line = [emergence_verification.site_percolation_2d(L=L_vis, p_occupy=float(pp), seed=14)["largest_cluster_fraction"] for pp in p_line]
ax4 = axes[1, 1]
ax4.plot(p_line, frac_line, "k.-", label="One $64 \\times 64$ lattice (seed 14)")
ax4.plot([r[0] for r in regimes], [res["largest_cluster_fraction"] for res in results_d1], "o", color="#C0392B", ms=8, label="Maps (a)-(c)")
ax4.axvline(0.5927, color="0.5", ls=":", label="$p_c \\approx 0.5927$")
ax4.set_xlabel("Occupation probability $p$")
ax4.set_ylabel(r"Largest-cluster fraction $P_\infty$")
ax4.set_title("Largest cluster across $p$")
ax4.legend(loc="lower right", fontsize=8.5)
label_panels(fig)
plt.show()
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 14.1. Site percolation on a 64 × 64 lattice. (a)–(c) Clusters at , 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 (seed 14); it rises steeply near (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 is qualitative. At , of the sites are occupied (in a cathode, by carbon black), yet the largest cluster covers of the domain and none spans it. At a thin, branched cluster connects top and bottom; at most occupied sites belong to one cluster, of all lattice sites.
2. Finite-Size Scaling: Why Phase Transitions Sharpen as ¶
On a finite sample, statistical fluctuations smooth the step function over a transition width . Plotting the ensemble spanning probability for reveals two universal signatures of criticality:
The S-curves steepen systematically with , and
All curves cross almost at a single scale-invariant fixed point right at .
heading("Demonstration 2: Finite-size scaling of P_span(p; L) and order parameter P_inf(p; L)")
p_c_exact = 0.592746
p_sweep = np.linspace(0.47, 0.71, 17)
L_list = [16, 32, 64]
n_ens = 80
span_curves: dict[int, np.ndarray] = {}
pinf_curves: dict[int, np.ndarray] = {}
for Lv in L_list:
sp_arr = np.zeros(p_sweep.size, dtype=float)
pi_arr = np.zeros(p_sweep.size, dtype=float)
for idx_p, pv in enumerate(p_sweep):
sp_cnt = 0
pi_sum = 0.0
for tr in range(n_ens):
r_mc = emergence_verification.site_percolation_2d(Lv, float(pv), seed=Lv * 10000 + tr)
sp_cnt += int(r_mc["percolates_top_to_bottom"])
pi_sum += r_mc["largest_cluster_fraction"]
sp_arr[idx_p] = sp_cnt / float(n_ens)
pi_arr[idx_p] = pi_sum / float(n_ens)
span_curves[Lv] = sp_arr
pinf_curves[Lv] = pi_arr
# Measure transition slope dP_span / dp near p_c (sharpening check):
mid_i = int(np.argmin(np.abs(p_sweep - p_c_exact)))
slopes = {Lv: (span_curves[Lv][mid_i + 1] - span_curves[Lv][mid_i - 1]) / (p_sweep[mid_i + 1] - p_sweep[mid_i - 1]) for Lv in L_list}
print("Finite-size transition slope dP_span/dp near p_c:", {Lv: round(float(slopes[Lv]), 2) for Lv in L_list})
print(f"At p = {p_sweep[mid_i]:.3f} (~p_c): P_span = {[round(float(span_curves[Lv][mid_i]), 2) for Lv in L_list]}")
assert slopes[64] > slopes[32] > slopes[16] > 2.0
assert span_curves[64][0] == 0.0 and span_curves[64][-1] == 1.0
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
for Lv, sty in zip(L_list, ["g--^", "b-s", "r-o"]):
ax1.plot(p_sweep, span_curves[Lv], sty, ms=4.5, lw=2.0, label=f"$L = {Lv}$")
ax2.plot(p_sweep, pinf_curves[Lv], sty, ms=4.5, lw=2.0, label=f"$L = {Lv}$")
for ax in (ax1, ax2):
ax.axvline(p_c_exact, color="k", ls=":", lw=1.6, label=f"$p_c \\approx {p_c_exact:.4f}$")
ax.set_xlabel("Site occupation probability $p$")
ax.legend(fontsize=8.3)
ax1.set_ylabel("Spanning probability $P_{\\mathrm{span}}(p; L)$")
ax1.set_title("Spanning probability")
ax2.set_ylabel("Giant-cluster fraction $P_\\infty(p; L)$")
ax2.set_title("Largest-cluster fraction $P_\\infty$")
label_panels(fig)
plt.show()
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 14.2. Finite-size scaling for , 32 and 64. (a) Spanning probability, whose slope at grows with . (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 rises from 7.5 at to 15.8 at , a factor of 2.1 (the scaling predicts ); in the limit the curve becomes a step at .
3. Fractal Tortuosity of the Shortest Percolating Path (grid_shortest_path_search)¶
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:
where 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 , blocked cul-de-sacs force diffusing ions along a self-similar fractal detour of length (), causing tortuosity to spike sharply near before relaxing toward 1.00 as .
heading("Demonstration 3: Percolating geodesic tortuosity peak near p_c via BFS shortest path")
def shortest_top_to_bottom_path(grid_bool: np.ndarray) -> dict:
"""Find shortest 4-connected path from any occupied top-row cell to any occupied bottom-row cell via virtual busbars."""
n = grid_bool.shape[0]
padded = np.full((n + 2, n), math.inf, dtype=float)
padded[0, :] = 1e-9
padded[1 : n + 1, :][grid_bool] = 1.0
padded[n + 1, :] = 1e-9
res_d = greedy_heuristic_search.grid_shortest_path_search(padded, start=(0, 0), goal=(n + 1, n - 1), method="dijkstra")
if not res_d["found"]:
return {"found": False, "geodesic_steps": math.inf, "interior_path": []}
interior_d = [(r - 1, c) for (r, c) in res_d["path"] if 1 <= r <= n]
return {"found": True, "geodesic_steps": len(interior_d), "interior_path": interior_d}
L_tort = 36
p_super = [0.595, 0.62, 0.66, 0.72, 0.80, 0.90, 0.98]
tort_means = []
sample_crit_path = None
sample_crit_grid = None
for pv in p_super:
t_vals = []
sd = 300
while len(t_vals) < 14 and sd < 480:
sd += 1
perc = emergence_verification.site_percolation_2d(L_tort, pv, seed=sd)
if perc["percolates_top_to_bottom"]:
sp = shortest_top_to_bottom_path(perc["grid"])
assert sp["found"]
t_vals.append(sp["geodesic_steps"] / float(L_tort))
if pv == 0.595 and sample_crit_path is None:
sample_crit_path = sp["interior_path"]
sample_crit_grid = perc["grid"]
tort_means.append(float(np.mean(t_vals)))
print("Supercritical tortuosity tau(p) = L_min / L across p:",
{pv: round(tv, 3) for pv, tv in zip(p_super, tort_means)})
assert tort_means[0] > 1.30 and tort_means[0] > tort_means[2] > tort_means[-1]
assert 1.0 <= tort_means[-1] < 1.04
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
vis_g = np.where(sample_crit_grid, 0.82, 0.12)
ax1.imshow(vis_g, cmap="Greys", vmin=0.0, vmax=1.0, interpolation="nearest")
ax1.grid(False)
pr_y = [r for r, _ in sample_crit_path]
pc_x = [c for _, c in sample_crit_path]
ax1.plot(pc_x, pr_y, color="#C0392B", lw=2.3, label=f"Shortest path ($\\tau = {len(sample_crit_path)/L_tort:.2f}$)")
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title(f"Shortest path ($L={L_tort},\\ p=0.595$)")
ax1.legend(loc="upper center", bbox_to_anchor=(0.5, -0.02), fontsize=8.2)
ax2.plot(p_super, tort_means, "r-o", ms=6, lw=2.2, label="Ensemble tortuosity $\\tau(p) = \\mathbb{E}[L_{\\min}]/L$")
ax2.axvline(0.592746, color="k", ls=":", lw=1.6, label="$p_c \\approx 0.5927$ (critical divergence)")
ax2.axhline(1.0, color="gray", ls="--", lw=1.3, label="Straight-line limit $\\tau = 1.00$")
ax2.set_xlabel("Pore / conductive site fraction $p$")
ax2.set_ylabel("Geodesic tortuosity $\\tau = L_{\\min} / L$")
ax2.set_title("Tortuosity against $p$")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
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 14.3. Tortuosity of the shortest spanning path. (a) The shortest top-to-bottom path through open sites on a 36 × 36 lattice at . (b) Ensemble tortuosity against : 1.46 just above , falling to 1 as .
What Demonstration 3 shows. Effective porous diffusivity scales as . Just above , not only is the connected pore fraction small, its path tortuosity reduces the diffusive flux by a further factor , 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 micrograph ( pixels)?
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 withRecursionError.Naive Global Label-Relabeling (
labels[labels == old_id] = new_idon every merge): Costs per cross-cluster bridge .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 , which is linear in for all practical sizes.
heading("Demonstration 4: Path-compressed union-find O(N) against naive equivalence-scan relabeling O(N^2)")
L_bench = np.array([12, 18, 26, 38, 54, 76])
ops_union_find, ops_naive_relabel = [], []
for Lb in L_bench:
n_side = int(Lb)
g_b = np.random.default_rng(1404 + n_side).random((n_side, n_side)) < 0.60
n_tot = n_side * n_side
# 1. Path-compressed Union-Find operation count:
parent = list(range(n_tot))
uf_ops = [0]
def _find_op(x: int) -> int:
uf_ops[0] += 1
while parent[x] != x:
uf_ops[0] += 1
parent[x] = parent[parent[x]]
x = parent[x]
return x
for r in range(n_side):
for c in range(n_side):
if not g_b[r, c]:
continue
idx = r * n_side + c
if r > 0 and g_b[r - 1, c]:
ra, rb = _find_op(idx), _find_op((r - 1) * n_side + c)
if ra != rb:
parent[max(ra, rb)] = min(ra, rb)
if c > 0 and g_b[r, c - 1]:
ra, rb = _find_op(idx), _find_op(r * n_side + c - 1)
if ra != rb:
parent[max(ra, rb)] = min(ra, rb)
for idx in range(n_tot):
if g_b[idx // n_side, idx % n_side]:
_find_op(idx)
ops_union_find.append(uf_ops[0])
# 2. Naive global array-relabeling (`labels[labels == old_lbl] = new_lbl` scans active grid on every merge):
lbl_naive = np.zeros((n_side, n_side), dtype=int)
next_id = 0
relabel_ops = 0
for r in range(n_side):
for c in range(n_side):
if not g_b[r, c]:
continue
relabel_ops += 1
up = int(lbl_naive[r - 1, c]) if r > 0 else 0
left = int(lbl_naive[r, c - 1]) if c > 0 else 0
if up == 0 and left == 0:
next_id += 1
lbl_naive[r, c] = next_id
elif up > 0 and left == 0:
lbl_naive[r, c] = up
elif up == 0 and left > 0:
lbl_naive[r, c] = left
elif up == left:
lbl_naive[r, c] = up
else:
keep, drop = min(up, left), max(up, left)
lbl_naive[r, c] = keep
# Scanning the r+1 populated rows to overwrite `drop -> keep` costs (r + 1) * n_side checks
relabel_ops += (r + 1) * n_side
lbl_naive[: r + 1, :][lbl_naive[: r + 1, :] == drop] = keep
ops_naive_relabel.append(relabel_ops)
n_sites = (L_bench ** 2).astype(float)
fit_comp = invariants_complexity.fit_empirical_complexity(n_sites, np.array(ops_union_find, dtype=float))
fit_naive = invariants_complexity.fit_empirical_complexity(n_sites, np.array(ops_naive_relabel, dtype=float))
print(f"Path-compressed Union-Find : empirical exponent p = {fit_comp['exponent_p']:.3f} ({fit_comp['complexity_class']}), ops at L=76 = {ops_union_find[-1]:,}")
print(f"Naive array relabeling : empirical exponent p = {fit_naive['exponent_p']:.3f} ({fit_naive['complexity_class']}), ops at L=76 = {ops_naive_relabel[-1]:,} ({ops_naive_relabel[-1]/ops_union_find[-1]:.1f}x more ops)")
assert 0.90 < fit_comp["exponent_p"] < 1.10
assert fit_naive["exponent_p"] > 1.70 and ops_naive_relabel[-1] > 15.0 * ops_union_find[-1]
fig, ax = plt.subplots(figsize=(7.5, 4.1))
ax.loglog(n_sites, ops_naive_relabel, "r-s", ms=6, lw=2.1, label=f"Naive global relabeling ($N^{{{fit_naive['exponent_p']:.2f}}} \\approx \\mathcal{{O}}(N^2)$)")
ax.loglog(n_sites, ops_union_find, "b-o", ms=6, lw=2.2, label=f"Path-compressed union-find ($N^{{{fit_comp['exponent_p']:.2f}}} \\approx \\mathcal{{O}}(N)$)")
ax.set_xlabel("Total lattice sites $N = L^2$ (log scale)")
ax.set_ylabel("Elementary operations")
ax.set_title("Path-compressed union-find against global relabelling")
ax.legend(fontsize=8.4)
log_ticks(ax, "x", [200, 500, 1000, 2000, 5000])
plt.show()
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 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 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 ), 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¶
heading("Inside the algorithm: Union-find percolation and standalone Hoshen-Kopelman raster labeler")
print(show_source(emergence_verification.site_percolation_2d))
def hoshen_kopelman_single_pass(grid: np.ndarray) -> dict:
"""Classic Hoshen-Kopelman (1976) raster-scan cluster labeler verifying exact cluster-size multisets."""
g = np.asarray(grid, dtype=bool)
n_r, n_c = g.shape
labels = np.zeros((n_r, n_c), dtype=int)
alias = [0] # 1-indexed disjoint-set alias table over cluster IDs only (much smaller than L^2)
def _root(lbl: int) -> int:
while alias[lbl] != lbl:
alias[lbl] = alias[alias[lbl]]
lbl = alias[lbl]
return lbl
for r in range(n_r):
for c in range(n_c):
if not g[r, c]:
continue
up = _root(int(labels[r - 1, c])) if (r > 0 and labels[r - 1, c] > 0) else 0
left = _root(int(labels[r, c - 1])) if (c > 0 and labels[r, c - 1] > 0) else 0
if up == 0 and left == 0:
new_id = len(alias)
alias.append(new_id)
labels[r, c] = new_id
elif up > 0 and left == 0:
labels[r, c] = up
elif up == 0 and left > 0:
labels[r, c] = left
else:
keep = min(up, left)
alias[max(up, left)] = keep
labels[r, c] = keep
# Canonicalize labels & count exact cluster sizes:
canon_map: dict[int, int] = {}
sizes: list[int] = []
for r in range(n_r):
for c in range(n_c):
if labels[r, c] > 0:
rt = _root(int(labels[r, c]))
cid = canon_map.get(rt)
if cid is None:
cid = len(sizes) + 1
canon_map[rt] = cid
sizes.append(0)
labels[r, c] = cid
sizes[cid - 1] += 1
top_set = set(labels[0, labels[0, :] > 0].tolist())
bot_set = set(labels[-1, labels[-1, :] > 0].tolist())
return {
"labels": labels,
"sorted_sizes": sorted(sizes, reverse=True),
"percolates": len(top_set & bot_set) > 0,
"provisional_labels_allocated": len(alias) - 1,
}
for p_test in [0.42, 0.593, 0.74]:
lib_p = emergence_verification.site_percolation_2d(56, p_test, seed=99)
hk_p = hoshen_kopelman_single_pass(lib_p["grid"])
# Extract sorted cluster sizes from library labels:
_, lib_counts = np.unique(lib_p["cluster_labels"][lib_p["cluster_labels"] > 0], return_counts=True)
lib_sorted = sorted(lib_counts.tolist(), reverse=True)
assert lib_sorted == hk_p["sorted_sizes"]
assert lib_p["percolates_top_to_bottom"] == hk_p["percolates"]
print(f"p={p_test:.3f}: exact multiset match across {len(lib_sorted)} clusters (top-3 sizes = {hk_p['sorted_sizes'][:3]}, HK aliases = {hk_p['provisional_labels_allocated']} << {56*56})")
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.
Verify a result. Generate an ensemble of fixed uniform threshold fields
U = rng.random((150, 50, 50))(). Prove that pixelwise couplinggrid = (U[k] < p)makes the ensemble spanning probability strictly non-decreasing in , then passpredicate = lambda p: ensemble_p_span(p) >= 0.5intodivide_spatial.parametric_binary_search_min(predicate, lo=0.45, hi=0.75, tol=1e-4)to locate automatically and compare against .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 . Verify exact matching-lattice topological duality across 200 random realizations (
top-to-bottom 4-connected occupied path existsNO left-to-right 8-connected vacant path exists), proving and exposing the 18.5 percentage-point prediction error at .Implement it yourself. Implement
random_resistor_network_conductance(perc_grid)in NumPy solving Kirchhoff’s current law on interior occupied sites of an lattice with on occupied top-row sites, on occupied bottom-row sites, and unit conductance between 4-connected occupied neighbors. Verify exact current conservation , separate the spanning cluster into the current-carrying backbone () vs. dead-end dangling mass (), and verify that near more than half of the spanning cluster carries no current.
heading("Self-check for the exercises")
assert not results_d1[0]["percolates_top_to_bottom"] and results_d1[1]["percolates_top_to_bottom"], "Critical percolation regime check failed"
assert slopes[64] > slopes[32] > slopes[16], "Finite-size sharpening check failed"
assert tort_means[0] > tort_means[-1] and tort_means[-1] < 1.04, "Geodesic tortuosity check failed"
assert 0.90 < fit_comp["exponent_p"] < 1.12, "Union-Find linear complexity check failed"
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.