In this fictional scenario, at 04:12 local time a earthquake fractures valley highways with rockslides, knocks out of cellular relay towers stochastically, and triggers thousands of duplicate emergency SOS beacon bursts across a alpine basin. Your engineering team has 30 minutes to size heavy-lift medical relief drones, identify cut-off survivor clusters, thread obstacle-aware mountain-pass flight corridors, optimize multi-site delivery tours, pack trauma payloads, schedule ground-crew launch turnarounds, and check the flight software before takeoff. This project combines all nine engthink modules and the 24 Mental Moves in one mission planner, with a check at every stage. All terrain, station and aircraft data are synthetic or assumed.
Learning objectives¶
Nondimensionalize rotorcraft cruise/hover power via
representation_scaling.buckingham_pi_nullspaceand size minimum Li-Po battery mass fraction viadivide_spatial.parametric_binary_search_min.Index surviving field relays in (
invariants_complexity.spatial_cell_list_neighbors), map connected survivor clusters (emergence_verification.site_percolation_2d), and deduplicate SOS bursts with zero false negatives (information_streams.bloom_filter_simulate).Thread minimum-energy mountain-pass corridors via
greedy_heuristic_search.grid_shortest_path_search(method='astar') and optimize multi-target delivery tours viaemergence_verification.simulated_annealing_tsp.Allocate trauma kits (
dynamic_optimality.knapsack_01_dp), compress ground turnaround (reductions_constraints.critical_path_dag), audit mission code (emergence_verification.metamorphic_differential_audit), and benchmark against exact Held-Karp & Beasley multi-sortie Split DP.
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. Phase I, Buckingham- Rotorcraft Scaling & Parametric Battery Sizing¶
Before routing a single drone across high-altitude mountain air ( at elevation), we must relate rotorcraft aerodynamic power [], total takeoff weight [], air density [], total rotor disk area [], and forward cruise speed []. Applying Mental Move #5 (representation_scaling.buckingham_pi_nullspace) to over collapses dimensionless groups:
The null-space basis printed below gives the squares of these two groups, which are equivalent.
Hover power grows as : adding extra battery mass increases stored energy linearly (), but the takeoff mass grows like , so the hover power grows like . Using Mental Move #11 (divide_spatial.parametric_binary_search_min), we find the exact minimum battery mass fraction achieving a mountain range with a safety reserve.
heading("Capstone phase 1: Buckingham-Pi drone power scaling and binary-searched battery sizing")
# Variables: [P (W = M L^2 T^-3), V (L T^-1), W (N = M L T^-2), rho (M L^-3), A (L^2)]
# Put repeating basis [W, rho, A] first -> columns [W, rho, A, P, V]:
dim_drone = np.array([
[ 1, 1, 0, 1, 0], # M
[ 1, -3, 2, 2, 1], # L
[-2, 0, 0, -3, -1], # T
], dtype=int)
pi_drone = representation_scaling.buckingham_pi_nullspace(dim_drone, var_names=["W", "rho", "A", "P", "V"])
print(f"Rank(D) = {pi_drone['rank']} -> {pi_drone['n_pi_groups']} dimensionless rotorcraft groups (residual = {pi_drone['nullspace_residual']:.1e}):")
for idx_g, grp_s in enumerate(pi_drone["formatted_groups"], start=1):
print(f" Pi_{idx_g} = {grp_s}")
assert pi_drone["n_pi_groups"] == 2 and pi_drone["nullspace_residual"] == 0.0
# Physical heavy-lift quad-rotor sizing at 1,800 m mountain altitude:
m_frame_kg = 5.5 # Carbon airframe + avionics + motors [kg]
m_payload_kg = 4.5 # Emergency trauma & defibrillator kit [kg]
rho_mtn = 1.02 # Mountain air density [kg/m^3]
area_disk = 0.85 # 4 rotors total swept area [m^2]
v_cruise = 18.0 # Cruise speed [m/s] (= 64.8 km/h)
e_spec_wh_kg = 195.0 # High-density Li-Po pack specific energy [Wh/kg]
eta_drivetrain = 0.74 # ESC + brushless motor + propulsive efficiency
def max_safe_range_km(f_bat: float) -> float:
"""Achievable range [km] keeping 20% emergency battery reserve under Pi_1(Pi_2) power law."""
if not (0.01 <= f_bat <= 0.72):
return 0.0
m_tot = (m_frame_kg + m_payload_kg) / (1.0 - f_bat)
m_bat = f_bat * m_tot
w_n = 9.81 * m_tot
v_h = math.sqrt(w_n / (2.0 * rho_mtn * area_disk)) # Induced hover velocity scale
# Translating cruise power = induced hover / sqrt(1 + (V/(2*v_h))^2) + parasitic机身 drag:
p_aero = (w_n * v_h) / math.sqrt(1.0 + (0.5 * v_cruise / v_h) ** 2) + 0.5 * rho_mtn * 0.045 * (v_cruise ** 3)
p_elec = p_aero / eta_drivetrain
usable_energy_j = 0.80 * m_bat * e_spec_wh_kg * 3600.0
flight_time_s = usable_energy_j / p_elec
return (v_cruise * flight_time_s) / 1000.0
target_range_km = 45.0
bs_bat = divide_spatial.parametric_binary_search_min(
lambda fb: max_safe_range_km(fb) >= target_range_km, lo=0.08, hi=0.62, tol=1e-6
)
f_star = bs_bat["threshold"]
m_tot_star = (m_frame_kg + m_payload_kg) / (1.0 - f_star)
print(f"Target 45.0 km mountain range (+20% reserve): f_bat* = {100*f_star:.2f}% ({bs_bat['evaluations']} evals)")
print(f" -> Battery mass = {f_star*m_tot_star:.2f} kg, Total takeoff mass = {m_tot_star:.2f} kg, Range check = {max_safe_range_km(f_star):.3f} km")
assert bs_bat["feasible"] and np.isclose(max_safe_range_km(f_star), target_range_km, atol=1e-3)
fb_grid = np.linspace(0.08, 0.65, 100)
rng_curve = [max_safe_range_km(float(fv)) for fv in fb_grid]
mtot_curve = [(m_frame_kg + m_payload_kg) / (1.0 - float(fv)) for fv in fb_grid]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.0))
ax1.plot(100 * fb_grid, rng_curve, "b-", lw=2.2, label="Safe mission range [km]")
ax1.axhline(target_range_km, color="k", ls=":", lw=1.4, label="Target $45\\ \\mathrm{km}$")
ax1.axvline(100 * f_star, color="r", ls="--", lw=1.6, label=f"$f_{{\\mathrm{{bat}}}}^\\star = {100*f_star:.1f}\\%$")
ax1.set_xlabel("Battery mass fraction $f_{\\mathrm{bat}}$ [%]")
ax1.set_ylabel("Achievable safe range [km]")
ax1.set_title("Range against battery fraction")
ax1.legend(fontsize=8.2)
ax2.plot(100 * fb_grid, mtot_curve, "m-", lw=2.2, label="$m_{\\mathrm{tot}} = (m_{\\mathrm{dry}})/(1 - f_{\\mathrm{bat}})$")
ax2.plot(100 * f_star, m_tot_star, "ro", ms=7, label=f"Selected MTOW = {m_tot_star:.1f} kg")
ax2.set_xlabel("Battery mass fraction $f_{\\mathrm{bat}}$ [%]")
ax2.set_ylabel("Gross takeoff mass $m_{\\mathrm{tot}}$ [kg]")
ax2.set_title("Take-off mass as $f_{\\mathrm{bat}} \\to 1$")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
Capstone phase 1: Buckingham-Pi drone power scaling and binary-searched battery sizing
======================================================================================
Rank(D) = 3 -> 2 dimensionless rotorcraft groups (residual = 0.0e+00):
Pi_1 = rho * A * P^2 / (W^3)
Pi_2 = rho * A * V^2 / (W)
Target 45.0 km mountain range (+20% reserve): f_bat* = 55.83% (22 evals)
-> Battery mass = 12.64 kg, Total takeoff mass = 22.64 kg, Range check = 45.000 km

