Suppose one of 16 isolation valves in a high-pressure chemical manifold is leaking, and historical maintenance logs show a strongly skewed failure distribution (synthetic here) where the top three high-cycling valves cause of the leaks and the cryogenic bypass valves rarely fail. If an operator tests valves sequentially down the pipe rack (), isolating a fault wastes up to 15 pressure-decay tests and hours of plant downtime; even halving by valve index always takes 4 tests, also for the most likely culprits. Shannon’s (1948) information theory shows that every diagnostic measurement is a question whose value equals the expected drop in uncertainty, and that no binary test tree can isolate the leaking valve in fewer than expected checks (Mental Move #21: Choose the Measurement That Maximizes Entropy Drop). In this lecture, you will compute self-information surprise and Shannon entropy (information_streams.shannon_entropy_metrics), detect subtle sensor distribution drift via asymmetric Kullback-Leibler divergence , synthesize minimum-test fault-isolation trees (information_streams.optimal_fault_diagnosis_tree), and quantify how noisy sensors reduce conditional entropy .
Learning objectives¶
Quantify event surprise and distribution uncertainty (
information_streams.shannon_entropy_metrics), explaining why rare anomalies carry high information bits while skewed priors lower minimum diagnostic cost below .Use Kullback-Leibler divergence to detect sensor drift and prove both Gibbs’ inequality () and directional asymmetry .
Construct greedy mutual-information fault-isolation trees (
information_streams.optimal_fault_diagnosis_tree), benchmark them against sequential linear scans and exact subset Dynamic Programming, and verify Shannon’s coding bound .Analyze noisy diagnostic channels via joint/conditional entropy and implement active Bayesian sensor polling that maximizes expected posterior entropy drop at every step.
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. Self-Information Surprise () & Shannon’s Entropy ¶
Why is a routine "Reactor pressure normal" log line () almost worthless to transmit, whereas "Relief valve V14 ruptured" () triggers immediate plant action? Shannon formalized the self-information (surprise) of outcome by requiring three axioms: (1) certainty carries zero surprise (), (2) rarer events carry strictly more surprise, and (3) independent events add their surprises: . Up to choice of logarithm base, the unique continuous solution is:
Taking the expectation over a discrete distribution defines Shannon Entropy:
with convention . The ratio measures informational efficiency (information_streams.shannon_entropy_metrics): only when all states are equiprobable (), whereas skewed engineering priors have —meaning smart coding or adaptive testing can beat naive halving.
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()
Demonstration 1: Event surprise (-log2 p) and skewed against uniform 16-valve entropy
=====================================================================================
Uniform 16-valve prior : H = 4.0000 bits (max = 4.00, eff = 100.0%)
Skewed 16-valve prior : H = 3.0047 bits (max = 4.00, eff = 75.1%)
Routine valve V0 (p=0.280) surprise = 1.84 bits vs. rare V15 (p=0.005) = 7.64 bits

Figure 12.1. Information content of the synthetic valve prior. (a) Failure probability (bars) and self-information (line); the entropy is 3.00 bits against 4.00 for a uniform prior. (b) Binary entropy , largest for a 50/50 split.
What Demonstration 1 shows.
On the left, rare valve () carries of surprise when it fails, yet contributes only to the entropy . Because the top three valves hold of the failure probability, bisecting without using spends 4 tests where allows about 3, a redundancy of .
On the right, the concave binary entropy curve peaks uniquely at (): a binary check whose
"YES"probability is yields only on average, so it would take about 12 such checks to gain what one balanced check gives.
2. Kullback-Leibler Divergence & Asymmetry in Drift Detection¶
Suppose an online acoustic monitor models healthy bearing vibrations with baseline histogram , while the live window exhibits empirical distribution . If we encode or diagnose live events using a code/tree optimized for stale model (whose ideal surprise lengths are ), our expected code length inflates from to the cross-entropy . The excess bit penalty is Kullback-Leibler (KL) Divergence:
By Jensen’s inequality (), with equality if and only if (Gibbs’ inequality). Note that is not a symmetric metric:
Forward becomes large whenever a new tail anomaly appears where and (zero-avoiding / tail-sensitive alarm).
Reverse weights discrepancies by , downplaying tiny emergent tail spikes where .
heading("Demonstration 2: KL divergence sensor-drift detection and directional asymmetry D_KL(p||q) != D_KL(q||p)")
x_bins = np.linspace(-3.5, 4.5, 24)
# Healthy baseline sensor histogram q (centered at 0, narrow Gaussian):
q_base = np.exp(-0.5 * (x_bins / 0.85) ** 2)
q_base /= np.sum(q_base)
# Emergent incipient cavitation fault p_fault: 88% healthy + 12% high-frequency tail spike near x = +3.2
tail_spike = np.exp(-0.5 * ((x_bins - 3.2) / 0.45) ** 2)
tail_spike /= np.sum(tail_spike)
p_fault = 0.88 * q_base + 0.12 * tail_spike
fwd_kl = information_streams.shannon_entropy_metrics(p_fault, q_base)["kl_divergence_bits"]
rev_kl = information_streams.shannon_entropy_metrics(q_base, p_fault)["kl_divergence_bits"]
self_kl = information_streams.shannon_entropy_metrics(q_base, q_base)["kl_divergence_bits"]
print(f"Zero-drift sanity check D_KL(q || q) = {self_kl:.3e} bits")
print(f"Forward D_KL(p_live || q_healthy) [tail alarm] = {fwd_kl:.4f} bits")
print(f"Reverse D_KL(q_healthy || p_live) = {rev_kl:.4f} bits (asymmetry ratio = {fwd_kl/rev_kl:.2f}x)")
assert abs(self_kl) < 1e-14
assert fwd_kl > 2.2 * rev_kl > 0.0
# Sweep mean drift delta in [-1.8, +2.4] comparing forward and reverse KL:
shifts = np.linspace(-1.8, 2.4, 85)
kl_pq_curve, kl_qp_curve = [], []
for d_mu in shifts:
p_s = 0.90 * np.exp(-0.5 * ((x_bins - d_mu) / 0.85) ** 2) + 0.10 * np.exp(-0.5 * ((x_bins - 1.4 * d_mu) / 1.15) ** 2)
p_s /= np.sum(p_s)
kl_pq_curve.append(information_streams.shannon_entropy_metrics(p_s, q_base)["kl_divergence_bits"])
kl_qp_curve.append(information_streams.shannon_entropy_metrics(q_base, p_s)["kl_divergence_bits"])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
ax1.plot(x_bins, q_base, "b-o", ms=4, lw=2.0, label="Healthy reference $q(x)$")
ax1.plot(x_bins, p_fault, "r-s", ms=4, lw=2.0, label="Incipient cavitation $p_{\\mathrm{live}}(x)$")
ax1.fill_between(x_bins, q_base, p_fault, color="#C0392B", alpha=0.18, label=f"$D_{{\\mathrm{{KL}}}}(p||q) = {fwd_kl:.2f}$ bits")
ax1.set_xlabel("Normalized vibration amplitude bin $x$")
ax1.set_ylabel("Bin probability")
ax1.set_title("A tail anomaly raises the forward KL divergence")
ax1.legend(fontsize=8.2)
ax2.plot(shifts, kl_pq_curve, "r-", lw=2.2, label="Forward $D_{\\mathrm{KL}}(p_{\\delta} || q)$")
ax2.plot(shifts, kl_qp_curve, "b--", lw=2.0, label="Reverse $D_{\\mathrm{KL}}(q || p_{\\delta})$")
ax2.axhline(0.15, color="k", ls=":", lw=1.3, label="Alarm threshold ($0.15$ bits)")
ax2.set_xlabel("Sensor mean drift $\\delta$")
ax2.set_ylabel("KL divergence [bits]")
ax2.set_title("Forward and reverse KL divergence")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
Demonstration 2: KL divergence sensor-drift detection and directional asymmetry D_KL(p||q) != D_KL(q||p)
========================================================================================================
Zero-drift sanity check D_KL(q || q) = 0.000e+00 bits
Forward D_KL(p_live || q_healthy) [tail alarm] = 0.7679 bits
Reverse D_KL(q_healthy || p_live) = 0.1696 bits (asymmetry ratio = 4.53x)

Figure 12.2. Drift detection with the KL divergence. (a) Healthy histogram and a live histogram with 12 % of the probability moved into a synthetic tail near . (b) Forward and reverse divergence for a shifted Gaussian; both are zero only when the distributions coincide, and they differ elsewhere.
What Demonstration 2 shows. Although only of the probability moves into the synthetic cavitation tail near , the forward divergence is 4.5 times the reverse divergence because magnifies new failure modes occurring in previously quiet spectral bins.
3. Optimal Binary Fault-Isolation Trees (optimal_fault_diagnosis_tree)¶
Returning to our 16-valve chemical manifold with skewed failure prior , suppose our piping header instrumentation provides binary pressure-hold tests encoded as a binary matrix , where if fault triggers test and 0 otherwise. How should an automated diagnostic engine choose which test to run next?
Given surviving candidate set with conditional weight , running test partitions into and with conditional split fraction . Because outcome is deterministic given the true fault (), the mutual information gained by test is its binary split entropy:
Maximizing (information_streams.optimal_fault_diagnosis_tree) greedily selects the physically available manifold test closest to a probability split at every node.
heading("Demonstration 3: Greedy info-gain fault tree against index halving and sequential valve scans")
# Construct realistic manifold test bank: 16 individual valve tests + 4 binary bit-plane headers + 14 contiguous pipe-section block tests:
indiv_tests = np.eye(n_valves, dtype=int)
bit_headers = np.array([[(m >> b) & 1 for m in range(n_valves)] for b in range(4)], dtype=int)
prefix_blocks = np.array([[1 if m <= k else 0 for m in range(n_valves)] for k in range(n_valves - 2)], dtype=int)
manifold_tmat = np.vstack([indiv_tests, bit_headers, prefix_blocks])
tree_opt = information_streams.optimal_fault_diagnosis_tree(p_skewed, manifold_tmat)
tree_idx_halving = information_streams.optimal_fault_diagnosis_tree(p_skewed, bit_headers)
# Compare against (1) naive physical-order linear scan V0, V1, ..., V14 (15 tests suffice for 16 valves)
# and (2) probability-sorted linear scan (test highest-p valve one at a time):
p_unord = p_skewed[[7, 12, 0, 14, 3, 9, 1, 15, 5, 11, 2, 8, 4, 13, 6, 10]] # physical rack order
steps_seq = np.minimum(np.arange(1, n_valves + 1), n_valves - 1)
exp_naive_linear = float(np.sum(p_unord * steps_seq))
exp_prob_linear = float(np.sum(np.sort(p_skewed)[::-1] * steps_seq))
# Helper to measure leaf depth for every fault m in a diagnosis tree:
def get_tree_depths(node: dict, m_count: int) -> np.ndarray:
depths = np.zeros(m_count, dtype=int)
def _walk(sub: dict, d: int) -> None:
if "leaf_fault" in sub:
depths[sub["leaf_fault"]] = d
else:
_walk(sub["if_0"], d + 1)
_walk(sub["if_1"], d + 1)
_walk(node, 0)
return depths
depths_opt = get_tree_depths(tree_opt["tree"], n_valves)
h_lb = tree_opt["shannon_lower_bound_bits"]
print(f"Shannon Entropy Lower Bound H(p) = {h_lb:.4f} bits")
print(f"Info-Gain Manifold Tree E[tests] = {tree_opt['expected_tests']:.4f} tests (redundancy = {tree_opt['redundancy_bits']:.4f} bits)")
print(f"Probability-Sorted One-by-One Scan = {exp_prob_linear:.4f} tests")
print(f"Binary Index Halving (bit headers) = {tree_idx_halving['expected_tests']:.4f} tests")
print(f"Naive Rack-Order Linear Scan = {exp_naive_linear:.4f} tests")
assert h_lb <= tree_opt["expected_tests"] < h_lb + 0.25
assert tree_opt["expected_tests"] < tree_idx_halving["expected_tests"] < exp_naive_linear
assert np.isclose(float(np.sum(p_skewed * depths_opt)), tree_opt["expected_tests"], atol=1e-12)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
methods = ["Shannon $H(p)$\nlower bound", "Info-gain\ntree", "Index\nhalving", "Probability-\nsorted scan", "Linear\nscan"]
vals_m = [h_lb, tree_opt["expected_tests"], tree_idx_halving["expected_tests"], exp_prob_linear, exp_naive_linear]
cols_m = ["#2E8B57", "#2166AC", "#7B4FA3", "#E08214", "#C0392B"]
ax1.bar(methods, vals_m, color=cols_m, edgecolor="k", alpha=0.88)
ax1.set_ylabel("Expected pressure tests $\\mathbb{E}[L]$")
ax1.set_title("Expected tests to isolate leaking valve ($M = 16$)")
ax2.plot(idx_v, surprise_bits, "k--o", ms=4.5, lw=1.8, label="Ideal Shannon code length $-\\log_2 p_i$")
ax2.step(idx_v, depths_opt, where="mid", color="#2166AC", lw=2.3, label="Info-gain tree depth $d_i$ [integer tests]")
ax2.set_xlabel("Valve index $i$ (sorted from common $V_0$ to rare $V_{15}$)")
ax2.set_ylabel("Tests required $d_i$ [bits / checks]")
ax2.set_title("Tree depth against ideal code length")
ax2.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=8.3)
label_panels(fig)
plt.show()
Demonstration 3: Greedy info-gain fault tree against index halving and sequential valve scans
=============================================================================================
Shannon Entropy Lower Bound H(p) = 3.0047 bits
Info-Gain Manifold Tree E[tests] = 3.0350 tests (redundancy = 0.0303 bits)
Probability-Sorted One-by-One Scan = 3.5510 tests
Binary Index Halving (bit headers) = 4.0000 tests
Naive Rack-Order Linear Scan = 7.0580 tests

