"""Larsen and Marx (2018), Chapter 12: The Analysis of Variance.

Companion code for Chapter 12 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 (../ch12-analysis-of-variance.html):

* Section 12.2, the F test: anova_oneway and anova_summary (the sums of squares, mean squares, F and P of
  Theorems 12.2.1 to 12.2.5 from raw data or from means, standard deviations and sizes), computing_formulas
  (equations 12.2.4 and 12.2.5), expected_ss (Theorem 12.2.1), glr_lambda (the F test as a likelihood ratio
  test), sim_f_ratio (Monte Carlo of the F ratio under H0 and H1) and the case studies.
* Appendix 12.A.2, the F ratio under H1: noncentrality (the parameter gamma of Theorem 12.A.2.2), nc_chi2_mgf
  (Theorem 12.A.2.1), power_f (power from the noncentral F law), power_balanced, sample_size_balanced.
* Section 12.3, Tukey's method: range_cdf and studentized_cdf (the Studentized range law of Definition 12.3.1,
  written as one-dimensional integrals), q_crit (the entries of the book's Table A.5), tukey_intervals (Theorem
  12.3.1, with the Tukey-Kramer extension for unequal sizes), tukey_groups (the underlining of Figure 12.3.2),
  fwer_all_pairs (the exact familywise error rate of unadjusted, Bonferroni and Tukey pairwise tests) and
  sim_fwer (the same by simulation).
* Section 12.4, contrasts: contrast_test (Definition 12.4.2, Theorem 12.4.2), helmert_contrasts (k - 1 mutually
  orthogonal contrasts for any sizes, Theorem 12.4.1), scheffe_crit and the three critical values compared.
* Section 12.5, data transformations: var_stab_sd (exact standard deviation of sqrt(Y), sqrt(Y + 3/8) and the
  arcsine transform of Poisson and binomial counts), f_size_unequal (the size of the F test when the variances
  differ).
* Browser demonstrations: demo_reference() exports the numbers that anova-f-test-demo.html and
  tukey-multiple-comparisons-demo.html show (../data/ch12-demos.json).

Figures. The book has seven numbered figures in Chapter 12. Reproduced: 12.2.2 (the F critical region of Case
Study 12.2.1), 12.3.1 (the Studentized range density Q(4, 8) with its 5% point 4.53) and 12.3.2 (the
underlined means of Case Study 12.3.1). Skipped, with reasons: 12.2.1 and 12.2.3 (the layout of an ANOVA table
and the table of Case Study 12.2.1: typeset as HTML tables in the notes instead; every number in them is
computed by anova_oneway). Three figures of our own illustrate the chapter: x12.1, the
noncentral F law and the power of the F test; x12.2, the exact familywise error rate of all pairwise t tests,
Bonferroni and Tukey as the number of means grows; x12.3, what unequal variances do to the F test and what the
square-root transformation does to the spread of Poisson counts.
Run `python3 ch12_analysis_of_variance.py --list`, `python3 ch12_analysis_of_variance.py` (all figures, about
30 s) or `python3 ch12_analysis_of_variance.py --fig 12.3.1`. Files go to ../img/ch12/.
"""
import json
import math
import os

import numpy as np
from scipy import integrate, special, stats

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

CH = 12
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))
T = book_data("ch12-tables")
T8 = book_data("ch08-tables")
HEART = [T8["heart_rates"][k] for k in ("nonsmokers", "light", "moderate", "heavy")]   # Case Study 12.2.1 = Table 8.1.1


# =========================================================================== Section 12.2
def anova_oneway(groups):
    """The one-way ANOVA table of Figure 12.2.1 from the k raw samples (list of lists)."""
    g = [np.asarray(x, float) for x in groups]
    k, nj = len(g), np.array([len(x) for x in g])
    n = int(nj.sum())
    ybar = np.array([x.mean() for x in g])
    grand = sum(x.sum() for x in g) / n
    sstr = float((nj * (ybar - grand) ** 2).sum())
    sse = float(sum(((x - x.mean()) ** 2).sum() for x in g))
    return _table(k, n, sstr, sse)


