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.

16. Random search and testing: simulated annealing, Latin hypercubes and metamorphic tests

School of Engineering, Nazarbayev University

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

  1. 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.

  2. 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.

  3. Falsify subtly buggy black-box / AI-generated solvers using permutation, translation, and scaling equivariance laws plus micro-oracles (emergence_verification.metamorphic_differential_audit).

  4. Implement automated Zeller Delta-Debugging counterexample shrinking and oracle-free metamorphic shortest-path verification.

Time: about 60 min

1. Variance Reduction in High Dimensions: Latin Hypercube Sampling (latin_hypercube_mc_integrate)

Tensor-product quadrature grids (mdm^d nodes) grow exponentially with the number dd of uncertain parameters (the curse of dimensionality), whereas crude Simple Random Sampling (SRS) X(i)∼Uniform([0,1]d)\mathbf{X}^{(i)} \sim \mathrm{Uniform}([0, 1]^d) suffers slow O(N−1/2)\mathcal{O}(N^{-1/2}) 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 j∈{1,…,d}j \in \{1, \dots, d\} into NN equal-probability strata [kN,k+1N)\left[\frac{k}{N}, \frac{k+1}{N}\right) and places exactly one sample per stratum on every 1-D projection via independent random permutations πj\pi_j:

Xi,j=πj(i)+Ui,jN,Ui,j∼Uniform(0,1)(1.1)X_{i, j} = \frac{\pi_j(i) + U_{i, j}}{N}, \qquad U_{i, j} \sim \mathrm{Uniform}(0, 1) \tag{1.1}

By Stein’s (1987) theorem, LHS cancels the additive main-effect variance ∑j=1dVar[gj(Xj)]\sum_{j=1}^d \mathrm{Var}[g_j(X_j)] of any smooth engineering response f(x)=μ+∑jgj(xj)+rinter(x)f(\mathbf{x}) = \mu + \sum_j g_j(x_j) + r_{\mathrm{inter}}(\mathbf{x}), so for a nearly additive response the variance falls by a large factor at the same number of function evaluations NN; for the test function used here the factor is between 155 and 915.


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 size 1254x462 with 2 Axes>

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 N=64N = 64 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 64×414≈26,00064 \times 414 \approx 26{,}000 evaluations for the same accuracy (estimated from the 1/N1/N 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 NN-station inspection tour, (N−1)!/2(N-1)!/2 closed tours exist (3.0×10623.0 \times 10^{62} for N=50N = 50). Purely greedy local descent (accept 2-opt segment reversal iff ΔL≤0\Delta L \le 0) 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 T>0T > 0, uphill moves (ΔL>0\Delta L > 0) are accepted with Metropolis-Boltzmann probability:

P(accept 2-opt)={1,ΔL≤0exp⁡(−ΔL/T),ΔL>0(2.1)\mathbb{P}(\text{accept } 2\text{-opt}) = \begin{cases} 1, & \Delta L \le 0 \\ \exp(-\Delta L / T), & \Delta L > 0 \end{cases} \tag{2.1}

Cooling Tk=αkTinitT_k = \alpha^k T_{\mathrm{init}} geometrically from hot exploration (Tinit≫ΔLT_{\mathrm{init}} \gg \Delta L, escaping crossed chords) down to cold polishing (Tfinal→0T_{\mathrm{final}} \to 0) turns tangled random tours into tours without crossings.


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 size 1254x462 with 2 Axes>

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 TT and recovers the 24-gon perimeter with a relative error of 1.1×10−161.1 \times 10^{-16}.


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 NN? 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 x∈Rn\mathbf{x} \in \mathbb{R}^n:

  1. Permutation Invariance: f(π(x))=f(x)f(\pi(\mathbf{x})) = f(\mathbf{x}) for every shuffle π\pi.

  2. Translation (Shift) Equivariance: f(x+c1)=f(x)+cf(\mathbf{x} + c\mathbf{1}) = f(\mathbf{x}) + c for every scalar offset c∈Rc \in \mathbb{R}.

  3. Positive Scale Equivariance: f(s x)=s f(x)f(s\,\mathbf{x}) = s\,f(\mathbf{x}) for every s>0s > 0.

  4. Adversarial Input Generation: Injecting duplicate values (xi=xjx_i = x_j), even vs. odd lengths, and ±106\pm 10^6 offsets.


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 size 858x429 with 1 Axes>

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.


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 size 792x418 with 1 Axes>

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 NN (Zeller & Hildebrandt 2002).

Check against the library


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.

  1. Verify a result. Implement NumPy estimators for (1) 1-D linear-interpolated quantile Q0.75(x)Q_{0.75}(\mathbf{x}), (2) 2-D Convex-Hull Perimeter P(X)P(\mathbf{X}) via Andrew’s O(Nlog⁡N)\mathcal{O}(N \log N) monotone chain, and (3) 1-D Wasserstein-1 distance W1(x,y)=1n∑∣x(i)−y(i)∣W_1(\mathbf{x}, \mathbf{y}) = \frac{1}{n}\sum |x_{(i)} - y_{(i)}|. Verify all permutation, translation (equivariance vs. invariance), orthogonal-rotation, positive-scaling, and triangle-inequality invariants to 10-12 across 100 randomized trials.

  2. Find how it fails. Audit two real-world traps: (a) Compare 20 independent runs of simulated_annealing_tsp on 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 exp⁡(−Δ/T)≈0\exp(-\Delta/T) \approx 0 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]) give 5/5 PASS to broken_ai_median = lambda x: float(x[len(x) // 2]), whereas metamorphic_differential_audit catches it immediately.

  3. Implement it yourself. Implement audit_shortest_path_metamorphic(solver_fn, n_trials=25, seed=42) in NumPy where solver_fn(cost_grid, start, goal) returns a dict with 'path' and 'total_cost' (using cell-entry cost convention sum(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 C(αG,s,g)=α C(G,s,g)C(\alpha G, s, g) = \alpha\,C(G, s, g), (2) Cell-entry reversal symmetry C(G,s,g)+G[s]=C(G,g,s)+G[g]C(G, s, g) + G[s] = C(G, g, s) + G[g], and (3) Bellman subpath optimality C(G,s,m)+C(G,m,g)=C(G,s,g)C(G, s, m) + C(G, m, g) = C(G, s, g) at the midpoint mm of path. Verify that astar with admissible heuristic_weight=1.0 passes 100% (0 violations), while inadmissible Greedy Weighted A* (heuristic_weight=3.5) fails.


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