File size: 2,508 Bytes
fd5366a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# Copyright (c) 2026 CLSA contributors
# SPDX-License-Identifier: MIT
"""Metrics: bootstrap behaviour, calibration, Clopper-Pearson bounds."""
from __future__ import annotations

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))

import numpy as np  # noqa: E402

from clsa.controller.risk import (  # noqa: E402
    clopper_pearson_upper,
    conformal_threshold,
    expected_calibration_error,
)
from clsa.eval.metrics import cluster_bootstrap, harm_rate, paired_bootstrap  # noqa: E402


def _rows(decs, harms, episodes, successes=None):
    successes = successes or [0.0] * len(decs)
    return [
        {
            "state_key": f"{e}-{i}",
            "decision": d,
            "harm": float(h),
            "success": float(s),
            "irreversible": bool(h > 0.8),
            "episode_id": e,
            "tokens": 10.0,
            "p_hat": float(h),
            "irr": bool(h > 0.8),
        }
        for i, (d, h, e, s) in enumerate(zip(decs, harms, episodes, successes))
    ]


def test_clopper_pearson_is_monotone():
    assert clopper_pearson_upper(0, 100) > 0.0
    assert clopper_pearson_upper(5, 1000) < clopper_pearson_upper(50, 1000)
    assert clopper_pearson_upper(100, 100) == 1.0


def test_ece_zero_when_perfect_and_large_when_wrong():
    p = np.array([0.0, 0.0, 1.0, 1.0])
    y = np.array([0, 0, 1, 1])
    assert expected_calibration_error(p, y) < 1e-9
    assert expected_calibration_error(np.array([0.9, 0.9]), np.array([0, 0])) > 0.5


def test_conformal_threshold_controls_miscoverage():
    safe = np.linspace(0, 0.9, 200)
    t = conformal_threshold(safe, alpha=0.1)
    assert 0.0 < t <= 0.9
    assert (safe > t).mean() <= 0.1 + 1e-9


def test_paired_bootstrap_is_deterministic_and_signed():
    eps = ["e0", "e0", "e1", "e1", "e2", "e2"]
    a = _rows(["execute"] * 6, [0, 0, 0, 1, 0, 1], eps)
    b = _rows(["execute"] * 6, [1, 1, 1, 1, 0, 1], eps)
    r1 = paired_bootstrap(a, b, harm_rate, n_boot=200, seed=3)
    r2 = paired_bootstrap(a, b, harm_rate, n_boot=200, seed=3)
    assert r1["diff"] == r2["diff"]
    assert r1["diff"] < 0, "the first arm should show lower harm in this fixture"


def test_cluster_bootstrap_reports_cluster_count():
    rows = _rows(
        ["execute"] * 6, [0, 1, 0, 1, 0, 1], ["e0", "e0", "e1", "e1", "e2", "e2"]
    )
    out = cluster_bootstrap(rows, harm_rate, n_boot=200, seed=1)
    assert out["n"] == len(rows)
    assert out["lo"] <= out["value"] <= out["hi"]