def anova_summary(nj, ybar, s):
    """Reconstruct the ANOVA table from sample sizes, means and standard deviations (Case Study 12.4.2)."""
    nj, ybar, s = (np.asarray(a, float) for a in (nj, ybar, s))
    n = int(nj.sum())
    grand = float((nj * ybar).sum() / n)
    return _table(len(nj), n, float((nj * (ybar - grand) ** 2).sum()), float(((nj - 1) * s ** 2).sum()))


def _table(k, n, sstr, sse):
    mstr, mse = sstr / (k - 1), sse / (n - k)
    F = mstr / mse
    return dict(k=k, n=n, df1=k - 1, df2=n - k, sstr=sstr, sse=sse, sst=sstr + sse, mstr=mstr, mse=mse, F=F,
                p=float(stats.f.sf(F, k - 1, n - k)), fcrit=float(stats.f.isf(0.05, k - 1, n - k)))


def computing_formulas(groups):
    """Equations (12.2.4) and (12.2.5): C = T..^2/n, SSTOT = sum Y^2 - C, SSTR = sum T.j^2/n_j - C."""
    g = [np.asarray(x, float) for x in groups]
    n = sum(len(x) for x in g)
    Cc = sum(x.sum() for x in g) ** 2 / n
    sst = sum((x ** 2).sum() for x in g) - Cc
    sstr = sum(x.sum() ** 2 / len(x) for x in g) - Cc
    return dict(C=float(Cc), sst=float(sst), sstr=float(sstr), sse=float(sst - sstr))


def expected_ss(mu, nj, sigma2):
    """Theorem 12.2.1 and the matching result for SSE: E SSTR = (k-1) sigma^2 + sum n_j (mu_j - mu)^2 and E SSE = (n-k) sigma^2."""
    mu, nj = np.asarray(mu, float), np.asarray(nj, float)
    n, k = nj.sum(), len(nj)
    mubar = float((nj * mu).sum() / n)
    return (k - 1) * sigma2 + float((nj * (mu - mubar) ** 2).sum()), (n - k) * sigma2


def glr_lambda(groups):
    """The generalized likelihood ratio of H0: mu_1 = ... = mu_k: lambda = (SSE / SSTOT)^(n/2) (the maximum likelihoods
    are (2 pi e SSE/n)^(-n/2) and (2 pi e SSTOT/n)^(-n/2))."""
    t = anova_oneway(groups)
    return (t["sse"] / t["sst"]) ** (t["n"] / 2)


def sim_f_ratio(mu, nj, sigma, reps=100000, seed=1):
    """F ratios of `reps` simulated one-way experiments (raw data are never needed: the group means are N(mu_j, sigma^2/n_j)
    and the within sum of squares is sigma^2 chi-squared(n-k), independent)."""
    rng = np.random.default_rng(seed)
    mu, nj = np.asarray(mu, float), np.asarray(nj, float)
    k, n = len(nj), nj.sum()
    ybar = rng.normal(mu, sigma / np.sqrt(nj), size=(reps, k))
    grand = (ybar * nj).sum(axis=1) / n
    sstr = (nj * (ybar - grand[:, None]) ** 2).sum(axis=1)
    sse = sigma ** 2 * rng.chisquare(n - k, size=reps)
    return (sstr / (k - 1)) / (sse / (n - k))


# =========================================================================== Appendix 12.A.2
def noncentrality(mu, nj, sigma2):
    """gamma = sum n_j (mu_j - mu)^2 / sigma^2 (Theorem 12.A.2.2)."""
    mu, nj = np.asarray(mu, float), np.asarray(nj, float)
    mubar = float((nj * mu).sum() / nj.sum())
    return float((nj * (mu - mubar) ** 2).sum() / sigma2)


def nc_chi2_mgf(t, r, gamma):
    """Theorem 12.A.2.1: M(t) = (1 - 2t)^(-r/2) exp(gamma t / (1 - 2t)), t < 1/2."""
    return (1 - 2 * t) ** (-r / 2) * np.exp(gamma * t / (1 - 2 * t))


