Worked solutions to the three exercises of Lecture 6. 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: Exponential call trees against polynomial DAG tabulation")
mm15 = [m for m in constants_benchmarks.MENTAL_MOVES_DB if m["id"] == 15][0]
print(f"Mental Move #{mm15['id']} ({mm15['name']}): {mm15['invariant']}")
def count_naive_alignment_calls(m: int, n: int) -> int:
"""Actual recursive tree walk for small (m, n) to verify Equation (1.1) directly."""
if m == 0 or n == 0:
return 1
return (
1
+ count_naive_alignment_calls(m - 1, n)
+ count_naive_alignment_calls(m, n - 1)
+ count_naive_alignment_calls(m - 1, n - 1)
)
# Compute exact call-tree size C(n, n) up to n = 14 via the recurrence, and verify against actual recursion for n <= 8:
n_max = 14
call_dp = np.ones((n_max + 1, n_max + 1), dtype=np.int64)
for i in range(1, n_max + 1):
for j in range(1, n_max + 1):
call_dp[i, j] = 1 + call_dp[i - 1, j] + call_dp[i, j - 1] + call_dp[i - 1, j - 1]
for n_chk in range(1, 9):
assert count_naive_alignment_calls(n_chk, n_chk) == int(call_dp[n_chk, n_chk])
n_vals = np.arange(1, n_max + 1)
naive_diag = np.array([call_dp[k, k] for k in n_vals], dtype=float)
dag_states = (n_vals + 1.0) ** 2
assert call_dp[14, 14] > 10_000_000_000 # about 1.19e10 calls at N = 14
assert int(dag_states[-1]) == 225 # vs. just 225 unique DAG cells
print(f"{'Length N':>8s} | {'Naive Tree Calls C(N,N)':>24s} | {'DAG States (N+1)^2':>19s} | {'Redundancy Ratio':>18s}")
print("-" * 78)
for k in [2, 4, 6, 8, 10, 12, 14]:
c_val = int(call_dp[k, k])
s_val = (k + 1) ** 2
print(f"{k:8d} | {c_val:24,d} | {s_val:19d} | {c_val / s_val:17.1f}x")
fig, ax = plt.subplots(figsize=(7.4, 4.1))
ax.semilogy(n_vals, naive_diag, marker="o", lw=2.3, color="#C0392B", label=r"Naive recursive tree calls $C(N, N) \sim 5.83^N$")
ax.semilogy(n_vals, dag_states, marker="s", lw=2.3, color="#2166AC", label=r"Memoized / tabulated DAG states $(N + 1)^2$")
ax.set_xlabel(r"Sequence length $N$")
ax.set_ylabel("Subproblem evaluations (log scale)")
ax.set_title("Recursive calls against distinct states")
ax.legend(fontsize=8.8)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify across a 10-sequence noisy DNA/telemetry corpus that dynamic_optimality.edit_distance_dp obeys the metric axioms (non-negativity, identity , symmetry , and the triangle inequality across all ordered triples—and confirm exact Needleman–Wunsch scaling .
heading("Exercise 1: Metric-space axioms of edit distance and Needleman-Wunsch score duality")
corpus = [
"",
"A",
"ACGTACGT",
"ACGTCGT",
"ACGGACGT",
"TACGTACG",
"ACGTACGA",
"TTCGATCG",
"GCGTACGT",
"ACGT_CGT",
]
n_seq = len(corpus)
dist_mat = np.zeros((n_seq, n_seq), dtype=int)
for i in range(n_seq):
for j in range(n_seq):
dist_mat[i, j] = dynamic_optimality.edit_distance_dp(corpus[i], corpus[j])
# 1. Identity of indiscernibles & strict positivity off-diagonal:
assert np.all(np.diag(dist_mat) == 0)
for i in range(n_seq):
for j in range(n_seq):
if i != j:
assert corpus[i] != corpus[j] and dist_mat[i, j] > 0
# 2. Exact symmetry d(x, y) == d(y, x):
assert np.array_equal(dist_mat, dist_mat.T)
# 3. Triangle inequality d(x, z) <= d(x, y) + d(y, z) across all 10^3 = 1,000 triples:
slacks_tri = []
for i in range(n_seq):
for j in range(n_seq):
for k in range(n_seq):
slack = int(dist_mat[i, j] + dist_mat[j, k] - dist_mat[i, k])
assert slack >= 0, f"Triangle inequality violated at ({i}, {j}, {k})"
slacks_tri.append(slack)
# 4. Needleman-Wunsch (0, -alpha, -alpha) scaling duality:
for alpha in [0.5, 1.0, 3.7]:
for i in range(5):
for j in range(5):
nw = dynamic_optimality.sequence_alignment_dp(
corpus[i], corpus[j], match_score=0.0, mismatch_penalty=-alpha, gap_penalty=-alpha
)
assert np.isclose(nw["score"], -alpha * dist_mat[i, j], atol=1e-12)
print(f"Verified all 4 metric axioms on {n_seq}x{n_seq} pairwise matrix and {len(slacks_tri)} ordered triples")
print(f"Minimum triangle slack min(d(x,y) + d(y,z) - d(x,z)) = {min(slacks_tri)} (tight equality achieved)")
fig, ax = plt.subplots(figsize=(6.8, 4.3))
im = ax.imshow(dist_mat, cmap="Blues")
ax.set_xticks(range(n_seq))
ax.set_yticks(range(n_seq))
ax.set_xlabel("Sequence index $j$")
ax.set_ylabel("Sequence index $i$")
ax.set_title("Edit distances $d(s_i, s_j)$")
ax.grid(False)
fig.colorbar(im, ax=ax, label="Edit distance [edits]")
plt.show()
Exercise 1: Metric-space axioms of edit distance and Needleman-Wunsch score duality
===================================================================================
Verified all 4 metric axioms on 10x10 pairwise matrix and 1000 ordered triples
Minimum triangle slack min(d(x,y) + d(y,z) - d(x,z)) = 0 (tight equality achieved)

Figure S6.1. Edit distances between the ten sequences of the corpus. The matrix is symmetric with a zero diagonal.
Explanation. Every valid edit script transforming ( operations) followed by an edit script transforming ( operations) composes into a valid transformation of length ; since is the minimum over all valid scripts , holds universally whenever single-character insertion and deletion costs are equal (guaranteeing symmetry as well).
Exercise 2¶
Problem. Verify all ValueError input guards on knapsack_01_dp and seam_carving_min_energy, then demonstrate quantitatively (a) why sweeping capacity forward in 1-D Knapsack DP corrupts 0/1 uniqueness into Unbounded Knapsack item cloning, and (b) why greedy local top-to-bottom seam stepping gets trapped by downstream barriers that global DP easily routes around.
heading("Exercise 2: Failure-mode audit — forward-sweep knapsack cloning and greedy seam trapping")
# 0. Input guard checks:
caught_guards = 0
for fn, bad_args in [
(dynamic_optimality.knapsack_01_dp, (np.array([0, 2]), np.array([5.0, 6.0]), 5)),
(dynamic_optimality.knapsack_01_dp, (np.array([2, 3]), np.array([5.0]), 5)),
(dynamic_optimality.knapsack_01_dp, (np.array([2, 3]), np.array([5.0, 6.0]), -1)),
(dynamic_optimality.seam_carving_min_energy, (np.ones((1, 5)),)),
(dynamic_optimality.seam_carving_min_energy, (np.array([[1.0, -0.5], [2.0, 1.0]]),)),
]:
try:
fn(*bad_args)
except ValueError:
caught_guards += 1
assert caught_guards == 5
# (a) 1-D Knapsack sweep-direction bug:
w_test = np.array([3, 4, 5], dtype=int)
v_test = np.array([16.0, 15.0, 18.0], dtype=float) # Item 0 has high density 16/3 = 5.33
cap_t = 10
def knapsack_1d_backward_correct(w: np.ndarray, v: np.ndarray, cap: int) -> float:
dp = np.zeros(cap + 1, dtype=float)
for wi, vi in zip(w, v):
for c in range(cap, int(wi) - 1, -1): # Reads strictly from previous iteration i-1
dp[c] = max(dp[c], dp[c - int(wi)] + float(vi))
return float(dp[cap])
def knapsack_1d_forward_buggy(w: np.ndarray, v: np.ndarray, cap: int) -> float:
dp = np.zeros(cap + 1, dtype=float)
for wi, vi in zip(w, v):
for c in range(int(wi), cap + 1): # BUG: reads already-updated dp[c - wi] in same row i
dp[c] = max(dp[c], dp[c - int(wi)] + float(vi))
return float(dp[cap])
v_ref = dynamic_optimality.knapsack_01_dp(w_test, v_test, cap_t)["max_value"]
v_bwd = knapsack_1d_backward_correct(w_test, v_test, cap_t)
v_fwd_bug = knapsack_1d_forward_buggy(w_test, v_test, cap_t)
assert np.isclose(v_bwd, v_ref, atol=1e-12) and np.isclose(v_ref, 34.0, atol=1e-12) # w=3+5 -> 16+18 = 34
assert np.isclose(v_fwd_bug, 48.0, atol=1e-12) # Cloned unique item 0 (w=3, v=16) THREE times: 3*16 = 48
# (b) Greedy myopic seam vs. global Avidan-Shamir DP on a bait-and-barrier energy landscape:
e_trap = np.full((12, 12), 2.0)
e_trap[0, 2] = 0.05 # Low-energy bait at top column c=2
e_trap[1:6, 2] = 0.10 # Low-energy funnel leading down column 2...
e_trap[7, 0:6] = 250.0 # ...straight into an inescapable wide high-energy wall
e_trap[:, 9] = 0.40 # Safe low-energy corridor on the right (column 9)
def greedy_top_down_seam(e_map: np.ndarray) -> tuple[np.ndarray, float]:
h, w = e_map.shape
cols = np.zeros(h, dtype=int)
cols[0] = int(np.argmin(e_map[0, :]))
for r in range(1, h):
c_lo, c_hi = max(0, cols[r - 1] - 1), min(w - 1, cols[r - 1] + 1)
cols[r] = c_lo + int(np.argmin(e_map[r, c_lo : c_hi + 1]))
return cols, float(np.sum(e_map[np.arange(h), cols]))
g_cols, g_energy = greedy_top_down_seam(e_trap)
dp_trap = dynamic_optimality.seam_carving_min_energy(e_trap)
assert g_energy > 250.0
assert np.isclose(dp_trap["min_total_energy"], 12 * 0.40, atol=1e-12)
print(f"Knapsack 1-D audit : True 0/1 = {v_ref:.1f} (backward = {v_bwd:.1f}) vs. Forward-sweep bug = {v_fwd_bug:.1f} (cloned item 3x)")
print(f"Seam Carving audit : Global DP energy = {dp_trap['min_total_energy']:.2f} vs. Greedy top-down trap = {g_energy:.2f} ({g_energy / dp_trap['min_total_energy']:.1f}x worse)")
Exercise 2: Failure-mode audit — forward-sweep knapsack cloning and greedy seam trapping
========================================================================================
Knapsack 1-D audit : True 0/1 = 34.0 (backward = 34.0) vs. Forward-sweep bug = 48.0 (cloned item 3x)
Seam Carving audit : Global DP energy = 4.80 vs. Greedy top-down trap = 260.55 (54.3x worse)
Explanation. (a) In 1-D Knapsack, dp[c - w_i] must hold from the previous item row. Sweeping c upward overwrites dp[3] = 16, then uses that updated dp[3] at c = 6 (dp[6] = 32) and c = 9 (dp[9] = 48), turning 0/1 into Unbounded Knapsack. (b) Because an 8-connected seam can drift laterally by at most column per row, entering the left bait at (0, 2) leaves the greedy walker trapped inside columns 0..5 when row 7’s 250.0 barrier arrives—whereas global DP integrates future row costs before committing at row 0.
Exercise 3¶
Problem. Implement remove_k_vertical_seams(image_2d, k_seams) using centered finite-difference gradient energy and dynamic_optimality.seam_carving_min_energy at each step. On a two-plume scalar field with k_seams = 16, verify exact output shape (36, 48), exact preservation of both plume maxima, and better preservation of high-intensity plume mass than right-side cropping.
heading("Exercise 3: Implement it yourself — iterative multi-seam scientific field retargeting")
def compute_grad_energy(field: np.ndarray) -> np.ndarray:
"""Compute non-negative L1 finite-difference gradient energy |df/dx| + |df/dy|."""
gx = np.zeros_like(field, dtype=float)
gy = np.zeros_like(field, dtype=float)
gx[:, 1:-1] = 0.5 * (field[:, 2:] - field[:, :-2])
gx[:, 0] = field[:, 1] - field[:, 0]
gx[:, -1] = field[:, -1] - field[:, -2]
gy[1:-1, :] = 0.5 * (field[2:, :] - field[:-2, :])
gy[0, :] = field[1, :] - field[0, :]
gy[-1, :] = field[-1, :] - field[-2, :]
return np.abs(gx) + np.abs(gy)
def remove_k_vertical_seams(image_2d: np.ndarray, k_seams: int) -> dict:
"""Iteratively carve k_seams minimum-energy 8-connected vertical seams from a 2-D array."""
cur = np.asarray(image_2d, dtype=float).copy()
h, w = cur.shape
if k_seams < 0 or k_seams >= w - 1:
raise ValueError("Require 0 <= k_seams <= width - 2.")
energies = []
for _ in range(k_seams):
e_map = compute_grad_energy(cur)
sol = dynamic_optimality.seam_carving_min_energy(e_map)
seam = sol["seam_cols"]
energies.append(sol["min_total_energy"])
# Remove exactly 1 column per row using a boolean mask:
keep_mask = np.ones_like(cur, dtype=bool)
keep_mask[np.arange(h), seam] = False
cur = cur[keep_mask].reshape(h, cur.shape[1] - 1)
return {"retargeted": cur, "seam_energies": np.array(energies, dtype=float)}
h0, w0, k_rem = 36, 64, 16
yy, xx = np.meshgrid(np.linspace(0.0, 1.0, h0), np.linspace(0.0, 1.0, w0), indexing="ij")
twin_plumes = (
2.0 * np.exp(-((xx - 0.24) ** 2 + (yy - 0.45) ** 2) / 0.006)
+ 1.8 * np.exp(-((xx - 0.80) ** 2 + (yy - 0.55) ** 2) / 0.006)
)
res_carve = remove_k_vertical_seams(twin_plumes, k_seams=k_rem)
carved_img = res_carve["retargeted"]
cropped_img = twin_plumes[:, : w0 - k_rem] # Naive right-border crop slices right through plume #2
assert carved_img.shape == (h0, w0 - k_rem)
# Both peak maxima (2.0 on left half, 1.8 on right half) survive intact in carved_img:
peak_orig_left = float(np.max(twin_plumes[:, : w0 // 2]))
peak_orig_right = float(np.max(twin_plumes[:, w0 // 2 :]))
peak_carv_left = float(np.max(carved_img[:, : (w0 - k_rem) // 2]))
peak_carv_right = float(np.max(carved_img[:, (w0 - k_rem) // 2 :]))
assert np.isclose(peak_carv_left, peak_orig_left, atol=1e-12)
assert np.isclose(peak_carv_right, peak_orig_right, atol=1e-12)
# High-concentration plume mass (phi > 0.25) preserved to >99.5% by seam carving vs. lost by cropping:
high_orig = float(np.sum(twin_plumes[twin_plumes > 0.25]))
loss_carve = abs(high_orig - float(np.sum(carved_img[carved_img > 0.25]))) / high_orig
loss_crop = abs(high_orig - float(np.sum(cropped_img[cropped_img > 0.25]))) / high_orig
assert loss_carve < 0.01 and loss_crop > 0.30
print(f"Original shape {twin_plumes.shape} -> Carved shape {carved_img.shape}")
print(f"Left/Right plume peaks : Original ({peak_orig_left:.3f}, {peak_orig_right:.3f}) -> Carved ({peak_carv_left:.3f}, {peak_carv_right:.3f})")
print(f"Plume core mass loss : Seam Carving = {100.0 * loss_carve:.3f}% vs. Naive Border Crop = {100.0 * loss_crop:.1f}%")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.0, 3.8))
ax1.imshow(twin_plumes, cmap="inferno", aspect="auto", vmin=0.0, vmax=2.0)
ax1.set_title(f"Original twin-plume field ({h0}x{w0})")
ax1.set_xlabel("Column $c$")
ax1.set_ylabel("Row $r$")
ax1.grid(False)
ax2.imshow(carved_img, cmap="inferno", aspect="auto", vmin=0.0, vmax=2.0)
ax2.set_title(f"Seam-carved field ({h0}x{w0 - k_rem}, both peaks intact)")
ax2.set_xlabel("Column $c$")
ax2.set_ylabel("Row $r$")
ax2.grid(False)
label_panels(fig)
plt.show()
Exercise 3: Implement it yourself — iterative multi-seam scientific field retargeting
=====================================================================================
Original shape (36, 64) -> Carved shape (36, 48)
Left/Right plume peaks : Original (1.982, 1.773) -> Carved (1.982, 1.773)
Plume core mass loss : Seam Carving = 0.000% vs. Naive Border Crop = 38.8%

Figure S6.2. Seam carving of a synthetic two-plume field. (a) The original 36 × 64 field. (b) The field after removing 16 seams, 36 × 48, with both plumes intact.
Summary. Recomputing the gradient energy field after each vertical seam removal prevents multiple seams from collapsing onto neighboring high-gradient shoulders, so the 16 seams remove 25 % of the width from the calm background: the plume core loses 0.000 % of its mass, against 38.8 % for cropping the right-hand border.