Homework · Runs in your browser

The experiment toolkit: bootstrap, permutation test, power, multiple comparisons, SRM and paired tests

Build the statistics toolkit of an experimentation platform with nothing but the standard library: a percentile bootstrap interval that takes its random generator as an argument, exact and randomised permutation tests, a two-proportion z-test, sample size and power, Bonferroni and Benjamini-Hochberg, a chi-square tail with a sample ratio mismatch check, McNemar’s test, and the corrected resampled t statistic. Edit starter.py, then run the tests. In the browser runner, press Run tests. In Colab or on your own machine, put starter.py and test_starter.py in one folder and run pytest. Nothing needs installing except pytest. Four small helpers are already written for you.

Hints:

  • The random generator is passed in (rng.randrange(n) for the bootstrap, rng.shuffle(list) for the permutation test), so the tests can script it. Draw one value at a time, in order, exactly as the docstring says.
  • Bootstrap indices: lo = floor(alpha / 2 x B), hi = ceil((1 - alpha / 2) x B) - 1, after rounding the products to 9 decimals. Check with a statistic that just counts upwards: B = 1000 and alpha = 0.05 must give the 26th and 975th values.
  • A randomised permutation p-value is (extreme + 1) / (B + 1), so it is never 0. The exact test has no +1: it counts every split, and the original split is one of them. Compare floats with the 1e-12 tolerance. The two-sided rule here is abs(t) >= abs(observed); scipy.stats.permutation_test instead doubles the smaller one-sided p-value, which gives 0.0396 rather than 0.0280 on the lesson’s data.
  • Sample size: n = (z_{1-alpha/2} + z_power)^2 x (p1 q1 + p2 q2) / (p1 - p2)^2, rounded up. Power keeps both tails: with no real effect it must equal alpha. Check: baseline 0.10 against 0.11 needs 14749 per arm.
  • Benjamini-Hochberg adjusted value: sort ascending, raw = m x p / rank, then take the running minimum from the largest rank down. Check: [0.5, 0.6, 0.1, 0.001] gives [0.6, 0.6, 0.2, 0.004].
  • SRM: expected counts from the design ratios, a chi-square statistic, and k - 1 degrees of freedom. Check: 10400 against 9600 under a 50/50 design gives a statistic of 32.0.
  • McNemar: only the items where the two models disagree matter. Check: 29 and 57 give a statistic of 8.48.
  • Try it: run 2000 simulated A/A tests through two_proportion_ztest and count how many have p < 0.05.

Running the tests needs JavaScript. You can still read the starter code below and run it on your own machine with pytest.

Tab inserts 4 spaces. To move on with the keyboard, press Esc, then Tab. Shift+Tab always moves back.

Show a solution

Try it yourself first. This site is static, so the solution is sent to your browser with the page; it is hidden here, not secret.

import math
from itertools import combinations
from statistics import NormalDist

EPS = 1e-12


def _mean(xs):
    return sum(xs) / len(xs)


def bootstrap_ci(data, stat, n_resamples, alpha, rng):
    """Percentile bootstrap confidence interval for stat(data).

    Make n_resamples resamples. Each one has len(data) items, and item j is
    data[rng.randrange(len(data))], drawn one at a time in order. Compute stat on every
    resample and sort the results as s[0] <= ... <= s[B-1] with B = n_resamples. The
    interval is (s[lo], s[hi]) with lo = floor(alpha / 2 * B) and
    hi = ceil((1 - alpha / 2) * B) - 1. Round alpha / 2 * B and (1 - alpha / 2) * B to
    9 decimals before floor and ceil, so float noise cannot move an index.
    Raise ValueError if data is empty, n_resamples < 1 or alpha is not in (0, 1).
    """
    n = len(data)
    if n == 0 or n_resamples < 1 or not 0 < alpha < 1:
        raise ValueError("need data, n_resamples >= 1 and 0 < alpha < 1")
    stats = []
    for _ in range(n_resamples):
        stats.append(stat([data[rng.randrange(n)] for _ in range(n)]))
    stats.sort()
    lo = int(math.floor(round(alpha / 2 * n_resamples, 9)))
    hi = int(math.ceil(round((1 - alpha / 2) * n_resamples, 9))) - 1
    return stats[lo], stats[hi]


def _check_alt(alternative):
    if alternative not in ("two-sided", "greater", "less"):
        raise ValueError("alternative must be 'two-sided', 'greater' or 'less'")


def _is_extreme(t, observed, alternative):
    if alternative == "greater":
        return t >= observed - EPS
    if alternative == "less":
        return t <= observed + EPS
    return abs(t) >= abs(observed) - EPS


