Solutions · 16. Random search and testing: simulated annealing, Latin hypercubes and metamorphic tests
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.
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: 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()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. 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.
heading("Exercise 1: Exact equivariance and invariance verification across quantile, convex hull and Wasserstein-1")
q75_fn = lambda x: float(np.quantile(x, 0.75))
def convex_hull_perimeter_2d(pts: np.ndarray) -> float:
"""Andrew's O(N log N) monotone-chain 2-D convex hull perimeter in pure NumPy."""
p = np.unique(np.asarray(pts, dtype=float), axis=0)
if p.shape[0] <= 1:
return 0.0
if p.shape[0] == 2:
return 2.0 * float(np.hypot(p[1, 0] - p[0, 0], p[1, 1] - p[0, 1]))
order = np.lexsort((p[:, 1], p[:, 0]))
p = p[order]
def _cross(o: np.ndarray, a: np.ndarray, b: np.ndarray) -> float:
return float((a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]))
lower: list[np.ndarray] = []
for pt in p:
while len(lower) >= 2 and _cross(lower[-2], lower[-1], pt) <= 0.0:
lower.pop()
lower.append(pt)
upper: list[np.ndarray] = []
for pt in reversed(p):
while len(upper) >= 2 and _cross(upper[-2], upper[-1], pt) <= 0.0:
upper.pop()
upper.append(pt)
hull = np.array(lower[:-1] + upper[:-1])
diffs = np.roll(hull, -1, axis=0) - hull
return float(np.sum(np.hypot(diffs[:, 0], diffs[:, 1])))
wasserstein1_1d = lambda x, y: float(np.mean(np.abs(np.sort(x) - np.sort(y))))
# 1. Audit Q_0.75 directly via emergence_verification.metamorphic_differential_audit:
rep_q75 = emergence_verification.metamorphic_differential_audit(
q75_fn, oracle_fn=None, relations=("permutation_invariance", "shift_equivariance", "scale_equivariance"), n_fuzz=100, seed=161
)
assert rep_q75["passed"]
# 2. Verify 2-D Convex-Hull Perimeter & 1-D Wasserstein-1 across 100 random trials:
rng_eq = np.random.default_rng(1601)
max_hull_err = 0.0
max_w1_err = 0.0
tri_slack_min = math.inf
for _ in range(100):
n_pts = int(rng_eq.integers(5, 35))
pts = rng_eq.normal(0.0, 8.0, size=(n_pts, 2))
shift_2d = rng_eq.uniform(-50.0, 50.0, size=(1, 2))
scale_pos = float(rng_eq.uniform(0.25, 6.0))
ang = float(rng_eq.uniform(-math.pi, math.pi))
rot_mat = np.array([[math.cos(ang), -math.sin(ang)], [math.sin(ang), math.cos(ang)]])
perm = rng_eq.permutation(n_pts)
p_base = convex_hull_perimeter_2d(pts)
p_perm = convex_hull_perimeter_2d(pts[perm])
p_rot_shift = convex_hull_perimeter_2d((pts @ rot_mat.T) + shift_2d)
p_scaled = convex_hull_perimeter_2d(scale_pos * pts)
max_hull_err = max(max_hull_err, abs(p_perm - p_base), abs(p_rot_shift - p_base), abs(p_scaled - scale_pos * p_base))
x = rng_eq.normal(-3.0, 5.0, size=n_pts)
y = rng_eq.normal(2.0, 7.0, size=n_pts)
z = rng_eq.normal(0.0, 6.0, size=n_pts)
c_sh = float(rng_eq.uniform(-30.0, 30.0))
w_xy = wasserstein1_1d(x, y)
w_perm = wasserstein1_1d(x[rng_eq.permutation(n_pts)], y[rng_eq.permutation(n_pts)])
w_shift = wasserstein1_1d(x + c_sh, y + c_sh)
w_scale = wasserstein1_1d(scale_pos * x, scale_pos * y)
max_w1_err = max(max_w1_err, abs(w_perm - w_xy), abs(w_shift - w_xy), abs(w_scale - scale_pos * w_xy))
tri_slack_min = min(tri_slack_min, (wasserstein1_1d(x, y) + wasserstein1_1d(y, z)) - wasserstein1_1d(x, z))
print(f"Q_0.75 metamorphic audit : {rep_q75['tests_run']} checks run, failures = {rep_q75['failures_found']}")
print(f"2-D Convex Perimeter : max |perm / SE(2) rigid motion / scale equivariance error| = {max_hull_err:.3e}")
print(f"1-D Wasserstein-1 metric : max |perm / shift-invariance / scale error| = {max_w1_err:.3e}, min triangle slack = {tri_slack_min:.3e} >= 0")
assert max_hull_err < 1e-11 and max_w1_err < 1e-12 and tri_slack_min >= -1e-13
# Plot original vs rotated+shifted+scaled convex hull visual verification:
pts_demo = np.random.default_rng(7).normal(0.0, 3.0, size=(22, 2))
ang_d = 0.85
rot_d = np.array([[math.cos(ang_d), -math.sin(ang_d)], [math.sin(ang_d), math.cos(ang_d)]])
pts_trans = 1.5 * (pts_demo @ rot_d.T) + np.array([12.0, 3.0])
fig, ax = plt.subplots(figsize=(7.6, 4.0))
ax.scatter(pts_demo[:, 0], pts_demo[:, 1], c="#2166AC", s=36, label=f"Original $X$ ($P = {convex_hull_perimeter_2d(pts_demo):.3f}$)")
ax.scatter(pts_trans[:, 0], pts_trans[:, 1], c="#E08214", s=36, label=f"$1.5 R_\\theta X + \\mathbf{{c}}$ ($P = {convex_hull_perimeter_2d(pts_trans):.3f} = 1.5 P(X)$)")
ax.set_aspect("equal", adjustable="datalim")
ax.set_xlabel("$x$"); ax.set_ylabel("$y$")
ax.set_title("Convex perimeter under rotation, shift and scaling")
ax.legend(fontsize=8.3)
plt.show()
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 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 (location statistics like mean, median, ) and shift invariance (dispersion, perimeter, variance, and metric distances like ). 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 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.
heading("Exercise 2: Instant-quenching local traps and weak hand-picked unit tests")
# --- Part A: Boltzmann Annealing vs. Zero-Temperature Quenching Across 20 Seeds ---
pts_32 = constants_benchmarks.make_sensor_station_coords(n_stations=32, seed=1602)
annealed_lens, quenched_lens = [], []
for sd in range(20):
# Shuffle initial starting order identically for each trial:
perm_pts = pts_32[np.random.default_rng(900 + sd).permutation(32)]
r_sa = emergence_verification.simulated_annealing_tsp(perm_pts, T_init=20.0, T_final=1e-3, n_steps=5000, seed=sd)
r_qu = emergence_verification.simulated_annealing_tsp(perm_pts, T_init=1e-5, T_final=1e-6, n_steps=5000, seed=sd)
annealed_lens.append(r_sa["best_length"])
quenched_lens.append(r_qu["best_length"])
print("[Part A] 32-Station TSP over 20 random starts:")
print(f" Boltzmann Annealing : mean = {np.mean(annealed_lens):.2f} km, worst = {np.max(annealed_lens):.2f} km")
print(f" Instant Quenching : mean = {np.mean(quenched_lens):.2f} km, worst = {np.max(quenched_lens):.2f} km")
assert np.mean(annealed_lens) < np.mean(quenched_lens) - 5.0
assert np.max(annealed_lens) < np.max(quenched_lens)
# --- Part B: Weak Hand-Picked Unit Tests ---
broken_ai_median = lambda x: float(np.asarray(x).ravel()[len(x) // 2]) # Forgot np.sort AND wrong on asymmetric even arrays
hand_picked_suite = [
np.array([1.0, 2.0, 3.0]),
np.array([10.0, 20.0, 30.0]),
np.array([-5.0, 0.0, 5.0]),
np.array([2.0, 4.0, 6.0, 8.0, 10.0]),
np.array([100.0, 200.0, 300.0]),
]
unit_passes = sum(int(np.isclose(broken_ai_median(tc), np.median(tc))) for tc in hand_picked_suite)
fuzz_audit = emergence_verification.metamorphic_differential_audit(
broken_ai_median, oracle_fn=lambda z: float(np.median(z)),
relations=("permutation_invariance", "shift_equivariance", "scale_equivariance"), n_fuzz=50, seed=42
)
print(f"\n[Part B] Hand-picked 5-test suite score : {unit_passes}/{len(hand_picked_suite)} (all pass)")
print(f" Metamorphic + micro-oracle fuzz : passed={fuzz_audit['passed']}, failures={fuzz_audit['failures_found']} / {fuzz_audit['tests_run']} checks")
print(f" First caught violation law : {fuzz_audit['first_counterexample']['law']}")
assert unit_passes == 5 and (not fuzz_audit["passed"]) and fuzz_audit["failures_found"] > 40
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.0))
ax1.boxplot([annealed_lens, quenched_lens], patch_artist=True, boxprops={"facecolor": "#A9C9E8", "edgecolor": "k"})
ax1.set_xticks([1, 2], ["Boltzmann SA\n($T: 20 \\to 10^{-3}$)", "Quench\n($T \\approx 0$)"])
ax1.set_ylabel("Final tour length across 20 starts [km]")
ax1.set_title("Annealing against quenching")
ax2.bar(["5 hand-picked\nsorted unit tests", "50 metamorphic\nand oracle trials"],
[100.0 * unit_passes / 5.0, 100.0 * (1.0 - fuzz_audit["failures_found"] / fuzz_audit["tests_run"])],
color=["#2E8B57", "#C0392B"], edgecolor="k", width=0.50)
ax2.set_ylabel("Pass rate [%]")
ax2.set_title("Hand-picked tests against metamorphic trials")
label_panels(fig)
plt.show()
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 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 , (2) Cell-entry reversal symmetry , and (3) Bellman subpath optimality at the midpoint 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.
heading("Exercise 3: Implement it yourself — oracle-free metamorphic shortest-path verifier")
def audit_shortest_path_metamorphic(solver_fn, n_trials: int = 25, tol: float = 1e-9, seed: int = 42) -> dict:
"""Audit any 2-D grid shortest-path solver using ONLY self-consistency metamorphic laws (zero oracle)."""
rng = np.random.default_rng(seed)
violations: list[dict] = []
checks = 0
for tr in range(n_trials):
h, w = 18, 18
# Rugged terrain with high-cost barriers + cheap winding channels so greedy inadmissible A* is tempted astray:
grid = 1.0 + 18.0 * (rng.random((h, w)) ** 3)
sr, sc = int(rng.integers(0, 5)), int(rng.integers(0, 5))
gr, gc = int(rng.integers(h - 5, h)), int(rng.integers(w - 5, w))
res_fwd = solver_fn(grid, (sr, sc), (gr, gc))
path = res_fwd["path"]
c_fwd = float(res_fwd["total_cost"])
# Sanity self-check: reported total_cost matches sum of entered cells along returned path
checks += 1
c_recomputed = sum(float(grid[r, c]) for r, c in path[1:])
if path[0] != (sr, sc) or path[-1] != (gr, gc) or not np.isclose(c_fwd, c_recomputed, rtol=tol, atol=tol):
violations.append({"trial": tr, "law": "path_cost_accounting", "gap": abs(c_fwd - c_recomputed)})
continue
# Law 1: Positive cost-scaling equivariance C(alpha * G, s, g) == alpha * C(G, s, g):
checks += 1
alpha = float(rng.uniform(0.3, 6.5))
c_scaled = float(solver_fn(alpha * grid, (sr, sc), (gr, gc))["total_cost"])
if not np.isclose(c_scaled, alpha * c_fwd, rtol=tol, atol=tol):
violations.append({"trial": tr, "law": "scale_equivariance", "gap": abs(c_scaled - alpha * c_fwd)})
# Law 2: Cell-entry reversal identity C(s -> g) + G[s] == C(g -> s) + G[g] (since sum_{k=0}^L G[p_k] is symmetric):
checks += 1
c_rev = float(solver_fn(grid, (gr, gc), (sr, sc))["total_cost"])
lhs_sym = c_fwd + float(grid[sr, sc])
rhs_sym = c_rev + float(grid[gr, gc])
if not np.isclose(lhs_sym, rhs_sym, rtol=tol, atol=tol):
violations.append({"trial": tr, "law": "reversal_symmetry", "gap": abs(lhs_sym - rhs_sym)})
# Law 3: Bellman Principle of Optimality at path midpoint m: C(s -> m) + C(m -> g) == C(s -> g)
if len(path) >= 4:
checks += 1
mid_pt = path[len(path) // 2]
c_sm = float(solver_fn(grid, (sr, sc), mid_pt)["total_cost"])
c_mg = float(solver_fn(grid, mid_pt, (gr, gc))["total_cost"])
if not np.isclose(c_sm + c_mg, c_fwd, rtol=tol, atol=tol):
violations.append({"trial": tr, "law": "bellman_subpath_optimality", "gap": abs((c_sm + c_mg) - c_fwd)})
return {"passed": len(violations) == 0, "violations_count": len(violations), "checks_run": checks, "violations": violations}
admissible_astar = lambda g, s, t: greedy_heuristic_search.grid_shortest_path_search(g, s, t, method="astar", heuristic_weight=1.0)
inadmissible_w35 = lambda g, s, t: greedy_heuristic_search.grid_shortest_path_search(g, s, t, method="astar", heuristic_weight=3.5)
def buggy_additive_tiebreak_astar(g: np.ndarray, s: tuple[int, int], t: tuple[int, int]) -> dict:
"""Buggy wrapper adding an unscaled +0.25 constant penalty per cell, breaking scale equivariance"""
r = greedy_heuristic_search.grid_shortest_path_search(g + 0.25, s, t, method="astar", heuristic_weight=1.0)
return {"path": r["path"], "total_cost": sum(float(g[rr, cc]) for rr, cc in r["path"][1:])}
aud_ok = audit_shortest_path_metamorphic(admissible_astar, n_trials=25, seed=42)
aud_inadm = audit_shortest_path_metamorphic(inadmissible_w35, n_trials=25, seed=42)
aud_unscaled = audit_shortest_path_metamorphic(buggy_additive_tiebreak_astar, n_trials=25, seed=42)
print(f"Admissible A* (w = 1.0) : passed = {aud_ok['passed']} ({aud_ok['violations_count']} violations / {aud_ok['checks_run']} checks)")
print(f"Inadmissible Weighted A* (w = 3.5): passed = {aud_inadm['passed']} ({aud_inadm['violations_count']} violations, e.g. {aud_inadm['violations'][0]['law']})")
print(f"Unscaled +0.25 Penalty Bug : passed = {aud_unscaled['passed']} ({aud_unscaled['violations_count']} violations, e.g. {aud_unscaled['violations'][0]['law']})")
assert aud_ok["passed"] and aud_ok["violations_count"] == 0
assert (not aud_inadm["passed"]) and aud_inadm["violations_count"] >= 5
assert (not aud_unscaled["passed"])
# Count violation breakdown by law for Inadmissible Weighted A*:
from collections import Counter
law_counts = Counter(v["law"] for v in aud_inadm["violations"])
fig, ax = plt.subplots(figsize=(7.4, 3.9))
laws_k = ["reversal_symmetry", "bellman_subpath_optimality", "scale_equivariance"]
ax.bar(["Reversal\nsymmetry", "Bellman subpath\noptimality", "Scale\nequivariance"],
[law_counts[k] for k in laws_k], color=["#C0392B", "#7B4FA3", "#2E8B57"], edgecolor="k", width=0.52)
ax.set_ylabel("Violations in 25 random terrains")
ax.set_title("Metamorphic violations of weighted A* ($w = 3.5$)")
plt.show()
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 S16.3. Violations of the three metamorphic laws by weighted A* with , 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 along a different asymmetric detour than backward search , and re-solving from midpoint changes the heuristic gradient—exposing suboptimality purely through internal inconsistency.