Figure 17.1. Battery sizing of the relief drone (assumed aircraft data). (a) Safe range against the battery mass fraction; the target of 45 km is reached at (dashed). (b) Take-off mass against the battery fraction, with the selected design, 22.6 kg.
What Phase I shows. The range curve on the left bends over instead of growing without limit as : the stored energy grows like with , while the hover power grows like , so beyond some fraction more battery mostly carries itself. For a 45 km range with a 20 % reserve the bisection gives , a battery of 12.64 kg in a 22.64 kg drone. All aircraft parameters in this chapter are assumed values.
2. Phase II, Spatial Relay Indexing, Percolation & Zero-FN SOS Deduplication¶
Across the earthquake zone, 60 solar emergency relay towers (constants_benchmarks.make_sensor_station_coords) attempt to form a multi-hop LoRa radio mesh (r_comm = 14.3 km).
Cell-List Spatial Hashing (
invariants_complexity.spatial_cell_list_neighbors): Finds all active LoRa links in instead of testing all pairs.Road-Grid Rubble Percolation (
emergence_verification.site_percolation_2d): Models ground-ambulance passability when of the valley road intersections are blocked (, so ground vehicles are cut off and drones are needed).Edge SOS Deduplication (
information_streams.bloom_filter_simulate): Suppresses duplicate SOS relays with of memory on the drone, without missing any survivor ID.
heading("Capstone phase 2: Spatial relay mesh, road percolation check and Bloom SOS deduplication")
station_xy = constants_benchmarks.make_sensor_station_coords(n_stations=60, seed=42)
r_lora_km = 14.3
cell_links = invariants_complexity.spatial_cell_list_neighbors(station_xy, cutoff_r=r_lora_km)
exact_links = invariants_complexity.brute_force_neighbors(station_xy, cutoff_r=r_lora_km)
assert cell_links["pairs"] == exact_links
# Union-Find connected components of the 60-station LoRa mesh (station 0 = Command Depot):
parent_st = list(range(60))
def _find_s(u: int) -> int:
while parent_st[u] != u:
parent_st[u] = parent_st[parent_st[u]]
u = parent_st[u]
return u
for u, v in cell_links["pairs"]:
ru, rv = _find_s(u), _find_s(v)
if ru != rv:
parent_st[max(ru, rv)] = min(ru, rv)
depot_root = _find_s(0)
online_mask = np.array([_find_s(i) == depot_root for i in range(60)], dtype=bool)
cutoff_sites = np.where(~online_mask)[0]
# Ground road-network site percolation at p_open = 0.54 (< p_c = 0.5927):
road_perc = emergence_verification.site_percolation_2d(L=48, p_occupy=0.54, seed=17)
# Deduplicate 320 unique survivor SOS beacons echoed across mesh hops in 4,096 bits (512 bytes):
sos_seen = [f"SOS-SURVIVOR-{i:04d}" for i in range(320)]
sos_new_burst = [f"SOS-NEW-{j:04d}" for j in range(1000)]
bf_sos = information_streams.bloom_filter_simulate(sos_seen, sos_seen + sos_new_burst, m_bits=4096)
cms_sos = information_streams.count_min_sketch_frequencies(
sos_seen * 3 + sos_seen[:10] * 25, width_w=64, depth_d=4
)
print(f"LoRa Cell-List Indexing : {cell_links['n_pairs']} links found in {cell_links['candidate_distance_checks']} checks ({cell_links['speedup_over_all_pairs']:.1f}x faster than all-pairs)")
print(f"Radio Mesh Connectivity : {int(np.sum(online_mask))}/60 stations reach Depot #0; {cutoff_sites.size} isolated stations require direct drone recon")
print(f"Ground Road Percolation : p_open = 0.54 < p_c -> percolates_top_to_bottom = {road_perc['percolates_top_to_bottom']} (trucks blocked)")
print(f"512-Byte SOS Bloom Filter: False Negatives = {bf_sos['false_negatives']} (0 missed SOS), FPR = {100*bf_sos['empirical_fpr']:.2f}%, CMS min_err = {cms_sos['min_overestimate']}")
assert bf_sos["false_negatives"] == 0 and cms_sos["min_overestimate"] >= 0
assert not road_perc["percolates_top_to_bottom"] and cutoff_sites.size >= 4
fig, ax = plt.subplots(figsize=(7.6, 4.4))
for u, v in cell_links["pairs"]:
col_e = "#A9C9E8" if online_mask[u] else "#F2B8AE"
ax.plot([station_xy[u, 0], station_xy[v, 0]], [station_xy[u, 1], station_xy[v, 1]], color=col_e, lw=0.9, zorder=1)
ax.scatter(station_xy[online_mask, 0], station_xy[online_mask, 1], c="#2166AC", s=38, zorder=3, label=f"Depot-connected relays ({int(np.sum(online_mask))})")
ax.scatter(station_xy[~online_mask, 0], station_xy[~online_mask, 1], c="#C0392B", marker="^", s=64, zorder=4, label=f"Cut-off priority cluster ({cutoff_sites.size})")
ax.scatter([station_xy[0, 0]], [station_xy[0, 1]], c="#F2C744", edgecolors="k", marker="*", s=190, zorder=5, label="Command depot #0")
ax.set_xlabel("East $x$ [km]"); ax.set_ylabel("North $y$ [km]")
ax.set_title("Relay network and cut-off stations")
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.12), ncol=3, fontsize=8.2)
plt.show()
Capstone phase 2: Spatial relay mesh, road percolation check and Bloom SOS deduplication
========================================================================================
LoRa Cell-List Indexing : 156 links found in 382 checks (4.6x faster than all-pairs)
Radio Mesh Connectivity : 51/60 stations reach Depot #0; 9 isolated stations require direct drone recon
Ground Road Percolation : p_open = 0.54 < p_c -> percolates_top_to_bottom = False (trucks blocked)
512-Byte SOS Bloom Filter: False Negatives = 0 (0 missed SOS), FPR = 0.30%, CMS min_err = 0