def permutation_test(a, b, n_resamples, rng, alternative="two-sided"):
    """Randomised permutation test for a difference in means, mean(a) - mean(b).

    Pool a then b into one list. For each of n_resamples rounds call rng.shuffle on the
    SAME list (it keeps its order between rounds), take the first len(a) values as the
    new a and the rest as the new b, and compute the same difference. A round counts as
    extreme when the permuted difference t satisfies: 'greater' t >= observed - 1e-12,
    'less' t <= observed + 1e-12, 'two-sided' abs(t) >= abs(observed) - 1e-12.
    Return (observed, p) with p = (extreme + 1) / (n_resamples + 1).
    Raise ValueError for an empty sample, n_resamples < 1 or an unknown alternative.
    """
    _check_alt(alternative)
    if not a or not b or n_resamples < 1:
        raise ValueError("need two non-empty samples and n_resamples >= 1")
    na = len(a)
    observed = _mean(a) - _mean(b)
    pooled = list(a) + list(b)
    extreme = 0
    for _ in range(n_resamples):
        rng.shuffle(pooled)
        t = _mean(pooled[:na]) - _mean(pooled[na:])
        if _is_extreme(t, observed, alternative):
            extreme += 1
    return observed, (extreme + 1) / (n_resamples + 1)


def exact_permutation_test(a, b, alternative="two-sided"):
    """Exact permutation test: try every way to choose which pooled values form sample a.

    Same statistic and the same 1e-12 tolerance as permutation_test, but no +1: the
    p-value is extreme / total, counted over all comb(len(a) + len(b), len(a)) choices
    (the original split is one of them). Return (observed, p). Raise ValueError for an
    empty sample, an unknown alternative, or more than 200000 choices.
    """
    _check_alt(alternative)
    if not a or not b:
        raise ValueError("need two non-empty samples")
    n, na = len(a) + len(b), len(a)
    if math.comb(n, na) > 200000:
        raise ValueError("too many permutations for an exact test")
    pooled = list(a) + list(b)
    total_sum = sum(pooled)
    observed = _mean(a) - _mean(b)
    extreme = total = 0
    for idx in combinations(range(n), na):
        sa = sum(pooled[i] for i in idx)
        t = sa / na - (total_sum - sa) / (n - na)
        total += 1
        if _is_extreme(t, observed, alternative):
            extreme += 1
    return observed, extreme / total


def two_proportion_ztest(x1, n1, x2, n2):
    """Two-sided z-test for two proportions with the pooled standard error.

    p1 = x1 / n1, p2 = x2 / n2, pooled p = (x1 + x2) / (n1 + n2),
    se = sqrt(p (1 - p) (1 / n1 + 1 / n2)), z = (p2 - p1) / se,
    p-value = 2 (1 - Phi(|z|)) = erfc(|z| / sqrt(2)).
    Return (p2 - p1, z, p_value). Raise ValueError if a count is outside 0..n, an n is
    not positive, or the pooled proportion is 0 or 1 (no variation).
    """
    if n1 <= 0 or n2 <= 0 or not 0 <= x1 <= n1 or not 0 <= x2 <= n2:
        raise ValueError("need 0 <= x <= n and n > 0 in both groups")
    pooled = (x1 + x2) / (n1 + n2)
    if pooled in (0.0, 1.0):
        raise ValueError("pooled proportion is 0 or 1: no variation")
    se = math.sqrt(pooled * (1 - pooled) * (1 / n1 + 1 / n2))
    diff = x2 / n2 - x1 / n1
    z = diff / se
    return diff, z, math.erfc(abs(z) / math.sqrt(2))


def sample_size_per_arm(p1, p2, alpha=0.05, power=0.8):
    """Users needed per arm to detect p1 versus p2 with a two-sided z-test.

    n = (z_{1-alpha/2} + z_{power})^2 * (p1 (1 - p1) + p2 (1 - p2)) / (p1 - p2)^2,
    rounded UP to a whole number. Use statistics.NormalDist().inv_cdf for the z values.
    Raise ValueError if p1 == p2, a proportion is not strictly between 0 and 1, or
    alpha or power is not strictly between 0 and 1.
    """
    if not (0 < p1 < 1 and 0 < p2 < 1 and 0 < alpha < 1 and 0 < power < 1) or p1 == p2:
        raise ValueError("need different proportions in (0, 1) and alpha, power in (0, 1)")
    nd = NormalDist()
    z_sum = nd.inv_cdf(1 - alpha / 2) + nd.inv_cdf(power)
    return math.ceil(z_sum ** 2 * (p1 * (1 - p1) + p2 * (1 - p2)) / (p1 - p2) ** 2)


def power_two_proportions(p1, p2, n, alpha=0.05):
    """Power of the two-sided z-test with n users per arm when the true rates are p1 and p2.

    se = sqrt((p1 (1 - p1) + p2 (1 - p2)) / n), d = |p1 - p2| / se,
    power = Phi(d - z_{1-alpha/2}) + Phi(-d - z_{1-alpha/2}); keep both tails.
    Raise ValueError if n < 1, a proportion is not strictly between 0 and 1, or alpha is
    not strictly between 0 and 1.
    """
    if n < 1 or not (0 < p1 < 1 and 0 < p2 < 1 and 0 < alpha < 1):
        raise ValueError("need n >= 1, proportions in (0, 1) and alpha in (0, 1)")
    nd = NormalDist()
    se = math.sqrt((p1 * (1 - p1) + p2 * (1 - p2)) / n)
    d = abs(p1 - p2) / se
    zc = nd.inv_cdf(1 - alpha / 2)
    return nd.cdf(d - zc) + nd.cdf(-d - zc)


