An AI coding assistant can write a 50-line heuristic optimizer or numerical estimator in seconds; finding out whether it hides an edge-case bug, when no closed-form answer exists to compare with, is harder. This lecture takes up two related problems: (1) exploring high-dimensional integrals and rugged combinatorial landscapes without getting trapped in terrible local minima, and (2) verifying black-box or AI-generated solvers without a global oracle (Mental Move #24: Fuzz Fast or AI Code Against Metamorphic & Micro-Oracles). In this lecture, you will reduce Monte Carlo sampling variance via Latin Hypercube Sampling (emergence_verification.latin_hypercube_mc_integrate), escape 2-opt local traps via Metropolis-Boltzmann Simulated Annealing (emergence_verification.simulated_annealing_tsp), catch 4 realistic subtle AI code bugs automatically via emergence_verification.metamorphic_differential_audit, and build a Delta-Debugging Counterexample Shrinker that reduces a 16-element failing input to a 2-element counterexample.
Learning objectives¶
Reduce multidimensional Monte Carlo integration variance via stratified Latin Hypercube Sampling (
emergence_verification.latin_hypercube_mc_integrate) and explain why LHS eliminates 1-D marginal clumping.Optimize rugged 2-D Travelling Salesperson tours via 2-opt Boltzmann Simulated Annealing (
emergence_verification.simulated_annealing_tsp), benchmarking against exact convex-polygon perimeters and greedy quenching.Falsify subtly buggy black-box / AI-generated solvers using permutation, translation, and scaling equivariance laws plus micro-oracles (
emergence_verification.metamorphic_differential_audit).Implement automated Zeller Delta-Debugging counterexample shrinking and oracle-free metamorphic shortest-path verification.
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. Variance Reduction in High Dimensions: Latin Hypercube Sampling (latin_hypercube_mc_integrate)¶
Tensor-product quadrature grids ( nodes) grow exponentially with the number of uncertain parameters (the curse of dimensionality), whereas crude Simple Random Sampling (SRS) suffers slow convergence because random points clump in some intervals and leave gaps in others.
McKay, Beckman & Conover’s (1979) Latin Hypercube Sampling (LHS) partitions every coordinate axis into equal-probability strata and places exactly one sample per stratum on every 1-D projection via independent random permutations :
By Stein’s (1987) theorem, LHS cancels the additive main-effect variance of any smooth engineering response , so for a nearly additive response the variance falls by a large factor at the same number of function evaluations ; for the test function used here the factor is between 155 and 915.
heading("Demonstration 1: Latin hypercube sampling (LHS) against crude Monte Carlo variance reduction")
# 6-D nonlinear thermal-structural reliability integral on [0, 1]^6 with exact analytical mean:
# f(x) = sum_{j=1}^6 c_j * exp(c_j * x_j) / (exp(c_j) - 1) + 0.35 * (x_0 - 0.5) * (x_1 - 0.5)
# Exact integral over [0, 1]^6 of each main-effect term is 1.0, and interaction term is 0.0 => Exact Mean = 6.0
c_vec = np.array([1.4, -1.1, 0.9, 1.6, -0.8, 1.2])
def thermal_response_6d(x_mat: np.ndarray) -> np.ndarray:
main = np.sum((c_vec * np.exp(x_mat * c_vec)) / (np.exp(c_vec) - 1.0), axis=1)
inter = 0.35 * (x_mat[:, 0] - 0.5) * (x_mat[:, 1] - 0.5)
return main + inter
sample_budgets = [16, 32, 64, 128, 256]
srs_stds, lhs_stds, vrr_list = [], [], []
for n_s in sample_budgets:
res_mc = emergence_verification.latin_hypercube_mc_integrate(
thermal_response_6d, d_dim=6, n_samples=n_s, n_trials=60, seed=1601 + n_s
)
srs_stds.append(res_mc["srs_std"])
lhs_stds.append(res_mc["lhs_std"])
vrr_list.append(res_mc["variance_reduction_ratio"])
res_64 = emergence_verification.latin_hypercube_mc_integrate(thermal_response_6d, d_dim=6, n_samples=64, n_trials=60, seed=42)
print(f"Exact 6-D integral = 6.000000 | At N=64: LHS mean = {res_64['lhs_mean']:.5f} (std={res_64['lhs_std']:.4f}) vs. SRS std = {res_64['srs_std']:.4f}")
print(f"Variance Reduction Ratios Var(SRS)/Var(LHS) across N={sample_budgets}: {[round(v, 1) for v in vrr_list]}")
assert abs(res_64["lhs_mean"] - 6.0) < 0.015
assert all(v > 12.0 for v in vrr_list) and vrr_list[-1] > 30.0
# Illustrate 2-D N=12 marginal stratification vs. clumped Simple Random Sampling:
rng_vis = np.random.default_rng(16)
pts_srs = rng_vis.random((12, 2))
pts_lhs = np.column_stack([(rng_vis.permutation(12) + rng_vis.random(12)) / 12.0 for _ in range(2)])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.2))
for g_line in np.linspace(0.0, 1.0, 13):
ax1.axhline(g_line, color="gray", lw=0.5, alpha=0.45)
ax1.axvline(g_line, color="gray", lw=0.5, alpha=0.45)
ax1.scatter(pts_srs[:, 0], pts_srs[:, 1], c="#C0392B", marker="x", s=58, lw=2.0, label="Crude SRS (empty/double strata)")
ax1.scatter(pts_lhs[:, 0], pts_lhs[:, 1], c="#2166AC", edgecolors="k", s=58, label="Latin hypercube (one per row and column)")
ax1.set_xlim(0, 1); ax1.set_ylim(0, 1)
ax1.set_xlabel("$x_1$"); ax1.set_ylabel("$x_2$")
ax1.set_title("Random sample and Latin hypercube, 12 points")
ax1.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=8.0)
ax2.loglog(sample_budgets, srs_stds, "r-s", ms=6, lw=2.1, label="Crude Monte Carlo $\\sigma_{\\mathrm{SRS}} \\sim N^{-1/2}$")
ax2.loglog(sample_budgets, lhs_stds, "b-o", ms=6, lw=2.2, label="Latin hypercube $\\sigma_{\\mathrm{LHS}}$ ")
ax2.set_xlabel("Function evaluations $N$ (log scale)")
ax2.set_ylabel("Estimator standard error (log scale)")
ax2.set_title("Standard error of a 6-D integral")
ax2.legend(fontsize=8.2)
log_ticks(ax2, "x", [16, 32, 64, 128, 256])
label_panels(fig)
plt.show()
Demonstration 1: Latin hypercube sampling (LHS) against crude Monte Carlo variance reduction
============================================================================================
Exact 6-D integral = 6.000000 | At N=64: LHS mean = 5.99972 (std=0.0038) vs. SRS std = 0.0935
Variance Reduction Ratios Var(SRS)/Var(LHS) across N=[16, 32, 64, 128, 256]: [155.0, 398.7, 414.0, 915.5, 597.8]

