"""Larsen and Marx (2018), Chapter 9: Two-Sample Inferences.

Companion code for Chapter 9 of R. J. Larsen and M. L. Marx, An Introduction to Mathematical Statistics
and Its Applications, 6th edition (Pearson, 2018), written from scratch with numpy, scipy and matplotlib. The
functions are short and meant to be read next to the lecture notes (../ch09-two-sample-inference.html):

* Section 9.2, testing H0: mu_X = mu_Y: pooled_t and pooled_t_summary (Theorems 9.2.1 and 9.2.2), welch_t_summary and
  welch_nu_theta (Theorem 9.2.3, in the book's theta form and in Satterthwaite's form), glr_pooled (equation
  9.A.1.5), pooled_tau and pooled_size_limit (when the pooled test is robust), power_pooled_t (non-central t) and
  the three case studies.
* Section 9.3, the F test: f_test, f_crit, glr_var (the likelihood ratio of Question 9.3.9 as a function of
  the variance ratio), glr_var_cutoffs (the exact likelihood-ratio cut-offs, which differ slightly from the
  equal-tailed ones of Theorem 9.3.1) and f_size_kurtosis (the F test is not robust).
* Section 9.4, two binomial samples: two_prop_z (Theorem 9.4.1), two_prop_G (equation 9.4.1, -2 ln lambda) and
  pearson_x2 (z squared is Pearson's chi-squared statistic of the 2 x 2 table).
* Section 9.5, confidence intervals: ci_pooled, ci_welch, ci_var_ratio, ci_prop_diff (Theorems 9.5.1 to 9.5.3) and
  ci_agresti_caffo (the "add one success and one failure to each sample" repair of the Wald interval).
* Section 9.6, choosing samples: randomization_variance (the exact variance of the difference of means under
  random assignment), n_per_group (the sample size for a given power) and neyman_allocation.
* Browser demonstrations: demo_reference() exports the exact numbers that f-test-variances-demo.html and
  random-assignment-demo.html show (../data/ch09-demos.json).

Figures. The book has six numbered figures in Chapter 9. Those computed from data or from a model are reproduced:
9.2.1 (the Student t critical region of Case Study 9.2.1), 9.3.2 (the alpha-wave frequencies of Case Study 9.3.1)
and 9.3.3 (the F critical region of that case study). Skipped, with reasons: 9.3.1 (a schematic of two machines
and engineering specifications) and 9.6.1 (a screen shot of a statistical package's SAMPLE command; the random
split of twenty rats is made by random_split with a seeded generator instead). Three figures of our own
illustrate the chapter: x9.1, the true size of the pooled test, the Welch test and the "F test first, then t test"
procedure when the variances differ; x9.2, the true size of the F test for equal variances when the data are not
normal, with the asymptotic formula; x9.3, the exact coverage of the interval of Theorem 9.5.3 and of the
Agresti-Caffo repair when the two success probabilities are equal.
Run `python3 ch09_two_sample_inference.py --list`, `python3 ch09_two_sample_inference.py` (all figures, about 40 s)
or `python3 ch09_two_sample_inference.py --fig 9.3.3`. Files go to ../img/ch09/.
"""
import json
import math
import os

import numpy as np
from scipy import optimize, stats

import common
from common import BLUE, GREEN, GREY, MAGENTA, ORANGE, PURPLE, RED, book_data, savefig
import matplotlib.pyplot as plt

CH = 9
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))
N01 = stats.norm
T = book_data("ch09-tables")


# =========================================================================== Section 9.2
def pooled_t_summary(n, xbar, sx, m, ybar, sy):
    """Theorem 9.2.2: the pooled standard deviation s_p, the ratio t and its degrees of freedom."""
    df = n + m - 2
    sp = math.sqrt(((n - 1) * sx ** 2 + (m - 1) * sy ** 2) / df)
    return sp, (xbar - ybar) / (sp * math.sqrt(1 / n + 1 / m)), df