def bonferroni_reject(pvals, alpha=0.05):
    """Reject hypothesis i when p_i <= alpha / m, with m the number of p-values."""
    m = len(pvals)
    return [p <= alpha / m + EPS for p in pvals]


def bh_adjust(pvals):
    """Benjamini-Hochberg adjusted p-values, returned in the input order.

    Sort ascending (ties keep input order), rank k = 1..m. The raw value is
    m * p_(k) / k. The adjusted value for rank k is the smallest raw value over ranks
    k, k+1, ..., m, capped at 1. Return [] for an empty list.
    """
    m = len(pvals)
    order = sorted(range(m), key=lambda i: (pvals[i], i))
    adjusted = [0.0] * m
    running = 1.0
    for rank in range(m, 0, -1):
        i = order[rank - 1]
        running = min(running, pvals[i] * m / rank)
        adjusted[i] = running
    return adjusted


def bh_reject(pvals, q=0.05):
    """Reject hypothesis i when its BH adjusted p-value is <= q (plus 1e-12)."""
    return [a <= q + EPS for a in bh_adjust(pvals)]


def _gamma_upper_regularized(a, x):
    if x <= 0:
        return 1.0
    if x < a + 1:
        term = total = 1.0 / a
        n = a
        for _ in range(1000):
            n += 1
            term *= x / n
            total += term
            if abs(term) < abs(total) * 1e-15:
                break
        return 1.0 - total * math.exp(-x + a * math.log(x) - math.lgamma(a))
    tiny = 1e-300
    b = x + 1 - a
    c = 1 / tiny
    d = 1 / b
    h = d
    for i in range(1, 1000):
        an = -i * (i - a)
        b += 2
        d = an * d + b
        d = tiny if abs(d) < tiny else d
        c = b + an / c
        c = tiny if abs(c) < tiny else c
        d = 1 / d
        delta = d * c
        h *= delta
        if abs(delta - 1) < 1e-15:
            break
    return math.exp(-x + a * math.log(x) - math.lgamma(a)) * h


def chi2_sf(x, df):
    """P(chi-square with df degrees of freedom >= x): the upper tail, i.e. the p-value.

    It equals the regularised upper incomplete gamma function Q(df / 2, x / 2). Return 1.0
    for x <= 0. Raise ValueError unless df is a positive integer.
    """
    if not isinstance(df, int) or df < 1:
        raise ValueError("df must be a positive integer")
    return min(1.0, max(0.0, _gamma_upper_regularized(df / 2, x / 2)))


def srm_check(observed, expected_ratios):
    """Sample ratio mismatch: chi-square goodness of fit of arm counts to the design.

    expected_i = total * ratio_i / sum(ratios); statistic = sum (o - e)^2 / e;
    p-value = chi2_sf(statistic, k - 1). Return (statistic, p_value).
    Raise ValueError unless there are k >= 2 arms, equal-length inputs, every observed
    count is non-negative, every ratio is positive and the total is positive.
    """
    k = len(observed)
    if k < 2 or len(expected_ratios) != k or any(o < 0 for o in observed):
        raise ValueError("need k >= 2 arms, matching ratios and non-negative counts")
    if any(r <= 0 for r in expected_ratios) or sum(observed) <= 0:
        raise ValueError("ratios must be positive and the total must be positive")
    total = sum(observed)
    rsum = sum(expected_ratios)
    stat = 0.0
    for o, r in zip(observed, expected_ratios):
        e = total * r / rsum
        stat += (o - e) ** 2 / e
    return stat, chi2_sf(stat, k - 1)


def mcnemar_test(b, c):
    """McNemar's test with continuity correction.

    b = items model A got right and B got wrong, c = items A got wrong and B got right.
    statistic = max(|b - c| - 1, 0)^2 / (b + c), p-value = chi2_sf(statistic, 1).
    Return (statistic, p_value); if b + c == 0 return (0.0, 1.0).
    Raise ValueError if b or c is negative.
    """
    if b < 0 or c < 0:
        raise ValueError("counts cannot be negative")
    if b + c == 0:
        return 0.0, 1.0
    stat = max(abs(b - c) - 1, 0) ** 2 / (b + c)
    return stat, chi2_sf(stat, 1)


def corrected_resampled_t(diffs, n_train, n_test):
    """Nadeau-Bengio corrected resampled t statistic for k paired score differences.

    t = mean(diffs) / sqrt((1 / k + n_test / n_train) * s2), where s2 is the sample
    variance of diffs with divisor k - 1. Raise ValueError if k < 2, n_train or n_test
    is not positive, or s2 is 0.
    """
    k = len(diffs)
    if k < 2 or n_train <= 0 or n_test <= 0:
        raise ValueError("need at least 2 differences and positive set sizes")
    mu = _mean(diffs)
    s2 = sum((d - mu) ** 2 for d in diffs) / (k - 1)
    if s2 == 0:
        raise ValueError("zero variance")
    return mu / math.sqrt((1 / k + n_test / n_train) * s2)
Show the tests (test_starter.py)

Python

import math
import random
from itertools import combinations

import pytest