def power_f(gamma, k, n, alpha=0.05):
    """Power of the F test: P(F'_{k-1, n-k}(gamma) >= F_{1-alpha, k-1, n-k}), as a Poisson(gamma/2) mixture of
    central beta tail probabilities (a noncentral chi-squared with r df is a central one with r + 2J df, J ~ Poisson(gamma/2))."""
    r1, r2 = k - 1, n - k
    crit = stats.f.isf(alpha, r1, r2)
    x = r1 * crit / (r1 * crit + r2)
    lam = gamma / 2
    j = np.arange(0, int(lam + 12 * math.sqrt(lam + 1) + 60))
    w = stats.poisson.pmf(j, lam)
    return float((w * special.betainc(r2 / 2, r1 / 2 + j, 1 - x)).sum())


def power_balanced(mu, r, sigma, alpha=0.05):
    """Power of the F test for k groups of r observations with true means mu and standard deviation sigma."""
    k = len(mu)
    return power_f(noncentrality(mu, [r] * k, sigma ** 2), k, k * r, alpha)


def sample_size_balanced(mu, sigma, alpha=0.05, power=0.8, rmax=2000):
    """Smallest group size r with power >= `power`."""
    for r in range(2, rmax):
        if power_balanced(mu, r, sigma, alpha) >= power:
            return r
    return None


def nc_f_density(x, k, n, gamma):
    """Density of the noncentral F law (Definition 12.A.2.2), scipy's implementation."""
    with np.errstate(over="ignore"):
        return stats.ncf.pdf(x, k - 1, n - k, gamma)


# =========================================================================== Section 12.3
def range_cdf(r, k):
    """P(max - min <= r) for k independent standard normal variables: k int phi(x) [Phi(x + r) - Phi(x)]^(k-1) dx."""
    f = lambda x: k * stats.norm.pdf(x) * (stats.norm.cdf(x + r) - stats.norm.cdf(x)) ** (k - 1)
    return integrate.quad(f, -np.inf, np.inf, epsabs=1e-12, epsrel=1e-12)[0]


def studentized_cdf(q, k, nu):
    """P(Q_{k,nu} <= q) = E[ range_cdf(q S, k) ] with S = sqrt(chi2_nu / nu) independent of the range (Definition 12.3.1)."""
    # Gauss-Legendre on s = sqrt(chi2/nu): density of S is 2 nu f_chi2(nu s^2) s ... integrate in u = chi2 instead
    def f(u):
        return range_cdf(q * math.sqrt(u / nu), k) * stats.chi2.pdf(u, nu)
    return integrate.quad(f, 0, np.inf, epsabs=1e-10, epsrel=1e-10, limit=200)[0]


def q_crit(alpha, k, nu):
    """Q_{alpha,k,nu}: the 100(1 - alpha)th percentile of the Studentized range (the book's Table A.5)."""
    return float(stats.studentized_range.isf(alpha, k, nu))


def tukey_intervals(ybar, nj, mse, alpha=0.05):
    """All pairwise Tukey intervals for mu_i - mu_j. Equal sizes: Theorem 12.3.1 (half-width Q sqrt(MSE / r)); unequal
    sizes: the Tukey-Kramer half-width (Q / sqrt 2) sqrt(MSE (1/n_i + 1/n_j)), which is conservative."""
    ybar, nj = np.asarray(ybar, float), np.asarray(nj, float)
    k, nu = len(ybar), int(nj.sum() - len(ybar))
    Q = q_crit(alpha, k, nu)
    out = []
    for i in range(k):
        for j in range(i + 1, k):
            half = Q / math.sqrt(2) * math.sqrt(mse * (1 / nj[i] + 1 / nj[j]))
            d = ybar[i] - ybar[j]
            out.append(dict(i=i, j=j, diff=float(d), lo=float(d - half), hi=float(d + half), reject=not (d - half < 0 < d + half)))
    return out


def tukey_groups(ybar, halfwidth):
    """Maximal sets of means (sorted ascending) whose spread is below `halfwidth`: the lines drawn under the means in Figure 12.3.2."""
    order = np.argsort(ybar)
    ys = np.asarray(ybar)[order]
    out = []
    for a in range(len(ys)):
        b = a
        while b + 1 < len(ys) and ys[b + 1] - ys[a] < halfwidth:
            b += 1
        if b > a and not any(a >= s and b <= e for s, e in out):
            out.append((a, b))
    return order, ys, out