def pooled_t(x, y):
    """(s_p, t, df) from two raw samples."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    return pooled_t_summary(len(x), x.mean(), x.std(ddof=1), len(y), y.mean(), y.std(ddof=1))


def t_pvalue(t, df, side="two"):
    """P-value of a t ratio: 'two', 'greater' (H1: mu_X > mu_Y) or 'less'."""
    if side == "greater":
        return stats.t.sf(t, df)
    if side == "less":
        return stats.t.cdf(t, df)
    return 2 * stats.t.sf(abs(t), df)


def welch_nu_theta(theta, n, m):
    """The degrees of freedom of Theorem 9.2.3 (before rounding) as a function of theta = s_X^2 / s_Y^2."""
    return (theta + n / m) ** 2 / (theta ** 2 / (n - 1) + (n / m) ** 2 / (m - 1))


def welch_nu(sx2, n, sy2, m):
    """Satterthwaite's form of the same number: (a + b)^2 / (a^2/(n-1) + b^2/(m-1)), a = s_X^2/n, b = s_Y^2/m."""
    a, b = sx2 / n, sy2 / m
    return (a + b) ** 2 / (a * a / (n - 1) + b * b / (m - 1))


def welch_t_summary(n, xbar, sx, m, ybar, sy):
    """Theorem 9.2.3: (w, nu unrounded). The book rounds nu to the nearest integer for its tables."""
    w = (xbar - ybar) / math.sqrt(sx ** 2 / n + sy ** 2 / m)
    return w, welch_nu(sx ** 2, n, sy ** 2, m)