from starter import (
    bh_adjust,
    bh_reject,
    bonferroni_reject,
    bootstrap_ci,
    chi2_sf,
    corrected_resampled_t,
    exact_permutation_test,
    mcnemar_test,
    permutation_test,
    power_two_proportions,
    sample_size_per_arm,
    srm_check,
    two_proportion_ztest,
)


def mean(xs):
    return sum(xs) / len(xs)


class ScriptedRng:
    """Stand-in for random.Random: scripted draws and a rotate-left shuffle."""

    def __init__(self, draws=None):
        self.draws = list(draws or [])
        self.calls = []
        self.shuffles = 0

    def randrange(self, n):
        self.calls.append(n)
        return self.draws.pop(0) if self.draws else 0

    def shuffle(self, items):
        self.shuffles += 1
        items.append(items.pop(0))


# ---- bootstrap_ci ------------------------------------------------------------

def test_bootstrap_uses_the_scripted_draws_and_the_documented_indices():
    data = [1, 2, 4, 8, 16]
    tuples = [(0, 1, 2, 3, 4), (4, 4, 4, 4, 4), (2, 3, 0, 0, 1), (0, 0, 0, 0, 0), (1, 4, 4, 2, 2),
              (3, 3, 3, 1, 0), (2, 2, 2, 2, 3), (0, 4, 1, 3, 2), (1, 1, 1, 1, 1), (3, 4, 4, 4, 0)]
    rng = ScriptedRng([i for t in tuples for i in t])
    got = bootstrap_ci(data, sum, 10, 0.2, rng)
    expected = sorted(sum(data[i] for i in t) for t in tuples)
    assert got == (expected[1], expected[8])
    assert got != (expected[0], expected[9])
    assert rng.calls == [5] * 50
    assert rng.draws == []


def test_bootstrap_resamples_are_as_large_as_the_data_and_stat_gets_a_list():
    seen = []

    def stat(xs):
        seen.append(list(xs))
        return len(xs)

    bootstrap_ci([7, 8, 9], stat, 4, 0.5, ScriptedRng([2, 1, 0] * 4))
    assert seen == [[9, 8, 7]] * 4


def counter_stat():
    state = {"i": -1}

    def stat(xs):
        state["i"] += 1
        return state["i"]

    return stat


def test_bootstrap_index_arithmetic_including_float_edges():
    cases = [
        (0.05, 1000, 25, 974),
        (0.1, 100, 5, 94),
        (0.5, 10, 2, 7),
        (0.58, 100, 29, 70),
        (0.9, 100, 45, 54),
        (0.84, 50, 21, 28),
    ]
    for alpha, n_res, lo, hi in cases:
        assert bootstrap_ci([1, 2, 3], counter_stat(), n_res, alpha, ScriptedRng()) == (lo, hi)


def test_bootstrap_sorts_the_statistics_before_picking():
    values = iter([9, 1, 8, 2, 7, 3, 6, 4, 5, 0])
    lo, hi = bootstrap_ci([1, 2], lambda xs: next(values), 10, 0.2, ScriptedRng())
    assert (lo, hi) == (1, 8)


def test_bootstrap_constant_data_gives_a_point_interval():
    assert bootstrap_ci([3.0] * 6, mean, 50, 0.05, random.Random(0)) == (3.0, 3.0)


def test_bootstrap_of_skewed_data_is_asymmetric_and_contains_the_mean():
    data = [3, 5, 4, 9, 4, 6, 3, 5, 4, 5, 20, 4]
    lo, hi = bootstrap_ci(data, mean, 1000, 0.05, random.Random(1))
    m = mean(data)
    assert lo < m < hi
    assert hi - m > m - lo
    narrow = bootstrap_ci(data, mean, 1000, 0.5, random.Random(1))
    assert lo < narrow[0] < narrow[1] < hi


def test_bootstrap_validation():
    with pytest.raises(ValueError):
        bootstrap_ci([], mean, 10, 0.05, random.Random(0))
    with pytest.raises(ValueError):
        bootstrap_ci([1, 2], mean, 0, 0.05, random.Random(0))
    for bad in (0, 1, -0.1, 1.5):
        with pytest.raises(ValueError):
            bootstrap_ci([1, 2], mean, 10, bad, random.Random(0))


# ---- exact_permutation_test ---------------------------------------------------

def brute_force(a, b, alternative):
    pooled = list(a) + list(b)
    n, na = len(pooled), len(a)
    obs = mean(a) - mean(b)
    hits = total = 0
    for idx in combinations(range(n), na):
        chosen = set(idx)
        ta = mean([pooled[i] for i in idx])
        tb = mean([pooled[i] for i in range(n) if i not in chosen])
        t = ta - tb
        total += 1
        if alternative == "greater":
            hits += t >= obs - 1e-9
        elif alternative == "less":
            hits += t <= obs + 1e-9
        else:
            hits += abs(t) >= abs(obs) - 1e-9
    return obs, hits / total


