Worked solutions to the three exercises of Lecture 14. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
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))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
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()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Generate an ensemble of fixed uniform threshold fields U = rng.random((150, 50, 50)) (). Prove that pixelwise coupling grid = (U[k] < p) makes the ensemble spanning probability strictly non-decreasing in , 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 automatically and compare against .
heading("Exercise 1: Automated percolation threshold discovery via common-random-number bisection")
rng_crn = np.random.default_rng(1401)
n_ens_e1 = 80
L_e1 = 50
u_fields = rng_crn.random((n_ens_e1, L_e1, L_e1))
def spans_top_bottom_fast(g: np.ndarray) -> bool:
"""BFS check whether 4-connected occupied True cells bridge row 0 to row L-1."""
from collections import deque
n = g.shape[0]
starts = [(0, c) for c in range(n) if g[0, c]]
if not starts or not np.any(g[-1, :]):
return False
seen = np.zeros((n, n), dtype=bool)
q = deque(starts)
for r, c in starts:
seen[r, c] = True
while q:
r, c = q.popleft()
if r == n - 1:
return True
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n and g[nr, nc] and not seen[nr, nc]:
seen[nr, nc] = True
q.append((nr, nc))
return False
probe_history: list[tuple[float, float]] = []
def ensemble_pspan(p_val: float) -> float:
cnt = sum(1 for k in range(n_ens_e1) if spans_top_bottom_fast(u_fields[k] < p_val))
frac = cnt / float(n_ens_e1)
probe_history.append((p_val, frac))
return frac
bisect_res = divide_spatial.parametric_binary_search_min(
lambda pv: ensemble_pspan(pv) >= 0.50, lo=0.45, hi=0.75, tol=1e-4
)
pc_est = bisect_res["threshold"]
pc_inf = 0.59274605
abs_err_pc = abs(pc_est - pc_inf)
print(f"Bisection converged in {bisect_res['evaluations']} ensemble evaluations: p_c(L=50) = {pc_est:.5f}")
print(f"Infinite-lattice benchmark p_c = {pc_inf:.5f} (|error| = {abs_err_pc:.5f})")
assert bisect_res["feasible"] and bisect_res["evaluations"] <= 16
assert abs_err_pc < 0.012
p_dense = np.linspace(0.52, 0.66, 15)
ps_dense = [sum(1 for k in range(n_ens_e1) if spans_top_bottom_fast(u_fields[k] < pv)) / float(n_ens_e1) for pv in p_dense]
assert np.all(np.diff(ps_dense) >= -1e-15) # Exact CRN monotonicity
fig, ax = plt.subplots(figsize=(7.5, 4.1))
ax.plot(p_dense, ps_dense, "b-", lw=2.2, label="CRN monotone $\\hat{P}_{\\mathrm{span}}(p; L=50)$")
pr_x = [x for x, _ in probe_history]
pr_y = [y for _, y in probe_history]
ax.scatter(pr_x, pr_y, c="#C0392B", s=42, zorder=5, label=f"Binary-search probes ({bisect_res['evaluations']} evals)")
ax.axvline(pc_est, color="#C0392B", ls="--", lw=1.7, label=f"Bisected $p_c(50) = {pc_est:.4f}$")
ax.axvline(pc_inf, color="k", ls=":", lw=1.6, label=f"Exact $p_c^\\infty = {pc_inf:.4f}$")
ax.axhline(0.50, color="gray", ls="-.", lw=1.2)
ax.set_xlabel("Occupation probability $p$")
ax.set_ylabel("Ensemble spanning probability $\\hat{P}_{\\mathrm{span}}(p)$")
ax.set_title("Threshold by bisection with common random numbers")
ax.legend(fontsize=8.2)
plt.show()
Exercise 1: Automated percolation threshold discovery via common-random-number bisection
========================================================================================
Bisection converged in 14 ensemble evaluations: p_c(L=50) = 0.59414
Infinite-lattice benchmark p_c = 0.59275 (|error| = 0.00139)