Figure 12.3. Fault isolation. (a) Expected number of tests for the five strategies, with the entropy as lower bound. (b) Depth of each valve in the information-gain tree (steps) against the ideal code length (dashed): common valves are found in 2 tests, rare ones in 7.
What Demonstration 3 shows. In the right-hand plot, optimal_fault_diagnosis_tree assigns 2 tests to the two most failure-prone valves () and 7 tests to the rarest valves (), following the ideal non-integer curve . The expected number of tests, 3.035, is 0.030 above Shannon’s lower bound , and 57 % below the rack-order linear scan (7.058 tests).
4. Noisy Sensor Channels & Conditional Entropy ¶
Real industrial sensors are rarely noise-free: an ultrasonic leak detector can suffer crossover error (missing a real leak or raising a false alarm with probability ). In Shannon’s Binary Symmetric Channel (BSC), a binary test with split probability produces noisy reading . How many bits of uncertainty about fault does one noisy reading actually remove?
Two consequences of Eq. (4.1):
At (
50% coin-flip sensor), , so —the sensor conveys zero bits regardless of how many times you poll it.At (wires soldered backwards), and recovers all of the noiseless information, because an inverted sensor is as informative as a correct one once its bit is flipped.
heading("Demonstration 4: Mutual information through a noisy sensor channel and repeated polling")
eps_grid = np.linspace(0.0, 1.0, 201)
def bsc_mutual_info(q_split: float, eps: float) -> float:
p_y1 = q_split * (1.0 - eps) + (1.0 - q_split) * eps
hy = information_streams.shannon_entropy_metrics([p_y1, 1.0 - p_y1])["entropy_bits"]
hy_given_x = information_streams.shannon_entropy_metrics([eps, 1.0 - eps])["entropy_bits"] if 0.0 < eps < 1.0 else 0.0
return max(0.0, hy - hy_given_x)
mi_q50 = np.array([bsc_mutual_info(0.50, float(ev)) for ev in eps_grid])
mi_q15 = np.array([bsc_mutual_info(0.15, float(ev)) for ev in eps_grid])
# Track posterior entropy H(X | Y_1..Y_k) across k repeated independent noisy binary header checks on 16 valves:
rng_ch = np.random.default_rng(1204)
true_v = 2
k_polls = 18
noise_levels = [0.05, 0.15, 0.30, 0.50]
post_ent_traces = {}
for eps_v in noise_levels:
post = p_skewed.copy()
trace = [information_streams.shannon_entropy_metrics(post)["entropy_bits"]]
for step in range(k_polls):
# Pick manifold test maximizing noisy mutual information on current posterior:
best_t, best_ig = 0, -1.0
for t_i in range(manifold_tmat.shape[0]):
q1 = float(np.sum(post[manifold_tmat[t_i] == 1]))
ig = bsc_mutual_info(q1, eps_v)
if ig > best_ig:
best_ig, best_t = ig, t_i
clean_bit = int(manifold_tmat[best_t, true_v])
obs_bit = clean_bit ^ int(rng_ch.random() < eps_v)
z_vec = manifold_tmat[best_t]
like = np.where(z_vec == obs_bit, 1.0 - eps_v, eps_v)
post = (post * like) / np.sum(post * like)
trace.append(information_streams.shannon_entropy_metrics(post)["entropy_bits"])
post_ent_traces[eps_v] = np.array(trace)
print(f"Channel capacity at eps=0.00: {mi_q50[0]:.3f} bit | eps=0.15: {bsc_mutual_info(0.5, 0.15):.3f} bit | eps=0.50: {mi_q50[100]:.3e} bit | eps=1.00: {mi_q50[-1]:.3f} bit")
print(f"Final posterior H after {k_polls} polls: eps=0.05 -> {post_ent_traces[0.05][-1]:.4f} bits, eps=0.50 -> {post_ent_traces[0.50][-1]:.4f} bits")
assert np.isclose(mi_q50[0], 1.0, atol=1e-12) and np.isclose(mi_q50[-1], 1.0, atol=1e-12)
assert mi_q50[100] < 1e-14
assert post_ent_traces[0.05][-1] < 1e-3 and np.isclose(post_ent_traces[0.50][-1], met_skw["entropy_bits"], atol=1e-12)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.1))
ax1.plot(eps_grid, mi_q50, "b-", lw=2.3, label="Balanced split $q = 0.50$ (BSC capacity)")
ax1.plot(eps_grid, mi_q15, "r--", lw=2.0, label="Unbalanced test $q = 0.15$")
ax1.axvline(0.5, color="k", ls=":", lw=1.3, label="Coin-flip sensor ($\\epsilon = 0.50 \\Rightarrow 0$ bits)")
ax1.set_xlabel("Sensor crossover error probability $\\epsilon$")
ax1.set_ylabel("Mutual information $I(X; Y)$ [bits/reading]")
ax1.set_title("Information of one noisy reading")
ax1.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=1, fontsize=8.1)
poll_x = np.arange(k_polls + 1)
for eps_v, sty in zip(noise_levels, ["g-o", "b-s", "m-^", "r--"]):
ax2.plot(poll_x, post_ent_traces[eps_v], sty, ms=3.8, lw=1.9, label=f"Noise $\\epsilon = {eps_v:.2f}$")
ax2.set_xlabel("Active noisy sensor polls $k$")
ax2.set_ylabel("Posterior fault entropy $H(X | Y_{1:k})$ [bits]")
ax2.set_title("Posterior entropy against polls")
ax2.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=8.3)
label_panels(fig)
plt.show()
Demonstration 4: Mutual information through a noisy sensor channel and repeated polling
=======================================================================================
Channel capacity at eps=0.00: 1.000 bit | eps=0.15: 0.390 bit | eps=0.50: 0.000e+00 bit | eps=1.00: 1.000 bit
Final posterior H after 18 polls: eps=0.05 -> 0.0000 bits, eps=0.50 -> 3.0047 bits