Figure 16.1. Latin hypercube sampling. (a) Twelve points of a random sample (crosses), with empty and doubly occupied strata, and of a Latin hypercube (circles), with one point in every row and column. (b) Standard error of the 6-D integral against the number of evaluations; the variance ratio is 155 to 915.
What Demonstration 1 shows. At the standard deviation of the LHS estimate of this 6-D integral is 0.0038, against 0.0935 for simple random sampling. With the measured variance ratio of 414, simple random sampling would need about evaluations for the same accuracy (estimated from the scaling of the variance). For an expensive finite-element or CFD model, the stratification saves almost all of the solver calls.
2. Escaping Combinatorial Traps: Simulated Annealing (simulated_annealing_tsp)¶
On an -station inspection tour, closed tours exist ( for ). Purely greedy local descent (accept 2-opt segment reversal iff ) gets stuck in the very first local valley it enters. Kirkpatrick, Gelatt & Vecchi’s (1983) Simulated Annealing borrows from the annealing of metals: at artificial temperature , uphill moves () are accepted with Metropolis-Boltzmann probability:
Cooling geometrically from hot exploration (, escaping crossed chords) down to cold polishing () turns tangled random tours into tours without crossings.
heading("Demonstration 2: 2-opt simulated annealing on exact 24-gon benchmark and 50-station sensor network")
circ_bm = constants_benchmarks.make_circle_tour_benchmark(n_nodes=24, radius=10.0, seed=42)
sa_circ = emergence_verification.simulated_annealing_tsp(
circ_bm["coords"], T_init=12.0, T_final=1e-3, n_steps=7000, seed=42
)
rel_err_circ = abs(sa_circ["best_length"] - circ_bm["exact_min_length"]) / circ_bm["exact_min_length"]
# 50-station clustered field network: compare Greedy Nearest-Neighbor vs. SA:
pts_50 = constants_benchmarks.make_sensor_station_coords(n_stations=50, seed=42)
def greedy_nearest_neighbor_tsp(pts: np.ndarray, start_idx: int = 0) -> tuple[np.ndarray, float]:
n = pts.shape[0]
unvisited = set(range(n))
tour = [start_idx]
unvisited.remove(start_idx)
while unvisited:
cur = tour[-1]
nxt = min(unvisited, key=lambda j: (pts[cur, 0] - pts[j, 0]) ** 2 + (pts[cur, 1] - pts[j, 1]) ** 2)
tour.append(nxt)
unvisited.remove(nxt)
t_arr = np.array(tour, dtype=int)
diffs = np.roll(pts[t_arr], -1, axis=0) - pts[t_arr]
return t_arr, float(np.sum(np.hypot(diffs[:, 0], diffs[:, 1])))
nn_tour_50, nn_len_50 = greedy_nearest_neighbor_tsp(pts_50, start_idx=0)
sa_50 = emergence_verification.simulated_annealing_tsp(pts_50, T_init=25.0, T_final=1e-3, n_steps=12000, seed=42)
print(f"24-Gon Exact Global Perimeter = {circ_bm['exact_min_length']:.6f} | SA initial = {sa_circ['initial_length']:.2f} -> SA final = {sa_circ['best_length']:.6f} (err = {rel_err_circ:.2e})")
print(f"50-Station Sensor Tour: Random initial = {sa_50['initial_length']:.1f} km | Greedy NN = {nn_len_50:.1f} km | Simulated Annealing = {sa_50['best_length']:.1f} km")
assert rel_err_circ < 1e-12
assert sa_50["best_length"] < 0.92 * nn_len_50 < sa_50["initial_length"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.2))
ax1.plot(sa_50["length_history"], color="#2166AC", lw=2.0, label=f"SA best-so-far ({sa_50['best_length']:.1f} km)")
ax1.axhline(nn_len_50, color="#E08214", ls="--", lw=1.8, label=f"Greedy nearest-neighbor ({nn_len_50:.1f} km)")
ax1.set_xlabel("2-opt Metropolis iterations")
ax1.set_ylabel("Closed tour length [km]")
ax1.set_title("Annealing of a 50-station tour")
ax1.legend(fontsize=8.3)
cyc_nn = np.append(nn_tour_50, nn_tour_50[0])
cyc_sa = np.append(sa_50["best_tour"], sa_50["best_tour"][0])
ax2.plot(pts_50[cyc_nn, 0], pts_50[cyc_nn, 1], "r--", lw=1.1, alpha=0.55, label="Greedy NN (long return jumps)")
ax2.plot(pts_50[cyc_sa, 0], pts_50[cyc_sa, 1], "b-o", ms=4.2, lw=1.9, label="SA 2-opt annealed tour")
ax2.set_xlabel("East $x$ [km]")
ax2.set_ylabel("North $y$ [km]")
ax2.set_title("Annealed and greedy tours")
ax2.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=8.1)
label_panels(fig)
plt.show()
Demonstration 2: 2-opt simulated annealing on exact 24-gon benchmark and 50-station sensor network
==================================================================================================
24-Gon Exact Global Perimeter = 62.652572 | SA initial = 293.06 -> SA final = 62.652572 (err = 1.13e-16)
50-Station Sensor Tour: Random initial = 2202.8 km | Greedy NN = 581.8 km | Simulated Annealing = 527.3 km