Figure 17.2. Synthetic relay network after the earthquake. 51 stations (blue) connect to the command depot (star); 9 stations (triangles) are cut off and need a direct drone visit.
What Phase II shows. The cell list finds the 156 radio links with 382 distance checks instead of 1,770, and the connected components show that 9 of the 60 stations have no radio path to Command Depot #0, so they need a direct drone visit. The road lattice at does not percolate, and the 512-byte Bloom filter misses no SOS ID, with a false-positive rate of .
3. Phase III, A* Mountain-Pass Corridors & Simulated Annealing Multi-Site Routing¶
Flying straight across the central ridge of the synthetic terrain drains the battery quickly (cost_grid elevation penalty in constants_benchmarks.make_topographic_terrain). We combine two search paradigms:
Micro-Corridor Search (
greedy_heuristic_search.grid_shortest_path_search, Mental Move #18): Threads minimum-energy terrain paths through low mountain saddle passes using admissible A* (method="astar",allow_diagonal=True), expanding fewer grid cells than Dijkstra and returning the same minimum corridor cost.Macro-Tour Optimization (
emergence_verification.simulated_annealing_tsp): Orders 12 priority relief drop-zones (Command Depot + cut-off stations + high-triage beacons) into a minimum-length aerial loop.
heading("Capstone phase 3: A* mountain-pass corridor threading and 12-site simulated annealing tour")
terrain = constants_benchmarks.make_topographic_terrain(nx=64, ny=64, seed=42)
cost_map = terrain["cost_grid"].copy()
# Add impassable no-fly landslide plume / severe rotor-downdraft cliff cells (cost = inf):
cost_map[26:34, 29:33] = math.inf
# Compare A* vs. Dijkstra from SW Command Base (8, 8) to NE Isolated Village (54, 55):
start_rc, goal_rc = (8, 8), (54, 55)
astar_corridor = greedy_heuristic_search.grid_shortest_path_search(
cost_map, start_rc, goal_rc, method="astar", heuristic_weight=1.0, allow_diagonal=True
)
dijk_corridor = greedy_heuristic_search.grid_shortest_path_search(
cost_map, start_rc, goal_rc, method="dijkstra", allow_diagonal=True
)
# Select 12 priority relief waypoints (Depot #0 + cut-off relays + highest-SOS hubs) and anneal 2-opt tour:
priority_idx = np.unique(np.concatenate([[0], cutoff_sites, [5, 11, 18, 25, 33, 41, 48, 53]]))[:12]
priority_xy = station_xy[priority_idx]
sa_mission = emergence_verification.simulated_annealing_tsp(
priority_xy, T_init=25.0, T_final=1e-3, n_steps=8000, seed=17
)
print(f"Mountain Corridor {start_rc} -> {goal_rc}:")
print(f" Dijkstra cost = {dijk_corridor['total_cost']:.6f} ({dijk_corridor['nodes_expanded']} cells expanded)")
print(f" A* cost = {astar_corridor['total_cost']:.6f} ({astar_corridor['nodes_expanded']} cells expanded -> {100*(1 - astar_corridor['nodes_expanded']/dijk_corridor['nodes_expanded']):.1f}% fewer)")
print(f"12-Site Priority Relief Tour: initial = {sa_mission['initial_length']:.2f} km -> annealed = {sa_mission['best_length']:.2f} km")
assert astar_corridor["found"] and np.isclose(astar_corridor["total_cost"], dijk_corridor["total_cost"], rtol=1e-12)
assert astar_corridor["nodes_expanded"] < 0.78 * dijk_corridor["nodes_expanded"]
assert sa_mission["best_length"] < 0.72 * sa_mission["initial_length"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.3))
im1 = ax1.imshow(terrain["elevation_m"], origin="lower", cmap="terrain", extent=[0, 100, 0, 100])
ax1.grid(False)
# Mark blocked no-fly cliff zone:
ax1.fill([29*100/64, 33*100/64, 33*100/64, 29*100/64], [26*100/64, 26*100/64, 34*100/64, 34*100/64],
color="k", alpha=0.75, label="No-fly plume")
py_km = [r * 100.0 / 63.0 for r, _ in astar_corridor["path"]]
px_km = [c * 100.0 / 63.0 for _, c in astar_corridor["path"]]
ax1.plot(px_km, py_km, color="#C0392B", lw=2.5, label="Optimal A* saddle-pass corridor")
ax1.set_xlabel("East $x$ [km]"); ax1.set_ylabel("North $y$ [km]")
ax1.set_title("A* corridor around the no-fly zone")
ax1.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=7.9)
plt.colorbar(im1, ax=ax1, fraction=0.046, pad=0.04, label="Elevation [m]")
cyc_m = np.append(sa_mission["best_tour"], sa_mission["best_tour"][0])
ax2.plot(priority_xy[cyc_m, 0], priority_xy[cyc_m, 1], "b-o", ms=6, lw=2.1, label=f"SA 12-site tour ({sa_mission['best_length']:.1f} km)")
ax2.scatter([priority_xy[0, 0]], [priority_xy[0, 1]], c="#F2C744", edgecolors="k", marker="*", s=190, zorder=5, label="Command depot")
ax2.set_xlabel("East $x$ [km]"); ax2.set_ylabel("North $y$ [km]")
ax2.set_title("Annealed multi-target relief tour")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
Capstone phase 3: A* mountain-pass corridor threading and 12-site simulated annealing tour
==========================================================================================
Mountain Corridor (8, 8) -> (54, 55):
Dijkstra cost = 105.179715 (2968 cells expanded)
A* cost = 105.179715 (1980 cells expanded -> 33.3% fewer)
12-Site Priority Relief Tour: initial = 524.98 km -> annealed = 272.65 km

