Worked solutions to the three exercises of Lecture 9. 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: Step-minimal BFS against energy-minimal Dijkstra on mountain terrain")
mm18 = [m for m in constants_benchmarks.MENTAL_MOVES_DB if m["id"] == 18][0]
print(f"Mental Move #{mm18['id']} ({mm18['name']}): {mm18['invariant']}")
terrain = constants_benchmarks.make_topographic_terrain(nx=56, ny=56, seed=42)
elev_m = terrain["elevation_m"]
cost_grid = terrain["cost_grid"]
start_ab, goal_ab = (6, 6), (48, 48)
res_bfs = greedy_heuristic_search.grid_shortest_path_search(cost_grid, start_ab, goal_ab, method="bfs")
res_dijk = greedy_heuristic_search.grid_shortest_path_search(cost_grid, start_ab, goal_ab, method="dijkstra")
assert res_bfs["found"] and res_dijk["found"]
assert len(res_bfs["path"]) <= len(res_dijk["path"]) # BFS minimizes step count (85 cells = 84 Manhattan steps)
assert res_dijk["total_cost"] < 0.80 * res_bfs["total_cost"] # Dijkstra saves >20% traversal energy via the saddle pass
print(f"Unweighted BFS (min hops) : {len(res_bfs['path']) - 1:3d} steps | Terrain Energy Cost = {res_bfs['total_cost']:.2f}")
print(f"Exact Dijkstra (min cost) : {len(res_dijk['path']) - 1:3d} steps | Terrain Energy Cost = {res_dijk['total_cost']:.2f} (saves {100.0 * (1.0 - res_dijk['total_cost']/res_bfs['total_cost']):.1f}% energy)")
bfs_rc = np.array(res_bfs["path"])
dijk_rc = np.array(res_dijk["path"])
fig, ax = plt.subplots(figsize=(7.2, 5.0))
im = ax.imshow(elev_m, origin="lower", cmap="terrain")
ax.contour(elev_m, levels=8, colors="black", linewidths=0.45, alpha=0.45)
ax.plot(bfs_rc[:, 1], bfs_rc[:, 0], lw=2.3, ls="--", color="#C0392B", label=f"Unweighted BFS (cost = {res_bfs['total_cost']:.1f})")
ax.plot(dijk_rc[:, 1], dijk_rc[:, 0], lw=2.6, color="#19D3C5", label=f"Optimal Dijkstra (cost = {res_dijk['total_cost']:.1f})")
ax.scatter([start_ab[1], goal_ab[1]], [start_ab[0], goal_ab[0]], s=75, c=["white", "#F2C744"], edgecolors="black", zorder=5)
ax.set_xlabel("Grid column $c$")
ax.set_ylabel("Grid row $r$")
ax.set_title("Fewest steps (BFS) against least cost (Dijkstra)")
ax.grid(False)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=1, fontsize=8.5)
fig.colorbar(im, ax=ax, label="Elevation [m]")
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Across every directed 4-neighbor and 8-neighbor edge of make_topographic_terrain(56, 56, seed=42), verify heuristic consistency and , and verify that is monotonically non-decreasing along admissible 's expansion order.
heading("Exercise 1: Exhaustive edge-consistency and monotone f-contour verification")
t56 = constants_benchmarks.make_topographic_terrain(nx=56, ny=56, seed=42)["cost_grid"]
h, w = t56.shape
gr, gc = 44, 46
c_min = float(np.min(t56))
r_idx, c_idx = np.meshgrid(np.arange(h), np.arange(w), indexing="ij")
h4_map = c_min * (np.abs(gr - r_idx) + np.abs(gc - c_idx))
h8_map = c_min * np.hypot(gr - r_idx, gc - c_idx)
assert h4_map[gr, gc] == 0.0 and h8_map[gr, gc] == 0.0
moves_4 = [(-1, 0, 1.0), (1, 0, 1.0), (0, -1, 1.0), (0, 1, 1.0)]
moves_8 = moves_4 + [(-1, -1, math.sqrt(2.0)), (-1, 1, math.sqrt(2.0)), (1, -1, math.sqrt(2.0)), (1, 1, math.sqrt(2.0))]
min_slack_4 = math.inf
cnt_edges_4 = 0
for dr, dc, slen in moves_4:
r0 = slice(max(0, -dr), min(h, h - dr))
c0 = slice(max(0, -dc), min(w, w - dc))
r1 = slice(max(0, dr), min(h, h + dr))
c1 = slice(max(0, dc), min(w, w + dc))
slack = slen * t56[r1, c1] + h4_map[r1, c1] - h4_map[r0, c0]
min_slack_4 = min(min_slack_4, float(np.min(slack)))
cnt_edges_4 += slack.size
min_slack_8 = math.inf
cnt_edges_8 = 0
for dr, dc, slen in moves_8:
r0 = slice(max(0, -dr), min(h, h - dr))
c0 = slice(max(0, -dc), min(w, w - dc))
r1 = slice(max(0, dr), min(h, h + dr))
c1 = slice(max(0, dc), min(w, w + dc))
slack = slen * t56[r1, c1] + h8_map[r1, c1] - h8_map[r0, c0]
min_slack_8 = min(min_slack_8, float(np.min(slack)))
cnt_edges_8 += slack.size
assert min_slack_4 >= -1e-12 and min_slack_8 >= -1e-12
# Verify f(u) = g(u) + h(u) is monotonically non-decreasing in A* expansion order:
import heapq
g_arr = np.full((h, w), math.inf)
closed = np.zeros((h, w), dtype=bool)
g_arr[8, 8] = 0.0
pq = [(float(h8_map[8, 8]), 8, 8)]
popped_f = []
while pq:
f_u, r, c = heapq.heappop(pq)
if closed[r, c]:
continue
closed[r, c] = True
popped_f.append(f_u)
if (r, c) == (gr, gc):
break
for dr, dc, slen in moves_8:
nr, nc = r + dr, c + dc
if 0 <= nr < h and 0 <= nc < w and not closed[nr, nc]:
ng = g_arr[r, c] + slen * float(t56[nr, nc])
if ng < g_arr[nr, nc] - 1e-13:
g_arr[nr, nc] = ng
heapq.heappush(pq, (ng + float(h8_map[nr, nc]), nr, nc))
popped_f_arr = np.array(popped_f)
assert np.all(np.diff(popped_f_arr) >= -1e-12)
print(f"4-neighbor consistency verified on {cnt_edges_4:,d} directed edges | min(w + h(v) - h(u)) = {min_slack_4:+.3e}")
print(f"8-neighbor consistency verified on {cnt_edges_8:,d} directed edges | min(w + h(v) - h(u)) = {min_slack_8:+.3e}")
print(f"Monotone non-decreasing f-sequence verified across all {len(popped_f_arr)} A* pops (min df = {np.min(np.diff(popped_f_arr)):+.3e})")
Exercise 1: Exhaustive edge-consistency and monotone f-contour verification
===========================================================================
4-neighbor consistency verified on 12,320 directed edges | min(w + h(v) - h(u)) = +0.000e+00
8-neighbor consistency verified on 24,420 directed edges | min(w + h(v) - h(u)) = +1.445e-04
Monotone non-decreasing f-sequence verified across all 1440 A* pops (min df = +2.503e-05)
Explanation. By the norm triangle inequality and , we have . Consistency forces , guaranteeing that no closed vertex can ever be reached later with a smaller -cost.
Exercise 2¶
Problem. Verify ValueError guards on grid_shortest_path_search, then demonstrate quantitatively (a) how replacing with or in breaks admissibility and returns a suboptimal path, and (b) how pairing a Manhattan heuristic with 8-neighbor diagonal moves returns a strictly suboptimal route.
heading("Exercise 2: Failure-mode audit — inadmissible c_max scaling and Manhattan-on-diagonals bug")
t56 = constants_benchmarks.make_topographic_terrain(nx=56, ny=56, seed=42)["cost_grid"]
# 0. Input guard checks:
caught = 0
for bad_call in [
lambda: greedy_heuristic_search.grid_shortest_path_search(np.ones((4,)), (0, 0), (1, 1)),
lambda: greedy_heuristic_search.grid_shortest_path_search(t56, (-1, 0), (5, 5)),
lambda: greedy_heuristic_search.grid_shortest_path_search(np.array([[1.0, 0.0], [1.0, 1.0]]), (0, 0), (1, 1)),
lambda: greedy_heuristic_search.grid_shortest_path_search(t56, (0, 0), (5, 5), method="bellman"),
lambda: greedy_heuristic_search.grid_shortest_path_search(t56, (0, 0), (5, 5), heuristic_weight=-0.5),
]:
try:
bad_call()
except ValueError:
caught += 1
assert caught == 5
obs_grid = np.ones((4, 4)); obs_grid[3, 3] = math.inf
assert greedy_heuristic_search.grid_shortest_path_search(obs_grid, (0, 0), (3, 3))["found"] is False
# (a) Using c_mean or c_max instead of c_min is equivalent to heuristic_weight = c_mean/c_min or c_max/c_min > 1:
c_min = float(np.min(t56))
c_max = float(np.max(t56))
opt_route = greedy_heuristic_search.grid_shortest_path_search(t56, (6, 6), (48, 48), method="astar", heuristic_weight=1.0)
bug_cmax = greedy_heuristic_search.grid_shortest_path_search(t56, (6, 6), (48, 48), method="astar", heuristic_weight=c_max / c_min)
assert bug_cmax["total_cost"] > opt_route["total_cost"] + 5.0
# (b) Buggy 8-neighbor A* mistakenly using Manhattan distance |dr| + |dc| instead of Euclidean hypot(dr, dc):
import heapq
def buggy_diagonal_astar_manhattan(grid: np.ndarray, start: tuple[int, int], goal: tuple[int, int]) -> float:
h, w = grid.shape
c0 = float(np.min(grid))
s2 = math.sqrt(2.0)
moves = [(-1,0,1.0),(1,0,1.0),(0,-1,1.0),(0,1,1.0),(-1,-1,s2),(-1,1,s2),(1,-1,s2),(1,1,s2)]
g = np.full((h, w), math.inf)
closed = np.zeros((h, w), dtype=bool)
g[start] = 0.0
pq = [(c0 * (abs(goal[0] - start[0]) + abs(goal[1] - start[1])), start[0], start[1])]
while pq:
_, r, c = heapq.heappop(pq)
if closed[r, c]:
continue
closed[r, c] = True
if (r, c) == goal:
return float(g[r, c])
for dr, dc, slen in moves:
nr, nc = r + dr, c + dc
if 0 <= nr < h and 0 <= nc < w and not closed[nr, nc]:
ng = g[r, c] + slen * float(grid[nr, nc])
if ng < g[nr, nc] - 1e-13:
g[nr, nc] = ng
h_bad = c0 * (abs(goal[0] - nr) + abs(goal[1] - nc)) # BUG: 2.0 > sqrt(2) on diagonals
heapq.heappush(pq, (ng + h_bad, nr, nc))
return math.inf
# Corridor benchmark: direct horizontal path has slight penalty (1.28), whereas diagonal detour costs 1.00 * sqrt(2):
g_diag_trap = np.ones((15, 15), dtype=float)
g_diag_trap[7, 1:14] = 1.28 # Direct horizontal row r=7 has mild mud; diagonal bypass uses clean 1.00 cells
c_true_8 = greedy_heuristic_search.grid_shortest_path_search(g_diag_trap, (7, 0), (7, 14), method="astar", allow_diagonal=True)["total_cost"]
c_bug_manh = buggy_diagonal_astar_manhattan(g_diag_trap, (7, 0), (7, 14))
assert c_bug_manh > c_true_8 + 0.3
print(f"(a) Inadmissible c_max scaling : True Optimal = {opt_route['total_cost']:.2f} vs. c_max Bug = {bug_cmax['total_cost']:.2f} (+{bug_cmax['total_cost'] - opt_route['total_cost']:.2f} penalty)")
print(f"(b) Manhattan on 8-neighbor : True Optimal = {c_true_8:.4f} vs. Manhattan-Heuristic Bug = {c_bug_manh:.4f} (missed diagonal bypass)")
Exercise 2: Failure-mode audit — inadmissible c_max scaling and Manhattan-on-diagonals bug
==========================================================================================
(a) Inadmissible c_max scaling : True Optimal = 107.35 vs. c_max Bug = 140.31 (+32.95 penalty)
(b) Manhattan on 8-neighbor : True Optimal = 14.8284 vs. Manhattan-Heuristic Bug = 15.2244 (missed diagonal bypass)
Explanation. On 8-neighbor grids, moving diagonally by decreases Manhattan distance by while costing as little as . That heuristic overestimate penalizes off-axis diagonal detours around mud/ridges, causing to pop the goal prematurely along a suboptimal axis-aligned route.
Exercise 3¶
Problem. Implement multi_waypoint_terrain_planner(cost_grid, depot, waypoints) combining pairwise 8-neighbor admissible shortest paths with exact Held–Karp subset DP () to route an autonomous rover from depot through geological targets and back to depot. Verify exact cost agreement against all permutations and compare against greedy Nearest-Neighbor.
heading("Exercise 3: Implement it yourself — multi-waypoint rover terrain tour (A* + Held-Karp DP)")
import itertools
def multi_waypoint_terrain_planner(
cost_grid: np.ndarray,
depot: tuple[int, int],
waypoints: list[tuple[int, int]],
) -> dict:
"""Compute exact minimum-energy closed rover tour over terrain via pairwise 8-neighbor A* + Held-Karp DP."""
nodes = [depot] + list(waypoints)
n = len(nodes) # n = K + 1 (node 0 is depot, 1..K are waypoints)
dist = np.zeros((n, n), dtype=float)
seg_paths: dict[tuple[int, int], list[tuple[int, int]]] = {}
for i in range(n):
for j in range(n):
if i == j:
continue
res = greedy_heuristic_search.grid_shortest_path_search(
cost_grid, nodes[i], nodes[j], method="astar", allow_diagonal=True
)
dist[i, j] = res["total_cost"]
seg_paths[(i, j)] = res["path"]
k = len(waypoints)
full_mask = (1 << k) - 1
# dp[mask, last] where last in 0..k-1 corresponds to node (last + 1):
dp = np.full((1 << k, k), math.inf)
parent = np.full((1 << k, k), -1, dtype=int)
for j in range(k):
dp[1 << j, j] = dist[0, j + 1]
for mask in range(1, full_mask + 1):
for j in range(k):
if not ((mask >> j) & 1):
continue
prev_mask = mask ^ (1 << j)
if prev_mask == 0:
continue
for i in range(k):
if (prev_mask >> i) & 1:
cand = dp[prev_mask, i] + dist[i + 1, j + 1]
if cand < dp[mask, j]:
dp[mask, j] = cand
parent[mask, j] = i
best_cost = math.inf
best_last = -1
for j in range(k):
tot = dp[full_mask, j] + dist[j + 1, 0]
if tot < best_cost:
best_cost = tot
best_last = j
order_wp = []
cur_m, cur_j = full_mask, best_last
while cur_j != -1:
order_wp.append(cur_j + 1)
nxt_j = int(parent[cur_m, cur_j])
cur_m ^= (1 << cur_j)
cur_j = nxt_j
order_wp.reverse()
tour_nodes = [0] + order_wp + [0]
stitched: list[tuple[int, int]] = []
for a, b in zip(tour_nodes[:-1], tour_nodes[1:]):
seg = seg_paths[(a, b)]
stitched.extend(seg if not stitched else seg[1:])
return {"tour_order": tour_nodes, "total_cost": float(best_cost), "dist_matrix": dist, "full_grid_path": stitched}
terr_rv = constants_benchmarks.make_topographic_terrain(nx=56, ny=56, seed=42)
cg_rv = terr_rv["cost_grid"]
depot_rv = (8, 8)
wps_rv = [(42, 10), (14, 46), (48, 44), (10, 28), (44, 28), (28, 50)]
plan = multi_waypoint_terrain_planner(cg_rv, depot_rv, wps_rv)
dmat = plan["dist_matrix"]
# 1. Verify Held-Karp exactness against all 6 = 720 permutations:
bf_min = min(
dmat[0, perm[0]] + sum(dmat[perm[idx], perm[idx + 1]] for idx in range(5)) + dmat[perm[-1], 0]
for perm in itertools.permutations(range(1, 7))
)
assert np.isclose(plan["total_cost"], bf_min, atol=1e-11)
# 2. Compare against Greedy Nearest-Neighbor tour from depot:
unvis = set(range(1, 7))
cur = 0
nn_cost = 0.0
while unvis:
nxt = min(unvis, key=lambda j: dmat[cur, j])
nn_cost += dmat[cur, nxt]
cur = nxt
unvis.remove(nxt)
nn_cost += dmat[cur, 0]
assert plan["total_cost"] < nn_cost - 5.0
print(f"Optimal Rover Tour Order : {plan['tour_order']} ({len(plan['full_grid_path'])} terrain cells)")
print(f"Held-Karp Exact Tour Cost : {plan['total_cost']:.4f} (720-permutation oracle = {bf_min:.4f})")
print(f"Greedy Nearest-Neighbor : {nn_cost:.4f} (Held-Karp saves {nn_cost - plan['total_cost']:.2f} energy units)")
fp = np.array(plan["full_grid_path"])
pts_all = np.array([depot_rv] + wps_rv)
fig, ax = plt.subplots(figsize=(7.0, 4.7))
ax.imshow(terr_rv["elevation_m"], origin="lower", cmap="terrain")
ax.plot(fp[:, 1], fp[:, 0], lw=2.2, color="#19D3C5", label=f"Optimal rover tour (cost = {plan['total_cost']:.1f})")
ax.scatter(pts_all[1:, 1], pts_all[1:, 0], s=65, c="#C0392B", edgecolors="black", zorder=5, label="6 science targets")
ax.scatter([depot_rv[1]], [depot_rv[0]], s=95, marker="*", c="#F2C744", edgecolors="black", zorder=6, label="Rover depot")
ax.set_xlabel("Column $c$")
ax.set_ylabel("Row $r$")
ax.set_title("Rover tour: A* legs ordered by Held-Karp")
ax.grid(False)
ax.legend(loc="center left", bbox_to_anchor=(1.02, 0.5), fontsize=8)
plt.show()
Exercise 3: Implement it yourself — multi-waypoint rover terrain tour (A* + Held-Karp DP)
=========================================================================================
Optimal Rover Tour Order : [0, 4, 2, 6, 3, 5, 1, 0] (142 terrain cells)
Held-Karp Exact Tour Cost : 283.4500 (720-permutation oracle = 283.4500)
Greedy Nearest-Neighbor : 318.5014 (Held-Karp saves 35.05 energy units)

Figure S9.1. Rover tour from the depot (star) through six targets on the synthetic terrain. The Held–Karp order with A* legs costs 283.4.
Summary. The problem splits into two parts: pairwise searches reduce the terrain to a table of exact energies between the depot and the targets, and Held–Karp dynamic programming orders the visits. The tour cost, 283.45, equals the best of all 720 permutations and is 35.05 units below the nearest-neighbour tour.