def fwer_all_pairs(k, nu, alpha=0.05):
    """Exact familywise error rates when all k means are equal (so the largest pairwise difference is the range R):
    the pairwise t tests (each at level alpha) reject something iff R/S > sqrt(2) t_{alpha/2,nu}; Bonferroni with
    m = k(k-1)/2 uses t_{alpha/(2m),nu}; Tukey uses Q_{alpha,k,nu}. Each is a tail probability of the Studentized range."""
    m = k * (k - 1) // 2
    sq = math.sqrt(2)
    return dict(unadjusted=float(stats.studentized_range.sf(sq * stats.t.isf(alpha / 2, nu), k, nu)),
                bonferroni=float(stats.studentized_range.sf(sq * stats.t.isf(alpha / (2 * m), nu), k, nu)),
                tukey=float(stats.studentized_range.sf(q_crit(alpha, k, nu), k, nu)),
                independent=1 - (1 - alpha) ** m)


def sim_fwer(k, r, alpha=0.05, reps=100000, seed=3):
    """Monte Carlo of fwer_all_pairs (equal means): group means N(0, 1/r), MSE ~ chi2_{k(r-1)} / (k(r-1))."""
    rng = np.random.default_rng(seed)
    nu = k * (r - 1)
    ybar = rng.normal(0, 1 / math.sqrt(r), size=(reps, k))
    s = np.sqrt(rng.chisquare(nu, size=reps) / nu)
    R = (ybar.max(axis=1) - ybar.min(axis=1)) / (s / math.sqrt(r))              # the Studentized range
    m = k * (k - 1) // 2
    sq = math.sqrt(2)
    return dict(unadjusted=float((R > sq * stats.t.isf(alpha / 2, nu)).mean()),
                bonferroni=float((R > sq * stats.t.isf(alpha / (2 * m), nu)).mean()),
                tukey=float((R > q_crit(alpha, k, nu)).mean()))


# =========================================================================== Section 12.4
def contrast_test(c, ybar, nj, mse, df_error):
    """Definition 12.4.2 and Theorem 12.4.2: the estimate, SSC, F = SSC / MSE (1 and n - k df) and its P-value."""
    c, ybar, nj = (np.asarray(a, float) for a in (c, ybar, nj))
    chat = float((c * ybar).sum())
    w = float((c ** 2 / nj).sum())
    ssc = chat ** 2 / w
    F = ssc / mse
    return dict(chat=chat, se=math.sqrt(mse * w), ssc=ssc, F=F, p=float(stats.f.sf(F, 1, df_error)))


def helmert_contrasts(nj):
    """k - 1 mutually orthogonal contrasts (sum_j c_sj c_tj / n_j = 0) for any sample sizes: orthonormalise in R^k the
    vectors orthogonal to s = (sqrt n_1, ..., sqrt n_k), then c_ij = a_ij sqrt(n_j). Returns a (k-1) x k array."""
    nj = np.asarray(nj, float)
    s = np.sqrt(nj)
    k = len(nj)
    basis = [s / np.linalg.norm(s)]
    for j in range(k - 1):                                   # Gram-Schmidt on the unit vectors e_1, ..., e_{k-1}
        v = np.zeros(k)
        v[j] = 1.0
        for b in basis:
            v = v - (v @ b) * b
        basis.append(v / np.linalg.norm(v))
    A = np.array(basis[1:])
    return A * s


def scheffe_crit(k, nu, alpha=0.05):
    """The Scheffe critical value for the F ratio of any contrast chosen after the data: (k-1) F_{1-alpha,k-1,nu}."""
    return (k - 1) * float(stats.f.isf(alpha, k - 1, nu))


def critical_values(k, nu, alpha=0.05):
    """Critical value of the F = t^2 statistic of a single pairwise comparison: planned contrast, Tukey (Q^2/2), Scheffe."""
    return dict(planned=float(stats.f.isf(alpha, 1, nu)), tukey=q_crit(alpha, k, nu) ** 2 / 2, scheffe=scheffe_crit(k, nu, alpha))


