Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

12. Information: entropy, Kullback–Leibler divergence and fault diagnosis

School of Engineering, Nazarbayev University

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 68 %68\,\% of the leaks and the cryogenic bypass valves rarely fail. If an operator tests valves sequentially down the pipe rack (V0,V1,…,V15V_0, V_1, \dots, V_{15}), 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 H(p)=−∑ipilog⁡2piH(p) = -\sum_i p_i \log_2 p_i 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 DKL(p∥q)D_{\mathrm{KL}}(p \| q), synthesize minimum-test fault-isolation trees (information_streams.optimal_fault_diagnosis_tree), and quantify how noisy sensors reduce conditional entropy H(X∣Y)H(X \mid Y).

Learning objectives

  1. Quantify event surprise −log⁡2pi-\log_2 p_i and distribution uncertainty H(p)H(p) (information_streams.shannon_entropy_metrics), explaining why rare anomalies carry high information bits while skewed priors lower minimum diagnostic cost below log⁡2M\log_2 M.

  2. Use Kullback-Leibler divergence DKL(p∥q)D_{\mathrm{KL}}(p \| q) to detect sensor drift and prove both Gibbs’ inequality (DKL≥0D_{\mathrm{KL}} \ge 0) and directional asymmetry DKL(p∥q)≠DKL(q∥p)D_{\mathrm{KL}}(p \| q) \neq D_{\mathrm{KL}}(q \| p).

  3. 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 H(p)≤E[L]<H(p)+1H(p) \le \mathbb{E}[L] < H(p) + 1.

  4. Analyze noisy diagnostic channels via joint/conditional entropy H(X∣Y)H(X \mid Y) and implement active Bayesian sensor polling that maximizes expected posterior entropy drop at every step.

Time: about 60 min

1. Self-Information Surprise (−log⁡2pi-\log_2 p_i) & Shannon’s Entropy H(p)H(p)

Why is a routine "Reactor pressure normal" log line (p=0.999p = 0.999) almost worthless to transmit, whereas "Relief valve V14 ruptured" (p=10−4p = 10^{-4}) triggers immediate plant action? Shannon formalized the self-information (surprise) of outcome ii by requiring three axioms: (1) certainty carries zero surprise (I(1)=0I(1) = 0), (2) rarer events carry strictly more surprise, and (3) independent events add their surprises: I(pipj)=I(pi)+I(pj)I(p_i p_j) = I(p_i) + I(p_j). Up to choice of logarithm base, the unique continuous solution is:

I(pi)=−log⁡2pi[bits](1.1)I(p_i) = -\log_2 p_i \quad [\text{bits}] \tag{1.1}

Taking the expectation over a discrete distribution p=(p0,…,pM−1)p = (p_0, \dots, p_{M-1}) defines Shannon Entropy:

H(p)=E[I(pX)]=−∑i=0M−1pilog⁡2pi[bits],0≤H(p)≤log⁡2M(1.2)H(p) = \mathbb{E}[I(p_X)] = -\sum_{i=0}^{M-1} p_i \log_2 p_i \quad [\text{bits}], \qquad 0 \le H(p) \le \log_2 M \tag{1.2}

with convention 0log⁡20≡lim⁡u→0+ulog⁡2u=00 \log_2 0 \equiv \lim_{u \to 0^+} u \log_2 u = 0. The ratio η=H(p)/log⁡2M∈[0,1]\eta = H(p)/\log_2 M \in [0, 1] measures informational efficiency (information_streams.shannon_entropy_metrics): η=1\eta = 1 only when all MM states are equiprobable (pi=1/Mp_i = 1/M), whereas skewed engineering priors have η<1\eta < 1—meaning smart coding or adaptive testing can beat naive ⌈log⁡2M⌉\lceil \log_2 M \rceil halving.


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 size 1254x451 with 3 Axes>

Figure 12.1. Information content of the synthetic valve prior. (a) Failure probability pip_i (bars) and self-information −log⁡2pi-\log_2 p_i (line); the entropy is 3.00 bits against 4.00 for a uniform prior. (b) Binary entropy H2(q)H_2(q), largest for a 50/50 split.

What Demonstration 1 shows.

  1. On the left, rare valve V15V_{15} (p15=0.005p_{15} = 0.005) carries 7.64 bits7.64\ \mathrm{bits} of surprise when it fails, yet contributes only 0.005×7.64=0.038 bits0.005 \times 7.64 = 0.038\ \mathrm{bits} to the entropy H(p)=3.00 bitsH(p) = 3.00\ \mathrm{bits}. Because the top three valves hold 68 %68\,\% of the failure probability, bisecting 16→8→4→2→116 \to 8 \to 4 \to 2 \to 1 without using pip_i spends 4 tests where H(p)H(p) allows about 3, a redundancy of 1.00 bit1.00\ \mathrm{bit}.

  2. On the right, the concave binary entropy curve H2(q)H_2(q) peaks uniquely at q=0.5q = 0.5 (1.00 bit1.00\ \mathrm{bit}): a binary check whose "YES" probability is 99 %99\,\% yields only H2(0.01)=0.081 bitsH_2(0.01) = 0.081\ \mathrm{bits} on average, so it would take about 12 such checks to gain what one balanced 50/5050/50 check gives.


