Worked solutions to the three exercises of Lecture 17. 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("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()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. 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. Benchmark emergence_verification.simulated_annealing_tsp against held_karp_exact_tsp, proving SA achieves < 0.5% optimality gap while comparing state counts against brute-force tours.
heading("Exercise 1: Exact Held-Karp bitmask DP TSP on 11 relief sites against simulated annealing")
def held_karp_exact_tsp(dist_matrix: np.ndarray) -> dict:
"""Exact O(N^2 * 2^(N-1)) Bellman-Held-Karp bitmask DP with optimal tour backpointer reconstruction."""
dmat = np.asarray(dist_matrix, dtype=float)
n = dmat.shape[0]
assert dmat.shape == (n, n) and n >= 3
n_sub = 1 << (n - 1) # bit (j - 1) encodes whether node j in {1..n-1} is visited
dp = np.full((n_sub, n), math.inf, dtype=float)
parent = np.full((n_sub, n), -1, dtype=int)
for j in range(1, n):
m_j = 1 << (j - 1)
dp[m_j, j] = dmat[0, j]
parent[m_j, j] = 0
transitions = 0
for mask in range(1, n_sub):
for j in range(1, n):
bit_j = 1 << (j - 1)
if not (mask & bit_j):
continue
prev_mask = mask ^ bit_j
if prev_mask == 0:
continue
for i in range(1, n):
if prev_mask & (1 << (i - 1)):
transitions += 1
cand = dp[prev_mask, i] + dmat[i, j]
if cand < dp[mask, j]:
dp[mask, j] = cand
parent[mask, j] = i
full_mask = n_sub - 1
best_len = math.inf
last_node = -1
for j in range(1, n):
tot = dp[full_mask, j] + dmat[j, 0]
if tot < best_len:
best_len = tot
last_node = j
# Reconstruct optimal closed tour [0, ..., last_node]:
tour = [0] * n
cur_m = full_mask
cur_u = last_node
for pos in range(n - 1, 0, -1):
tour[pos] = cur_u
prev_u = int(parent[cur_m, cur_u])
cur_m ^= 1 << (cur_u - 1)
cur_u = prev_u
return {
"optimal_tour": np.array(tour, dtype=int),
"optimal_length": float(best_len),
"dp_table_entries": int(n_sub * n),
"transitions_evaluated": transitions,
}
pts_11 = constants_benchmarks.make_sensor_station_coords(n_stations=60, seed=42)[:11]
dmat_11 = np.hypot(pts_11[:, None, 0] - pts_11[None, :, 0], pts_11[:, None, 1] - pts_11[None, :, 1])
hk_11 = held_karp_exact_tsp(dmat_11)
sa_11 = emergence_verification.simulated_annealing_tsp(pts_11, T_init=25.0, T_final=1e-3, n_steps=8000, seed=42)
# Verify reconstructed tour length equals optimal_length:
hk_t = hk_11["optimal_tour"]
re_len = sum(float(dmat_11[hk_t[k], hk_t[(k + 1) % 11]]) for k in range(11))
rel_gap_pct = 100.0 * (sa_11["best_length"] - hk_11["optimal_length"]) / hk_11["optimal_length"]
bf_tours_11 = math.factorial(10) // 2
print(f"11-Site Exact Held-Karp Optimum = {hk_11['optimal_length']:.6f} km (reconstructed check = {re_len:.6f} km)")
print(f"Simulated Annealing Tour Length = {sa_11['best_length']:.6f} km (optimality gap = {rel_gap_pct:.4f}% < 0.5%)")
print(f"Held-Karp DP table cells = {hk_11['dp_table_entries']:,} ({hk_11['transitions_evaluated']:,} transitions) vs. Brute-Force (10!/2) = {bf_tours_11:,} tours")
assert hk_11["dp_table_entries"] == 11 * (2 ** 10)
assert np.isclose(re_len, hk_11["optimal_length"], rtol=1e-13)
assert -1e-11 <= rel_gap_pct < 0.50
n_vals_comp = np.arange(5, 16)
bf_curve = [math.factorial(int(nv) - 1) // 2 for nv in n_vals_comp]
hk_curve = [int(nv) * (2 ** (int(nv) - 1)) for nv in n_vals_comp]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
cyc_hk = np.append(hk_t, hk_t[0])
ax1.plot(pts_11[cyc_hk, 0], pts_11[cyc_hk, 1], "g-o", ms=6.5, lw=2.4, label=f"Held-Karp global opt ({hk_11['optimal_length']:.2f} km)")
cyc_s11 = np.append(sa_11["best_tour"], sa_11["best_tour"][0])
ax1.plot(pts_11[cyc_s11, 0], pts_11[cyc_s11, 1], "b--", lw=1.5, label=f"SA 2-opt ({sa_11['best_length']:.2f} km)")
ax1.set_xlabel("East $x$ [km]"); ax1.set_ylabel("North $y$ [km]")
ax1.set_title("Exact and annealed tours, 11 sites")
ax1.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=8.2)
ax2.semilogy(n_vals_comp, bf_curve, "r-s", ms=5, lw=2.1, label="Brute-force $(N-1)!/2$")
ax2.semilogy(n_vals_comp, hk_curve, "b-o", ms=5, lw=2.2, label="Held-Karp DP $N \\cdot 2^{N-1}$")
ax2.axvline(11, color="k", ls=":", lw=1.4, label="$N = 11$ ($161\\times$ state savings)")
ax2.set_xlabel("Number of mission sites $N$")
ax2.set_ylabel("States / tours (log scale)")
ax2.set_title("Held-Karp states against brute-force tours")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
Exercise 1: Exact Held-Karp bitmask DP TSP on 11 relief sites against simulated annealing
=========================================================================================
11-Site Exact Held-Karp Optimum = 272.016203 km (reconstructed check = 272.016203 km)
Simulated Annealing Tour Length = 272.016203 km (optimality gap = 0.0000% < 0.5%)
Held-Karp DP table cells = 11,264 (23,040 transitions) vs. Brute-Force (10!/2) = 1,814,400 tours

Figure S17.1. Exact tour. (a) The Held–Karp tour through 11 sites (solid) and the annealed tour (dashed), both 272.02 km. (b) States of the Held–Karp table and brute-force tours against the number of sites.
Explanation. Why is Held–Karp so much cheaper than brute force? Regardless of which of the permutations visited subset before arriving at endpoint , the future cost to visit and return to 0 depends only on . Collapsing prefix permutations onto a single bitmask state reduces from tours down to states. The exact optimum then serves as a reference for heuristics such as simulated annealing, which here finds the optimal 11-site tour, 272.02 km.
Exercise 2¶
Problem. 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) on make_topographic_terrain(64, 64, seed=42) (assuming constant base cell cost 1.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 ).
heading("Exercise 2: Straight path across the ridge and relay network below its threshold")
# --- Part A: Flat-Earth Straight-Line Budget vs. True Ridge Energy & A* Pass Detour ---
terr_e2 = constants_benchmarks.make_topographic_terrain(64, 64, seed=42)
cg_e2 = terr_e2["cost_grid"]
s_pt, g_pt = (10, 10), (52, 52)
# Straight diagonal grid path (10,10) -> (11,11) -> ... -> (52,52) using allow_diagonal=True (step_len = sqrt(2)):
straight_cells = [(k, k) for k in range(10, 53)]
s2 = math.sqrt(2.0)
flat_assumed_cost = sum(s2 * 1.0 for _ in straight_cells[1:])
battery_budget = 1.75 * flat_assumed_cost # Naive planner adds 75% flat-earth margin (= 103.9 units)
true_straight_cum = np.cumsum([0.0] + [s2 * float(cg_e2[r, c]) for r, c in straight_cells[1:]])
true_straight_total = float(true_straight_cum[-1])
astar_pass = greedy_heuristic_search.grid_shortest_path_search(
cg_e2, s_pt, g_pt, method="astar", heuristic_weight=1.0, allow_diagonal=True
)
# Cumulative energy along A* saddle-pass path:
ap = astar_pass["path"]
astar_cum = [0.0]
for idx_s in range(1, len(ap)):
dr = abs(ap[idx_s][0] - ap[idx_s - 1][0])
dc = abs(ap[idx_s][1] - ap[idx_s - 1][1])
slen = s2 if (dr == 1 and dc == 1) else 1.0
astar_cum.append(astar_cum[-1] + slen * float(cg_e2[ap[idx_s][0], ap[idx_s][1]]))
crash_step = int(np.argmax(true_straight_cum > battery_budget))
print(f"[Part A] Flat-earth assumed cost = {flat_assumed_cost:.1f} (Battery budget w/ +75% reserve = {battery_budget:.1f})")
print(f" True straight-ridge energy = {true_straight_total:.1f} -> battery exhausted at step {crash_step}/{len(straight_cells)-1} mid-ridge")
print(f" Elevation-aware A* pass = {astar_pass['total_cost']:.1f} (arrives safely within {battery_budget:.1f} budget? {astar_pass['total_cost'] < battery_budget})")
assert true_straight_total > battery_budget > astar_pass["total_cost"]
assert astar_pass["total_cost"] < 0.74 * true_straight_total
# --- Part B: Continuum Radio-Relay Percolation Sweep r_comm in [8, 34] km ---
xy_60 = constants_benchmarks.make_sensor_station_coords(60, seed=42)
r_sweep_km = np.linspace(8.0, 34.0, 27)
depot_reach_pct, giant_comp_pct = [], []
for rc_v in r_sweep_km:
pairs = invariants_complexity.spatial_cell_list_neighbors(xy_60, float(rc_v))["pairs"]
par = list(range(60))
def _f(u: int) -> int:
while par[u] != u:
par[u] = par[par[u]]
u = par[u]
return u
for u, v in pairs:
ru, rv = _f(u), _f(v)
if ru != rv:
par[max(ru, rv)] = min(ru, rv)
roots = [_f(i) for i in range(60)]
_, cnts = np.unique(roots, return_counts=True)
depot_reach_pct.append(100.0 * sum(1 for r0 in roots if r0 == roots[0]) / 60.0)
giant_comp_pct.append(100.0 * int(np.max(cnts)) / 60.0)
idx_r11 = int(np.argmin(np.abs(r_sweep_km - 11.0)))
idx_r26 = int(np.argmin(np.abs(r_sweep_km - 26.0)))
dark_at_11 = 100.0 - depot_reach_pct[idx_r11]
print(f"[Part B] At subcritical r = 11 km: {dark_at_11:.1f}% of survivor beacons are unreachable (> 40%)")
print(f" At supercritical r = 26 km: {depot_reach_pct[idx_r26]:.1f}% of survivor beacons reach Command Depot")
assert dark_at_11 > 40.0 and depot_reach_pct[idx_r26] >= 95.0
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
ax1.plot(np.linspace(0, 100, len(true_straight_cum)), true_straight_cum, "r-", lw=2.3, label="Straight ridge-climb energy")
ax1.plot(np.linspace(0, 100, len(astar_cum)), astar_cum, "g-", lw=2.3, label="A* saddle-pass detour energy")
ax1.axhline(battery_budget, color="k", ls="--", lw=1.6, label=f"Battery pack cap ({battery_budget:.0f})")
ax1.set_xlabel("Mission progress $s \\to g$ [%]")
ax1.set_ylabel("Cumulative propulsion energy [cost units]")
ax1.set_title("The straight path exhausts the battery on the ridge")
ax1.legend(fontsize=8.0)
ax2.plot(r_sweep_km, depot_reach_pct, "b-o", ms=4.5, lw=2.2, label="Beacons reaching depot #0 [%]")
ax2.plot(r_sweep_km, giant_comp_pct, "m--", lw=1.8, label="Largest mesh cluster [%]")
ax2.axvline(11.0, color="r", ls=":", lw=1.6, label=f"$r=11$ km ({dark_at_11:.0f}% dark)")
ax2.set_xlabel("LoRa radio range $r_{\\mathrm{comm}}$ [km]")
ax2.set_ylabel("Connected survivor stations [%]")
ax2.set_title("Connected stations against radio range")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
Exercise 2: Straight path across the ridge and relay network below its threshold
================================================================================
[Part A] Flat-earth assumed cost = 59.4 (Battery budget w/ +75% reserve = 103.9)
True straight-ridge energy = 137.6 -> battery exhausted at step 24/42 mid-ridge
Elevation-aware A* pass = 98.5 (arrives safely within 103.9 budget? True)
[Part B] At subcritical r = 11 km: 96.7% of survivor beacons are unreachable (> 40%)
At supercritical r = 26 km: 100.0% of survivor beacons reach Command Depot