# =========================================================================== Section 12.5
def var_stab_sd(mu, kind="sqrt"):
    """Exact standard deviation of a transformed Poisson(mu) count, multiplied by 2 for the square-root transforms, so that
    the large-mu limit is 1: kind in 'raw' (sd of Y), 'sqrt' (2 sqrt Y) and 'anscombe' (2 sqrt(Y + 3/8))."""
    y = np.arange(0, int(mu + 12 * math.sqrt(mu + 1) + 40))
    p = stats.poisson.pmf(y, mu)
    g = {"raw": y.astype(float), "sqrt": 2 * np.sqrt(y), "anscombe": 2 * np.sqrt(y + 3 / 8)}[kind]
    m = (p * g).sum()
    return float(math.sqrt((p * (g - m) ** 2).sum()))


def arcsine_sd(n, p):
    """Exact standard deviation of 2 sqrt(n) arcsin(sqrt(Y/n)) for Y ~ Binomial(n, p); the limit is 1."""
    y = np.arange(0, n + 1)
    w = stats.binom.pmf(y, n, p)
    g = 2 * math.sqrt(n) * np.arcsin(np.sqrt(y / n))
    m = (w * g).sum()
    return float(math.sqrt((w * (g - m) ** 2).sum()))


def f_size_unequal(nj, sigmas, alpha=0.05, reps=200000, seed=5):
    """Rejection rate of the 5% F test when all means are equal but the standard deviations are sigma_j (Section 12.5)."""
    rng = np.random.default_rng(seed)
    nj, sg = np.asarray(nj, float), np.asarray(sigmas, float)
    k, n = len(nj), nj.sum()
    ybar = rng.normal(0, sg / np.sqrt(nj), size=(reps, k))
    s2 = sg ** 2 * rng.chisquare(nj - 1, size=(reps, k)) / (nj - 1)
    grand = (ybar * nj).sum(axis=1) / n
    sstr = (nj * (ybar - grand[:, None]) ** 2).sum(axis=1)
    sse = ((nj - 1) * s2).sum(axis=1)
    F = (sstr / (k - 1)) / (sse / (n - k))
    return float((F > stats.f.isf(alpha, k - 1, n - k)).mean())


def expected_ms_unequal(nj, sigmas):
    """Under H0 with unequal variances: E SSTR = sum (1 - n_j/n) sigma_j^2 and E SSE = sum (n_j - 1) sigma_j^2."""
    nj, sg2 = np.asarray(nj, float), np.asarray(sigmas, float) ** 2
    n, k = nj.sum(), len(nj)
    return float(((1 - nj / n) * sg2).sum() / (k - 1)), float(((nj - 1) * sg2).sum() / (n - k))


# =========================================================================== case studies
def case_study_numbers():
    """The numbers printed in the notes for the case studies and the selected questions."""
    out = {}
    out["cs221"] = anova_oneway(HEART)
    out["cs231"] = anova_oneway(T["cs231_antibiotics"]["groups"])
    out["cs241"] = anova_oneway(T["cs241_walking"]["groups"])
    tp = T["cs242_tips"]
    out["cs242"] = anova_summary(tp["n"], tp["mean"], tp["sd"])
    return out


# =========================================================================== figures
def _fx(ax, xlabel, ylabel):
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    for s in ("top", "right"):
        ax.spines[s].set_visible(False)


def fig_12_2_2(out=None):
    """Figure 12.2.2: the F(3, 20) density and the 5% critical region beyond 3.10 of Case Study 12.2.1 (observed F = 6.12)."""
    t = anova_oneway(HEART)
    crit = stats.f.isf(0.05, 3, 20)
    x = np.linspace(0, 8, 600)
    fig, ax = plt.subplots(figsize=(5.2, 3.2))
    ax.plot(x, stats.f.pdf(x, 3, 20), color=BLUE)
    xs = np.linspace(crit, 8, 200)
    ax.fill_between(xs, stats.f.pdf(xs, 3, 20), color=RED, alpha=0.35)
    ax.axvline(crit, color=RED, lw=1)
    ax.axvline(t["F"], color=GREEN, lw=1.6)
    ax.annotate("area = 0.05", (crit + 0.35, 0.07), color=RED, fontsize=9)
    ax.annotate("$F_{.95,3,20}=%.2f$" % crit, (crit + 0.1, 0.55), color=RED, fontsize=9)
    ax.annotate("observed $F=%.2f$" % t["F"], (t["F"] + 0.1, 0.30), color=GREEN, fontsize=9)
    ax.set_ylim(0, 0.8)
    _fx(ax, "$y$", "$f_{F_{3,20}}(y)$")
    return savefig(fig, CH, "fig12-2-2", out)