Figure S14.1. Ensemble spanning probability on 50 × 50 lattices with common random numbers (line), the points evaluated by bisection, and the bisected threshold 0.5941 against .
Explanation. If you re-seeded a fresh random generator inside predicate(p), Monte Carlo jitter near would violate monotonicity (for example True at 0.591 and False at 0.592) and corrupt binary search. Coupling all evaluations to the same underlying uniform matrix U (Common Random Numbers, coupling Mental Moves #11 and #23) turns the noisy simulation into a deterministic, monotone step function, and bisection narrows the interval by a factor of 3,000 in 14 ensemble evaluations. The result, , differs from the infinite-lattice value by 0.0014.
Exercise 2¶
Problem. 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 exists NO left-to-right 8-connected vacant path exists), proving and exposing the 18.5 percentage-point prediction error at .
heading("Exercise 2: Exact 4- against 8-connectivity topological duality and 18.5% threshold shift")
from collections import deque
def spans_grid(g: np.ndarray, eight_conn: bool, top_to_bottom: bool = True) -> bool:
"""Check top-to-bottom (or left-to-right) connectivity under 4- or 8-neighbor stencil."""
mat = g if top_to_bottom else g.T
n = mat.shape[0]
starts = [(0, c) for c in range(n) if mat[0, c]]
if not starts or not np.any(mat[-1, :]):
return False
moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
if eight_conn:
moves += [(-1, -1), (-1, 1), (1, -1), (1, 1)]
seen = np.zeros((n, n), dtype=bool)
q = deque(starts)
for r, c in starts:
seen[r, c] = True
while q:
r, c = q.popleft()
if r == n - 1:
return True
for dr, dc in moves:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n and mat[nr, nc] and not seen[nr, nc]:
seen[nr, nc] = True
q.append((nr, nc))
return False
# 1. Verify exact deterministic Hex/Square topological duality on 200 random grids near criticality:
rng_d2 = np.random.default_rng(1402)
duality_matches = 0
for _ in range(200):
p_rand = float(rng_d2.uniform(0.35, 0.65))
grid_r = rng_d2.random((40, 40)) < p_rand
occ_4_tb = spans_grid(grid_r, eight_conn=False, top_to_bottom=True)
vac_8_lr = spans_grid(~grid_r, eight_conn=True, top_to_bottom=False)
# Exact Jordan-curve lattice theorem: occupied 4-path top->bottom XOR vacant 8-path left->right
assert occ_4_tb == (not vac_8_lr)
duality_matches += 1
# 2. Sweep p in [0.28, 0.72] on L = 48 comparing P_span,4(p) vs P_span,8(p):
p_grid_e2 = np.linspace(0.28, 0.72, 19)
ps4, ps8 = [], []
for pv in p_grid_e2:
c4, c8 = 0, 0
for tr in range(80):
gr = np.random.default_rng(7000 + tr).random((48, 48)) < float(pv)
c4 += int(spans_grid(gr, eight_conn=False, top_to_bottom=True))
c8 += int(spans_grid(gr, eight_conn=True, top_to_bottom=True))
ps4.append(c4 / 80.0)
ps8.append(c8 / 80.0)
idx_50 = int(np.argmin(np.abs(p_grid_e2 - 0.50)))
print(f"Topological duality verified on {duality_matches}/200 random realizations (0 exceptions)")
print(f"At p = {p_grid_e2[idx_50]:.2f}: 4-connected P_span = {100*ps4[idx_50]:.1f}% (insulating) vs. 8-connected P_span = {100*ps8[idx_50]:.1f}% (percolating)")
assert ps4[idx_50] == 0.0 and ps8[idx_50] == 1.0
fig, ax = plt.subplots(figsize=(7.6, 4.1))
ax.plot(p_grid_e2, ps8, "r-s", ms=5, lw=2.2, label="8-connected Moore stencil ($p_{c,8} = 1 - p_{c,4} \\approx 0.4073$)")
ax.plot(p_grid_e2, ps4, "b-o", ms=5, lw=2.2, label="4-connected von Neumann stencil ($p_{c,4} \\approx 0.5927$)")
ax.axvspan(0.4073, 0.5927, color="#E08214", alpha=0.18, label="Thresholds differ by 18.5 percentage points")
ax.axvline(0.407254, color="r", ls=":", lw=1.5)
ax.axvline(0.592746, color="b", ls=":", lw=1.5)
ax.set_xlabel("Site occupation fraction $p$")
ax.set_ylabel("Spanning probability $P_{\\mathrm{span}}(p; L=48)$")
ax.set_title("4- and 8-neighbour spanning: $p_{c,8} + p_{c,4} = 1$")
ax.legend(loc="center left", bbox_to_anchor=(1.01, 0.5), fontsize=8.2)
plt.show()
Exercise 2: Exact 4- against 8-connectivity topological duality and 18.5% threshold shift
=========================================================================================
Topological duality verified on 200/200 random realizations (0 exceptions)
At p = 0.50: 4-connected P_span = 0.0% (insulating) vs. 8-connected P_span = 100.0% (percolating)