Figure S17.2. Two mission failures. (a) Cumulative energy along the straight path and along the A* detour against the battery capacity (dashed). (b) Fraction of stations connected to the depot against the radio range.
Explanation. Both failures come from replacing a nonlinear threshold by an average. (a) The cell cost rises quadratically with elevation, up to 10.5 times the valley cost at the top of the ridge, so the geometrically longer A* detour (98.5) is cheaper than the straight line (137.6), which exhausts the battery after 24 of 42 steps. (b) Reducing the radio range from 26 km to 11 km crosses the percolation threshold of the relay network: 96.7 % of the survivor beacons can no longer reach the depot.
Exercise 3¶
Problem. 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 -node dist_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 sortie depot -> seq[i] -> ... -> seq[j-1] -> depot iff 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("Exercise 3: Implement it yourself — Beasley's DAG split DP for battery-constrained multi-sortie routing")
def plan_battery_constrained_multi_drone_sorties(
dist_matrix: np.ndarray,
depot_idx: int = 0,
max_range_km: float = 195.0,
) -> dict:
"""Order-First Split-Second (Beasley 1983) multi-sortie planner under strict per-sortie battery range."""
dmat = np.asarray(dist_matrix, dtype=float)
n_tot = dmat.shape[0]
dep = int(depot_idx)
customers = [i for i in range(n_tot) if i != dep]
m_cust = len(customers)
# Step 1: 2-opt Simulated Annealing on the customer giant-tour sequence (using exact dmat):
rng = np.random.default_rng(1703)
seq = np.array(customers, dtype=int)
def _cyc_len(order: np.ndarray) -> float:
return sum(float(dmat[order[k], order[(k + 1) % m_cust]]) for k in range(m_cust))
cur_l = _cyc_len(seq)
best_seq = seq.copy()
best_l = cur_l
t_cur = 30.0
alpha = (1e-3 / 30.0) ** (1.0 / 5999.0)
for _ in range(6000):
i = int(rng.integers(0, m_cust - 1))
j = int(rng.integers(i + 1, m_cust))
if i == 0 and j == m_cust - 1:
continue
cand = seq.copy()
cand[i : j + 1] = cand[i : j + 1][::-1]
nl = _cyc_len(cand)
dl = nl - cur_l
if dl <= 0.0 or rng.random() < math.exp(-dl / t_cur):
seq = cand
cur_l = nl
if nl < best_l - 1e-12:
best_l = nl
best_seq = cand.copy()
t_cur *= alpha
# Try all m_cust cyclic rotations of best_seq and keep the globally shortest Beasley DAG split
best_overall_cost = math.inf
best_sorties: list[list[int]] = []
best_sortie_kms: list[float] = []
best_ordered_seq = best_seq.copy()
for shift in range(m_cust):
rot = np.roll(best_seq, -shift)
# Beasley Split DP on DAG vertices 0 .. m_cust:
dp = np.full(m_cust + 1, math.inf, dtype=float)
prev_cut = np.full(m_cust + 1, -1, dtype=int)
edge_len = np.full((m_cust, m_cust + 1), math.inf, dtype=float)
dp[0] = 0.0
for i in range(m_cust):
chain = 0.0
for j in range(i + 1, m_cust + 1):
if j == i + 1:
chain = float(dmat[dep, rot[i]])
else:
chain += float(dmat[rot[j - 2], rot[j - 1]])
round_trip = chain + float(dmat[rot[j - 1], dep])
if round_trip <= max_range_km + 1e-12:
edge_len[i, j] = round_trip
if dp[i] + round_trip < dp[j] - 1e-12:
dp[j] = dp[i] + round_trip
prev_cut[j] = i
else:
# Triangle inequality -> extending sortie further only increases round_trip if dmat metric,
# but evaluate full row cleanly in case of non-Euclidean terrain costs
pass
if dp[m_cust] < best_overall_cost - 1e-12:
best_overall_cost = float(dp[m_cust])
best_ordered_seq = rot.copy()
cuts: list[tuple[int, int]] = []
cur = m_cust
while cur > 0:
prv = int(prev_cut[cur])
if prv < 0:
break
cuts.append((prv, cur))
cur = prv
cuts.reverse()
best_sorties = [[dep] + rot[a:b].tolist() + [dep] for a, b in cuts]
best_sortie_kms = [float(edge_len[a, b]) for a, b in cuts]
if not math.isfinite(best_overall_cost):
raise ValueError("Infeasible max_range_km: at least one relief site exceeds 2 * dist(depot, site)")
return {
"sorties": best_sorties,
"sortie_lengths_km": best_sortie_kms,
"n_sorties": len(best_sorties),
"total_fleet_km": best_overall_cost,
"giant_seq": best_ordered_seq,
}
# Test on a 16-site mountain relief network (Depot #0 + 15 survivor beacons):
pts_16 = constants_benchmarks.make_sensor_station_coords(n_stations=16, seed=42)
dmat_16 = np.hypot(pts_16[:, None, 0] - pts_16[None, :, 0], pts_16[:, None, 1] - pts_16[None, :, 1])
max_rng_cap = 195.0
fleet_plan = plan_battery_constrained_multi_drone_sorties(dmat_16, depot_idx=0, max_range_km=max_rng_cap)
# 1. Verify every sortie starts/ends at depot, respects max_range_km, and visits all 15 survivor sites once
visited_cust = []
for srt, slen in zip(fleet_plan["sorties"], fleet_plan["sortie_lengths_km"]):
assert srt[0] == 0 and srt[-1] == 0
re_s = sum(float(dmat_16[srt[k], srt[k + 1]]) for k in range(len(srt) - 1))
assert np.isclose(slen, re_s, rtol=1e-12) and slen <= max_rng_cap + 1e-9
visited_cust.extend(srt[1:-1])
assert sorted(visited_cust) == list(range(1, 16))
# 2. Certify Beasley's O(M^2) DAG Split DP against exhaustive 2^14 = 16,384 cut bitmasks on giant_seq
g_seq = fleet_plan["giant_seq"]
m_c = g_seq.size # 15 -> 2^14 = 16,384 possible split subsets
brute_min_split = math.inf
for mask in range(1 << (m_c - 1)):
# Bit b == 1 means split right after g_seq[b]:
cuts_idx = [0] + [b + 1 for b in range(m_c - 1) if (mask >> b) & 1] + [m_c]
tot_c = 0.0
ok = True
for idx_c in range(len(cuts_idx) - 1):
sub = g_seq[cuts_idx[idx_c] : cuts_idx[idx_c + 1]]
rt = float(dmat_16[0, sub[0]]) + sum(float(dmat_16[sub[k], sub[k + 1]]) for k in range(len(sub) - 1)) + float(dmat_16[sub[-1], 0])
if rt > max_rng_cap + 1e-12:
ok = False
break
tot_c += rt
if ok and tot_c < brute_min_split:
brute_min_split = tot_c
print(f"16-Site Multi-Sortie Relief Plan (max battery range = {max_rng_cap:.0f} km):")
print(f" Number of sorties = {fleet_plan['n_sorties']} | Sortie lengths = {[round(x, 1) for x in fleet_plan['sortie_lengths_km']]} km")
print(f" Beasley DAG Split total = {fleet_plan['total_fleet_km']:.6f} km vs. 2^14 Exhaustive Cut Oracle = {brute_min_split:.6f} km")
assert np.isclose(fleet_plan["total_fleet_km"], brute_min_split, rtol=1e-12)
assert fleet_plan["n_sorties"] >= 2
fig, ax = plt.subplots(figsize=(7.6, 4.4))
palette = ["#2166AC", "#2E8B57", "#E08214", "#7B4FA3", "#C0392B"]
for idx_s, (srt, slen) in enumerate(zip(fleet_plan["sorties"], fleet_plan["sortie_lengths_km"]), start=1):
col = palette[(idx_s - 1) % len(palette)]
ax.plot(pts_16[srt, 0], pts_16[srt, 1], "-o", color=col, ms=6, lw=2.2, label=f"Sortie {idx_s}: {slen:.1f} / {max_rng_cap:.0f} km ({len(srt)-2} sites)")
ax.scatter([pts_16[0, 0]], [pts_16[0, 1]], c="#F2C744", edgecolors="k", marker="*", s=210, zorder=6, label="Charging depot #0")
ax.set_xlabel("East $x$ [km]"); ax.set_ylabel("North $y$ [km]")
ax.set_title("Four sorties from the depot (range 195 km)")
ax.legend(loc="center left", bbox_to_anchor=(1.01, 0.5), fontsize=8.1)
plt.show()
Exercise 3: Implement it yourself — Beasley's DAG split DP for battery-constrained multi-sortie routing
=======================================================================================================
16-Site Multi-Sortie Relief Plan (max battery range = 195 km):
Number of sorties = 4 | Sortie lengths = [135.4, 135.2, 192.3, 176.5] km
Beasley DAG Split total = 639.384683 km vs. 2^14 Exhaustive Cut Oracle = 639.384683 km

Figure S17.3. The four sorties of the split plan from the charging depot (star), each within the range of 195 km.
Summary. Beasley’s split reduces the NP-hard distance-constrained vehicle routing problem to two parts: a simulated annealing search for the order of the sites (Part V) and an exact shortest-path dynamic program on a DAG for the cuts (Parts III and IV). For this order, the split total, 639.38 km in 4 sorties, agrees to 10-12 with exhaustive search over all 214 ways of cutting the tour (Mental Move #24). The optimality holds for the given order only; the order itself comes from a heuristic.