def fig_12_3_1(out=None):
    """Figure 12.3.1: the density of the Studentized range Q(4, 8); the area 0.05 lies beyond 4.53."""
    crit = q_crit(0.05, 4, 8)
    x = np.linspace(0, 9, 500)
    f = stats.studentized_range.pdf(x, 4, 8)
    fig, ax = plt.subplots(figsize=(5.2, 3.2))
    ax.plot(x, f, color=BLUE)
    xs = np.linspace(crit, 9, 200)
    ax.fill_between(xs, stats.studentized_range.pdf(xs, 4, 8), color=RED, alpha=0.35)
    ax.axvline(crit, color=RED, lw=1)
    ax.annotate("area = 0.05", (crit + 0.35, 0.03), color=RED, fontsize=9)
    ax.annotate("$Q_{.05,4,8}=%.2f$" % crit, (crit + 0.2, 0.2), color=RED, fontsize=9)
    _fx(ax, "$y$", "$f_{Q_{4,8}}(y)$")
    return savefig(fig, CH, "fig12-3-1", out)


def fig_12_3_2(out=None):
    """Figure 12.3.2: the five sample means of Case Study 12.3.1 on a binding-percentage axis, with a line under every set of
    means that Tukey's method does not separate."""
    g = T["cs231_antibiotics"]["groups"]
    t = anova_oneway(g)
    ybar = np.array([np.mean(x) for x in g])
    half = q_crit(0.05, 5, 15) * math.sqrt(t["mse"] / 4)
    order, ys, grp = tukey_groups(ybar, half)
    fig, ax = plt.subplots(figsize=(6.0, 2.2))
    ax.axhline(0, color="black", lw=0.8)
    ax.scatter(ys, np.zeros(5), color=BLUE, zorder=3)
    for h, (pos, idx) in enumerate(zip(ys, order)):
        ax.annotate("(%d)" % (idx + 1), (pos, 0.18 + (0.22 if h in (3,) else 0)), ha="center", fontsize=10)
    for h, (a, b) in enumerate(grp):
        ax.plot([ys[a] - 0.4, ys[b] + 0.4], [-0.35 - 0.2 * h] * 2, color="black", lw=1.8)
    ax.set_xlim(0, 40)
    ax.set_ylim(-1.0, 0.7)
    ax.set_yticks([])
    for s in ("top", "right", "left"):
        ax.spines[s].set_visible(False)
    ax.set_xlabel("binding percentage")
    return savefig(fig, CH, "fig12-3-2", out)