Figure 12.4. Noisy tests. (a) Mutual information of one reading against the crossover probability for a balanced and an unbalanced test; it vanishes at . (b) Posterior entropy against the number of polls for four noise levels; at it does not decrease.
Inside the algorithm¶
Look at information_streams.optimal_fault_diagnosis_tree: at each branch it greedily picks the single test maximizing immediate 1-step mutual information . Is 1-step greedy information gain always globally optimal when the physical test matrix is restricted to awkward pipe segments? Not necessarily—finding the guaranteed globally minimum-expected-cost decision tree is NP-hard for arbitrary test matrices. Below, we inspect both library functions and build an exact memoized Bellman Dynamic Programming solver exact_dp_fault_tree over bitmask subsets to check how close greedy Shannon info-gain comes to the exact global optimum.
Check against the library¶
heading("Inside the algorithm: Shannon metrics, greedy info-gain tree and exact bitmask DP benchmark")
print(show_source(information_streams.shannon_entropy_metrics))
print(show_source(information_streams.optimal_fault_diagnosis_tree))
def exact_dp_fault_tree(fault_probs: np.ndarray, test_matrix: np.ndarray) -> dict:
"""Solve the exact globally minimum-expected-tests binary decision tree via bitmask Bellman DP."""
p = np.asarray(fault_probs, dtype=float).ravel()
p = p / np.sum(p)
tmat = np.asarray(test_matrix, dtype=int)
m = p.size
memo: dict[int, tuple[float, int]] = {}
# Precompute bitmask of ones for each test row:
t_masks = [sum((1 << j) for j in range(m) if tmat[ti, j] == 1) for ti in range(tmat.shape[0])]
def _solve(mask: int) -> tuple[float, int]:
if mask & (mask - 1) == 0: # power of two -> single leaf fault
return 0.0, -1
if mask in memo:
return memo[mask]
w_sub = sum(float(p[j]) for j in range(m) if (mask >> j) & 1)
best_cost = math.inf
best_t = -1
for ti, tm in enumerate(t_masks):
m1 = mask & tm
m0 = mask & (~tm)
if m0 == 0 or m1 == 0:
continue
c0, _ = _solve(m0)
c1, _ = _solve(m1)
tot = w_sub + c0 + c1
if tot < best_cost - 1e-14:
best_cost = tot
best_t = ti
if best_t < 0:
raise ValueError("Indistinguishable subset in exact_dp_fault_tree.")
memo[mask] = (best_cost, best_t)
return best_cost, best_t
full_mask = (1 << m) - 1
opt_exp, root_t = _solve(full_mask)
return {"exact_expected_tests": opt_exp, "root_test": root_t, "subsets_memoized": len(memo)}
# Benchmark on a constrained 10-valve manifold with 18 arbitrary overlapping pipe-group tests:
rng_dp = np.random.default_rng(77)
p_10 = np.array([0.27, 0.21, 0.15, 0.11, 0.08, 0.06, 0.045, 0.035, 0.025, 0.015])
tmat_10 = np.vstack([np.eye(10, dtype=int), rng_dp.integers(0, 2, size=(8, 10))])
greedy_10 = information_streams.optimal_fault_diagnosis_tree(p_10, tmat_10)
exact_10 = exact_dp_fault_tree(p_10, tmat_10)
subopt_gap_pct = 100.0 * (greedy_10["expected_tests"] - exact_10["exact_expected_tests"]) / exact_10["exact_expected_tests"]
print(f"10-Valve Constrained Manifold: Shannon H(p) = {greedy_10['shannon_lower_bound_bits']:.4f} bits")
print(f" Exact Bellman Subset DP = {exact_10['exact_expected_tests']:.4f} tests ({exact_10['subsets_memoized']} subsets evaluated)")
print(f" Greedy Info-Gain Heuristic= {greedy_10['expected_tests']:.4f} tests (optimality gap = {subopt_gap_pct:.3f}%)")
assert greedy_10["shannon_lower_bound_bits"] <= exact_10["exact_expected_tests"] <= greedy_10["expected_tests"] + 1e-12
assert subopt_gap_pct < 3.0
Inside the algorithm: Shannon metrics, greedy info-gain tree and exact bitmask DP benchmark
===========================================================================================
def shannon_entropy_metrics(p: np.ndarray, q: np.ndarray | None = None) -> dict:
"""Evaluate Shannon entropy H(p) [bits], efficiency H/log2(K), and optional KL divergence D_KL(p || q) [bits]."""
p_arr = np.asarray(p, dtype=float).ravel()
if p_arr.size == 0 or np.any(p_arr < 0.0) or np.sum(p_arr) <= 0.0:
raise ValueError("Require non-empty non-negative probability vector p with positive sum.")
p_norm = p_arr / np.sum(p_arr)
nz = p_norm > 0.0
h_bits = -float(np.sum(p_norm[nz] * np.log2(p_norm[nz])))
h_max = math.log2(p_norm.size) if p_norm.size > 1 else 0.0
eff = (h_bits / h_max) if h_max > 0.0 else 1.0
kl_bits = None
cross_bits = None
if q is not None:
q_arr = np.asarray(q, dtype=float).ravel()
if q_arr.size != p_norm.size or np.any(q_arr < 0.0) or np.sum(q_arr) <= 0.0:
raise ValueError("q must match p length with non-negative entries and positive sum.")
q_norm = q_arr / np.sum(q_arr)
if np.any((p_norm > 0.0) & (q_norm <= 0.0)):
kl_bits = math.inf
cross_bits = math.inf
else:
cross_bits = -float(np.sum(p_norm[nz] * np.log2(q_norm[nz])))
kl_bits = max(0.0, cross_bits - h_bits)
return {
"entropy_bits": h_bits,
"max_entropy_bits": h_max,
"efficiency": eff,
"kl_divergence_bits": kl_bits,
"cross_entropy_bits": cross_bits,
}
def optimal_fault_diagnosis_tree(fault_probs: np.ndarray, test_matrix: np.ndarray) -> dict:
"""Build a binary fault-isolation tree by greedily selecting tests maximizing Shannon mutual information."""
probs = np.asarray(fault_probs, dtype=float).ravel()
tmat = np.asarray(test_matrix, dtype=int)
if probs.size < 2 or np.any(probs <= 0.0) or tmat.ndim != 2 or tmat.shape[1] != probs.size:
raise ValueError("Require strictly positive fault_probs (M >= 2) and binary test_matrix of shape (T, M).")
if np.any((tmat != 0) & (tmat != 1)):
raise ValueError("test_matrix entries must be binary (0 or 1).")
probs = probs / np.sum(probs)
h_lb = shannon_entropy_metrics(probs)["entropy_bits"]
def _build(candidates: list[int]) -> tuple[dict, float]:
# Returns (subtree_dict, expected_tests_weighted_by_subset_prob)
sub_p = probs[candidates]
tot_w = float(np.sum(sub_p))
if len(candidates) == 1:
return {"leaf_fault": candidates[0]}, 0.0
# Pick test row splitting candidates with probability closest to 50/50 (maximizes binary H(split)):
best_t = -1
best_gain = -1.0
best_zeros: list[int] = []
best_ones: list[int] = []
for t_idx in range(tmat.shape[0]):
zeros = [c for c in candidates if tmat[t_idx, c] == 0]
ones = [c for c in candidates if tmat[t_idx, c] == 1]
if not zeros or not ones:
continue
p1 = float(np.sum(probs[ones])) / tot_w
p0 = 1.0 - p1
gain = -(p0 * math.log2(p0) + p1 * math.log2(p1))
if gain > best_gain + 1e-14:
best_gain = gain
best_t = t_idx
best_zeros = zeros
best_ones = ones
if best_t < 0:
raise ValueError(f"Fault subset {candidates} is indistinguishable under the supplied test_matrix.")
tree_0, cost_0 = _build(best_zeros)
tree_1, cost_1 = _build(best_ones)
return {"test_index": best_t, "if_0": tree_0, "if_1": tree_1}, tot_w + cost_0 + cost_1
tree, exp_tests = _build(list(range(probs.size)))
return {
"expected_tests": float(exp_tests),
"shannon_lower_bound_bits": h_lb,
"redundancy_bits": float(exp_tests - h_lb),
"tree": tree,
}
10-Valve Constrained Manifold: Shannon H(p) = 2.8733 bits
Exact Bellman Subset DP = 2.8950 tests (1013 subsets evaluated)
Greedy Info-Gain Heuristic= 2.9000 tests (optimality gap = 0.173%)
Exercises¶
Worked solutions are in 12_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. 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).
Find how it fails. Audit two real-world failure modes in information-based diagnostics: (a) Show how unguarded
np.sum(-p * np.log2(p))returnsnanon sparse histograms andq_i = 0yieldsinfKL 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 why6 vs 6leaves states and cannot finish in 3 weighings, and build a complete verified 3-weighing solver starting with4 vs 4.Implement it yourself. Implement
bayesian_active_sensor_polling(prior_probs, sensor_tpr, sensor_fpr, true_fault, max_steps=12, seed=42)in NumPy. Support fault candidates wheresensor_tprandsensor_fprspecify 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("Self-check for the exercises")
assert np.isclose(met_uni["entropy_bits"], 4.0, atol=1e-12), "Uniform 16-valve entropy must equal 4.0 bits"
assert fwd_kl > 2.2 * rev_kl > 0.0, "KL divergence asymmetry check failed"
assert h_lb <= tree_opt["expected_tests"] < tree_idx_halving["expected_tests"] < exp_naive_linear, "Fault tree ordering failed"
assert exact_10["exact_expected_tests"] <= greedy_10["expected_tests"] + 1e-12, "Bellman DP lower bound failed"
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.