Figure 16.2. Simulated annealing on 50 synthetic stations. (a) Best tour length against the number of 2-opt iterations; the dashed line is the greedy nearest-neighbour tour. (b) The annealed tour (solid) and the greedy tour (dashed), which has long return jumps.
Why Greedy Nearest-Neighbor Loses on Demonstration 2: Greedy nearest neighbour takes cheap local hops first and leaves isolated stations to the end, which forces long jumps across the map: its tour is 581.8 km, against 527.3 km for simulated annealing. Annealing accepts temporary uphill moves at high and recovers the 24-gon perimeter with a relative error of .
3. Auditing Black-Box & AI-Generated Code: Metamorphic & Micro-Oracle Fuzzing¶
Suppose an LLM coding assistant writes a fast “robust location / dispersion estimator” for your sensor pipeline. You pass 3 toy examples and they look plausible—how do you systematically hunt silent mathematical bugs when no closed-form solution exists for large ? Chen et al.'s (1998) Metamorphic Testing + Differential Micro-Oracles (emergence_verification.metamorphic_differential_audit) test structural equivariance laws that any valid implementation must obey for all inputs :
Permutation Invariance: for every shuffle .
Translation (Shift) Equivariance: for every scalar offset .
Positive Scale Equivariance: for every .
Adversarial Input Generation: Injecting duplicate values (), even vs. odd lengths, and offsets.
heading("Demonstration 3: Four bugs of the kind found in generated code")
# Reference clean location estimator: exact sample median
clean_median = lambda x: float(np.median(x))
# 4 subtle "AI-generated" bugs that pass casual glance inspection:
def ai_bug1_even_median_precedence(x: np.ndarray) -> float:
"""BUG 1: Forgot parentheses around (s[n//2 - 1] + s[n//2]) on even-length arrays"""
s = np.sort(x)
n = s.size
return float(s[n // 2]) if (n % 2 == 1) else float(0.5 * s[n // 2 - 1] + s[n // 2])
def ai_bug2_hardcoded_outlier_clip(x: np.ndarray) -> float:
"""BUG 2: Hardcoded |x| < 50.0 outlier filter instead of scale/shift-invariant MAD"""
keep = x[np.abs(x) < 50.0]
return float(np.mean(keep)) if keep.size > 0 else 0.0
def ai_bug3_duplicate_div_zero(x: np.ndarray) -> float:
"""BUG 3: Range-weighted mean dividing by (max(x) - min(x)) without guarding constant/duplicate arrays"""
if x.size == 1:
return float(x[0])
span = float(np.max(x) - np.min(x))
with np.errstate(divide="ignore", invalid="ignore"):
w = 1.0 + 0.0 * ((x - np.min(x)) / span) # 0 / 0 -> NaN when all elements equal
return float(np.mean(w * x))
def ai_bug4_anchor_first_element(x: np.ndarray) -> float:
"""BUG 4: Anchors wind-angle / phase wrap to x[0], breaking permutation invariance"""
wrapped = ((x - x[0] + 10.0) % 20.0) - 10.0
return float(x[0] + np.mean(wrapped))
candidates = [
("Reference np.median", clean_median),
("Bug 1: even-length precedence", ai_bug1_even_median_precedence),
("Bug 2: hard-coded threshold 50", ai_bug2_hardcoded_outlier_clip),
("Bug 3: division by zero on duplicates", ai_bug3_duplicate_div_zero),
("Bug 4: anchored on the first element", ai_bug4_anchor_first_element),
]
audit_counts = []
print(f"{'Candidate Solver':36s} | {'Passed?':7s} | {'Failures':8s} | {'First Violated Law'}")
print("-" * 82)
for label, fn in candidates:
# Pure oracle-free metamorphic audit (oracle_fn=None):
rep = emergence_verification.metamorphic_differential_audit(
fn,
oracle_fn=None,
relations=("permutation_invariance", "shift_equivariance", "scale_equivariance"),
n_fuzz=80,
seed=42,
)
audit_counts.append(rep["failures_found"])
first_law = "None (100% Clean)" if rep["passed"] else rep["first_counterexample"]["law"]
print(f"{label:36s} | {str(rep['passed']):7s} | {rep['failures_found']:8d} | {first_law}")
assert audit_counts[0] == 0
assert all(c > 0 for c in audit_counts[1:])
fig, ax = plt.subplots(figsize=(7.8, 3.9))
short_lbls = ["Reference\nnp.median", "Bug 1:\neven length", "Bug 2:\nhard-coded clip", "Bug 3:\ndivision by zero", "Bug 4:\norder anchor"]
bar_cols = ["#2E8B57"] + ["#C0392B"] * 4
ax.bar(short_lbls, audit_counts, color=bar_cols, edgecolor="k", width=0.55, alpha=0.88)
ax.set_ylabel("Metamorphic violations in 80 fuzz trials")
ax.set_title("Metamorphic violations per candidate")
plt.show()
Demonstration 3: Four bugs of the kind found in generated code
==============================================================
Candidate Solver | Passed? | Failures | First Violated Law
----------------------------------------------------------------------------------
Reference np.median | True | 0 | None (100% Clean)
Bug 1: even-length precedence | False | 44 | shift_equivariance
Bug 2: hard-coded threshold 50 | False | 44 | shift_equivariance
Bug 3: division by zero on duplicates | False | 6 | permutation_invariance
Bug 4: anchored on the first element | False | 116 | permutation_invariance

Figure 16.3. Metamorphic violations found in 80 random inputs for np.median and four buggy versions. The reference passes; every bug violates at least one law.
What Demonstration 3 shows. We passed oracle_fn=None—we never told the auditor what the function was supposed to compute—yet testing permutation, shift, and scale equivariance over 80 randomized + duplicate-injected inputs caught all 4 bugs, while np.median passed with no violation.
4. Counterexample Shrinking: Reducing a 16-Element Failing Input to 2 Elements¶
When random fuzzing catches a bug, first_counterexample["input"] is often a long vector of arbitrary floats such as [-8.4192837, 14.29104, ..., -3.1182] (here 16 elements), which is hard to debug. Counterexample Shrinking (popularized by QuickCheck, Hypothesis, and Andreas Zeller’s Delta Debugging) repeatedly deletes elements and simplifies surviving numbers (0.0, 1.0, integers) while keeping the failure predicate True—handing you the smallest possible human-readable witness.
heading("Demonstration 4: Shrinking failing inputs to minimal 2- or 3-element witnesses")
def shrink_counterexample_simple(x_init: np.ndarray, is_buggy_fn) -> np.ndarray:
"""Chunk-halving + 1-or-2-element deletion + integer-rounding shrinker (handles even-length parity bugs)."""
cur = np.asarray(x_init, dtype=float).copy()
assert is_buggy_fn(cur)
# Phase 1: Halve slices and delete singletons OR adjacent pairs (crucial when bug requires even n):
changed = True
while changed and cur.size > 1:
changed = False
if cur.size >= 4 and is_buggy_fn(cur[: cur.size // 2]):
cur = cur[: cur.size // 2]
changed = True
continue
for step_del in (1, 2):
if cur.size > step_del:
for i in range(cur.size - step_del + 1):
cand = np.delete(cur, slice(i, i + step_del))
if cand.size >= 1 and is_buggy_fn(cand):
cur = cand
changed = True
break
if changed:
break
# Phase 2: Try replacing each surviving coordinate with 0.0, 1.0, 2.0, -1.0, or rounded integer
for i in range(cur.size):
for simple_v in [0.0, 1.0, 2.0, -1.0, round(float(cur[i]), 0), round(float(cur[i]), 1)]:
cand = cur.copy()
cand[i] = simple_v
if is_buggy_fn(cand):
cur = cand
break
return cur
# Grab a messy random failure for Bug 1 (even-length median precedence) & Bug 4 (order-dependent wrap):
rng_f = np.random.default_rng(1604)
raw_fail_bug1 = rng_f.normal(3.7, 11.4, size=16) # 16 ugly floats
pred_bug1 = lambda z: not np.isclose(ai_bug1_even_median_precedence(z + 10.0), ai_bug1_even_median_precedence(z) + 10.0)
raw_fail_bug4 = np.array([9.2341, -8.8172, 1.4429, 7.9182, -9.4123, 3.1827, -4.2918, 8.7712, -7.1123, 0.4123, 6.221, -8.991])
pred_bug4 = lambda z: not np.isclose(ai_bug4_anchor_first_element(z), ai_bug4_anchor_first_element(z[::-1]))
min_w1 = shrink_counterexample_simple(raw_fail_bug1, pred_bug1)
min_w4 = shrink_counterexample_simple(raw_fail_bug4, pred_bug4)
print(f"Bug 1 (Shift Law) : Raw fuzz len = {raw_fail_bug1.size} -> Shrunk len = {min_w1.size}, witness = {min_w1.tolist()}")
print(f" Check on {min_w1.tolist()}: f(x) = {ai_bug1_even_median_precedence(min_w1):.1f}, f(x+10) = {ai_bug1_even_median_precedence(min_w1 + 10.0):.1f} != f(x)+10 = {ai_bug1_even_median_precedence(min_w1)+10.0:.1f}")
print(f"Bug 4 (Perm Law) : Raw fuzz len = {raw_fail_bug4.size} -> Shrunk len = {min_w4.size}, witness = {min_w4.tolist()}")
assert min_w1.size == 2 and pred_bug1(min_w1)
assert min_w4.size <= 3 and pred_bug4(min_w4)
fig, ax = plt.subplots(figsize=(7.2, 3.8))
x_b = np.arange(2)
ax.bar(x_b - 0.18, [raw_fail_bug1.size, raw_fail_bug4.size], width=0.35, color="#9AA5B1", edgecolor="k", label="Raw fuzzer crash length")
ax.bar(x_b + 0.18, [min_w1.size, min_w4.size], width=0.35, color="#2166AC", edgecolor="k", label="Shrunk minimal witness length")
ax.set_xticks(x_b)
ax.set_xticklabels(["Bug 1: shift law\n[0.0, 0.0]", "Bug 4: permutation law"])
ax.set_ylabel("Input array length $n$")
ax.set_title("Failing input before and after shrinking")
ax.legend(fontsize=8.4)
plt.show()
Demonstration 4: Shrinking failing inputs to minimal 2- or 3-element witnesses
==============================================================================
Bug 1 (Shift Law) : Raw fuzz len = 16 -> Shrunk len = 2, witness = [0.0, 0.0]
Check on [0.0, 0.0]: f(x) = 0.0, f(x+10) = 15.0 != f(x)+10 = 10.0
Bug 4 (Perm Law) : Raw fuzz len = 12 -> Shrunk len = 2, witness = [1.0, -9.0]

Figure 16.4. Length of the failing input before and after shrinking for bugs 1 and 4: 16 and 12 elements reduce to 2.
Inside the algorithm¶
Look at min_w1 = [0.0, 0.0] in Demonstration 4: on [0.0, 0.0], 0.5 * 0 + 0 = 0, whereas shifting by +10 gives [10.0, 10.0] -> 0.5 * 10 + 10 = 15 != 10—exposing the missing parentheses in two zeros. Below, let us inspect simulated_annealing_tsp and metamorphic_differential_audit, and implement Andreas Zeller’s logarithmic-chunk ddmin (delta_debugging_counterexample_shrinker), which splits a failing input into chunks and keeps a chunk whenever it alone still fails. When a single element causes the failure, this takes a few rounds per halving (here 14 predicate calls for 64 elements); in the worst case the number of tests grows quadratically with (Zeller & Hildebrandt 2002).
Check against the library¶
heading("Inside the algorithm: SA, metamorphic auditor and Zeller's ddmin counterexample shrinker")
print(show_source(emergence_verification.simulated_annealing_tsp))
print(show_source(emergence_verification.metamorphic_differential_audit))
def delta_debugging_counterexample_shrinker(failing_x: np.ndarray, fails_fn) -> dict:
"""Zeller (2002) ddmin chunk-bisection counterexample reducer + integer value simplifier."""
cur = np.asarray(failing_x, dtype=float).ravel().copy()
if not fails_fn(cur):
raise ValueError("Initial failing_x must satisfy fails_fn(failing_x) == True.")
calls = 1
granularity = 2
while cur.size >= 2:
chunks = np.array_split(np.arange(cur.size), min(granularity, cur.size))
reduced = False
# 1. Try reducing directly TO a single chunk:
for ch in chunks:
cand = cur[ch]
calls += 1
if cand.size >= 1 and fails_fn(cand):
cur = cand
granularity = 2
reduced = True
break
if reduced:
continue
# 2. Try removing one chunk (keeping its complement):
for ch in chunks:
keep_idx = np.setdiff1d(np.arange(cur.size), ch, assume_unique=True)
cand = cur[keep_idx]
calls += 1
if cand.size >= 1 and fails_fn(cand):
cur = cand
granularity = max(granularity - 1, 2)
reduced = True
break
if not reduced:
if granularity >= cur.size:
break
granularity = min(cur.size, 2 * granularity)
# Value simplification pass:
for i in range(cur.size):
for v_try in (0.0, 1.0, -1.0, round(float(cur[i]), 0)):
cand = cur.copy()
cand[i] = v_try
calls += 1
if fails_fn(cand):
cur = cand
break
return {"minimal_input": cur, "original_len": int(failing_x.size), "minimal_len": int(cur.size), "oracle_calls": calls}
# Shrink a 64-element array where ONLY 2 specific outlier values (> 50) trigger Bug 2's hardcoded clip
big_arr = np.zeros(64, dtype=float)
big_arr[19] = 32.7381
big_arr[47] = -4.1928
pred_b2_scale = lambda z: not np.isclose(ai_bug2_hardcoded_outlier_clip(2.0 * z), 2.0 * ai_bug2_hardcoded_outlier_clip(z))
dd_res = delta_debugging_counterexample_shrinker(big_arr, pred_b2_scale)
print(f"ddmin shrunk length {dd_res['original_len']} -> {dd_res['minimal_len']} in {dd_res['oracle_calls']} predicate calls: witness = {dd_res['minimal_input'].tolist()}")
assert dd_res["minimal_len"] <= 2 and pred_b2_scale(dd_res["minimal_input"])
assert dd_res["oracle_calls"] < 40
Inside the algorithm: SA, metamorphic auditor and Zeller's ddmin counterexample shrinker
========================================================================================
def simulated_annealing_tsp(
coords: np.ndarray,
T_init: float = 15.0,
T_final: float = 1e-3,
n_steps: int = 6000,
seed: int = 42,
) -> dict:
"""Optimize a closed 2-D Euclidean tour via 2-opt segment reversals and Boltzmann Simulated Annealing."""
pts = np.asarray(coords, dtype=float)
if pts.ndim != 2 or pts.shape[1] != 2 or pts.shape[0] < 4:
raise ValueError("Require (N, 2) coords with N >= 4.")
if T_init <= T_final or T_final <= 0.0 or n_steps < 10:
raise ValueError("Require T_init > T_final > 0 and n_steps >= 10.")
n = pts.shape[0]
rng = np.random.default_rng(seed)
tour = np.arange(n, dtype=int)
cur_len = _tour_length(pts, tour)
init_len = cur_len
best_tour = tour.copy()
best_len = cur_len
hist = np.empty(n_steps, dtype=float)
snap_steps = set(np.linspace(0, n_steps - 1, 6, dtype=int).tolist())
snapshots: list[tuple[int, float, np.ndarray]] = [(0, cur_len, tour.copy())]
alpha = (float(T_final) / float(T_init)) ** (1.0 / max(1, n_steps - 1))
temp = float(T_init)
for step in range(n_steps):
i = int(rng.integers(0, n - 1))
j = int(rng.integers(i + 1, n))
if i == 0 and j == n - 1:
hist[step] = best_len
temp *= alpha
continue
a, b = tour[i - 1], tour[i]
c, d = tour[j], tour[(j + 1) % n]
old_edges = math.hypot(pts[a, 0] - pts[b, 0], pts[a, 1] - pts[b, 1]) + math.hypot(
pts[c, 0] - pts[d, 0], pts[c, 1] - pts[d, 1]
)
new_edges = math.hypot(pts[a, 0] - pts[c, 0], pts[a, 1] - pts[c, 1]) + math.hypot(
pts[b, 0] - pts[d, 0], pts[b, 1] - pts[d, 1]
)
delta = new_edges - old_edges
if delta <= 0.0 or rng.random() < math.exp(-delta / temp):
tour[i : j + 1] = tour[i : j + 1][::-1]
cur_len += delta
if cur_len < best_len - 1e-12:
best_len = cur_len
best_tour = tour.copy()
hist[step] = best_len
if step in snap_steps and step > 0:
snapshots.append((step, best_len, best_tour.copy()))
temp *= alpha
exact_best = _tour_length(pts, best_tour)
return {
"best_tour": best_tour,
"best_length": exact_best,
"initial_length": init_len,
"length_history": hist,
"snapshots": snapshots,
}
def metamorphic_differential_audit(
candidate_fn: Callable[[np.ndarray], float | np.ndarray],
oracle_fn: Callable[[np.ndarray], float | np.ndarray] | None = None,
relations: tuple[str, ...] = ("permutation_invariance", "shift_equivariance", "scale_equivariance"),
n_fuzz: int = 80,
tol: float = 1e-8,
seed: int = 42,
) -> dict:
"""Audit a black-box or AI-generated numerical solver via micro-oracle differential fuzzing + metamorphic laws."""
if n_fuzz < 1:
raise ValueError("n_fuzz must be >= 1.")
rng = np.random.default_rng(seed)
failures: list[dict] = []
tests_run = 0
for trial in range(n_fuzz):
length = int(rng.integers(1, 18))
if trial % 5 == 0:
# Adversarial duplicates + extreme offsets:
base = float(rng.choice([0.0, -1e6, 1e6]))
x = base + rng.choice([-2.0, 0.0, 0.0, 3.5], size=length)
else:
x = rng.normal(0.0, 10.0, size=length)
y_cand = np.asarray(candidate_fn(x.copy()), dtype=float)
if oracle_fn is not None:
tests_run += 1
y_ora = np.asarray(oracle_fn(x.copy()), dtype=float)
if y_cand.shape != y_ora.shape or not np.allclose(y_cand, y_ora, rtol=tol, atol=tol):
failures.append({"law": "micro_oracle", "input": x.copy(), "got": y_cand, "expected": y_ora})
for rel in relations:
tests_run += 1
if rel == "permutation_invariance":
xp = x[rng.permutation(x.size)]
yp = np.asarray(candidate_fn(xp), dtype=float)
if not np.allclose(yp, y_cand, rtol=tol, atol=tol):
failures.append({"law": rel, "input": x.copy(), "got": yp, "expected": y_cand})
elif rel == "shift_equivariance":
c_shift = float(rng.uniform(-25.0, 25.0))
ys = np.asarray(candidate_fn(x + c_shift), dtype=float)
if not np.allclose(ys, y_cand + c_shift, rtol=tol, atol=tol):
failures.append({"law": rel, "input": x.copy(), "got": ys, "expected": y_cand + c_shift})
elif rel == "scale_equivariance":
s_fac = float(rng.uniform(0.2, 7.5))
ym = np.asarray(candidate_fn(s_fac * x), dtype=float)
if not np.allclose(ym, s_fac * y_cand, rtol=tol, atol=tol):
failures.append({"law": rel, "input": x.copy(), "got": ym, "expected": s_fac * y_cand})
elif rel == "idempotence":
yi = np.asarray(candidate_fn(y_cand.copy()), dtype=float)
if not np.allclose(yi, y_cand, rtol=tol, atol=tol):
failures.append({"law": rel, "input": x.copy(), "got": yi, "expected": y_cand})
else:
raise ValueError(f"Unsupported metamorphic relation {rel!r}.")
return {
"passed": len(failures) == 0,
"failures_found": len(failures),
"first_counterexample": failures[0] if failures else None,
"tests_run": tests_run,
}
ddmin shrunk length 64 -> 1 in 14 predicate calls: witness = [33.0]
Exercises¶
Worked solutions are in 16_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Implement NumPy estimators for (1) 1-D linear-interpolated quantile , (2) 2-D Convex-Hull Perimeter via Andrew’s monotone chain, and (3) 1-D Wasserstein-1 distance . Verify all permutation, translation (equivariance vs. invariance), orthogonal-rotation, positive-scaling, and triangle-inequality invariants to 10-12 across 100 randomized trials.
Find how it fails. Audit two real-world traps: (a) Compare 20 independent runs of
simulated_annealing_tspon a 32-station network under Proper Annealing (T_init=20.0, T_final=1e-3, n_steps=6000) vs. Instant Quenching (T_init=1e-5, T_final=1e-6, n_steps=6000, where rejects every uphill escape); (b) Show how 5 hand-picked sorted unit tests ([1, 2, 3],[10, 20, 30],[-5, 0, 5],[2, 4, 6, 8, 10],[100, 200, 300]) give5/5 PASStobroken_ai_median = lambda x: float(x[len(x) // 2]), whereasmetamorphic_differential_auditcatches it immediately.Implement it yourself. Implement
audit_shortest_path_metamorphic(solver_fn, n_trials=25, seed=42)in NumPy wheresolver_fn(cost_grid, start, goal)returns a dict with'path'and'total_cost'(using cell-entry cost conventionsum(cost_grid[r, c] for r, c in path[1:])). Without calling any external reference solver, test three exact oracle-free metamorphic laws: (1) Positive cost-scaling equivariance , (2) Cell-entry reversal symmetry , and (3) Bellman subpath optimality at the midpoint ofpath. Verify thatastarwith admissibleheuristic_weight=1.0passes 100% (0 violations), while inadmissible Greedy Weighted A* (heuristic_weight=3.5) fails.
heading("Self-check for the exercises")
assert all(v > 12.0 for v in vrr_list), "LHS variance reduction check failed"
assert rel_err_circ < 1e-12 and sa_50["best_length"] < 0.92 * nn_len_50, "SA TSP optimality check failed"
assert audit_counts[0] == 0 and all(c > 0 for c in audit_counts[1:]), "Metamorphic bug-detection check failed"
assert dd_res["minimal_len"] <= 2 and pred_b2_scale(dd_res["minimal_input"]), "ddmin counterexample shrinker check failed"
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.