Skip to main content

decision_cert/
monitor.rs

1//! Monitoring without labels against a v1.2 certificate's stored confidence histogram
2//! (spec/decision-certificate.v1.2.md §4). The Python verifier's `decision_cert._monitor` is a port
3//! with the same arithmetic in the same order.
4
5use crate::Histogram;
6
7/// Pearson's chi-square test of homogeneity between the stored histogram and a window's.
8#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct ShiftScore {
10    pub statistic: f64,
11    pub df: u64,
12    pub p_value: f64,
13}
14
15impl Histogram {
16    /// The histogram of `confidences` on `bins`. Pass None for a case the rule abstains on whatever
17    /// the threshold (unscored, or above `rule.cannot_tell_above`), as the issuer counts it. None when a confidence is
18    /// outside [0, 1] or `bins` has fewer than two edges.
19    pub fn of(bins: &[f64], confidences: impl IntoIterator<Item = Option<f64>>) -> Option<Self> {
20        let mut counts = vec![0u64; bins.len().checked_sub(1).filter(|&k| k > 0)?];
21        let mut unscored = 0u64;
22        for c in confidences {
23            match c {
24                None => unscored += 1,
25                Some(c) => counts[bin_of(bins, c)?] += 1,
26            }
27        }
28        Some(Self { counts, unscored })
29    }
30
31    /// The cases it counts: the bins and the unscored.
32    pub fn total(&self) -> u64 {
33        self.counts
34            .iter()
35            .fold(self.unscored, |t, &c| t.saturating_add(c))
36    }
37}
38
39/// The bin of `confidence`: `i` with `bins[i] <= confidence < bins[i + 1]`; the last bin also holds
40/// 1. None for a confidence outside [0, 1] (or NaN), or fewer than two edges.
41pub fn bin_of(bins: &[f64], confidence: f64) -> Option<usize> {
42    if !(0.0..=1.0).contains(&confidence) || bins.len() < 2 {
43        return None;
44    }
45    let i = bins.partition_point(|&e| e <= confidence);
46    Some(i.saturating_sub(1).min(bins.len() - 2))
47}
48
49/// Compare a window's histogram with the certificate's (spec §4). The columns are the bins and the
50/// unscored count; columns empty in both are dropped. With an empty side or one column left there
51/// is nothing to compare: statistic 0, df 0, p-value 1. None when the bin counts differ.
52pub fn shift_score(baseline: &Histogram, window: &Histogram) -> Option<ShiftScore> {
53    if baseline.counts.len() != window.counts.len() {
54        return None;
55    }
56    let row = |h: &Histogram| {
57        let mut r = h.counts.clone();
58        r.push(h.unscored);
59        r
60    };
61    let (r1, r2) = (row(baseline), row(window));
62    let n1 = r1.iter().map(|&x| x as f64).sum::<f64>();
63    let n2 = r2.iter().map(|&x| x as f64).sum::<f64>();
64    let kept: Vec<(u64, u64)> = r1
65        .into_iter()
66        .zip(r2)
67        .filter(|&(a, b)| a > 0 || b > 0)
68        .collect();
69    if n1 == 0.0 || n2 == 0.0 || kept.len() < 2 {
70        return Some(ShiftScore {
71            statistic: 0.0,
72            df: 0,
73            p_value: 1.0,
74        });
75    }
76    let n = n1 + n2;
77    let mut stat = 0.0;
78    for &(a, b) in &kept {
79        let col = a as f64 + b as f64;
80        let (e1, e2) = (n1 * col / n, n2 * col / n);
81        stat += (a as f64 - e1).powi(2) / e1;
82        stat += (b as f64 - e2).powi(2) / e2;
83    }
84    let df = kept.len() as u64 - 1;
85    Some(ShiftScore {
86        statistic: stat,
87        df,
88        p_value: chi2_sf(stat, df),
89    })
90}
91
92const LANCZOS_G: f64 = 7.0;
93const LANCZOS: [f64; 9] = [
94    0.999_999_999_999_809_9,
95    676.520_368_121_885_1,
96    -1_259.139_216_722_402_8,
97    771.323_428_777_653_1,
98    -176.615_029_162_140_6,
99    12.507_343_278_686_905,
100    -0.138_571_095_265_720_12,
101    9.984_369_578_019_572e-6,
102    1.505_632_735_149_311_6e-7,
103];
104const EPS: f64 = 1e-15;
105const TINY: f64 = 1e-300;
106const MAX_ITER: usize = 10_000;
107
108/// ln Γ(z) for z >= 0.5 (Lanczos, g = 7, nine coefficients).
109fn ln_gamma(z: f64) -> f64 {
110    let z = z - 1.0;
111    let mut s = LANCZOS[0];
112    for (i, c) in LANCZOS.iter().enumerate().skip(1) {
113        s += c / (z + i as f64);
114    }
115    let t = z + LANCZOS_G + 0.5;
116    0.5 * (2.0 * std::f64::consts::PI).ln() + (z + 0.5) * t.ln() - t + s.ln()
117}
118
119/// P(X >= x) for X ~ chi-square with `df` degrees of freedom: the regularised upper incomplete
120/// gamma Q(df/2, x/2), by its series below a + 1 and its continued fraction above. 1 for df 0.
121pub fn chi2_sf(x: f64, df: u64) -> f64 {
122    if df == 0 || x.is_nan() || x <= 0.0 {
123        return 1.0;
124    }
125    let (a, h) = (df as f64 / 2.0, x / 2.0);
126    let front = -h + a * h.ln() - ln_gamma(a);
127    if h < a + 1.0 {
128        let (mut ap, mut term) = (a, 1.0 / a);
129        let mut total = term;
130        for _ in 0..MAX_ITER {
131            ap += 1.0;
132            term *= h / ap;
133            total += term;
134            if term.abs() < total.abs() * EPS {
135                break;
136            }
137        }
138        return (1.0 - total * front.exp()).max(0.0);
139    }
140    let mut b = h + 1.0 - a;
141    let mut c = 1.0 / TINY;
142    let mut d = 1.0 / b;
143    let mut f = d;
144    for i in 1..MAX_ITER {
145        let i = i as f64;
146        let an = -i * (i - a);
147        b += 2.0;
148        d = an * d + b;
149        if d.abs() < TINY {
150            d = TINY;
151        }
152        c = b + an / c;
153        if c.abs() < TINY {
154            c = TINY;
155        }
156        d = 1.0 / d;
157        let step = d * c;
158        f *= step;
159        if (step - 1.0).abs() < EPS {
160            break;
161        }
162    }
163    (front.exp() * f).min(1.0)
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn chi2_tail_matches_known_values() {
172        // scipy.stats.chi2.sf, to 1e-12 relative
173        let known = [
174            (3.841_458_820_694_124, 1, 0.049_999_999_999_999_94),
175            (5.991_464_547_107_979, 2, 0.050_000_000_000_000_08),
176            (30.143_527_205_646_16, 19, 0.050_000_000_000_000_01),
177            (10.0, 3, 0.018_566_135_463_043_23),
178            (150.0, 100, 0.000_903_932_042_354_018_4),
179        ];
180        for (x, df, p) in known {
181            let got = chi2_sf(x, df);
182            assert!(
183                (got - p).abs() <= 1e-12 * p.max(1e-300) + 1e-15,
184                "{x} {df}: {got} vs {p}"
185            );
186        }
187        assert_eq!(chi2_sf(0.0, 4), 1.0);
188        assert_eq!(chi2_sf(1e5, 2), 0.0);
189    }
190
191    #[test]
192    fn bins_are_half_open_and_the_last_holds_one() {
193        let bins = [0.0, 0.5, 0.9, 1.0];
194        assert_eq!(bin_of(&bins, 0.0), Some(0));
195        assert_eq!(bin_of(&bins, 0.5), Some(1));
196        assert_eq!(bin_of(&bins, 0.899_999), Some(1));
197        assert_eq!(bin_of(&bins, 0.9), Some(2));
198        assert_eq!(bin_of(&bins, 1.0), Some(2));
199        assert_eq!(bin_of(&bins, 1.01), None);
200        assert_eq!(bin_of(&bins, f64::NAN), None);
201        let h = Histogram::of(&bins, [Some(0.95), None, Some(0.1), Some(1.0)]).unwrap();
202        assert_eq!((h.counts, h.unscored), (vec![1, 0, 2], 1));
203    }
204
205    #[test]
206    fn identical_histograms_do_not_shift_and_disjoint_ones_do() {
207        let a = Histogram {
208            counts: vec![10, 20, 30, 0],
209            unscored: 5,
210        };
211        let same = shift_score(&a, &a).unwrap();
212        assert_eq!((same.statistic, same.df, same.p_value), (0.0, 3, 1.0));
213        let b = Histogram {
214            counts: vec![0, 0, 0, 60],
215            unscored: 0,
216        };
217        assert!(shift_score(&a, &b).unwrap().p_value < 1e-20);
218        let empty = Histogram {
219            counts: vec![0; 4],
220            unscored: 0,
221        };
222        assert_eq!(shift_score(&a, &empty).unwrap().df, 0);
223        let short = Histogram {
224            counts: vec![1],
225            unscored: 0,
226        };
227        assert!(shift_score(&a, &short).is_none());
228    }
229}