def fig_x12_1(out=None):
    """Own figure: (a) the null F(3, 20) law and the noncentral law for the heart-rate means with sigma^2 = MSE, the power shaded;
    (b) power against the noncentrality parameter for k = 4, n = 24 and against the group size for the heart-rate pattern."""
    t = anova_oneway(HEART)
    mu = [np.mean(x) for x in HEART]
    gamma = noncentrality(mu, [6] * 4, t["mse"])
    crit = stats.f.isf(0.05, 3, 20)
    fig, axs = plt.subplots(1, 2, figsize=(9.2, 3.4))
    ax = axs[0]
    x = np.linspace(0.001, 14, 600)
    ax.plot(x, stats.f.pdf(x, 3, 20), color=BLUE, label="$H_0$: central $F_{3,20}$")
    ax.plot(x, nc_f_density(x, 4, 24, gamma), color=ORANGE, label="$H_1$: noncentral, $\\gamma=%.1f$" % gamma)
    xs = np.linspace(crit, 14, 300)
    ax.fill_between(xs, nc_f_density(xs, 4, 24, gamma), color=ORANGE, alpha=0.3)
    ax.axvline(crit, color=RED, lw=1)
    ax.text(crit + 0.2, 0.66, "$F_{.95,3,20}=%.2f$" % crit, color=RED, fontsize=8.5)
    ax.text(8.2, 0.12, "power %.2f" % power_f(gamma, 4, 24), color=ORANGE, fontsize=9)
    ax.legend(frameon=False, loc="upper right", fontsize=8.5)
    _fx(ax, "$F$", "density")
    ax.set_ylim(0, 0.8)
    ax.text(0.03, 0.93, "(a)", transform=ax.transAxes, fontsize=10)
    ax = axs[1]
    gg = np.linspace(0, 40, 200)
    ax.plot(gg, [power_f(g_, 4, 24) for g_ in gg], color=ORANGE, label="$k=4$, $n=24$")
    ax.plot(gg, [power_f(g_, 4, 12) for g_ in gg], color=PURPLE, label="$k=4$, $n=12$")
    ax.plot(gg, [power_f(g_, 4, 60) for g_ in gg], color=GREEN, label="$k=4$, $n=60$")
    ax.axhline(0.05, color=GREY, lw=0.8, ls=":")
    ax.plot([gamma], [power_f(gamma, 4, 24)], "o", color=RED)
    ax.set_ylim(0, 1.02)
    ax.legend(frameon=False, loc="lower right", fontsize=8.5)
    _fx(ax, "noncentrality parameter $\\gamma=\\sum n_j(\\mu_j-\\mu)^2/\\sigma^2$", "power of the 5% $F$ test")
    ax.text(0.03, 0.93, "(b)", transform=ax.transAxes, fontsize=10)
    fig.tight_layout()
    return savefig(fig, CH, "figx12-1", out)


def fig_x12_2(out=None):
    """Own figure: the true familywise error rate of testing every pair of k equal means with r = 10 observations per mean."""
    ks = np.arange(2, 13)
    r = 10
    ex = [fwer_all_pairs(int(k), int(k) * (r - 1)) for k in ks]
    fig, ax = plt.subplots(figsize=(5.8, 3.5))
    ax.plot(ks, [e["unadjusted"] for e in ex], "o-", color=RED, label="all pairwise $t$ tests, each at 5%")
    ax.plot(ks, [e["independent"] for e in ex], ":", color=GREY, label="$1-0.95^m$ (if the tests were independent)")
    ax.plot(ks, [e["bonferroni"] for e in ex], "s-", color=BLUE, label="Bonferroni, each at $5\\%/m$")
    ax.plot(ks, [e["tukey"] for e in ex], "^-", color=GREEN, label="Tukey")
    ax.axhline(0.05, color="black", lw=0.7, ls="--")
    ax.set_ylim(0, 1.0)
    ax.legend(frameon=False, fontsize=8.5, loc="upper left")
    _fx(ax, "number of means $k$ (all $m=k(k-1)/2$ pairs tested)", "chance of a false rejection")
    return savefig(fig, CH, "figx12-2", out)


