Skip to main content

graphrt_eval/
stats.rs

1//! Statistics over repeated trials and judge calibration.
2//!
3//! - [`pass_at_k`] and [`pass_hat_k`]: unbiased estimators from `n` trials with
4//!   `c` successes of the chance that at least one of `k` trials passes
5//!   (capability) and that all `k` pass (reliability, τ-bench's pass^k).
6//! - [`Agreement`]: a judge's binary verdicts against human labels: confusion
7//!   matrix, raw agreement, TPR, TNR and Cohen's kappa.
8
9use serde::{Deserialize, Serialize};
10
11/// Unbiased pass@k from `n` trials with `c` passes: `1 - C(n-c, k) / C(n, k)`
12/// (Chen et al. 2021, the Codex estimator of `1 - (1 - p)^k`).
13///
14/// `k` is clamped to `1..=n`; with no trials the result is 0.
15///
16/// ```
17/// // 5 trials, 2 passed: 1 - C(3,2)/C(5,2) = 1 - 3/10
18/// assert!((graphrt_eval::stats::pass_at_k(5, 2, 2) - 0.7).abs() < 1e-12);
19/// ```
20pub fn pass_at_k(n: u32, c: u32, k: u32) -> f64 {
21    if n == 0 {
22        return 0.0;
23    }
24    1.0 - choose_ratio(n - c.min(n), n, k.clamp(1, n))
25}
26
27/// Unbiased pass^k from `n` trials with `c` passes: `C(c, k) / C(n, k)`, the
28/// probability that `k` trials drawn without replacement all passed; its
29/// expectation is `p^k` for a per-trial pass probability `p`.
30///
31/// `k` is clamped to `1..=n`; with no trials the result is 0.
32///
33/// ```
34/// // 5 trials, 2 passed: C(2,2)/C(5,2) = 1/10
35/// assert!((graphrt_eval::stats::pass_hat_k(5, 2, 2) - 0.1).abs() < 1e-12);
36/// ```
37pub fn pass_hat_k(n: u32, c: u32, k: u32) -> f64 {
38    if n == 0 {
39        return 0.0;
40    }
41    choose_ratio(c.min(n), n, k.clamp(1, n))
42}
43
44/// `C(a, k) / C(n, k)` for `a <= n`, as the product `Π (a - i) / (n - i)` over
45/// `i < k` (no factorials, so no overflow); 0 when `a < k`.
46fn choose_ratio(a: u32, n: u32, k: u32) -> f64 {
47    if a < k {
48        return 0.0;
49    }
50    (0..k).map(|i| f64::from(a - i) / f64::from(n - i)).product()
51}
52
53/// A binary judge against binary human labels (positive = `pass`).
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
55#[non_exhaustive]
56pub struct Confusion {
57    /// Judge pass, label pass.
58    pub tp: u32,
59    /// Judge pass, label fail.
60    pub fp: u32,
61    /// Judge fail, label fail.
62    pub tn: u32,
63    /// Judge fail, label pass.
64    #[serde(rename = "fn")]
65    pub fn_: u32,
66}
67
68impl Confusion {
69    /// Count one judged example.
70    pub fn add(&mut self, predicted: bool, label: bool) {
71        match (predicted, label) {
72            (true, true) => self.tp += 1,
73            (true, false) => self.fp += 1,
74            (false, false) => self.tn += 1,
75            (false, true) => self.fn_ += 1,
76        }
77    }
78
79    pub fn total(&self) -> u32 {
80        self.tp + self.fp + self.tn + self.fn_
81    }
82
83    /// The metrics of this matrix.
84    pub fn agreement(&self) -> Agreement {
85        let n = f64::from(self.total());
86        let ratio = |num: u32, den: u32| (den > 0).then(|| f64::from(num) / f64::from(den));
87        let observed = ratio(self.tp + self.tn, self.total());
88        // Chance agreement from the marginals: P(both pass) + P(both fail).
89        let kappa = observed.and_then(|po| {
90            let judge_pass = f64::from(self.tp + self.fp) / n;
91            let label_pass = f64::from(self.tp + self.fn_) / n;
92            let pe = judge_pass * label_pass + (1.0 - judge_pass) * (1.0 - label_pass);
93            // Kappa is undefined when chance agreement is certain (one class only).
94            (pe < 1.0 - 1e-12).then(|| (po - pe) / (1.0 - pe))
95        });
96        Agreement {
97            agreement: observed,
98            tpr: ratio(self.tp, self.tp + self.fn_),
99            tnr: ratio(self.tn, self.tn + self.fp),
100            kappa,
101        }
102    }
103}
104
105/// Agreement metrics; `None` where the denominator is zero (or, for kappa,
106/// when chance agreement is 1).
107#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
108#[non_exhaustive]
109pub struct Agreement {
110    /// `(tp + tn) / n`.
111    pub agreement: Option<f64>,
112    /// Sensitivity: `tp / (tp + fn)`, passes the judge recognises.
113    pub tpr: Option<f64>,
114    /// Specificity: `tn / (tn + fp)`, failures the judge catches.
115    pub tnr: Option<f64>,
116    /// Cohen's kappa: `(po - pe) / (1 - pe)`, agreement corrected for chance.
117    pub kappa: Option<f64>,
118}
119
120#[cfg(test)]
121mod tests {
122    #![allow(clippy::unwrap_used)]
123
124    use super::*;
125
126    fn close(a: f64, b: f64) -> bool {
127        (a - b).abs() < 1e-12
128    }
129
130    #[test]
131    fn pass_at_k_matches_hand_computed_values() {
132        // n=5, c=2, k=2: 1 - C(3,2)/C(5,2) = 1 - 3/10.
133        assert!(close(pass_at_k(5, 2, 2), 0.7));
134        // n=10, c=3, k=3: 1 - C(7,3)/C(10,3) = 1 - 35/120.
135        assert!(close(pass_at_k(10, 3, 3), 1.0 - 35.0 / 120.0));
136        // k=1 is the plain pass rate.
137        assert!(close(pass_at_k(4, 1, 1), 0.25));
138        // Too few failures to fill k draws: certain success.
139        assert!(close(pass_at_k(5, 4, 2), 1.0));
140        assert!(close(pass_at_k(3, 0, 3), 0.0));
141        assert!(close(pass_at_k(3, 3, 3), 1.0));
142        // k is clamped to n; no trials is 0.
143        assert!(close(pass_at_k(2, 1, 5), 1.0));
144        assert!(close(pass_at_k(0, 0, 1), 0.0));
145    }
146
147    #[test]
148    fn pass_hat_k_matches_hand_computed_values() {
149        // n=5, c=2, k=2: C(2,2)/C(5,2) = 1/10.
150        assert!(close(pass_hat_k(5, 2, 2), 0.1));
151        // n=10, c=7, k=3: C(7,3)/C(10,3) = 35/120.
152        assert!(close(pass_hat_k(10, 7, 3), 35.0 / 120.0));
153        // n=4, c=3, k=2: C(3,2)/C(4,2) = 3/6.
154        assert!(close(pass_hat_k(4, 3, 2), 0.5));
155        assert!(close(pass_hat_k(4, 1, 1), 0.25));
156        assert!(close(pass_hat_k(3, 2, 3), 0.0));
157        assert!(close(pass_hat_k(3, 3, 3), 1.0));
158        assert!(close(pass_hat_k(2, 1, 5), 0.0), "k clamped to n=2");
159        assert!(close(pass_hat_k(0, 0, 1), 0.0));
160    }
161
162    #[test]
163    fn pass_hat_k_is_unbiased_for_p_to_the_k() {
164        // Average the estimator over every outcome of n=4 Bernoulli(0.75) trials.
165        let (n, k, p) = (4u32, 3u32, 0.75f64);
166        let mut expected = 0.0;
167        for c in 0..=n {
168            let ways = (0..c).map(|i| f64::from(n - i) / f64::from(i + 1)).product::<f64>();
169            let probability = ways * p.powi(c as i32) * (1.0 - p).powi((n - c) as i32);
170            expected += probability * pass_hat_k(n, c, k);
171        }
172        assert!((expected - p.powi(3)).abs() < 1e-12, "{expected}");
173    }
174
175    #[test]
176    fn agreement_metrics_match_hand_computed_values() {
177        let mut m = Confusion::default();
178        for (predicted, label, times) in [(true, true, 40), (true, false, 10), (false, false, 40), (false, true, 10)] {
179            for _ in 0..times {
180                m.add(predicted, label);
181            }
182        }
183        let a = m.agreement();
184        assert!(close(a.agreement.unwrap(), 0.8));
185        assert!(close(a.tpr.unwrap(), 0.8));
186        assert!(close(a.tnr.unwrap(), 0.8));
187        // po = 0.8, pe = 0.5*0.5 + 0.5*0.5 = 0.5: kappa = 0.3 / 0.5.
188        assert!(close(a.kappa.unwrap(), 0.6));
189
190        // Skewed: tp 45, fp 15, tn 30, fn 10 (n=100).
191        let m = Confusion { tp: 45, fp: 15, tn: 30, fn_: 10 };
192        let a = m.agreement();
193        assert!(close(a.agreement.unwrap(), 0.75));
194        assert!(close(a.tpr.unwrap(), 45.0 / 55.0));
195        assert!(close(a.tnr.unwrap(), 30.0 / 45.0));
196        // pe = 0.6*0.55 + 0.4*0.45 = 0.51: kappa = 0.24 / 0.49.
197        assert!(close(a.kappa.unwrap(), 0.24 / 0.49));
198    }
199
200    #[test]
201    fn agreement_handles_degenerate_matrices() {
202        let empty = Confusion::default().agreement();
203        assert_eq!(empty, Agreement::default());
204        // Everything labelled and judged pass: perfect agreement, kappa undefined.
205        let all_pass = Confusion { tp: 5, ..Confusion::default() }.agreement();
206        assert_eq!(all_pass.agreement, Some(1.0));
207        assert_eq!(all_pass.tnr, None);
208        assert_eq!(all_pass.kappa, None);
209        // Always the opposite: kappa -1.
210        let opposite = Confusion { fp: 3, fn_: 3, ..Confusion::default() }.agreement();
211        assert!(close(opposite.kappa.unwrap(), -1.0));
212    }
213}