def test_exact_permutation_known_values():
    obs, p = exact_permutation_test([1, 2, 3], [4, 5, 6])
    assert obs == pytest.approx(-3.0)
    assert p == pytest.approx(0.1)
    assert exact_permutation_test([1, 2, 3], [4, 5, 6], "less")[1] == pytest.approx(0.05)
    assert exact_permutation_test([1, 2, 3], [4, 5, 6], "greater")[1] == pytest.approx(1.0)
    assert exact_permutation_test([4, 5, 6], [1, 2, 3], "greater")[1] == pytest.approx(0.05)


def test_exact_permutation_matches_brute_force():
    pairs = [
        ([12, 15, 9, 20, 31, 11], [8, 10, 7, 11, 9, 14, 6]),
        ([1, 2, 10], [3, 4]),
        ([0.1, 0.2, 0.3, 0.7], [0.15, 0.25, 0.9]),
        ([5, 5, 6], [5, 6, 6, 6]),
    ]
    for a, b in pairs:
        for alternative in ("two-sided", "greater", "less"):
            obs, p = exact_permutation_test(a, b, alternative)
            exp_obs, exp_p = brute_force(a, b, alternative)
            assert obs == pytest.approx(exp_obs)
            assert p == pytest.approx(exp_p, abs=1e-12)


def test_exact_permutation_ties_count_as_extreme():
    assert exact_permutation_test([1, 1], [1, 1])[1] == 1.0
    assert exact_permutation_test([2, 2], [1, 1], "greater")[1] == pytest.approx(1 / 6)
    # the observed split itself is always one of the counted splits, so p is never 0
    assert exact_permutation_test([100, 101, 102], [1, 2, 3])[1] >= 1 / 20


def test_exact_permutation_float_noise_does_not_hide_ties():
    a = [0.1, 0.2, 0.3]
    b = [0.3, 0.2, 0.1]
    assert exact_permutation_test(a, b)[1] == 1.0


def test_exact_permutation_validation():
    with pytest.raises(ValueError):
        exact_permutation_test([], [1])
    with pytest.raises(ValueError):
        exact_permutation_test([1], [])
    with pytest.raises(ValueError):
        exact_permutation_test([1, 2], [3], "bigger")
    with pytest.raises(ValueError):
        # comb(21, 10) = 352,716 is just above the 200,000 limit: a missing guard fails fast, not by hanging
        exact_permutation_test(list(range(11)), list(range(10)))
    assert exact_permutation_test(list(range(9)), list(range(9)))[1] > 0


# ---- permutation_test (randomised) ---------------------------------------------

def test_permutation_scripted_shuffle_gives_the_documented_p_values():
    a, b = [1, 2, 3], [4, 5, 6]
    obs, p = permutation_test(a, b, 6, ScriptedRng())
    assert obs == pytest.approx(-3.0)
    assert p == pytest.approx(3 / 7)
    assert permutation_test(a, b, 6, ScriptedRng(), "greater")[1] == pytest.approx(1.0)
    assert permutation_test(a, b, 6, ScriptedRng(), "less")[1] == pytest.approx(2 / 7)


def test_permutation_adds_one_so_p_is_never_zero_and_shuffles_the_same_list():
    rng = ScriptedRng()
    obs, p = permutation_test([1, 2, 3], [4, 5, 6], 2, rng)
    assert p == pytest.approx(1 / 3)
    assert rng.shuffles == 2
    assert permutation_test([1, 2, 3], [4, 5, 6], 1, ScriptedRng())[1] == pytest.approx(1 / 2)


def test_permutation_does_not_change_the_inputs():
    a, b = [1, 2, 3], [4, 5, 6]
    permutation_test(a, b, 20, random.Random(0))
    assert a == [1, 2, 3] and b == [4, 5, 6]


def test_permutation_unequal_sizes_use_the_first_len_a_values():
    # pooled [10, 0, 0, 0]; a has 1 value. Rotations give a = [0], [0], [0], [10].
    obs, p = permutation_test([10], [0, 0, 0], 4, ScriptedRng(), "greater")
    assert obs == pytest.approx(10.0)
    assert p == pytest.approx(2 / 5)


def test_permutation_ties_and_float_noise_count_as_extreme():
    obs, p = permutation_test([1, 1], [1, 1], 10, random.Random(0))
    assert obs == 0 and p == 1.0
    obs, p = permutation_test([0.1, 0.2, 0.3], [0.3, 0.2, 0.1], 10, random.Random(0))
    assert p == 1.0


def test_permutation_agrees_with_the_exact_test_with_a_real_rng():
    a = [12, 15, 9, 20, 31, 11]
    b = [8, 10, 7, 11, 9, 14, 6]
    exact = exact_permutation_test(a, b)[1]
    approx = permutation_test(a, b, 4000, random.Random(3))[1]
    assert approx == pytest.approx(exact, abs=0.015)
    assert permutation_test(a, b, 4000, random.Random(3), "greater")[1] < approx
    big = permutation_test([10] * 8 + [11], [0] * 8 + [1], 999, random.Random(0))[1]
    assert big == pytest.approx(0.001, abs=0.0021)


def test_permutation_validation():
    for args in (([], [1], 5), ([1], [], 5), ([1], [2], 0)):
        with pytest.raises(ValueError):
            permutation_test(*args, ScriptedRng())
    with pytest.raises(ValueError):
        permutation_test([1], [2], 5, ScriptedRng(), "bigger")