def glr_pooled(x, y):
    """The likelihood ratio of Appendix 9.A.1, lambda^{2/(n+m)} = (n+m-2) / (n+m-2+t^2) (equation 9.A.1.5), computed
    directly from the two maximised likelihoods."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    n, m = len(x), len(y)
    allv = np.concatenate([x, y])
    s_om = ((allv - allv.mean()) ** 2).sum() / (n + m)
    s_Om = (((x - x.mean()) ** 2).sum() + ((y - y.mean()) ** 2).sum()) / (n + m)
    return (s_Om / s_om) ** ((n + m) / 2)


def pooled_tau(sx2, sy2, lam):
    """Asymptotic variance of the pooled t ratio under H0 when n/(n+m) -> lam (Filling the gap 9.4):
    tau = ((1-lam) sigma_X^2 + lam sigma_Y^2) / (lam sigma_X^2 + (1-lam) sigma_Y^2). tau = 1 if lam = 1/2."""
    return ((1 - lam) * sx2 + lam * sy2) / (lam * sx2 + (1 - lam) * sy2)


def pooled_size_limit(sx2, sy2, lam, alpha=0.05):
    """Limiting size of the two-sided pooled t test of nominal level alpha: 2 (1 - Phi(z_{alpha/2} / sqrt(tau)))."""
    return 2 * N01.sf(N01.isf(alpha / 2) / math.sqrt(pooled_tau(sx2, sy2, lam)))


def power_pooled_t(delta, n, m, alpha=0.05, side="two"):
    """Exact power of the pooled t test (non-central t). delta = (mu_X - mu_Y) / sigma."""
    df = n + m - 2
    nc = delta / math.sqrt(1 / n + 1 / m)
    if side == "two":
        c = stats.t.isf(alpha / 2, df)
        return stats.nct.sf(c, df, nc) + stats.nct.cdf(-c, df, nc)
    c = stats.t.isf(alpha, df)
    return stats.nct.sf(c, df, nc) if side == "greater" else stats.nct.cdf(-c, df, nc)


def sim_size_t(n, m, sx, sy, reps=20000, seed=9, alpha=0.05, pretest=False):
    """Simulated rejection rates under H0 (equal means) of the pooled t test, the Welch test and, optionally,
    the two-stage rule 'F test at level alpha first; if it rejects use Welch, otherwise pooled'."""
    rng = np.random.default_rng(seed)
    x = rng.standard_normal((reps, n)) * sx
    y = rng.standard_normal((reps, m)) * sy
    vx, vy = x.var(axis=1, ddof=1), y.var(axis=1, ddof=1)
    d = x.mean(axis=1) - y.mean(axis=1)
    sp2 = ((n - 1) * vx + (m - 1) * vy) / (n + m - 2)
    tp = d / np.sqrt(sp2 * (1 / n + 1 / m))
    rp = np.abs(tp) >= stats.t.isf(alpha / 2, n + m - 2)
    a, b = vx / n, vy / m
    nu = (a + b) ** 2 / (a * a / (n - 1) + b * b / (m - 1))
    rw = np.abs(d / np.sqrt(a + b)) >= stats.t.isf(alpha / 2, nu)
    out = [rp.mean(), rw.mean()]
    if pretest:
        F = vy / vx
        rej_f = (F <= stats.f.ppf(alpha / 2, m - 1, n - 1)) | (F >= stats.f.ppf(1 - alpha / 2, m - 1, n - 1))
        out.append(np.where(rej_f, rw, rp).mean())
    return out


# =========================================================================== Section 9.3
def f_test(sx2, n, sy2, m, alpha=0.05):
    """Theorem 9.3.1(c): the ratio F = s_Y^2 / s_X^2, the equal-tailed cut-offs (F_{alpha/2,m-1,n-1},
    F_{1-alpha/2,m-1,n-1}) and the two-sided P-value 2 min(P(F' <= F), P(F' >= F))."""
    F = sy2 / sx2
    lo, hi = stats.f.ppf([alpha / 2, 1 - alpha / 2], m - 1, n - 1)
    p = 2 * min(stats.f.cdf(F, m - 1, n - 1), stats.f.sf(F, m - 1, n - 1))
    return F, lo, hi, min(1.0, p)


def f_crit(p, dfn, dfd):
    """F_{p,dfn,dfd}: the number with area p to its LEFT under the F(dfn, dfd) density (the book's notation)."""
    return stats.f.ppf(p, dfn, dfd)


def _log_glr_var(u, n, m):
    """ln lambda as a function of u = ln r."""
    logc = (n + m) / 2 * math.log(n + m) - n / 2 * math.log(n) - m / 2 * math.log(m)
    return logc + m / 2 * u - (n + m) / 2 * np.logaddexp(0.0, u)


def glr_var(r, n, m):
    """Likelihood ratio of Question 9.3.9 as a function of r = sum (y-ybar)^2 / sum (x-xbar)^2:
    lambda(r) = (n+m)^{(n+m)/2} / (n^{n/2} m^{m/2}) * r^{m/2} / (1+r)^{(n+m)/2}. It is 1 at r = m/n."""
    return np.exp(_log_glr_var(np.log(np.asarray(r, float)), n, m))


def glr_var_cutoffs(n, m, alpha=0.05):
    """The exact generalized-likelihood-ratio cut-offs (r1, r2) for r = B/A: lambda(r1) = lambda(r2) and
    P(r1 < r < r2) = 1 - alpha under H0, found numerically. Returned in F units, F = r (n-1)/(m-1)."""
    k = (n - 1) / (m - 1)
    u0 = math.log(m / n)
    prob = lambda u: stats.f.cdf(math.exp(u) * k, m - 1, n - 1)

    def right_of(u1):
        target = _log_glr_var(u1, n, m)
        return optimize.brentq(lambda u: _log_glr_var(u, n, m) - target, u0, u0 + 400)

    def excess(u1):
        return prob(u1) + (1 - prob(right_of(u1))) - alpha

    u1 = optimize.brentq(excess, u0 - 12, u0 - 1e-3)
    return math.exp(u1) * k, math.exp(right_of(u1)) * k


def f_size_kurtosis(kappa, alpha=0.05):
    """Asymptotic size of the two-sided F test when both samples have fourth standardised moment kappa (normal: 3):
    2 (1 - Phi(z_{alpha/2} sqrt(2/(kappa-1)))) (Filling the gap 9.11)."""
    return 2 * N01.sf(N01.isf(alpha / 2) * math.sqrt(2 / (kappa - 1)))


def draw_standardised(rng, shape, size):
    """Mean 0, variance 1 samples with a given shape: normal, uniform, laplace, t5, expo (centred exponential)."""
    if shape == "normal":
        return rng.standard_normal(size)
    if shape == "uniform":
        return (rng.random(size) - 0.5) * math.sqrt(12)
    if shape == "laplace":
        return rng.laplace(size=size) / math.sqrt(2)
    if shape == "t5":
        return rng.standard_t(5, size) * math.sqrt(3 / 5)
    if shape == "expo":
        return rng.exponential(size=size) - 1
    raise ValueError(shape)


KAPPA = {"normal": 3.0, "uniform": 1.8, "laplace": 6.0, "t5": 9.0, "expo": 9.0}


def sim_f_size(shape, n, m, ratio=1.0, reps=40000, alpha=0.05, seed=93):
    """Simulated rejection rate of the F test of Theorem 9.3.1(c) when sigma_Y / sigma_X = ratio."""
    rng = np.random.default_rng(seed)
    vx = draw_standardised(rng, shape, (reps, n)).var(axis=1, ddof=1)
    vy = (ratio * draw_standardised(rng, shape, (reps, m))).var(axis=1, ddof=1)
    F = vy / vx
    return float(((F <= stats.f.ppf(alpha / 2, m - 1, n - 1)) | (F >= stats.f.ppf(1 - alpha / 2, m - 1, n - 1))).mean())


def f_power_normal(ratio, n, m, alpha=0.05):
    """Exact power of the F test for normal data when sigma_Y^2 / sigma_X^2 = ratio^2."""
    lo, hi = stats.f.ppf([alpha / 2, 1 - alpha / 2], m - 1, n - 1)
    th = ratio ** 2
    return stats.f.cdf(lo / th, m - 1, n - 1) + stats.f.sf(hi / th, m - 1, n - 1)


# =========================================================================== Section 9.4
def two_prop_z(x, n, y, m):
    """Theorem 9.4.1: z with the pooled estimate pe = (x + y)/(n + m)."""
    pe = (x + y) / (n + m)
    return (x / n - y / m) / math.sqrt(pe * (1 - pe) * (1 / n + 1 / m))


def _xlogx(a, b):
    return 0.0 if a == 0 else a * math.log(a / b)


def two_prop_G(x, n, y, m):
    """-2 ln lambda for equation (9.4.1): twice the sum over the four cells of O ln(O/E)."""
    pe = (x + y) / (n + m)
    cells = [(x, n * pe), (n - x, n * (1 - pe)), (y, m * pe), (m - y, m * (1 - pe))]
    return 2 * sum(_xlogx(o, e) for o, e in cells)


def pearson_x2(x, n, y, m):
    """Pearson's chi-squared statistic of the 2 x 2 table (it equals z squared exactly)."""
    pe = (x + y) / (n + m)
    cells = [(x, n * pe), (n - x, n * (1 - pe)), (y, m * pe), (m - y, m * (1 - pe))]
    return sum((o - e) ** 2 / e for o, e in cells)


def two_prop_exact_size(n, m, p, alpha=0.05, kind="z"):
    """Exact size of the two-sided pooled z test (kind='z') at p_X = p_Y = p, by enumerating all (x, y)."""
    xs, ys = np.meshgrid(np.arange(n + 1), np.arange(m + 1), indexing="ij")
    pe = (xs + ys) / (n + m)
    with np.errstate(divide="ignore", invalid="ignore"):
        z = (xs / n - ys / m) / np.sqrt(pe * (1 - pe) * (1 / n + 1 / m))
    z = np.where(np.isfinite(z), z, 0.0)
    w = np.outer(stats.binom.pmf(np.arange(n + 1), n, p), stats.binom.pmf(np.arange(m + 1), m, p))
    return float(w[np.abs(z) >= N01.isf(alpha / 2)].sum())


# =========================================================================== Section 9.5
def ci_pooled(n, xbar, sx, m, ybar, sy, level=0.95):
    """Theorem 9.5.1."""
    sp, _, df = pooled_t_summary(n, xbar, sx, m, ybar, sy)
    h = stats.t.isf((1 - level) / 2, df) * sp * math.sqrt(1 / n + 1 / m)
    return xbar - ybar - h, xbar - ybar + h


def ci_welch(n, xbar, sx, m, ybar, sy, level=0.95, rounded_df=False):
    """The comment after Theorem 9.5.1 (unequal variances); rounded_df follows the book's rounding of nu."""
    nu = welch_nu(sx ** 2, n, sy ** 2, m)
    if rounded_df:
        nu = round(nu)
    h = stats.t.isf((1 - level) / 2, nu) * math.sqrt(sx ** 2 / n + sy ** 2 / m)
    return xbar - ybar - h, xbar - ybar + h


def ci_var_ratio(sx2, n, sy2, m, level=0.95):
    """Theorem 9.5.2: (s_X^2/s_Y^2 F_{a/2,m-1,n-1}, s_X^2/s_Y^2 F_{1-a/2,m-1,n-1})."""
    a = 1 - level
    r = sx2 / sy2
    return r * stats.f.ppf(a / 2, m - 1, n - 1), r * stats.f.ppf(1 - a / 2, m - 1, n - 1)


def ci_prop_diff(x, n, y, m, level=0.95):
    """Theorem 9.5.3 (the Wald interval for p_X - p_Y)."""
    px, py = x / n, y / m
    h = N01.isf((1 - level) / 2) * math.sqrt(px * (1 - px) / n + py * (1 - py) / m)
    return px - py - h, px - py + h


def ci_agresti_caffo(x, n, y, m, level=0.95):
    """Add one success and one failure to each sample, then use the Wald formula (Agresti and Caffo, 2000)."""
    return ci_prop_diff(x + 1, n + 2, y + 1, m + 2, level)


def exact_coverage_diff(n, m, p, q, level=0.95, kind="wald"):
    """Exact probability that the interval for p_X - p_Y covers the true difference p - q (full enumeration)."""
    xs, ys = np.meshgrid(np.arange(n + 1), np.arange(m + 1), indexing="ij")
    a, b, nn, mm = (xs + 1, ys + 1, n + 2, m + 2) if kind == "ac" else (xs, ys, n, m)
    px, py = a / nn, b / mm
    h = N01.isf((1 - level) / 2) * np.sqrt(px * (1 - px) / nn + py * (1 - py) / mm)
    d = px - py
    w = np.outer(stats.binom.pmf(np.arange(n + 1), n, p), stats.binom.pmf(np.arange(m + 1), m, q))
    return float(w[(d - h <= p - q) & (p - q <= d + h)].sum())


# =========================================================================== Section 9.6
def randomization_variance(u, n):
    """Exact variance of (mean of the n units drawn into group X) - (mean of the other m) when all C(N, n) splits of
    the fixed numbers u are equally likely: S^2 (1/n + 1/m), with S^2 the divisor-(N-1) variance of u."""
    u = np.asarray(u, float)
    m = len(u) - n
    return u.var(ddof=1) * (1 / n + 1 / m)


def n_per_group(delta, alpha=0.05, power=0.9, side="two"):
    """Smallest n = m for which the pooled t test has the given power against delta = (mu_X - mu_Y)/sigma
    (exact, non-central t); also returns the normal approximation 2 (z_a + z_b)^2 / delta^2."""
    za = N01.isf(alpha / 2 if side == "two" else alpha)
    approx = 2 * ((za + N01.isf(1 - power)) / delta) ** 2
    n = max(2, int(math.floor(approx * 0.8)))
    while power_pooled_t(delta, n, n, alpha, side) < power:
        n += 1
    return n, approx


def neyman_allocation(N, sx, sy):
    """Group sizes minimising Var(Xbar - Ybar) = sx^2/n + sy^2/m for n + m = N (n proportional to sigma_X)."""
    n = N * sx / (sx + sy)
    return n, N - n


def sim_assignment(scores, beta, delta, reps=40000, seed=11, n=10, alpha=0.05):
    """Twenty rats, treatment effect delta on the aggression score. The experimenter picks n rats for treatment one at a
    time, each remaining rat with probability proportional to exp(-beta z_i), z_i the standardised score (beta = 0 is a
    random split; beta > 0 avoids the aggressive rats). Returns the mean and SD of xbar - ybar and the rejection rate
    of the two-sided pooled t test at level alpha."""
    sc = np.asarray(scores, float)
    z = (sc - sc.mean()) / sc.std(ddof=1)
    rng = np.random.default_rng(seed)
    key = -np.log(rng.random((reps, len(sc)))) / np.exp(-beta * z)        # Efraimidis-Spirakis keys
    sel = np.argsort(key, axis=1)[:, :n]
    mask = np.zeros((reps, len(sc)), bool)
    np.put_along_axis(mask, sel, True, axis=1)
    y = sc[None, :] + delta * mask
    m = len(sc) - n
    xs = np.where(mask, y, np.nan)
    ys = np.where(~mask, y, np.nan)
    xb, yb = np.nanmean(xs, axis=1), np.nanmean(ys, axis=1)
    vx, vy = np.nanvar(xs, axis=1, ddof=1), np.nanvar(ys, axis=1, ddof=1)
    sp2 = ((n - 1) * vx + (m - 1) * vy) / (n + m - 2)
    t = (xb - yb) / np.sqrt(sp2 * (1 / n + 1 / m))
    return float((xb - yb).mean()), float((xb - yb).std()), float((np.abs(t) >= stats.t.isf(alpha / 2, n + m - 2)).mean())


def random_split(N, n, seed):
    """A seeded random subset of n of the labels 1..N (the book's Figure 9.6.1 does this with a package)."""
    return sorted(int(v) + 1 for v in np.random.default_rng(seed).choice(N, n, replace=False))


# =========================================================================== case studies and questions
def case_study_numbers():
    """The numbers of Case Studies 9.2.1 to 9.5.3 recomputed from the printed tables (or printed summaries)."""
    out = {}
    tw, qc = T["cs921_twain"], T["cs921_qcs"]
    out["cs921"] = pooled_t(tw, qc)
    out["cs922a"] = pooled_t_summary(229, 2.14, .94, 243, 4.21, .83)
    out["cs922b"] = pooled_t_summary(229, 3.61, .84, 243, 4.05, .95)
    lg, sm = np.array(T["cs923_large"], float), np.array(T["cs923_small"], float)
    out["cs923"] = welch_t_summary(12, lg.mean(), lg.std(ddof=1), 12, sm.mean(), sm.std(ddof=1))
    nc, so = np.array(T["cs931_nonconfined"]), np.array(T["cs931_solitary"])
    out["cs931"] = f_test(nc.var(ddof=1), 10, so.var(ddof=1), 10)
    ma, fe = np.array(T["cs951_male"]), np.array(T["cs951_female"])
    out["cs951"] = ci_pooled(8, ma.mean(), ma.std(ddof=1), 8, fe.mean(), fe.std(ddof=1))
    g3, g5 = np.array(T["cs952_three"]), np.array(T["cs952_five"])
    out["cs952"] = ci_var_ratio(g3.var(ddof=1), 7, g5.var(ddof=1), 5)
    out["cs941"] = two_prop_z(34, 40, 19, 35)
    out["cs942"] = two_prop_z(55, 160, 60, 192)
    out["cs953"] = ci_prop_diff(11604, 58593, 4139, 28155)
    return out


# =========================================================================== figures
def fig_9_2_1(out=None):
    """Figure 9.2.1: the two-sided 0.01 Student t region (16 df) and the observed t = 3.88 of Case Study 9.2.1."""
    t = np.linspace(-5, 5, 800)
    c = stats.t.isf(0.005, 16)
    _, tobs, _ = pooled_t(T["cs921_twain"], T["cs921_qcs"])
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.plot(t, stats.t.pdf(t, 16), color=BLUE)
    for s in (1, -1):
        tt = t[s * t >= c]
        ax.fill_between(tt, stats.t.pdf(tt, 16), color=RED, alpha=.4)
    ax.axvline(tobs, color=GREEN, lw=1.6)
    ax.text(tobs - 0.1, 0.30, "observed\n$t=%.2f$" % tobs, color=GREEN, fontsize=8.5, ha="right")
    ax.text(c + 0.1, 0.03, "0.005", color=RED, fontsize=8.5); ax.text(-c - 0.1, 0.03, "0.005", color=RED, fontsize=8.5, ha="right")
    ax.text(2.4, 0.11, "reject $H_0$", color=RED, fontsize=8.5); ax.text(-3.0, 0.11, "reject $H_0$", color=RED, fontsize=8.5, ha="right")
    ax.set_xticks([-c, 0, c]); ax.set_xticklabels(["$-2.9208$", "0", "2.9208"])
    ax.set_xlabel("t (Student, 16 df)"); ax.set_ylabel("density"); ax.set_xlim(-5, 5); ax.set_ylim(0, 0.42)
    savefig(fig, CH, "fig9-2-1", out)


def fig_9_3_2(out=None):
    """Figure 9.3.2: alpha-wave frequencies of the nonconfined and the solitary-confinement prisoners."""
    nc, so = T["cs931_nonconfined"], T["cs931_solitary"]
    fig, ax = plt.subplots(figsize=(5.2, 2.5))
    for row, (v, lab, col) in enumerate(((so, "Solitary", RED), (nc, "Nonconfined", BLUE))):
        v = np.array(v)
        # stack equal values so that every dot is visible
        levels = {}
        ys = []
        for a in v:
            k = round(a, 1)
            levels[k] = levels.get(k, 0) + 1
            ys.append(row + 0.11 * (levels[k] - 1) + 0.1)
        ax.plot(v, ys, "o", color=col, ms=5.5, alpha=.85)
        ax.plot([v.mean()], [row - 0.12], marker="^", color=col, ms=7)
    ax.set_yticks([0.15, 1.15]); ax.set_yticklabels(["Solitary\nconfinement", "Nonconfined"]); ax.set_ylim(-0.3, 1.75)
    ax.set_xlabel("alpha-wave frequency (cps)"); ax.set_xlim(8.8, 11.4); ax.grid(axis="x", alpha=.25)
    ax.text(11.35, -0.22, "triangles: sample means", fontsize=7.5, ha="right", color=GREY)
    savefig(fig, CH, "fig9-3-2", out)


def fig_9_3_3(out=None):
    """Figure 9.3.3: the F(9, 9) density, its 0.025 tails and the observed ratio 1.70 of Case Study 9.3.1."""
    F, lo, hi, _ = case_study_numbers()["cs931"]
    x = np.linspace(0.001, 6.5, 800)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.plot(x, stats.f.pdf(x, 9, 9), color=BLUE)
    for a, b in ((0.001, lo), (hi, 6.5)):
        xx = x[(x >= a) & (x <= b)]
        ax.fill_between(xx, stats.f.pdf(xx, 9, 9), color=RED, alpha=.4)
    ax.axvline(F, color=GREEN, lw=1.6); ax.text(F + 0.1, 0.80, "observed\n$F=%.2f$" % F, color=GREEN, fontsize=8.5)
    ax.annotate("0.025", xy=(0.18, 0.12), xytext=(1.05, 0.08), color=RED, fontsize=8.5, arrowprops=dict(arrowstyle="->", color=RED))
    ax.text(hi + 0.1, 0.07, "0.025", color=RED, fontsize=8.5)
    ax.set_xticks([lo, 1, 2, 3, hi, 5, 6]); ax.set_xticklabels(["%.3f" % lo, "1", "2", "3", "%.2f" % hi, "5", "6"])
    ax.set_xlabel("$s_Y^2/s_X^2$ ($F$ with 9 and 9 df under $H_0$)"); ax.set_ylabel("density"); ax.set_xlim(0, 6.5); ax.set_ylim(0, 1.0)
    savefig(fig, CH, "fig9-3-3", out)


def fig_x9_1(out=None):
    """Own figure: true size of the pooled t test, Welch's test and 'F test first' when the standard deviations differ."""
    ratios = np.array([1 / 4, 1 / 3, 1 / 2, 1 / 1.5, 1, 1.5, 2, 3, 4])
    fig, axes = common.panel_grid(1, 2, size=(3.7, 3.0))
    for ax, (n, m, lab) in zip(axes[0], ((30, 10, "n = 30, m = 10"), (10, 10, "n = m = 10"))):
        res = np.array([sim_size_t(n, m, 1.0, r, reps=20000, pretest=True) for r in ratios])
        ax.plot(ratios, res[:, 0], "-o", color=RED, ms=3.5, label="pooled t")
        ax.plot(ratios, res[:, 1], "-s", color=BLUE, ms=3.5, label="Welch")
        ax.plot(ratios, res[:, 2], "-^", color=GREEN, ms=3.5, label="F test, then t")
        ax.axhline(0.05, color="k", lw=.8, ls=":")
        ax.set_xscale("log"); ax.set_xticks([0.25, 0.5, 1, 2, 4]); ax.set_xticklabels(["1/4", "1/2", "1", "2", "4"])
        ax.set_xlabel("$\\sigma_Y/\\sigma_X$"); ax.set_ylim(0, 0.45); ax.grid(alpha=.25); ax.set_title(lab, fontsize=9)
    axes[0, 0].set_ylabel("rejection rate when $\\mu_X=\\mu_Y$"); axes[0, 0].legend(fontsize=7.5, loc="upper center")
    common.panel_label(axes[0, 0], "a", "upper left"); common.panel_label(axes[0, 1], "b", "upper left")
    fig.tight_layout()
    savefig(fig, CH, "figx9-1", out)


def fig_x9_2(out=None):
    """Own figure: the true size of the nominal 5% F test for equal variances when the data are not normal."""
    shapes = ["uniform", "normal", "laplace", "t5"]
    names = ["uniform\n($\\kappa=1.8$)", "normal\n($\\kappa=3$)", "Laplace\n($\\kappa=6$)", "$t_5$\n($\\kappa=9$)"]
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    xs = np.arange(4)
    for off, (n, col) in zip((-0.2, 0.2), ((10, ORANGE), (50, BLUE))):
        ax.bar(xs + off, [sim_f_size(s, n, n, reps=30000) for s in shapes], width=0.38, color=col, label="n = m = %d" % n)
    ax.plot(xs, [f_size_kurtosis(KAPPA[s]) for s in shapes], "k_", ms=22, mew=1.6, label="limit as $n\\to\\infty$")
    ax.axhline(0.05, color="k", lw=.8, ls=":")
    ax.set_xticks(xs); ax.set_xticklabels(names, fontsize=8); ax.set_ylabel("rejection rate when $\\sigma_X=\\sigma_Y$"); ax.set_ylim(0, 0.42)
    ax.legend(fontsize=8, loc="upper left")
    savefig(fig, CH, "figx9-2", out)


def fig_x9_3(out=None):
    """Own figure: exact coverage of the 95% interval of Theorem 9.5.3 and of the Agresti-Caffo repair, p_X = p_Y = p."""
    p = np.linspace(0.02, 0.98, 481)
    fig, axes = common.panel_grid(1, 2, size=(3.7, 3.0))
    for ax, n, lab in zip(axes[0], (20, 100), ("n = m = 20", "n = m = 100")):
        ax.plot(p, [exact_coverage_diff(n, n, v, v) for v in p], color=RED, lw=.9, label="Theorem 9.5.3")
        ax.plot(p, [exact_coverage_diff(n, n, v, v, kind="ac") for v in p], color=BLUE, lw=.9, label="Agresti-Caffo")
        ax.axhline(0.95, color="k", lw=.8, ls=":")
        ax.set_ylim(0.76, 1.0); ax.set_xlabel("$p_X=p_Y=p$"); ax.set_title(lab, fontsize=9); ax.grid(alpha=.25)
    axes[0, 0].set_ylabel("exact coverage of the 95% interval"); axes[0, 0].legend(fontsize=7.5, loc="lower center")
    common.panel_label(axes[0, 0], "a", "upper left"); common.panel_label(axes[0, 1], "b", "upper left")
    fig.tight_layout()
    savefig(fig, CH, "figx9-3", out)


# =========================================================================== demo reference numbers
RAT_SCORES = [round(v, 1) for v in np.random.default_rng(906).normal(50, 10, 20)]


def demo_reference():
    """Exact or large-simulation numbers shown by the two demonstrations (the same formulas run in the browser)."""
    out = {}
    f = {}
    for key, (n, m) in {"10-10": (10, 10), "20-20": (20, 20), "10-30": (10, 30)}.items():
        lo, hi = stats.f.ppf([.025, .975], m - 1, n - 1)
        f[key] = dict(lo=float(lo), hi=float(hi),
                      power_normal={str(r): float(f_power_normal(r, n, m)) for r in (1, 1.5, 2, 3)},
                      size={s: sim_f_size(s, n, m, reps=200000, seed=7) for s in ("normal", "uniform", "laplace", "t5", "expo")})
    out["ftest"] = f
    out["ftest_limit"] = {s: f_size_kurtosis(KAPPA[s]) for s in KAPPA}
    sc = np.array(RAT_SCORES)
    out["rats"] = dict(scores=RAT_SCORES, mean=float(sc.mean()), S=float(sc.std(ddof=1)),
                       sd_diff=math.sqrt(randomization_variance(sc, 10)), splits=math.comb(20, 10))
    sim = {}
    for beta in (0, 0.25, 0.5, 1):
        for delta in (0, 10):
            mu, sd, rej = sim_assignment(RAT_SCORES, beta, delta, reps=100000)
            sim["%s_%s" % (beta, delta)] = dict(mean=mu, sd=sd, reject=rej)
    out["rats"]["sim"] = sim
    return out


def export_json():
    os.makedirs(DATA_OUT, exist_ok=True)
    path = os.path.join(DATA_OUT, "ch09-demos.json")
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(demo_reference(), fh, indent=1)
    print("wrote", os.path.relpath(path, os.getcwd()))


FIGURES = {
    "9.2.1": fig_9_2_1, "9.3.2": fig_9_3_2, "9.3.3": fig_9_3_3,
    "x9.1": fig_x9_1, "x9.2": fig_x9_2, "x9.3": fig_x9_3,
}

if __name__ == "__main__":
    import sys
    common.run(FIGURES, CH)
    if len(sys.argv) == 1:
        export_json()