2. Kullback-Leibler Divergence DKL(p∥q)D_{\mathrm{KL}}(p \| q) & Asymmetry in Drift Detection

Suppose an online acoustic monitor models healthy bearing vibrations with baseline histogram qq, while the live window exhibits empirical distribution pp. If we encode or diagnose live events X∼pX \sim p using a code/tree optimized for stale model qq (whose ideal surprise lengths are −log⁡2qi-\log_2 q_i), our expected code length inflates from H(p)H(p) to the cross-entropy H(p,q)=−∑ipilog⁡2qiH(p, q) = -\sum_i p_i \log_2 q_i. The excess bit penalty is Kullback-Leibler (KL) Divergence:

DKL(p∥q)=H(p,q)−H(p)=∑i:pi>0pilog⁡2piqi≥0(2.1)D_{\mathrm{KL}}(p \| q) = H(p, q) - H(p) = \sum_{i : p_i > 0} p_i \log_2 \frac{p_i}{q_i} \ge 0 \tag{2.1}

By Jensen’s inequality (log⁡2u≤(u−1)/ln⁡2\log_2 u \le (u - 1)/\ln 2), DKL(p∥q)≥0D_{\mathrm{KL}}(p \| q) \ge 0 with equality if and only if p=qp = q (Gibbs’ inequality). Note that DKLD_{\mathrm{KL}} is not a symmetric metric:

  • Forward DKL(plive∥qmodel)D_{\mathrm{KL}}(p_{\mathrm{live}} \| q_{\mathrm{model}}) becomes large whenever a new tail anomaly appears where qi≈0q_i \approx 0 and pi>0p_i > 0 (zero-avoiding / tail-sensitive alarm).

  • Reverse DKL(qmodel∥plive)D_{\mathrm{KL}}(q_{\mathrm{model}} \| p_{\mathrm{live}}) weights discrepancies by qiq_i, downplaying tiny emergent tail spikes where qi≪1q_i \ll 1.


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 size 1254x451 with 2 Axes>