# ---- two_proportion_ztest --------------------------------------------------------

def test_ztest_known_values():
    diff, z, p = two_proportion_ztest(1000, 10000, 1090, 10000)
    assert diff == pytest.approx(0.009)
    assert z == pytest.approx(2.0803507859630455)
    assert p == pytest.approx(0.037493369762011466)


def test_ztest_is_symmetric_in_the_arms_and_uses_the_pooled_error():
    d1, z1, p1 = two_proportion_ztest(30, 100, 45, 200)
    d2, z2, p2 = two_proportion_ztest(45, 200, 30, 100)
    assert d1 == pytest.approx(-d2) and z1 == pytest.approx(-z2) and p1 == pytest.approx(p2)
    pooled = 75 / 300
    se = math.sqrt(pooled * (1 - pooled) * (1 / 100 + 1 / 200))
    assert z1 == pytest.approx((45 / 200 - 30 / 100) / se)
    assert p1 == pytest.approx(math.erfc(abs(z1) / math.sqrt(2)))


def test_ztest_no_difference_and_extreme_difference():
    assert two_proportion_ztest(50, 100, 50, 100) == (0.0, 0.0, 1.0)
    diff, z, p = two_proportion_ztest(0, 1000, 100, 1000)
    assert diff == pytest.approx(0.1) and z > 9 and p < 1e-15


def test_ztest_validation():
    for args in ((5, 0, 1, 10), (5, 10, 1, 0), (-1, 10, 1, 10), (11, 10, 1, 10), (1, 10, -1, 10), (1, 10, 11, 10), (0, 10, 0, 10), (10, 10, 10, 10)):
        with pytest.raises(ValueError):
            two_proportion_ztest(*args)


# ---- sample size and power ---------------------------------------------------------

def test_sample_size_known_values():
    cases = [
        (0.10, 0.11, 0.05, 0.8, 14749),
        (0.10, 0.12, 0.05, 0.8, 3839),
        (0.10, 0.105, 0.05, 0.8, 57760),
        (0.30, 0.35, 0.05, 0.8, 1374),
        (0.50, 0.55, 0.01, 0.9, 2961),
        (0.40, 0.45, 0.10, 0.7, 918),
        (0.05, 0.055, 0.05, 0.8, 31231),
    ]
    for p1, p2, alpha, power, n in cases:
        assert sample_size_per_arm(p1, p2, alpha, power) == n
        assert sample_size_per_arm(p2, p1, alpha, power) == n


def test_sample_size_rounds_up_and_halving_the_lift_quadruples_it():
    assert sample_size_per_arm(0.10, 0.11) == 14749  # exact value 14748.045: round() would give 14748
    ratio = sample_size_per_arm(0.10, 0.105) / sample_size_per_arm(0.10, 0.11)
    assert 3.8 < ratio < 4.1
    assert sample_size_per_arm(0.1, 0.11, alpha=0.01) > sample_size_per_arm(0.1, 0.11)
    assert sample_size_per_arm(0.1, 0.11, power=0.9) > sample_size_per_arm(0.1, 0.11)


def test_sample_size_validation():
    for args in ((0.1, 0.1), (0, 0.1), (0.1, 1), (-0.1, 0.2), (0.1, 1.2)):
        with pytest.raises(ValueError):
            sample_size_per_arm(*args)
    for kw in ({"alpha": 0}, {"alpha": 1}, {"power": 0}, {"power": 1}):
        with pytest.raises(ValueError):
            sample_size_per_arm(0.1, 0.2, **kw)


def test_power_known_values_and_consistency_with_sample_size():
    assert power_two_proportions(0.30, 0.35, 500) == pytest.approx(0.3938436399598035, abs=1e-9)
    assert power_two_proportions(0.30, 0.35, 1374) == pytest.approx(0.8001282761077719, abs=1e-9)
    assert power_two_proportions(0.30, 0.35, 500, 0.01) == pytest.approx(0.18794784906400586, abs=1e-9)
    assert power_two_proportions(0.5, 0.51, 10) == pytest.approx(0.05022917841361774, abs=1e-9)
    for p1, p2 in ((0.1, 0.11), (0.2, 0.25), (0.5, 0.55)):
        n = sample_size_per_arm(p1, p2)
        assert power_two_proportions(p1, p2, n) >= 0.8
        assert power_two_proportions(p1, p2, n - 3) < 0.8


def test_power_with_no_effect_equals_alpha_because_both_tails_count():
    assert power_two_proportions(0.5, 0.5 + 1e-9, 100) == pytest.approx(0.05, abs=1e-6)
    assert power_two_proportions(0.5, 0.5 + 1e-9, 100, alpha=0.2) == pytest.approx(0.2, abs=1e-6)


def test_power_is_symmetric_and_grows_with_n():
    assert power_two_proportions(0.3, 0.4, 200) == pytest.approx(power_two_proportions(0.4, 0.3, 200))
    assert power_two_proportions(0.3, 0.4, 100) < power_two_proportions(0.3, 0.4, 200) < power_two_proportions(0.3, 0.4, 400)