Figure S14.2. Spanning probability on lattices with 4- and 8-neighbour connectivity. The thresholds differ by 18.5 percentage points (shaded).
Explanation. On a 2-D square grid, a 4-connected river of occupied cells from North to South is blocked if and only if a continuous wall of vacant cells stretches from West to East—and because two diagonal wall stones block a 4-connected orthogonal step (corner-touching blocks orthogonal crossing), the blocking wall is 8-connected. By symmetry at , , forcing . Allowing diagonal neighbours in image segmentation or pore-network code without thought shifts the threshold by 18.5 percentage points: at the 4-connected lattice never spans and the 8-connected lattice always does.
Exercise 3¶
Problem. 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("Exercise 3: Implement it yourself — Kirchhoff random resistor network (backbone against dangling ends)")
from collections import deque
def random_resistor_network_conductance(perc_grid: np.ndarray) -> dict:
"""Solve exact nodal voltages V and effective conductance G_eff on a 2-D 4-connected percolating lattice."""
g = np.asarray(perc_grid, dtype=bool)
n_r, n_c = g.shape
# Identify the exact spanning cluster(s) connecting row 0 AND row n_r - 1 via 4-connected BFS:
visited = np.zeros((n_r, n_c), dtype=bool)
span_mask = np.zeros((n_r, n_c), dtype=bool)
for c0 in range(n_c):
if g[0, c0] and not visited[0, c0]:
comp = [(0, c0)]
visited[0, c0] = True
q = deque([(0, c0)])
touches_bottom = False
while q:
r, c = q.popleft()
if r == n_r - 1:
touches_bottom = True
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < n_r and 0 <= nc < n_c and g[nr, nc] and not visited[nr, nc]:
visited[nr, nc] = True
comp.append((nr, nc))
q.append((nr, nc))
if touches_bottom:
for rr, cc in comp:
span_mask[rr, cc] = True
n_span = int(np.sum(span_mask))
if n_span == 0:
return {
"effective_conductance": 0.0,
"voltage_field": np.zeros_like(g, dtype=float),
"node_current_field": np.zeros_like(g, dtype=float),
"spanning_mask": span_mask,
"backbone_mask": span_mask.copy(),
"spanning_sites": 0,
"backbone_sites": 0,
"dangling_fraction_of_spanning": 0.0,
}
# Restrict linear system strictly to interior spanning-cluster nodes (rows 1 .. n_r - 2):
node_id = np.full((n_r, n_c), -1, dtype=int)
interior_coords: list[tuple[int, int]] = []
for r in range(1, n_r - 1):
for c in range(n_c):
if span_mask[r, c]:
node_id[r, c] = len(interior_coords)
interior_coords.append((r, c))
m_unk = len(interior_coords)
v_field = np.zeros((n_r, n_c), dtype=float)
v_field[0, span_mask[0, :]] = 1.0
v_field[-1, span_mask[-1, :]] = 0.0
if m_unk > 0:
mat_g = np.zeros((m_unk, m_unk), dtype=float)
rhs = np.zeros(m_unk, dtype=float)
for u_idx, (r, c) in enumerate(interior_coords):
deg = 0.0
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < n_r and 0 <= nc < n_c and span_mask[nr, nc]:
deg += 1.0
if nr == 0:
rhs[u_idx] += 1.0 # V_top = 1.0 V
elif nr == n_r - 1:
pass # V_bot = 0.0 V
else:
mat_g[u_idx, node_id[nr, nc]] -= 1.0
mat_g[u_idx, u_idx] = deg
v_int = np.linalg.solve(mat_g, rhs)
for u_idx, (r, c) in enumerate(interior_coords):
v_field[r, c] = v_int[u_idx]
# Compute through-current at every spanning site (0.5 * sum |I_uv| for interior, total injected for busbars):
i_node = np.zeros((n_r, n_c), dtype=float)
i_top_in = 0.0
i_bot_out = 0.0
for r in range(n_r):
for c in range(n_c):
if not span_mask[r, c]:
continue
abs_sum = 0.0
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < n_r and 0 <= nc < n_c and span_mask[nr, nc]:
dv = v_field[r, c] - v_field[nr, nc]
abs_sum += abs(dv)
if r == 0 and nr == 1:
i_top_in += dv
if r == n_r - 1 and nr == n_r - 2:
i_bot_out += -dv
i_node[r, c] = abs_sum if r in (0, n_r - 1) else 0.5 * abs_sum
assert np.isclose(i_top_in, i_bot_out, rtol=1e-9, atol=1e-10)
backbone_mask = span_mask & (i_node > 1e-8)
n_back = int(np.sum(backbone_mask))
dang_frac = (n_span - n_back) / float(n_span)
return {
"effective_conductance": float(i_top_in),
"voltage_field": v_field,
"node_current_field": i_node,
"spanning_mask": span_mask,
"backbone_mask": backbone_mask,
"spanning_sites": n_span,
"backbone_sites": n_back,
"dangling_fraction_of_spanning": dang_frac,
}
# Solve near-critical percolating resistor network at L = 34, p = 0.598:
perc_near = None
for sd_try in range(1, 60):
cand_p = emergence_verification.site_percolation_2d(34, 0.598, seed=sd_try)
if cand_p["percolates_top_to_bottom"]:
kirch_cand = random_resistor_network_conductance(cand_p["grid"])
if kirch_cand["dangling_fraction_of_spanning"] > 0.35:
perc_near = cand_p
kirch_near = kirch_cand
break
assert perc_near is not None and perc_near["percolates_top_to_bottom"]
print(f"Near-critical lattice (L=34, p=0.605): G_eff = {kirch_near['effective_conductance']:.4f} S")
print(f" Spanning cluster sites = {kirch_near['spanning_sites']} | Active backbone = {kirch_near['backbone_sites']} | Zero-current dangling = {100*kirch_near['dangling_fraction_of_spanning']:.1f}%")
assert kirch_near["effective_conductance"] > 0.0
assert kirch_near["dangling_fraction_of_spanning"] > 0.35
# Sweep p in [0.54, 0.96] comparing geometric giant-cluster fraction P_inf(p) vs. effective conductance G_eff(p):
p_cond_sweep = np.linspace(0.54, 0.96, 10)
g_eff_curve, pinf_cond_curve = [], []
for pv in p_cond_sweep:
g_sum, p_sum = 0.0, 0.0
for tr in range(8):
pr = emergence_verification.site_percolation_2d(26, float(pv), seed=800 + tr)
kr = random_resistor_network_conductance(pr["grid"])
g_sum += kr["effective_conductance"]
p_sum += pr["largest_cluster_fraction"]
g_eff_curve.append(g_sum / 8.0)
pinf_cond_curve.append(p_sum / 8.0)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.2))
# Color map: white = vacant/isolated, gold = zero-current dangling branch of giant cluster, crimson = active current backbone
rgb_k = np.full((34, 34, 3), 0.95)
dang_mask = kirch_near["spanning_mask"] & (~kirch_near["backbone_mask"])
rgb_k[dang_mask] = [0.949, 0.780, 0.267]
rgb_k[kirch_near["backbone_mask"]] = [0.753, 0.224, 0.169]
ax1.imshow(rgb_k, interpolation="nearest")
ax1.grid(False)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title(f"Backbone (red) and dead ends (gold, {100*kirch_near['dangling_fraction_of_spanning']:.0f} %)")
ax2.plot(p_cond_sweep, pinf_cond_curve, "b-o", ms=5, lw=2.1, label="Geometric mass $P_\\infty(p) \\sim (p-p_c)^{0.14}$")
ax2.plot(p_cond_sweep, g_eff_curve, "r-s", ms=5, lw=2.2, label="Conductance $G_{\\mathrm{eff}}(p) \\sim (p-p_c)^{1.30}$")
ax2.axvline(0.5927, color="k", ls=":", lw=1.5, label="$p_c \\approx 0.593$")
ax2.set_xlabel("Conductive filler fraction $p$")
ax2.set_ylabel("Order parameter / conductance [S]")
ax2.set_title("Cluster mass and conductance")
ax2.legend(fontsize=8.1)
label_panels(fig)
plt.show()
Exercise 3: Implement it yourself — Kirchhoff random resistor network (backbone against dangling ends)
======================================================================================================
Near-critical lattice (L=34, p=0.605): G_eff = 0.0336 S
Spanning cluster sites = 373 | Active backbone = 120 | Zero-current dangling = 67.8%

Figure S14.3. Random resistor network. (a) Spanning cluster at with the current-carrying backbone (red) and the dead ends (gold), 68 % of the cluster. (b) Mass of the spanning cluster and conductance against ; the conductance rises much more slowly.
Summary. The mass of the spanning cluster rises steeply above , with the small exponent , whereas the conductance rises far more slowly (in two dimensions ). The reason is visible in the gold pixels: near most of the spanning cluster consists of dead ends attached by a single site, where Kirchhoff’s law makes the current zero. At and , of the spanning cluster carries no current.