Figure 12.2. Drift detection with the KL divergence. (a) Healthy histogram qq and a live histogram pp with 12 % of the probability moved into a synthetic tail near x=3.2x = 3.2. (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 12 %12\,\% of the probability moves into the synthetic cavitation tail near x=+3.2x = +3.2, the forward divergence DKL(plive∥qhealthy)=0.768 bitsD_{\mathrm{KL}}(p_{\mathrm{live}} \| q_{\mathrm{healthy}}) = 0.768\ \mathrm{bits} is 4.5 times the reverse divergence DKL(qhealthy∥plive)=0.170 bitsD_{\mathrm{KL}}(q_{\mathrm{healthy}} \| p_{\mathrm{live}}) = 0.170\ \mathrm{bits} because log⁡2(pi/qi)\log_2(p_i / q_i) 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 pp, suppose our piping header instrumentation provides TT binary pressure-hold tests encoded as a (T×M)(T \times M) binary matrix A\mathbf{A}, where At,m=1A_{t, m} = 1 if fault mm triggers test tt and 0 otherwise. How should an automated diagnostic engine choose which test to run next?

Given surviving candidate set S⊆{0,…,M−1}S \subseteq \{0, \dots, M-1\} with conditional weight WS=∑m∈SpmW_S = \sum_{m \in S} p_m, running test tt partitions SS into S0(t)S_0(t) and S1(t)S_1(t) with conditional split fraction qt=1WS∑m∈S1(t)pmq_t = \frac{1}{W_S}\sum_{m \in S_1(t)} p_m. Because outcome Yt∈{0,1}Y_t \in \{0, 1\} is deterministic given the true fault X∈SX \in S (H(Yt∣X)=0H(Y_t \mid X) = 0), the mutual information gained by test tt is its binary split entropy:

I(X;Yt∣X∈S)=H(Yt∣X∈S)−H(Yt∣X)⏟0=H2(qt)=−qtlog⁡2qt−(1−qt)log⁡2(1−qt)(3.1)I(X; Y_t \mid X \in S) = H(Y_t \mid X \in S) - \underbrace{H(Y_t \mid X)}_{0} = H_2(q_t) = -q_t \log_2 q_t - (1 - q_t)\log_2(1 - q_t) \tag{3.1}

Maximizing H2(qt)H_2(q_t) (information_streams.optimal_fault_diagnosis_tree) greedily selects the physically available manifold test closest to a 50/5050/50 probability split at every node.


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 size 1254x451 with 2 Axes>

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 −log⁡2pi-\log_2 p_i (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 (V0,V1V_0, V_1) and 7 tests to the rarest valves (V12–V15V_{12}\text{–}V_{15}), following the ideal non-integer curve −log⁡2pi-\log_2 p_i. The expected number of tests, 3.035, is 0.030 above Shannon’s lower bound H(p)=3.005 bitsH(p) = 3.005\ \mathrm{bits}, and 57 % below the rack-order linear scan (7.058 tests).


4. Noisy Sensor Channels & Conditional Entropy H(X∣Y)H(X \mid Y)

Real industrial sensors are rarely noise-free: an ultrasonic leak detector can suffer crossover error ϵ∈[0,1]\epsilon \in [0, 1] (missing a real leak or raising a false alarm with probability ϵ\epsilon). In Shannon’s Binary Symmetric Channel (BSC), a binary test with split probability q=P(Z=1)q = \mathbb{P}(Z = 1) produces noisy reading Y=Z⊕Bernoulli(ϵ)Y = Z \oplus \mathrm{Bernoulli}(\epsilon). How many bits of uncertainty about fault XX does one noisy reading actually remove?

ΔH=I(X;Y)=H(Y)−H(Y∣X)=H2 ⁣(q(1−ϵ)+(1−q)ϵ)−H2(ϵ)(4.1)\Delta H = I(X; Y) = H(Y) - H(Y \mid X) = H_2\!\big(q(1 - \epsilon) + (1 - q)\epsilon\big) - H_2(\epsilon) \tag{4.1}

Two consequences of Eq. (4.1):

  1. At ϵ=0.5\epsilon = 0.5 (50% coin-flip sensor), H(Y∣X)=H2(0.5)=1 bit=H(Y)H(Y \mid X) = H_2(0.5) = 1\ \mathrm{bit} = H(Y), so I(X;Y)=0I(X; Y) = 0—the sensor conveys zero bits regardless of how many times you poll it.

  2. At ϵ=1.0\epsilon = 1.0 (wires soldered backwards), H2(1)=0H_2(1) = 0 and I(X;Y)=H2(q)I(X; Y) = H_2(q) recovers all of the noiseless information, because an inverted sensor is as informative as a correct one once its bit is flipped.


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 size 1254x451 with 2 Axes>

Figure 12.4. Noisy tests. (a) Mutual information of one reading against the crossover probability ϵ\epsilon for a balanced and an unbalanced test; it vanishes at ϵ=0.5\epsilon = 0.5. (b) Posterior entropy against the number of polls for four noise levels; at ϵ=0.5\epsilon = 0.5 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 H2(qt)H_2(q_t). Is 1-step greedy information gain always globally optimal when the physical test matrix A\mathbf{A} 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 S⊆{0,…,M−1}S \subseteq \{0, \dots, M-1\} to check how close greedy Shannon info-gain comes to the exact global optimum.

Check against the library


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.

  1. Verify a result. Verify the Chain Rule of Shannon Entropy H(X,Y)=H(X)+H(Y∣X)=H(Y)+H(X∣Y)H(X, Y) = H(X) + H(Y \mid X) = H(Y) + H(X \mid Y), symmetry I(X;Y)=I(Y;X)I(X; Y) = I(Y; X), conditioning bound 0≤H(X∣Y)≤H(X)0 \le H(X \mid Y) \le H(X), and exact KL identity I(X;Y)=DKL(PXY∥PX⊗PY)I(X; Y) = D_{\mathrm{KL}}(P_{XY} \| P_X \otimes P_Y) across a continuum of coupled (8×6)(8 \times 6) fault-sensor joint distributions parameterized by coupling strength λ∈[0,1]\lambda \in [0, 1] (where λ=0\lambda = 0 is independent PXPYTP_X P_Y^T and λ=1\lambda = 1 is a sharp diagnostic sensor channel).

  2. Find how it fails. 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 H3H_3 for weighing kk vs. kk coins (k∈{1..6}k \in \{1..6\}), prove why 6 vs 6 leaves 12>32=912 > 3^2 = 9 states and cannot finish in 3 weighings, and build a complete verified 3-weighing solver starting with 4 vs 4.

  3. Implement it yourself. Implement bayesian_active_sensor_polling(prior_probs, sensor_tpr, sensor_fpr, true_fault, max_steps=12, seed=42) in NumPy. Support MM fault candidates where sensor_tpr and sensor_fpr specify noisy binary sensors (either 1-D arrays of length MM for per-valve point sensors or 2-D (T, M) sensitivity matrices). At each step tt, evaluate the exact expected posterior Shannon entropy EYs[H(ppost(⋅∣Ys))]\mathbb{E}_{Y_s}[H(p_{\mathrm{post}}(\cdot \mid Y_s))] for every sensor ss, 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.


Self-check for the exercises
============================
All checks passed.