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.

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

School of Engineering, Nazarbayev University

Worked solutions to the three exercises of Lecture 16. 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.

Exercise 1

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


Exercise 1: Exact equivariance and invariance verification across quantile, convex hull and Wasserstein-1
=========================================================================================================
Q_0.75 metamorphic audit : 300 checks run, failures = 0
2-D Convex Perimeter     : max |perm / SE(2) rigid motion / scale equivariance error| = 1.137e-13
1-D Wasserstein-1 metric : max |perm / shift-invariance / scale error| = 7.105e-15, min triangle slack = 1.810e-01 >= 0
<Figure size 836x440 with 1 Axes>

Figure S16.1. A point set (circles) and its image under a rotation, a translation and a scaling by 1.5; the convex perimeter scales by exactly 1.5.

Explanation. Notice the critical difference between shift equivariance f(x+c)=f(x)+cf(\mathbf{x} + c) = f(\mathbf{x}) + c (location statistics like mean, median, Q0.75Q_{0.75}) and shift invariance f(x+c)=f(x)+0f(\mathbf{x} + c) = f(\mathbf{x}) + 0 (dispersion, perimeter, variance, and metric distances like W1W_1). Stating the symmetries of a function before writing it gives an exact metamorphic test suite at no extra cost.


Exercise 2

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


Exercise 2: Instant-quenching local traps and weak hand-picked unit tests
=========================================================================
[Part A] 32-Station TSP over 20 random starts:
  Boltzmann Annealing : mean = 446.94 km, worst = 459.74 km
  Instant Quenching   : mean = 457.67 km, worst = 494.93 km

[Part B] Hand-picked 5-test suite score : 5/5 (all pass)
         Metamorphic + micro-oracle fuzz : passed=False, failures=64 / 200 checks
         First caught violation law      : permutation_invariance
<Figure size 1254x440 with 2 Axes>

Figure S16.2. Two testing traps. (a) Final tour lengths over 20 starts with proper annealing and with instant quenching. (b) Pass rate of the buggy median under five hand-picked tests and under 50 metamorphic trials.

Explanation. Hand-written tests tend to use tidy, sorted, odd-length, symmetric vectors ([1, 2, 3], [-5, 0, 5]) where x[len(x)//2] happens to coincide with np.median(x). Randomized permutation fuzzing immediately shuffles [1, 2, 3] -> [3, 1, 2], catching the missing np.sort on the very first permutation check without needing human imagination.


Exercise 3

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


Exercise 3: Implement it yourself — oracle-free metamorphic shortest-path verifier
==================================================================================
Admissible A* (w = 1.0)           : passed = True (0 violations / 100 checks)
Inadmissible Weighted A* (w = 3.5): passed = False (27 violations, e.g. reversal_symmetry)
Unscaled +0.25 Penalty Bug        : passed = False (1 violations, e.g. scale_equivariance)
<Figure size 814x429 with 1 Axes>

Figure S16.3. Violations of the three metamorphic laws by weighted A* with w=3.5w = 3.5, found without a reference solver.

Summary. Notice how Bellman subpath optimality and reversal symmetry catch an inadmissible heuristic (w = 3.5) without ever running Dijkstra: an inflated goal heuristic pulls forward search s→gs \to g along a different asymmetric detour than backward search g→sg \to s, and re-solving from midpoint mm changes the heuristic gradient—exposing suboptimality purely through internal inconsistency.