Figure 17.3. Routing. (a) The A* corridor across the synthetic terrain around the no-fly zone. (b) The annealed tour through 12 sites, 272.7 km, starting from the command depot (star).
What Phase III shows. In the left map the A* corridor goes around the central peak and the no-fly zone instead of over them. It has the same cost as Dijkstra, 105.18, with 1,980 instead of 2,968 cell expansions (33 % fewer). Simulated annealing shortens the 12-site tour from 524.98 km to 272.65 km.
4. Phase IV, Knapsack Triage Packing, Launch CPM & Metamorphic Pre-Flight Audit¶
Before clearing the drone for launch, three final algorithmic modules close the loop:
0/1 Payload Knapsack (
dynamic_optimality.knapsack_01_dp, Mental Move #15): Packs discrete medical modules into the ( integer units) payload bay to maximize life-saving triage utility.Ground-Crew Critical Path (
reductions_constraints.critical_path_dag, Mental Move #20): Schedules parallel battery charging, IMU calibration, corridor upload, and payload rigging to pinpoint zero-slack launch bottlenecks.Compensated Telemetry & Metamorphic Safety Gate (
representation_scaling.kahan_babuska_sum,emergence_verification.metamorphic_differential_audit, Mental Move #24): Audits the flight-controller energy-summation routine against permutation, shift, and scaling laws prior to arming rotors.
heading("Capstone phase 4: 0/1 medical knapsack, launch turnaround CPM and pre-flight metamorphic gate")
# 1. 0/1 Knapsack medical payload selection (capacity = 45 units of 100 g = 4,500 g):
kit_names = ["Defibrillator", "Hemorrhage-Pack", "Antibiotics", "Water-Purifier", "Insulin-Cooler", "Splint-Set", "Sat-Beacon", "Thermal-Blankets"]
kit_weights_100g = np.array([18, 9, 6, 11, 10, 8, 7, 5], dtype=int)
kit_triage_val = np.array([92.0, 64.0, 48.0, 52.0, 58.0, 35.0, 46.0, 31.0])
knap_med = dynamic_optimality.knapsack_01_dp(kit_weights_100g, kit_triage_val, capacity=45)
packed_names = [kit_names[i] for i in knap_med["selected_indices"]]
# 2. Ground-crew launch turnaround Critical Path DAG [minutes]:
turnaround_tasks = {
"Inspect_Frame": 3.0,
"Swap_LiPo": 4.5,
"IMU_Calib": 3.5,
"Pack_Bay": 4.0,
"Upload_Route": 2.5,
"Rotor_Arm_Test": 2.0,
}
turnaround_deps = [
("Inspect_Frame", "Swap_LiPo"),
("Inspect_Frame", "Pack_Bay"),
("Swap_LiPo", "IMU_Calib"),
("IMU_Calib", "Rotor_Arm_Test"),
("Pack_Bay", "Rotor_Arm_Test"),
("Upload_Route", "Rotor_Arm_Test"),
]
cpm_launch = reductions_constraints.critical_path_dag(turnaround_tasks, turnaround_deps)
# 3. Compensated Kahan-Neumaier telemetry integration + Metamorphic pre-flight check on mean leg power:
micro_leg_joules = np.array([1.2e5] + [0.15] * 5000, dtype=np.float64)
kahan_chk = representation_scaling.kahan_babuska_sum(micro_leg_joules)
preflight_audit = emergence_verification.metamorphic_differential_audit(
lambda x: representation_scaling.kahan_babuska_sum(x)["neumaier_sum"] / float(x.size),
oracle_fn=lambda x: float(np.mean(x)),
relations=("permutation_invariance", "shift_equivariance", "scale_equivariance"),
n_fuzz=60,
seed=17,
)
print(f"Medical Payload Packed ({100*knap_med['total_weight']}g / 4500g, Triage Score = {knap_med['max_value']:.0f}): {packed_names}")
print(f"Launch Turnaround Makespan = {cpm_launch['project_duration']:.1f} min | Critical Path (slack=0) = {cpm_launch['critical_path']}")
print(f"Neumaier Energy Sum Error = {kahan_chk['neumaier_abs_error']:.2e} J | Pre-Flight Metamorphic Gate Passed = {preflight_audit['passed']} ({preflight_audit['tests_run']} checks)")
assert knap_med["total_weight"] <= 45 and knap_med["max_value"] >= 270.0
assert np.isclose(cpm_launch["project_duration"], 13.0) and cpm_launch["critical_path"] == ["Inspect_Frame", "Swap_LiPo", "IMU_Calib", "Rotor_Arm_Test"]
assert kahan_chk["neumaier_abs_error"] <= kahan_chk["naive_abs_error"] and preflight_audit["passed"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.5, 4.1))
picked_set = set(knap_med["selected_indices"])
cols_kp = ["#2E8B57" if i in picked_set else "#C5CCD3" for i in range(len(kit_names))]
ax1.barh(kit_names, kit_triage_val / kit_weights_100g, color=cols_kp, edgecolor="k", height=0.6)
ax1.set_xlabel("Value density [triage pts / 100g] (green = packed)")
ax1.set_title(f"0/1 knapsack optimal trauma kit ({100*knap_med['total_weight']:,} g of 4,500 g)")
tasks_ord = cpm_launch["topological_order"]
y_g = np.arange(len(tasks_ord))
for idx_t, t_name in enumerate(tasks_ord):
es_v = cpm_launch["earliest_start"][t_name]
dur_v = turnaround_tasks[t_name]
sl_v = cpm_launch["slack"][t_name]
c_bar = "#C0392B" if sl_v < 1e-9 else "#2166AC"
ax2.barh(idx_t, dur_v, left=es_v, color=c_bar, edgecolor="k", height=0.55)
if sl_v > 1e-9:
ax2.barh(idx_t, sl_v, left=es_v + dur_v, color="#A9C9E8", edgecolor="gray", ls="--", height=0.35)
ax2.set_yticks(y_g)
ax2.set_yticklabels(tasks_ord, fontsize=8.3)
ax2.set_xlabel("Turnaround timeline [min] (red = zero-slack critical, light blue = float)")
ax2.set_title(f"Ground launch CPM schedule ({cpm_launch['project_duration']:.1f} min)")
label_panels(fig)
plt.show()
Capstone phase 4: 0/1 medical knapsack, launch turnaround CPM and pre-flight metamorphic gate
=============================================================================================
Medical Payload Packed (4500g / 4500g, Triage Score = 282): ['Hemorrhage-Pack', 'Antibiotics', 'Insulin-Cooler', 'Splint-Set', 'Sat-Beacon', 'Thermal-Blankets']
Launch Turnaround Makespan = 13.0 min | Critical Path (slack=0) = ['Inspect_Frame', 'Swap_LiPo', 'IMU_Calib', 'Rotor_Arm_Test']
Neumaier Energy Sum Error = 0.00e+00 J | Pre-Flight Metamorphic Gate Passed = True (240 checks)