def fig_x12_3(out=None):
    """Own figure: (a) the size of the 5% F test when the variances are unequal; (b) the standard deviation of Poisson counts before
    and after the square-root transformations (scaled so that the target is 1)."""
    fig, axs = plt.subplots(1, 2, figsize=(9.2, 3.4))
    ax = axs[0]
    s = np.array([1, 1.5, 2, 3, 4, 6])
    ax.plot(s, [f_size_unequal([10, 10, 10], [1, 1, v], reps=60000, seed=11) for v in s], "o-", color=GREEN, label="equal sizes 10, 10, 10")
    ax.plot(s, [f_size_unequal([5, 10, 20], [v, 1, 1], reps=60000, seed=12) for v in s], "s-", color=RED, label="sizes 5, 10, 20; the small group is the noisy one")
    ax.plot(s, [f_size_unequal([5, 10, 20], [1, 1, v], reps=60000, seed=13) for v in s], "^-", color=BLUE, label="sizes 5, 10, 20; the large group is the noisy one")
    ax.axhline(0.05, color="black", lw=0.7, ls="--")
    ax.legend(frameon=False, fontsize=8, loc="upper left")
    ax.set_ylim(0, 0.45)
    _fx(ax, "ratio of the largest standard deviation to the others", "actual size of the nominal 5% test")
    ax.text(0.97, 0.05, "(a)", transform=ax.transAxes, fontsize=10, ha="right")
    ax = axs[1]
    mus = np.geomspace(0.5, 60, 28)
    ax.plot(mus, [var_stab_sd(m, "raw") for m in mus], color=RED, label="$Y$ (sd $=\\sqrt{\\mu}$)")
    ax.plot(mus, [var_stab_sd(m, "sqrt") for m in mus], color=BLUE, label="$2\\sqrt{Y}$")
    ax.plot(mus, [var_stab_sd(m, "anscombe") for m in mus], color=GREEN, label="$2\\sqrt{Y+3/8}$")
    ax.axhline(1, color="black", lw=0.7, ls="--")
    ax.set_xscale("log")
    ax.set_ylim(0, 3.2)
    ax.legend(frameon=False, fontsize=8.5, loc="upper left")
    _fx(ax, "Poisson mean $\\mu$", "sd of the transformed count")
    ax.text(0.97, 0.05, "(b)", transform=ax.transAxes, fontsize=10, ha="right")
    fig.tight_layout()
    return savefig(fig, CH, "figx12-3", out)


FIGURES = {"12.2.2": fig_12_2_2, "12.3.1": fig_12_3_1, "12.3.2": fig_12_3_2,
           "x12.1": fig_x12_1, "x12.2": fig_x12_2, "x12.3": fig_x12_3}


# =========================================================================== demo export
QTAB_NU = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 30, 40, 60, 120, 1000000]
QTAB_K = list(range(2, 13))


def demo_reference():
    """Numbers shown by the two demonstrations (the same formulas run in the browser)."""
    out = {}
    out["q_table"] = {"nu": QTAB_NU, "k": QTAB_K,
                      **{("a%02d" % round(100 * a)): [[round(q_crit(a, k, nu), 4) for nu in QTAB_NU] for k in QTAB_K] for a in (0.10, 0.05, 0.01)}}
    mu_h = [float(np.mean(x)) for x in HEART]
    th = anova_oneway(HEART)
    out["heart"] = dict(groups=HEART, names=["Nonsmokers", "Light", "Moderate", "Heavy"], means=mu_h, mse=th["mse"], F=th["F"], p=th["p"],
                        gamma=noncentrality(mu_h, [6] * 4, th["mse"]), power=power_f(noncentrality(mu_h, [6] * 4, th["mse"]), 4, 24))
    ta = T["cs231_antibiotics"]
    tt = anova_oneway(ta["groups"])
    out["antibiotics"] = dict(names=ta["names"], groups=ta["groups"], means=[float(np.mean(x)) for x in ta["groups"]], mse=tt["mse"], F=tt["F"],
                              Q=q_crit(0.05, 5, 15))
    pw = {}
    for key, (mu, r, sg) in {"null43": ([0, 0, 0, 0], 6, 9), "heart": (mu_h, 6, math.sqrt(th["mse"])), "one_shift": ([0, 0, 0, 9.0], 6, 9),
                             "heart_r15": (mu_h, 15, math.sqrt(th["mse"])), "k2": ([0, 9], 10, 9)}.items():
        g = noncentrality(mu, [r] * len(mu), sg ** 2)
        pw[key] = dict(k=len(mu), r=r, sigma=sg, gamma=g, power=power_f(g, len(mu), len(mu) * r), fcrit=float(stats.f.isf(0.05, len(mu) - 1, len(mu) * (r - 1))))
    out["power"] = pw
    out["fwer"] = {"%d-%d" % (k, r): dict(exact=fwer_all_pairs(k, k * (r - 1)), sim=sim_fwer(k, r, reps=200000, seed=k * 31 + r))
                   for k, r in ((3, 10), (5, 10), (10, 10), (5, 4), (4, 6))}
    out["fwer_grid"] = {"%d-%d" % (k, r): fwer_all_pairs(k, k * (r - 1)) for k in (3, 4, 5, 6, 8, 10) for r in (3, 4, 6, 10, 20)}
    return out


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


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