Worked solutions to the three exercises of Lecture 12. 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: Event surprise (-log2 p) and skewed against uniform 16-valve entropy")
n_valves = 16
p_uniform = np.full(n_valves, 1.0 / n_valves)
# Skewed chemical-manifold leak prior (high-cycling control valves V0..V2 fail far more often than cryogenic bypasses):
raw_weights = np.array([0.28, 0.24, 0.16, 0.08, 0.05, 0.04, 0.03, 0.025,
0.02, 0.018, 0.015, 0.012, 0.010, 0.008, 0.007, 0.005])
p_skewed = raw_weights / np.sum(raw_weights)
surprise_bits = -np.log2(p_skewed)
met_uni = information_streams.shannon_entropy_metrics(p_uniform)
met_skw = information_streams.shannon_entropy_metrics(p_skewed)
print(f"Uniform 16-valve prior : H = {met_uni['entropy_bits']:.4f} bits (max = {met_uni['max_entropy_bits']:.2f}, eff = {100*met_uni['efficiency']:.1f}%)")
print(f"Skewed 16-valve prior : H = {met_skw['entropy_bits']:.4f} bits (max = {met_skw['max_entropy_bits']:.2f}, eff = {100*met_skw['efficiency']:.1f}%)")
print(f"Routine valve V0 (p={p_skewed[0]:.3f}) surprise = {surprise_bits[0]:.2f} bits vs. rare V15 (p={p_skewed[-1]:.3f}) = {surprise_bits[-1]:.2f} bits")
assert np.isclose(met_uni["entropy_bits"], 4.0, atol=1e-12) and np.isclose(met_uni["efficiency"], 1.0, atol=1e-12)
assert 2.0 < met_skw["entropy_bits"] < 3.2 and surprise_bits[-1] > 4.0 * surprise_bits[0]
# Binary entropy curve H_2(q) = -q log2(q) - (1-q) log2(1-q):
q_grid = np.linspace(1e-4, 1.0 - 1e-4, 200)
h2_curve = [information_streams.shannon_entropy_metrics([qv, 1.0 - qv])["entropy_bits"] for qv in q_grid]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
idx_v = np.arange(n_valves)
ax1_t = ax1.twinx()
ax1.bar(idx_v, p_skewed, color="#2166AC", edgecolor="k", alpha=0.82, label="Leak probability $p_i$")
ax1_t.plot(idx_v, surprise_bits, "r-o", lw=2.0, ms=4.5, label="Surprise $-\\log_2 p_i$ [bits]")
ax1_t.spines["top"].set_visible(False)
ax1.set_xlabel("Manifold valve index $i$")
ax1.set_ylabel("Failure probability $p_i$", color="#2166AC")
ax1_t.set_ylabel("Self-information $-\\log_2 p_i$ [bits]", color="#C0392B")
ax1.set_title(f"16-valve prior ($H(p) = {met_skw['entropy_bits']:.2f}$ bits; uniform: $4.00$ bits)")
ax2.plot(q_grid, h2_curve, "b-", lw=2.3, label="$H_2(q) = -q\\log_2 q - (1-q)\\log_2(1-q)$")
ax2.axvline(0.5, color="r", ls="--", lw=1.5, label="50/50 test split ($H_2(0.5) = 1.00$ bit)")
ax2.set_xlabel("Binary outcome probability $q$")
ax2.set_ylabel("Binary entropy $H_2(q)$ [bits]")
ax2.set_title("Binary entropy")
ax2.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=8.3)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify the Chain Rule of Shannon Entropy , symmetry , conditioning bound , and exact KL identity across a continuum of coupled fault-sensor joint distributions parameterized by coupling strength (where is independent and is a sharp diagnostic sensor channel).
heading("Exercise 1: Chain rule of entropy and mutual information KL identity on coupled joint tables")
rng_e1 = np.random.default_rng(1201)
px_base = np.array([0.30, 0.22, 0.16, 0.11, 0.08, 0.06, 0.04, 0.03])
py_indep = np.array([0.25, 0.20, 0.18, 0.15, 0.12, 0.10])
p_indep_joint = np.outer(px_base, py_indep)
# Structured sensor emission P(Y | X) where faults concentrate onto distinct sensor bins:
cond_sharp = np.zeros((8, 6), dtype=float)
for i in range(8):
cond_sharp[i, i % 6] = 0.82
cond_sharp[i, (i + 1) % 6] = 0.18
p_sharp_joint = px_base[:, None] * cond_sharp
lambdas = np.linspace(0.0, 1.0, 21)
hx_list, hx_given_y_list, mi_chain_list, mi_kl_list = [], [], [], []
for lam in lambdas:
p_xy = (1.0 - lam) * p_indep_joint + lam * p_sharp_joint
p_x = np.sum(p_xy, axis=1)
p_y = np.sum(p_xy, axis=0)
h_xy = information_streams.shannon_entropy_metrics(p_xy.ravel())["entropy_bits"]
h_x = information_streams.shannon_entropy_metrics(p_x)["entropy_bits"]
h_y = information_streams.shannon_entropy_metrics(p_y)["entropy_bits"]
# Conditional entropies H(Y|X) = sum_x p(x) H(Y | X=x) and H(X|Y) = sum_y p(y) H(X | Y=y):
h_y_given_x = sum(
float(p_x[i]) * information_streams.shannon_entropy_metrics(p_xy[i, :] / p_x[i])["entropy_bits"]
for i in range(p_x.size)
)
h_x_given_y = sum(
float(p_y[j]) * information_streams.shannon_entropy_metrics(p_xy[:, j] / p_y[j])["entropy_bits"]
for j in range(p_y.size)
)
mi_1 = h_x - h_x_given_y
mi_2 = h_y - h_y_given_x
mi_kl = information_streams.shannon_entropy_metrics(p_xy.ravel(), np.outer(p_x, p_y).ravel())["kl_divergence_bits"]
assert np.isclose(h_xy, h_x + h_y_given_x, atol=1e-13)
assert np.isclose(h_xy, h_y + h_x_given_y, atol=1e-13)
assert np.isclose(mi_1, mi_2, atol=1e-13) and np.isclose(mi_1, mi_kl, atol=1e-13)
assert -1e-14 <= mi_1 and h_x_given_y <= h_x + 1e-14
hx_list.append(h_x)
hx_given_y_list.append(h_x_given_y)
mi_chain_list.append(mi_1)
mi_kl_list.append(mi_kl)
assert abs(mi_chain_list[0]) < 1e-14 and mi_chain_list[-1] > 1.4
print(f"At lambda=0 (independent): H(X)={hx_list[0]:.4f}, H(X|Y)={hx_given_y_list[0]:.4f}, I(X;Y)={mi_chain_list[0]:.2e} bits")
print(f"At lambda=1 (coupled) : H(X)={hx_list[-1]:.4f}, H(X|Y)={hx_given_y_list[-1]:.4f}, I(X;Y)={mi_chain_list[-1]:.4f} bits")
print("Max discrepancy between Chain-Rule I(X;Y) and D_KL(P_XY || P_X x P_Y):",
f"{np.max(np.abs(np.array(mi_chain_list) - np.array(mi_kl_list))):.2e} bits")
fig, ax = plt.subplots(figsize=(7.4, 4.1))
ax.plot(lambdas, hx_list, "k--", lw=2.0, label="Prior fault entropy $H(X)$")
ax.plot(lambdas, hx_given_y_list, "b-o", ms=4, lw=2.1, label="Conditional entropy $H(X | Y)$")
ax.plot(lambdas, mi_chain_list, "r-s", ms=4, lw=2.1, label="Mutual information $I(X; Y) = H(X) - H(X | Y)$")
ax.fill_between(lambdas, hx_given_y_list, hx_list, color="#C0392B", alpha=0.14, label="Uncertainty removed by sensor $Y$")
ax.set_xlabel("Sensor-fault coupling strength $\\lambda$")
ax.set_ylabel("Information [bits]")
ax.set_title("Chain rule: $H(X) = H(X | Y) + I(X; Y)$")
ax.legend(fontsize=8.3)
plt.show()
Exercise 1: Chain rule of entropy and mutual information KL identity on coupled joint tables
============================================================================================
At lambda=0 (independent): H(X)=2.6475, H(X|Y)=2.6475, I(X;Y)=0.00e+00 bits
At lambda=1 (coupled) : H(X)=2.6475, H(X|Y)=0.9388, I(X;Y)=1.7087 bits
Max discrepancy between Chain-Rule I(X;Y) and D_KL(P_XY || P_X x P_Y): 8.88e-16 bits