def test_power_validation():
    for args in ((0.3, 0.4, 0), (0, 0.4, 10), (0.3, 1, 10), (0.3, 0.4, 10, 0), (0.3, 0.4, 10, 1)):
        with pytest.raises(ValueError):
            power_two_proportions(*args)


# ---- multiple comparisons -----------------------------------------------------------

def test_bonferroni():
    assert bonferroni_reject([0.01, 0.04, 0.2]) == [True, False, False]
    assert bonferroni_reject([0.0125, 0.5, 0.5, 0.5]) == [True, False, False, False]
    assert bonferroni_reject([0.05 / 3, 0.05 / 3 + 0.001, 0.9]) == [True, False, False]
    assert bonferroni_reject([0.04], 0.05) == [True]
    assert bonferroni_reject([0.02, 0.03], alpha=0.1) == [True, True]
    assert bonferroni_reject([0.02, 0.03], alpha=0.04) == [True, False]
    assert bonferroni_reject([]) == []


def test_bh_adjust_scipy_documentation_example():
    assert bh_adjust([0.5, 0.6, 0.1, 0.001]) == pytest.approx([0.6, 0.6, 0.2, 0.004])


def test_bh_adjust_enforces_monotone_adjusted_values_and_keeps_input_order():
    assert bh_adjust([0.04, 0.01, 0.03]) == pytest.approx([0.04, 0.03, 0.04])
    assert bh_adjust([0.001, 0.012, 0.018, 0.030, 0.45]) == pytest.approx([0.005, 0.03, 0.03, 0.0375, 0.45])
    assert bh_adjust([0.45, 0.030, 0.018, 0.012, 0.001]) == pytest.approx([0.45, 0.0375, 0.03, 0.03, 0.005])


def test_bh_adjust_ties_and_edges():
    assert bh_adjust([0.02, 0.02, 0.02, 0.5]) == pytest.approx([0.08 / 3] * 3 + [0.5])
    assert bh_adjust([0.9, 0.95, 1.0]) == pytest.approx([1.0, 1.0, 1.0])
    assert bh_adjust([0.3]) == pytest.approx([0.3])
    assert bh_adjust([]) == []
    adj = bh_adjust([0.2, 0.04, 0.5, 0.01, 0.03])
    assert all(a >= p for a, p in zip(adj, [0.2, 0.04, 0.5, 0.01, 0.03]))


def test_bh_reject_is_step_up_and_beats_bonferroni():
    pv = [0.001, 0.012, 0.018, 0.030, 0.45]
    assert bh_reject(pv) == [True, True, True, True, False]
    assert bonferroni_reject(pv) == [True, False, False, False, False]
    # 0.034 at rank 2 has raw value 3 x 0.034 / 2 = 0.051, but is rescued by 0.04 at rank 3
    assert bh_reject([0.001, 0.034, 0.04]) == [True, True, True]
    assert bh_reject([0.001, 0.034, 0.04], 0.02) == [True, False, False]


def test_bh_reject_boundary_and_empty():
    assert bh_reject([0.01, 0.02, 0.03, 0.04], 0.04) == [True] * 4
    assert bh_reject([0.01, 0.02, 0.03, 0.04], 0.039) == [False] * 4
    assert bh_reject([]) == []


# ---- chi-square tail and SRM ------------------------------------------------------------

def test_chi2_sf_df1_matches_the_normal_tail():
    for x in (0.01, 0.5, 1.0, 3.841459, 8.0, 32.0, 120.0):
        assert chi2_sf(x, 1) == pytest.approx(math.erfc(math.sqrt(x / 2)), rel=1e-9, abs=1e-300)


def test_chi2_sf_closed_forms_for_df_2_3_4():
    for x in (0.2, 1.0, 5.0, 20.0, 60.0):
        assert chi2_sf(x, 2) == pytest.approx(math.exp(-x / 2), rel=1e-9)
        assert chi2_sf(x, 4) == pytest.approx(math.exp(-x / 2) * (1 + x / 2), rel=1e-9)
        assert chi2_sf(x, 3) == pytest.approx(math.erfc(math.sqrt(x / 2)) + math.sqrt(2 * x / math.pi) * math.exp(-x / 2), rel=1e-9)


def test_chi2_sf_scipy_documentation_values_and_edges():
    assert chi2_sf(2.0, 5) == pytest.approx(0.849, abs=5e-4)
    assert chi2_sf(3.5, 5) == pytest.approx(0.623, abs=5e-4)
    assert chi2_sf(3.841459, 1) == pytest.approx(0.05, abs=1e-6)
    assert chi2_sf(0, 3) == 1.0
    assert chi2_sf(-2, 3) == 1.0
    assert chi2_sf(10, 3) < chi2_sf(5, 3) < chi2_sf(1, 3) < 1
    assert chi2_sf(10, 1) < chi2_sf(10, 5) < chi2_sf(10, 12)


def test_chi2_sf_validation():
    for df in (0, -1, 1.5, "2"):
        with pytest.raises(ValueError):
            chi2_sf(3.0, df)


