"""Tests for stats.py. Run: python -m pytest -q""" import numpy as np import pytest from scipy.stats import binomtest from stats import wald_interval, wilson_interval, z_value def test_z_value() -> None: assert z_value(0.95) == pytest.approx(1.959964, abs=1e-6) assert z_value(0.90) == pytest.approx(1.644854, abs=1e-6) with pytest.raises(ValueError): z_value(1.0) def test_wilson_worked_example_18_of_20() -> None: lo, hi = wilson_interval(18, 20) assert lo == pytest.approx(0.699, abs=5e-4) assert hi == pytest.approx(0.972, abs=5e-4) def test_wilson_all_successes_is_not_degenerate() -> None: lo, hi = wilson_interval(20, 20) assert hi == pytest.approx(1.0) assert lo == pytest.approx(20 / (20 + z_value() ** 2)) # closed form for k = n assert wald_interval(20, 20) == pytest.approx((1.0, 1.0)) def test_wald_leaves_unit_interval_wilson_does_not() -> None: assert wald_interval(18, 20)[1] > 1.0 lo, hi = wilson_interval(18, 20) assert 0.0 <= lo < hi <= 1.0 def test_wilson_matches_scipy() -> None: for k, n in [(0, 10), (3, 10), (18, 20), (45, 50), (500, 1000)]: ci = binomtest(k, n).proportion_ci(confidence_level=0.95, method="wilson") assert wilson_interval(k, n) == pytest.approx((ci.low, ci.high), abs=1e-9) def test_wilson_coverage_close_to_nominal() -> None: rng = np.random.default_rng(0) n, p, trials = 20, 0.8, 4000 k = rng.binomial(n, p, size=trials) covered = np.mean([lo <= p <= hi for lo, hi in (wilson_interval(int(x), n) for x in k)]) assert 0.92 < covered < 0.98 def test_input_checks() -> None: with pytest.raises(ValueError): wilson_interval(1, 0) with pytest.raises(ValueError): wilson_interval(5, 4)