Skip to main content

lib_jsl_information/operators/
entropy.rs

1//! Entropy and related information measures (in bits).
2//!
3//! See the book entry [Entropy, divergence and mutual information](https://jwkunz.github.io/lib_jsl/book/information/entropy.html).
4
5/// The Shannon entropy of the byte distribution of `data`, in bits per byte (0 to 8).
6/// Empty input has zero entropy.
7pub fn entropy(data: &[u8]) -> f64 {
8    if data.is_empty() {
9        return 0.0;
10    }
11    // ANCHOR: entropy
12    let mut counts = [0u64; 256];
13    for &b in data {
14        counts[b as usize] += 1;
15    }
16    let n = data.len() as f64;
17    counts
18        .iter()
19        .filter(|&&c| c > 0)
20        .map(|&c| {
21            let p = c as f64 / n;
22            // Written as p log2(1/p), which is +0 (not -0) for p = 1.
23            p * (1.0 / p).log2()
24        })
25        .sum()
26    // ANCHOR_END: entropy
27}
28
29/// The Shannon entropy in bits of a probability distribution. Probabilities should sum to 1;
30/// zero entries contribute nothing. Returns `NaN` if any entry is negative or non-finite.
31pub fn entropy_from_probabilities(p: &[f64]) -> f64 {
32    if p.iter().any(|&x| !x.is_finite() || x < 0.0) {
33        return f64::NAN;
34    }
35    p.iter().filter(|&&x| x > 0.0).map(|&x| x * (1.0 / x).log2()).sum()
36}
37
38/// The cross entropy `-Σ p log2 q` in bits. Infinite if `q` is zero where `p` is positive.
39/// Returns `NaN` if the slices differ in length or contain negative values.
40pub fn cross_entropy(p: &[f64], q: &[f64]) -> f64 {
41    if p.len() != q.len() || p.iter().chain(q).any(|&x| !x.is_finite() || x < 0.0) {
42        return f64::NAN;
43    }
44    p.iter()
45        .zip(q)
46        .filter(|(pi, _)| **pi > 0.0)
47        .map(|(&pi, &qi)| if qi == 0.0 { f64::INFINITY } else { pi * (1.0 / qi).log2() })
48        .sum()
49}
50
51/// The Kullback-Leibler divergence `Σ p log2(p / q)` in bits.
52pub fn kl_divergence(p: &[f64], q: &[f64]) -> f64 {
53    cross_entropy(p, q) - entropy_from_probabilities(p)
54}
55
56/// The mutual information in bits of a joint distribution given as a row-major `rows x cols`
57/// probability table.
58pub fn mutual_information(joint: &[f64], rows: usize, cols: usize) -> f64 {
59    if rows * cols != joint.len() || joint.iter().any(|&x| !x.is_finite() || x < 0.0) {
60        return f64::NAN;
61    }
62    let mut pr = vec![0.0; rows];
63    let mut pc = vec![0.0; cols];
64    for r in 0..rows {
65        for c in 0..cols {
66            pr[r] += joint[r * cols + c];
67            pc[c] += joint[r * cols + c];
68        }
69    }
70    let mut mi = 0.0;
71    for r in 0..rows {
72        for c in 0..cols {
73            let p = joint[r * cols + c];
74            if p > 0.0 {
75                mi += p * (p / (pr[r] * pc[c])).log2();
76            }
77        }
78    }
79    mi
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn byte_entropy() {
88        assert_eq!(entropy(&[]), 0.0);
89        assert_eq!(entropy(&[7u8; 100]), 0.0);
90        assert!(entropy(&[7u8; 100]).is_sign_positive(), "zero, not negative zero");
91        assert!(entropy_from_probabilities(&[1.0]).is_sign_positive() && cross_entropy(&[1.0], &[1.0]).is_sign_positive());
92        assert!((entropy(&[0, 1]) - 1.0).abs() < 1e-15);
93        let all: Vec<u8> = (0..=255u8).collect();
94        assert!((entropy(&all) - 8.0).abs() < 1e-12);
95        // 3:1 split -> H(0.25) = 0.811278...
96        assert!((entropy(&[0, 0, 0, 1]) - 0.8112781244591328).abs() < 1e-14);
97    }
98
99    #[test]
100    fn distributions() {
101        assert!((entropy_from_probabilities(&[0.5, 0.5]) - 1.0).abs() < 1e-15);
102        assert!((entropy_from_probabilities(&[0.25; 4]) - 2.0).abs() < 1e-15);
103        assert_eq!(entropy_from_probabilities(&[1.0, 0.0]), 0.0);
104        assert!(entropy_from_probabilities(&[-0.1, 1.1]).is_nan());
105    }
106
107    #[test]
108    fn divergences_and_information() {
109        let p = [0.5, 0.5];
110        let q = [0.25, 0.75];
111        let kl = 0.5 * (0.5f64 / 0.25).log2() + 0.5 * (0.5f64 / 0.75).log2();
112        assert!((kl_divergence(&p, &q) - kl).abs() < 1e-14);
113        assert!(kl_divergence(&p, &p).abs() < 1e-15);
114        assert!(cross_entropy(&[1.0, 0.0], &[0.0, 1.0]).is_infinite());
115        // Independent variables carry no mutual information; identical ones carry H.
116        assert!(mutual_information(&[0.25, 0.25, 0.25, 0.25], 2, 2).abs() < 1e-15);
117        assert!((mutual_information(&[0.5, 0.0, 0.0, 0.5], 2, 2) - 1.0).abs() < 1e-15);
118    }
119}