def test_srm_check_known_values():
    stat, p = srm_check([10400, 9600], [1, 1])
    assert stat == pytest.approx(32.0)
    assert p == pytest.approx(math.erfc(4.0), rel=1e-6)
    stat, p = srm_check([520, 480], [1, 1])
    assert stat == pytest.approx(1.6)
    assert p == pytest.approx(0.2059, abs=1e-4)
    stat, p = srm_check([3400, 3300, 3300], [1, 1, 1])
    assert stat == pytest.approx(2.0)
    assert p == pytest.approx(math.exp(-1.0))


def test_srm_check_respects_unequal_designs_and_scale_of_the_ratios():
    assert srm_check([250, 750], [1, 3]) == pytest.approx((0.0, 1.0))
    assert srm_check([500, 250, 250], [2, 1, 1]) == pytest.approx((0.0, 1.0))
    assert srm_check([900, 1100], [1, 1])[0] == pytest.approx(20.0)
    assert srm_check([900, 1100], [5, 5]) == pytest.approx(srm_check([900, 1100], [1, 1]))
    stat, p = srm_check([300, 700], [1, 1])
    assert stat == pytest.approx(160.0)
    assert srm_check([700, 300], [1, 1]) == pytest.approx((stat, p))
    assert srm_check([100, 300], [1, 2])[0] == pytest.approx(((100 - 400 / 3) ** 2) / (400 / 3) + ((300 - 800 / 3) ** 2) / (800 / 3))


def test_srm_check_uses_k_minus_one_degrees_of_freedom():
    stat, p = srm_check([40, 30, 30, 20, 10], [1] * 5)
    assert stat == pytest.approx(((40 - 26) ** 2 + (30 - 26) ** 2 * 2 + (20 - 26) ** 2 + (10 - 26) ** 2) / 26)
    assert p == pytest.approx(chi2_sf(stat, 4))
    assert srm_check([16, 18, 16, 14, 12, 12], [1] * 6) == pytest.approx((2.0, 0.849), abs=5e-4)


def test_srm_check_validation():
    for args in (([10], [1]), ([5, 5], [1]), ([5, 5], [1, 1, 1]), ([-1, 5], [1, 1]), ([5, 5], [1, 0]), ([5, 5], [1, -1]), ([0, 0], [1, 1])):
        with pytest.raises(ValueError):
            srm_check(*args)


# ---- McNemar and the corrected resampled t ---------------------------------------------------

def test_mcnemar_known_values_and_continuity_correction():
    stat, p = mcnemar_test(29, 57)
    assert stat == pytest.approx(729 / 86)
    assert p == pytest.approx(0.0035971532, abs=1e-9)
    stat, p = mcnemar_test(10, 5)
    assert stat == pytest.approx(16 / 15)
    assert p == pytest.approx(0.30169958, abs=1e-7)


def test_mcnemar_is_symmetric_and_handles_ties_and_empty():
    assert mcnemar_test(5, 10) == pytest.approx(mcnemar_test(10, 5))
    assert mcnemar_test(7, 7) == (0.0, 1.0)
    assert mcnemar_test(7, 8) == (0.0, 1.0)
    assert mcnemar_test(0, 0) == (0.0, 1.0)
    stat, p = mcnemar_test(0, 12)
    assert stat == pytest.approx(121 / 12) and p < 0.002


def test_mcnemar_validation():
    for args in ((-1, 3), (3, -1)):
        with pytest.raises(ValueError):
            mcnemar_test(*args)


def test_corrected_t_known_values():
    assert corrected_resampled_t([1, 2, 3], 400, 100) == pytest.approx(2 / math.sqrt(1 / 3 + 0.25))
    diffs = [0.012, 0.020, 0.008, 0.015, 0.011, 0.018, 0.006, 0.014, 0.017, 0.009]
    assert corrected_resampled_t(diffs, 900, 100) == pytest.approx(6.16, abs=0.005)


def test_corrected_t_is_smaller_than_the_naive_t_and_signed():
    diffs = [0.5, 1.5, 1.0, 2.0, 0.0]
    k = len(diffs)
    m = mean(diffs)
    s2 = sum((d - m) ** 2 for d in diffs) / (k - 1)
    naive = m / math.sqrt(s2 / k)
    corr = corrected_resampled_t(diffs, 80, 20)
    assert 0 < corr < naive
    assert corrected_resampled_t([-d for d in diffs], 80, 20) == pytest.approx(-corr)
    assert corrected_resampled_t(diffs, 80, 20) > corrected_resampled_t(diffs, 80, 40)


def test_corrected_t_validation():
    for args in (([1.0], 10, 10), ([], 10, 10), ([1, 2], 0, 10), ([1, 2], 10, 0), ([2, 2, 2], 10, 10)):
        with pytest.raises(ValueError):
            corrected_resampled_t(*args)


def test_permutation_float_noise_in_the_comparison_is_tolerated():
    # Two of the six rotations give the same mean difference up to rounding error.
    obs, p = permutation_test([0.3, 0.3, 0.2], [0.9, 0.1, 0.4], 6, ScriptedRng())
    assert p == pytest.approx(5 / 7)