Skip to main content

graphrt_eval/
calibration.rs

1//! Judge calibration: an eval whose workflow is a judge and whose `expected`
2//! values are human labels. Every result is one (judge verdict, label) pair;
3//! the report adds the confusion matrix, raw agreement, TPR, TNR and Cohen's
4//! kappa (raw agreement alone flatters a judge on imbalanced labels).
5
6use std::fmt::Write as _;
7
8use serde::{Deserialize, Serialize};
9
10use crate::capture::RunStatus;
11use crate::config::Calibration;
12use crate::judge::{Judgement, UnknownPolicy, Verdict};
13use crate::report::{GateResult, TestResult};
14use crate::stats::Confusion;
15
16/// How well the judge agrees with the labels.
17#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
18#[non_exhaustive]
19pub struct CalibrationSummary {
20    /// Results with a `pass` / `fail` label.
21    pub labelled: u32,
22    /// Results in the confusion matrix.
23    pub judged: u32,
24    /// The judge said `unknown` (outside the matrix with `unknown: exclude`).
25    pub unknown: u32,
26    /// The judge run failed or returned no verdict.
27    pub errors: u32,
28    pub unknown_policy: UnknownPolicy,
29    pub confusion: Confusion,
30    pub agreement: Option<f64>,
31    pub tpr: Option<f64>,
32    pub tnr: Option<f64>,
33    pub kappa: Option<f64>,
34}
35
36/// Compare every result's judge verdict with its label (`expected`).
37pub fn calibrate(tests: &[TestResult], config: &Calibration) -> CalibrationSummary {
38    let threshold = config.threshold.unwrap_or(0.5);
39    let mut summary = CalibrationSummary { unknown_policy: config.unknown, ..CalibrationSummary::default() };
40    for test in tests {
41        let label = match test.expected.as_ref().and_then(Verdict::parse) {
42            Some(Verdict::Pass) => true,
43            Some(Verdict::Fail) => false,
44            _ => continue,
45        };
46        summary.labelled += 1;
47        let judgement =
48            (test.run.status == RunStatus::Succeeded).then(|| Judgement::read(&test.run.outputs).ok()).flatten();
49        let predicted = match judgement.map(|j| j.decide(threshold)) {
50            None => {
51                summary.errors += 1;
52                continue;
53            }
54            Some(Verdict::Unknown) => {
55                summary.unknown += 1;
56                if config.unknown == UnknownPolicy::Exclude {
57                    continue;
58                }
59                false
60            }
61            Some(verdict) => verdict == Verdict::Pass,
62        };
63        summary.confusion.add(predicted, label);
64    }
65    summary.judged = summary.confusion.total();
66    let metrics = summary.confusion.agreement();
67    summary.agreement = metrics.agreement;
68    summary.tpr = metrics.tpr;
69    summary.tnr = metrics.tnr;
70    summary.kappa = metrics.kappa;
71    summary
72}
73
74/// Apply the calibration thresholds (`min_kappa`, `min_tpr`, `min_tnr`) to the
75/// gate. An undefined metric (no examples of a class) fails its threshold.
76pub fn gate(summary: &CalibrationSummary, config: &Calibration, gate: &mut GateResult) {
77    let mut check = |name: &str, value: Option<f64>, min: Option<f64>| {
78        if let Some(min) = min {
79            gate.require(value.is_some_and(|v| v + 1e-9 >= min), || match value {
80                Some(v) => format!("{name} {v:.3} < {min:.3}"),
81                None => format!("{name} undefined (needs {min:.3})"),
82            });
83        }
84    };
85    check("kappa", summary.kappa, config.min_kappa);
86    check("TPR", summary.tpr, config.min_tpr);
87    check("TNR", summary.tnr, config.min_tnr);
88}
89
90/// The terminal block for a calibration summary.
91pub fn format_calibration(c: &CalibrationSummary) -> String {
92    let metric = |v: Option<f64>| v.map_or_else(|| "n/a".to_owned(), |v| format!("{v:.3}"));
93    let m = &c.confusion;
94    let mut out = String::new();
95    let _ = writeln!(
96        out,
97        "\ncalibration: {} labelled, {} judged, {} unknown ({}), {} error(s)",
98        c.labelled,
99        c.judged,
100        c.unknown,
101        if c.unknown_policy == UnknownPolicy::Exclude { "excluded" } else { "counted as fail" },
102        c.errors
103    );
104    let _ = writeln!(
105        out,
106        "  agreement {}  TPR {}  TNR {}  kappa {}",
107        metric(c.agreement),
108        metric(c.tpr),
109        metric(c.tnr),
110        metric(c.kappa)
111    );
112    let _ = writeln!(out, "                 label pass  label fail");
113    let _ = writeln!(out, "  judge pass     {:>10}  {:>10}", m.tp, m.fp);
114    let _ = writeln!(out, "  judge fail     {:>10}  {:>10}", m.fn_, m.tn);
115    out
116}
117
118#[cfg(test)]
119mod tests {
120    #![allow(clippy::unwrap_used, clippy::indexing_slicing)]
121
122    use super::*;
123    use crate::report::{RunSummary, TestStatus};
124    use serde_json::{Map, json};
125
126    fn labelled(label: serde_json::Value, outputs: serde_json::Value, status: RunStatus) -> TestResult {
127        TestResult {
128            id: "t".into(),
129            description: None,
130            source: "inline".into(),
131            tags: vec![],
132            trial: 0,
133            status: TestStatus::Passed,
134            pass: true,
135            score: 1.0,
136            reason: None,
137            vars: Map::new(),
138            expected: Some(label),
139            run: RunSummary { status, outputs: outputs.as_object().cloned().unwrap(), ..RunSummary::default() },
140            assertions: vec![],
141        }
142    }
143
144    fn suite() -> Vec<TestResult> {
145        let ok = RunStatus::Succeeded;
146        vec![
147            labelled(json!("pass"), json!({"verdict": "pass"}), ok), // tp
148            labelled(json!("pass"), json!({"verdict": "pass"}), ok), // tp
149            labelled(json!(true), json!({"verdict": "fail"}), ok),   // fn
150            labelled(json!("fail"), json!({"verdict": "fail"}), ok), // tn
151            labelled(json!("fail"), json!({"score": 0.9}), ok),      // fp (score >= 0.5)
152            labelled(json!("fail"), json!({"verdict": "unknown"}), ok),
153            labelled(json!("pass"), json!({"text": "no verdict"}), ok),
154            labelled(json!("pass"), json!({"verdict": "pass"}), RunStatus::Failed),
155            labelled(json!("n/a"), json!({"verdict": "pass"}), ok), // not a label
156        ]
157    }
158
159    #[test]
160    fn computes_the_confusion_matrix_and_agreement() {
161        let c = calibrate(&suite(), &Calibration::default());
162        assert_eq!((c.labelled, c.judged, c.unknown, c.errors), (8, 5, 1, 2));
163        assert_eq!(c.confusion, Confusion { tp: 2, fp: 1, tn: 1, fn_: 1 });
164        assert!((c.agreement.unwrap() - 0.6).abs() < 1e-12);
165        assert!((c.tpr.unwrap() - 2.0 / 3.0).abs() < 1e-12);
166        assert!((c.tnr.unwrap() - 0.5).abs() < 1e-12);
167        // po = 0.6, pe = 0.6*0.6 + 0.4*0.4 = 0.52: kappa = 0.08 / 0.48.
168        assert!((c.kappa.unwrap() - 0.08 / 0.48).abs() < 1e-12);
169        let text = format_calibration(&c);
170        assert!(text.contains("8 labelled, 5 judged, 1 unknown (excluded), 2 error(s)"), "{text}");
171        assert!(text.contains("kappa 0.167"), "{text}");
172    }
173
174    #[test]
175    fn unknown_can_count_as_fail_and_thresholds_gate() {
176        let config = Calibration { unknown: UnknownPolicy::Fail, min_kappa: Some(0.5), ..Calibration::default() };
177        let c = calibrate(&suite(), &config);
178        assert_eq!(c.confusion, Confusion { tp: 2, fp: 1, tn: 2, fn_: 1 });
179        let mut result = GateResult { pass_rate: 0.0, pass_hat_k: None, passed: true, failures: vec![] };
180        gate(&c, &config, &mut result);
181        assert!(!result.passed);
182        assert!(result.failures[0].starts_with("kappa 0.333 < 0.500"), "{:?}", result.failures);
183        let none = calibrate(&[], &Calibration { min_tnr: Some(0.5), ..Calibration::default() });
184        let mut result = GateResult { pass_rate: 0.0, pass_hat_k: None, passed: true, failures: vec![] };
185        gate(&none, &Calibration { min_tnr: Some(0.5), ..Calibration::default() }, &mut result);
186        assert!(result.failures[0].contains("TNR undefined"), "{:?}", result.failures);
187    }
188}