llm-bench

"""Tests for bench.core.stats (pure functions)."""
import unittest

import _util  # noqa: F401
from bench.core import stats


class Stats(unittest.TestCase):
    def test_bootstrap_deterministic_and_bounded(self):
        v = [1, 0, 1, 1, 0, 1, 0, 1]
        a = stats.bootstrap_ci(v, n_boot=500, seed=7)
        b = stats.bootstrap_ci(v, n_boot=500, seed=7)
        c = stats.bootstrap_ci(v, n_boot=500, seed=8)
        self.assertEqual(a, b)
        self.assertNotEqual(a, c)
        self.assertTrue(0 <= a[0] <= 0.625 <= a[1] <= 1)
        self.assertEqual(stats.bootstrap_ci([0.3]), (0.3, 0.3))
        self.assertIsNone(stats.bootstrap_ci([]))

    def test_wilson(self):
        lo, hi = stats.wilson(8, 10)
        self.assertAlmostEqual(lo, 0.4902, places=3)
        self.assertAlmostEqual(hi, 0.9433, places=3)
        self.assertEqual(stats.wilson(0, 5)[0], 0.0)
        self.assertIsNone(stats.wilson(0, 0))

    def test_mcnemar_known_table(self):
        self.assertAlmostEqual(stats.mcnemar_exact(1, 9), 2 * 11 / 1024)
        self.assertEqual(stats.mcnemar_exact(5, 5), 1.0)
        self.assertEqual(stats.mcnemar_exact(0, 0), 1.0)
        self.assertAlmostEqual(stats.mcnemar_exact(0, 6), 2 / 64)

    def test_mcnemar_items_pairing_and_ties(self):
        a = {"i1": 1.0, "i2": 1.0, "i3": 0.0, "i4": 0.5, "i5": 1.0, "only_a": 1.0}
        b = {"i1": 0.0, "i2": 1.0, "i3": 1.0, "i4": 1.0, "i5": 0.0, "only_b": 0.0}
        m = stats.mcnemar_items(a, b)
        self.assertEqual((m["b"], m["c"], m["n_both_pass"], m["n_tied_dropped"]), (2, 1, 1, 1))
        self.assertAlmostEqual(m["p"], 1.0)

    def test_paired_delta_intersection(self):
        a = {"x": 1.0, "y": 1.0, "z": 0.0}
        b = {"y": 0.0, "z": 0.0, "w": 1.0}
        d = stats.paired_delta(a, b, n_boot=100)
        self.assertEqual(d["n"], 2)
        self.assertAlmostEqual(d["mean_delta"], 0.5)
        self.assertEqual(stats.paired_delta({"a": 1}, {"b": 1})["n"], 0)


if __name__ == "__main__":
    unittest.main()