Figure S12.1. Entropies of the coupled fault-sensor distribution against the coupling . stays constant; falls and rises, and their sum equals at every .
Explanation. Writing and averaging over shows that the mutual information is the KL divergence from the product of marginals to the true joint law . Because by Gibbs’ inequality, observing a noisy measurement can never increase expected posterior entropy (though a single surprising realization can temporarily raise when a previously unlikely fault suddenly becomes plausible).
Exercise 2¶
Problem. Audit two real-world failure modes in information-based diagnostics: (a) Show how unguarded np.sum(-p * np.log2(p)) returns nan on sparse histograms and q_i = 0 yields inf KL divergence unless Laplace-smoothed; (b) Model all 24 states (12 coins x {heavy, light}) of the 12-Coin Two-Pan Balance Riddle, compute first-step ternary information gain for weighing vs. coins (), prove why 6 vs 6 leaves states and cannot finish in 3 weighings, and build a complete verified 3-weighing solver starting with 4 vs 4.
heading("Exercise 2: Sparse NaN/Inf entropy traps and exact information audit of the 12-coin balance riddle")
# --- Part A: Sparse histogram NaN & Zero-Support Infinite KL ---
counts_ref = np.array([42, 30, 18, 10, 0, 0], dtype=float)
counts_live = np.array([38, 28, 19, 11, 3, 1], dtype=float)
p_sparse = counts_ref / np.sum(counts_ref)
with np.errstate(divide="ignore", invalid="ignore"):
naive_h = -float(np.sum(p_sparse * np.log2(p_sparse)))
safe_h = information_streams.shannon_entropy_metrics(p_sparse)["entropy_bits"]
raw_kl = information_streams.shannon_entropy_metrics(counts_live, counts_ref)["kl_divergence_bits"]
smooth_kl = information_streams.shannon_entropy_metrics(counts_live + 0.5, counts_ref + 0.5)["kl_divergence_bits"]
print(f"[Part A] Naive -sum(p*log2(p)) on sparse bins = {naive_h} vs. guarded shannon_entropy_metrics = {safe_h:.4f} bits")
print(f" Unsmoothed D_KL(live || ref_with_zeros) = {raw_kl} vs. Jeffreys/Laplace (+0.5) = {smooth_kl:.4f} bits")
assert math.isnan(naive_h) and math.isfinite(safe_h)
assert math.isinf(raw_kl) and 0.0 < smooth_kl < 1.0
# --- Part B: 12-Coin Counterfeit Balance Riddle (24 states: coin c in 0..11, delta in {-1 light, +1 heavy}) ---
states_24 = [(c, w) for c in range(12) for w in (-1, +1)] # 24 equiprobable states
def eval_pan_weighing(cand_states: list[tuple[int, int]], left_coins: tuple[int, ...], right_coins: tuple[int, ...]):
buckets: dict[int, list[tuple[int, int]]] = {-1: [], 0: [], +1: []} # -1: left light, 0: balanced, +1: left heavy
l_set, r_set = set(left_coins), set(right_coins)
for c, w in cand_states:
tilt = w if c in l_set else (-w if c in r_set else 0)
buckets[tilt].append((c, w))
counts = np.array([len(buckets[-1]), len(buckets[0]), len(buckets[+1])], dtype=float)
h_bits = information_streams.shannon_entropy_metrics(counts)["entropy_bits"]
return buckets, int(np.max(counts)), h_bits
k_vals = list(range(1, 7))
max_branch_sizes, info_gains = [], []
print("\n[Part B] 1st Weighing k vs k | Branch sizes (L<R, L=R, L>R) | Max Branch (<=9 needed) | Info Gain [bits]")
print("-" * 92)
for k in k_vals:
b_k, mx_k, h_k = eval_pan_weighing(states_24, tuple(range(k)), tuple(range(k, 2 * k)))
max_branch_sizes.append(mx_k)
info_gains.append(h_k)
verdict = "feasible (<= 3^2=9)" if mx_k <= 9 else "impossible (> 9)"
print(f" {k} vs {k} coins | ({len(b_k[-1]):2d}, {len(b_k[0]):2d}, {len(b_k[1]):2d}) | {mx_k:2d} -> {verdict:19s} | {h_k:.4f}")
assert max_branch_sizes[5] == 12 and max_branch_sizes[3] == 8 # 6v6 leaves 12 (>9); 4v4 leaves (8,8,8) (<=9)
assert info_gains[3] > info_gains[5] # 4v4 gives log2(3)=1.585 bits vs 6v6=1.000 bit
# Exact recursive minimax solver verifying 4 vs 4 isolates ALL 24 states in <= 3 weighings:
from itertools import combinations
def build_3_weighing_tree(cands: list[tuple[int, int]], rem_weighings: int):
if len(cands) <= 1:
return {"solved": cands[0] if cands else None}
if rem_weighings == 0 or len(cands) > 3 ** rem_weighings:
return None
cap_next = 3 ** (rem_weighings - 1)
max_pan = min(6, 12 // 2)
for k_pan in range(1, max_pan + 1):
# Symmetry-reduced search: fix left pan from combinations, right pan from remaining:
for left_p in combinations(range(12), k_pan):
rem_coins = [c for c in range(12) if c not in left_p]
for right_p in combinations(rem_coins, k_pan):
buckets, mx_b, _ = eval_pan_weighing(cands, left_p, right_p)
if mx_b <= cap_next:
subtrees = {}
ok = True
for tilt in (-1, 0, +1):
if buckets[tilt]:
st = build_3_weighing_tree(buckets[tilt], rem_weighings - 1)
if st is None:
ok = False
break
subtrees[tilt] = st
if ok:
return {"left": left_p, "right": right_p, "branches": subtrees}
if rem_weighings == 3 and k_pan == 4:
break # First (0,1,2,3) vs (4,5,6,7) already works if valid
return None
# Build starting explicitly from 4 vs 4: (0,1,2,3) vs (4,5,6,7):
b_root, mx_root, _ = eval_pan_weighing(states_24, (0, 1, 2, 3), (4, 5, 6, 7))
root_4v4 = {"left": (0, 1, 2, 3), "right": (4, 5, 6, 7),
"branches": {t: build_3_weighing_tree(b_root[t], 2) for t in (-1, 0, +1)}}
assert all(v is not None for v in root_4v4["branches"].values())
# Simulate all 24 true (coin, heavy/light) cases through root_4v4 and assert 100% exact identification in 3 steps
solved_depths = []
for true_state in states_24:
node = root_4v4
steps_used = 0
while "solved" not in node:
steps_used += 1
c, w = true_state
tilt = w if c in node["left"] else (-w if c in node["right"] else 0)
node = node["branches"][tilt]
assert node["solved"] == true_state and steps_used <= 3
solved_depths.append(steps_used)
print(f"Verified 4-vs-4 ternary decision tree: identified 24/24 states in max {max(solved_depths)} weighings")
fig, ax = plt.subplots(figsize=(7.4, 4.0))
ax.bar(np.array(k_vals) - 0.17, max_branch_sizes, width=0.34, color="#C0392B", edgecolor="k", label="Worst-case branch states")
ax.axhline(9.0, color="k", ls="--", lw=1.6, label="2-weighing Shannon capacity $3^2 = 9$ states")
ax_r = ax.twinx()
ax_r.plot(np.array(k_vals) + 0.17, info_gains, "b-s", lw=2.2, ms=6, label="1st-weighing entropy $H_3$ [bits]")
ax_r.spines["top"].set_visible(False)
ax.set_xticks(k_vals)
ax.set_xticklabels([f"{k} vs {k}" for k in k_vals])
ax.set_xlabel("First-weighing pan size ($k$ coins against $k$ coins)")
ax.set_ylabel("Worst-case surviving states", color="#C0392B")
ax_r.set_ylabel("Information gained [bits]", color="#2166AC")
ax.set_title("First weighing of the 12-coin puzzle")
plt.show()
Exercise 2: Sparse NaN/Inf entropy traps and exact information audit of the 12-coin balance riddle
==================================================================================================
[Part A] Naive -sum(p*log2(p)) on sparse bins = nan vs. guarded shannon_entropy_metrics = 1.8242 bits
Unsmoothed D_KL(live || ref_with_zeros) = inf vs. Jeffreys/Laplace (+0.5) = 0.0671 bits
[Part B] 1st Weighing k vs k | Branch sizes (L<R, L=R, L>R) | Max Branch (<=9 needed) | Info Gain [bits]
--------------------------------------------------------------------------------------------
1 vs 1 coins | ( 2, 20, 2) | 20 -> impossible (> 9) | 0.8167
2 vs 2 coins | ( 4, 16, 4) | 16 -> impossible (> 9) | 1.2516
3 vs 3 coins | ( 6, 12, 6) | 12 -> impossible (> 9) | 1.5000
4 vs 4 coins | ( 8, 8, 8) | 8 -> feasible (<= 3^2=9) | 1.5850
5 vs 5 coins | (10, 4, 10) | 10 -> impossible (> 9) | 1.4834
6 vs 6 coins | (12, 0, 12) | 12 -> impossible (> 9) | 1.0000
Verified 4-vs-4 ternary decision tree: identified 24/24 states in max 3 weighings

Figure S12.2. First weighing of the 12-coin puzzle. Bars: largest number of states left after weighing against coins; only 4 against 4 leaves no more than (dashed). Line: information gained, largest at 4 against 4, bits.
Explanation. Weighing 6 vs 6 puts every coin on the scale, guaranteeing the scale cannot balance (). Throwing away the 3rd ternary outcome collapses a ternary balance into a binary device, leaving states—strictly exceeding the state capacity of the remaining two weighings. Leaving 4 coins off the pans (4 vs 4) splits , extracting the full on Step 1 so every branch fits comfortably inside states.
Exercise 3¶
Problem. Implement bayesian_active_sensor_polling(prior_probs, sensor_tpr, sensor_fpr, true_fault, max_steps=12, seed=42) in NumPy. Support fault candidates where sensor_tpr and sensor_fpr specify noisy binary sensors (either 1-D arrays of length for per-valve point sensors or 2-D (T, M) sensitivity matrices). At each step , evaluate the exact expected posterior Shannon entropy for every sensor , poll the sensor maximizing expected entropy reduction, draw a noisy binary reading, and update the posterior via Bayes’ rule. Benchmark active polling vs. round-robin polling across 250 Monte Carlo episodes.
heading("Exercise 3: Implement it yourself — active Bayesian noisy sensor polling")
def bayesian_active_sensor_polling(
prior_probs: np.ndarray,
sensor_tpr: np.ndarray,
sensor_fpr: np.ndarray,
true_fault: int,
max_steps: int = 12,
seed: int = 42,
) -> dict:
"""Sequentially poll the noisy binary sensor maximizing expected posterior Shannon entropy drop."""
post = np.asarray(prior_probs, dtype=float).ravel().copy()
post /= np.sum(post)
m = post.size
tpr_arr = np.asarray(sensor_tpr, dtype=float)
fpr_arr = np.asarray(sensor_fpr, dtype=float)
# Build (T, M) likelihood matrix P(Y_s = 1 | fault = j):
if tpr_arr.ndim == 1:
assert tpr_arr.size == m and fpr_arr.size == m
p_y1_given_x = np.broadcast_to(fpr_arr[:, None], (m, m)).copy()
np.fill_diagonal(p_y1_given_x, tpr_arr)
else:
p_y1_given_x = tpr_arr.copy()
n_sensors = p_y1_given_x.shape[0]
rng = np.random.default_rng(seed)
def _entropy(q_vec: np.ndarray) -> float:
nz = q_vec > 0.0
return -float(np.sum(q_vec[nz] * np.log2(q_vec[nz])))
ent_hist = [_entropy(post)]
map_prob_hist = [float(np.max(post))]
chosen_sensors: list[int] = []
for _ in range(max_steps):
cur_h = _entropy(post)
best_s = 0
best_drop = -1.0
for s in range(n_sensors):
like1 = p_y1_given_x[s]
like0 = 1.0 - like1
py1 = float(np.dot(post, like1))
py0 = 1.0 - py1
exp_post_h = 0.0
if py1 > 1e-15:
exp_post_h += py1 * _entropy((post * like1) / py1)
if py0 > 1e-15:
exp_post_h += py0 * _entropy((post * like0) / py0)
drop = cur_h - exp_post_h
if drop > best_drop + 1e-15:
best_drop = drop
best_s = s
chosen_sensors.append(best_s)
obs = int(rng.random() < p_y1_given_x[best_s, int(true_fault)])
like_obs = p_y1_given_x[best_s] if obs == 1 else (1.0 - p_y1_given_x[best_s])
post = (post * like_obs) / float(np.dot(post, like_obs))
ent_hist.append(_entropy(post))
map_prob_hist.append(float(np.max(post)))
return {
"final_posterior": post,
"map_estimate": int(np.argmax(post)),
"true_fault_posterior": float(post[int(true_fault)]),
"entropy_history": np.array(ent_hist),
"max_prob_history": np.array(map_prob_hist),
"chosen_sensors": chosen_sensors,
}
# Benchmark on an 8-valve chemical skid with heterogeneous noisy point + header sensors:
prior_8 = np.array([0.32, 0.24, 0.15, 0.10, 0.07, 0.05, 0.04, 0.03])
# 8 point sensors + 3 manifold header sensors (high TPR=0.92, low FPR=0.06):
tpr_8 = np.array([0.88, 0.90, 0.86, 0.89, 0.85, 0.87, 0.91, 0.88])
fpr_8 = np.array([0.08, 0.07, 0.09, 0.08, 0.10, 0.09, 0.07, 0.08])
# Compare Active Entropy-Drop Polling vs. Round-Robin Sequential Polling over 250 Monte Carlo episodes:
rng_mc = np.random.default_rng(2026)
n_ep = 250
max_st = 12
active_ent_curves = np.zeros((n_ep, max_st + 1))
rr_ent_curves = np.zeros((n_ep, max_st + 1))
active_acc, rr_acc = 0, 0
for ep in range(n_ep):
tf = int(rng_mc.choice(8, p=prior_8))
res_act = bayesian_active_sensor_polling(prior_8, tpr_8, fpr_8, true_fault=tf, max_steps=max_st, seed=5000 + ep)
active_ent_curves[ep] = res_act["entropy_history"]
active_acc += int(res_act["map_estimate"] == tf)
# Round-robin baseline with identical noise seed family:
rng_rr = np.random.default_rng(5000 + ep)
post_rr = prior_8.copy()
rr_ent_curves[ep, 0] = information_streams.shannon_entropy_metrics(post_rr)["entropy_bits"]
for st in range(max_st):
s_rr = st % 8
p1_vec = np.full(8, fpr_8[s_rr])
p1_vec[s_rr] = tpr_8[s_rr]
obs_rr = int(rng_rr.random() < p1_vec[tf])
lk = p1_vec if obs_rr == 1 else (1.0 - p1_vec)
post_rr = (post_rr * lk) / float(np.dot(post_rr, lk))
rr_ent_curves[ep, st + 1] = information_streams.shannon_entropy_metrics(post_rr)["entropy_bits"]
rr_acc += int(int(np.argmax(post_rr)) == tf)
mean_act_h = np.mean(active_ent_curves, axis=0)
mean_rr_h = np.mean(rr_ent_curves, axis=0)
print(f"After 6 polls : Active mean H = {mean_act_h[6]:.3f} bits vs. Round-Robin = {mean_rr_h[6]:.3f} bits")
print(f"After 12 polls: Active MAP accuracy = {100*active_acc/n_ep:.1f}% (H={mean_act_h[-1]:.3f}) vs. Round-Robin = {100*rr_acc/n_ep:.1f}% (H={mean_rr_h[-1]:.3f})")
assert mean_act_h[6] < 0.75 * mean_rr_h[6] and mean_act_h[-1] < 0.60 * mean_rr_h[-1]
assert active_acc > rr_acc and active_acc / n_ep > 0.88
fig, ax = plt.subplots(figsize=(7.5, 4.1))
steps_ax = np.arange(max_st + 1)
ax.plot(steps_ax, mean_rr_h, "r--s", ms=4.5, lw=2.0, label=f"Round-robin polling (12-step acc = {100*rr_acc/n_ep:.1f}%)")
ax.plot(steps_ax, mean_act_h, "b-o", ms=4.5, lw=2.3, label=f"Active entropy-drop polling (12-step acc = {100*active_acc/n_ep:.1f}%)")
ax.set_xlabel("Noisy sensor polls executed $t$")
ax.set_ylabel("Mean posterior entropy $\\mathbb{E}[H(p_t)]$ [bits]")
ax.set_title("Active polling against round-robin polling")
ax.legend(fontsize=8.5)
plt.show()
Exercise 3: Implement it yourself — active Bayesian noisy sensor polling
========================================================================
After 6 polls : Active mean H = 0.738 bits vs. Round-Robin = 1.043 bits
After 12 polls: Active MAP accuracy = 92.8% (H=0.235) vs. Round-Robin = 88.0% (H=0.458)

Figure S12.3. Mean posterior entropy against the number of noisy polls for round-robin polling (dashed) and for choosing each poll by the expected entropy drop (solid).
Summary. Choosing each poll by the expected drop in posterior entropy both confirms and bisects: when two suspects have similar posterior probabilities, one noisy reading cannot separate them, and the rule polls the sensors that discriminate between them again. After 12 polls the mean posterior entropy is 0.235 bits against 0.458 bits for round-robin polling, and the most probable fault is the true one in 92.8 % of the runs against 88.0 %.