Figure 17.4. Payload and launch. (a) Value density of the medical modules; the green ones are packed, 4,500 g in all. (b) Launch schedule; red tasks are critical, light bars show slack. The turnaround takes 13 min.
Inside the algorithm¶
Phases I–IV used all nine modules of engthink. How good is the annealed tour of Phase III? For waypoints, Bellman–Held–Karp bitmask dynamic programming computes the exact minimum tour in operations instead of . Below, we inspect constants_benchmarks.make_topographic_terrain and run a comprehensive verify_end_to_end_mission_invariants check of every phase of the mission.
Check against the library¶
heading("Inside the algorithm: Topographic benchmark and end-to-end mission invariant certifier")
print(show_source(constants_benchmarks.make_topographic_terrain))
def verify_end_to_end_mission_invariants(sub_coords_10: np.ndarray) -> dict:
"""Certify dimensional, zero-FN streaming, A* optimality, knapsack brute-force, and Held-Karp TSP invariants."""
# 1. Held-Karp exact DP on 10-waypoint sub-mission (2^9 * 10 = 5,120 states):
n = sub_coords_10.shape[0]
dmat = np.hypot(sub_coords_10[:, None, 0] - sub_coords_10[None, :, 0],
sub_coords_10[:, None, 1] - sub_coords_10[None, :, 1])
n_masks = 1 << (n - 1) # bit k in 0..n-2 represents node k+1
dp = np.full((n_masks, n), math.inf, dtype=float)
for j in range(1, n):
dp[1 << (j - 1), j] = dmat[0, j]
for mask in range(1, n_masks):
for j in range(1, n):
if not (mask & (1 << (j - 1))):
continue
prev_m = mask ^ (1 << (j - 1))
if prev_m == 0:
continue
for i in range(1, n):
if prev_m & (1 << (i - 1)):
cand = dp[prev_m, i] + dmat[i, j]
if cand < dp[mask, j]:
dp[mask, j] = cand
full_m = n_masks - 1
hk_exact = min(dp[full_m, j] + dmat[j, 0] for j in range(1, n))
sa_sub = emergence_verification.simulated_annealing_tsp(sub_coords_10, T_init=25.0, T_final=1e-3, n_steps=6000, seed=42)
# 2. Exact 2^8 = 256 brute-force subset check on Phase-4 medical knapsack:
bf_best_val = max(
float(np.sum(kit_triage_val[mask_b]))
for bits in range(1 << kit_weights_100g.size)
if np.sum(kit_weights_100g[mask_b := np.array([(bits >> b) & 1 for b in range(kit_weights_100g.size)], dtype=bool)]) <= 45
)
return {
"held_karp_10_exact_km": float(hk_exact),
"sa_10_km": sa_sub["best_length"],
"sa_rel_gap": abs(sa_sub["best_length"] - hk_exact) / hk_exact,
"knapsack_dp_matches_bruteforce": bool(np.isclose(knap_med["max_value"], bf_best_val, atol=1e-12)),
"mental_moves_catalog_count": len(constants_benchmarks.MENTAL_MOVES_DB),
}
cert_10 = verify_end_to_end_mission_invariants(priority_xy[:10])
print(f"10-Target Sub-Mission: Held-Karp Exact Optimum = {cert_10['held_karp_10_exact_km']:.6f} km | SA = {cert_10['sa_10_km']:.6f} km (gap = {100*cert_10['sa_rel_gap']:.4f}%)")
print(f"Knapsack DP == 2^8 Brute Force: {cert_10['knapsack_dp_matches_bruteforce']} | Total Mental Moves Cataloged = {cert_10['mental_moves_catalog_count']}")
assert cert_10["sa_rel_gap"] < 1e-9
assert cert_10["knapsack_dp_matches_bruteforce"] and cert_10["mental_moves_catalog_count"] == 24
Inside the algorithm: Topographic benchmark and end-to-end mission invariant certifier
======================================================================================
def make_topographic_terrain(nx: int = 64, ny: int = 64, seed: int = 42) -> dict:
"""Generate a smooth 2-D mountain/pass elevation field [m] and traversal cost grid for Dijkstra vs. A*."""
if nx < 8 or ny < 8:
raise ValueError("Require nx, ny >= 8.")
rng = np.random.default_rng(seed)
x = np.linspace(0.0, 1.0, nx)
y = np.linspace(0.0, 1.0, ny)
xx, yy = np.meshgrid(x, y, indexing="xy")
# Multi-ridge mountain barrier with two saddle passes + gentle background roughness:
pass_cut = 1.0 - 0.62 * np.exp(-((yy - 0.74) / 0.11) ** 2)
ridge1 = 920.0 * np.exp(-(((xx - 0.48) + 0.22 * (yy - 0.5)) / 0.11) ** 2) * pass_cut
ridge2 = 680.0 * np.exp(-(((xx - 0.72) ** 2 + (yy - 0.30) ** 2) / 0.032))
basin = 240.0 * np.exp(-(((xx - 0.24) ** 2 + (yy - 0.68) ** 2) / 0.045))
ripples = 35.0 * np.sin(4.0 * math.pi * xx + float(rng.uniform(0.0, 1.0))) * np.cos(3.0 * math.pi * yy)
elev = 150.0 + ridge1 + ridge2 + basin + ripples
# Strictly positive cell traversal cost >= 1.0 (base 1.0 + steep elevation penalty):
cost_grid = 1.0 + 9.5 * ((elev - np.min(elev)) / (np.max(elev) - np.min(elev))) ** 2
return {"x": x, "y": y, "elevation_m": elev, "cost_grid": cost_grid}
10-Target Sub-Mission: Held-Karp Exact Optimum = 264.414042 km | SA = 264.414042 km (gap = 0.0000%)
Knapsack DP == 2^8 Brute Force: True | Total Mental Moves Cataloged = 24
Exercises¶
Worked solutions are in 17_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Implement
held_karp_exact_tsp(dist_matrix)in NumPy solving the exact asymmetric/symmetric Travelling Salesperson Problem on priority relief sites ( table entries) with exact backpointer tour reconstruction. Benchmarkemergence_verification.simulated_annealing_tspagainstheld_karp_exact_tsp, proving SA achieves< 0.5%optimality gap while comparing state counts against brute-force tours.Find how it fails. Perform a Mission-Wide Failure Audit quantifying two dangerous shortcuts: (a) Compare a naive flat-earth straight-line flight path from
(10, 10)to(52, 52)onmake_topographic_terrain(64, 64, seed=42)(assuming constant base cell cost1.0, budgeting the flat cost for battery capacity) against the actual cumulative terrain-climb energy burned flying that straight ridge-crossing line vs. the elevation-aware A* saddle-pass detour. (b) Sweep LoRa communication range across the 60-station basin to expose the sharp continuum percolation blackout below the critical range (at ).Implement it yourself. Implement
plan_battery_constrained_multi_drone_sorties(dist_matrix, depot_idx, max_range_km)in NumPy solving multi-sortie capacitated relief routing across a 16-site network (1 Command Depot + 15 survivor sites, or general -nodedist_matrix). First order the non-depot sites using a 2-opt Simulated Annealing giant tour, then apply Beasley’s (1983) Shortest-Path DAG Split DP: construct an auxiliary -node DAG where directed edge () represents feasible sortiedepot -> seq[i] -> ... -> seq[j-1] -> depotiff its total distance , and find the exact minimum-total-distance partition. Verify 100% customer coverage, strict battery feasibility on every sortie, and exact optimality of the DAG Split step against exhaustive cut enumeration.
heading("Self-check for the exercises")
assert pi_drone["n_pi_groups"] == 2 and np.isclose(max_safe_range_km(f_star), target_range_km, atol=1e-3), "Phase 1 sizing check failed"
assert bf_sos["false_negatives"] == 0 and cell_links["pairs"] == exact_links, "Phase 2 mesh/Bloom check failed"
assert np.isclose(astar_corridor["total_cost"], dijk_corridor["total_cost"], rtol=1e-12), "Phase 3 A* optimality check failed"
assert cert_10["sa_rel_gap"] < 1e-9 and cert_10["knapsack_dp_matches_bruteforce"], "Phase 4/Inside certification failed"
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.