"""Larsen and Marx (2018), Chapter 7: Inferences Based on the Normal Distribution.

Companion code for Chapter 7 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 (../ch07-normal-inference.html):

* Section 7.2, z ratio versus t ratio: ratios_z_t (the simulation of Figure 7.2.1), z_interval_coverage (the true
  coverage of "ybar +- 1.96 s/sqrt(n)").
* Section 7.3, the sampling distributions: chi2_pdf, f_pdf (Theorem 7.3.3), t_pdf (Theorem 7.3.4), helmert
  (the orthogonal matrix of Appendix 7.A.1), var_t, wilson_hilferty (Questions 7.3.6 and 7.5.5).
* Section 7.4, inference about mu: t_interval (Theorem 7.4.1), t_test (Theorem 7.4.2), the case studies and
  examples (7.4.1, 7.4.2, Example 7.4.1, Example 7.4.2), true_size (the "true alpha" of the robustness discussion).
* Section 7.5, inference about sigma^2: var_interval (Theorem 7.5.1), var_test (Theorem 7.5.2), expected_width_ratio
  and smallest_n_width (Example 7.5.1), and three ways of choosing the two cut-offs of a chi-square test or
  interval: equal tails, the generalized likelihood ratio (Appendix 7.A.3) and the unbiased test.
* Section 7.6, Type II error: t_power and t_beta (noncentral t), nct_cdf_integral (the cdf as a one-dimensional
  integral), t_sample_size, johnson_welch (a normal approximation) and the book's simulation experiments.
* Browser demonstrations: demo_reference() exports the exact numbers that t-test-robustness-demo.html and
  variance-inference-demo.html show (../data/ch07-demos.json).

Figures. The book has 14 numbered figures in Chapter 7. Those computed from data, a model or a simulation are
reproduced: 7.2.1 (a fresh draw of 500 samples; the book's draw cannot be reproduced), 7.3.1, 7.3.2, 7.4.2,
7.4.3, 7.4.6 (a to d, with 2000 samples in place of the book's 100 so that the shapes are clear), 7.5.1, 7.5.3,
7.A.3.1 and 7.A.3.2 (the book draws these schematically; here they are computed for 19 observations at the 5%
level): ten figures. Not drawn, with reasons: 7.4.1 and 7.5.2 (excerpts of the t and chi-square tables, recomputed
as tables in the notes) and 7.4.4 (a golden rectangle, a sketch), 7.4.5 (a hypothetical density, a sketch).
Three figures of our own: x7.1, the true level of the nominal 5% two-sided t test against the sample size for
five populations; x7.2, the power of the one-sided t test (noncentral t) against that of the z test, with the
book's Example 7.6.1 and its gamma simulation; x7.3, the expected width of the 95% interval for sigma^2 and the
gain from the shortest interval.
Run `python3 ch07_normal_inference.py --list`, `python3 ch07_normal_inference.py` (all figures, about 15 s) or
`python3 ch07_normal_inference.py --fig 7.4.6`. Files go to ../img/ch07/.
"""
import json
import math
import os

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

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

CH = 7
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))
CACHE = os.path.join(HERE, "cache")
N01 = stats.norm


# =========================================================================== Section 7.2
def ratios_z_t(n=4, B=500, mu=0.0, sigma=1.0, seed=72):
    """B samples of size n from N(mu, sigma^2): the z ratios (sigma known) and the t ratios (S in place of sigma)."""
    rng = np.random.default_rng(seed)
    y = rng.normal(mu, sigma, size=(B, n))
    ybar = y.mean(1)
    s = y.std(1, ddof=1)
    return (ybar - mu) / (sigma / math.sqrt(n)), (ybar - mu) / (s / math.sqrt(n))


def z_interval_coverage(n, z=1.96):
    """True coverage P(|T_{n-1}| < z) of the interval ybar +- z s / sqrt(n) (S used in place of sigma)."""
    return stats.t.cdf(z, n - 1) - stats.t.cdf(-z, n - 1)


# =========================================================================== Section 7.3
def chi2_pdf(u, m):
    """Density of the chi-square law with m degrees of freedom (Definition 7.3.1), written out."""
    u = np.asarray(u, dtype=float)
    out = np.zeros_like(u)
    pos = u > 0
    out[pos] = np.exp((m / 2 - 1) * np.log(u[pos]) - u[pos] / 2 - (m / 2) * math.log(2) - special.gammaln(m / 2))
    return out


def f_pdf(w, m, n):
    """Density of F_{m,n} = (V/m)/(U/n), V ~ chi2_m, U ~ chi2_n (Theorem 7.3.3)."""
    w = np.asarray(w, dtype=float)
    c = math.exp(special.gammaln((m + n) / 2) - special.gammaln(m / 2) - special.gammaln(n / 2)
                 + (m / 2) * math.log(m) + (n / 2) * math.log(n))
    out = np.zeros_like(w)
    pos = w > 0
    out[pos] = c * w[pos] ** (m / 2 - 1) / (n + m * w[pos]) ** ((m + n) / 2)
    return out


def t_pdf(t, n):
    """Density of Student's t with n degrees of freedom (Theorem 7.3.4)."""
    t = np.asarray(t, dtype=float)
    c = math.exp(special.gammaln((n + 1) / 2) - special.gammaln(n / 2)) / math.sqrt(n * math.pi)
    return c * (1 + t ** 2 / n) ** (-(n + 1) / 2)


def var_t(n):
    """Variance of T_n: n/(n-2) for n > 2 (infinite for n = 1, 2)."""
    return n / (n - 2) if n > 2 else math.inf


def helmert(n):
    """The orthogonal n x n matrix whose last row is (1,...,1)/sqrt(n) (Appendix 7.A.1).

    Row k (k = 1..n-1) is (1,...,1,-k,0,...,0)/sqrt(k(k+1)): k ones, then -k, then zeros."""
    A = np.zeros((n, n))
    for k in range(1, n):
        A[k - 1, :k] = 1.0
        A[k - 1, k] = -k
        A[k - 1] /= math.sqrt(k * (k + 1))
    A[n - 1] = 1.0 / math.sqrt(n)
    return A


def wilson_hilferty(p, n):
    """Approximate 100p-th percentile of chi-square(n): n (1 - 2/(9n) + z_p sqrt(2/(9n)))^3 (Question 7.5.5)."""
    z = N01.ppf(p)
    return n * (1 - 2 / (9 * n) + z * math.sqrt(2 / (9 * n))) ** 3


def sd_s_ratio(n):
    """E(S)/sigma = c_n = sqrt(2/(n-1)) Gamma(n/2) / Gamma((n-1)/2) for a normal sample of size n."""
    return math.sqrt(2 / (n - 1)) * math.exp(special.gammaln(n / 2) - special.gammaln((n - 1) / 2))


# =========================================================================== Section 7.4
def t_stat(ybar, mu0, s, n):
    return (ybar - mu0) / (s / math.sqrt(n))


def t_interval(ybar, s, n, conf=0.95):
    """Theorem 7.4.1: ybar +- t_{alpha/2, n-1} s / sqrt(n)."""
    h = stats.t.ppf(1 - (1 - conf) / 2, n - 1) * s / math.sqrt(n)
    return ybar - h, ybar + h


def t_test(y, mu0, side="two", alpha=0.05):
    """Theorem 7.4.2 from raw data: (t, critical value, reject, P-value)."""
    y = np.asarray(y, dtype=float)
    n = len(y)
    t = t_stat(y.mean(), mu0, y.std(ddof=1), n)
    if side == "two":
        c = stats.t.ppf(1 - alpha / 2, n - 1)
        return t, c, abs(t) >= c, 2 * stats.t.sf(abs(t), n - 1)
    if side == "greater":
        c = stats.t.ppf(1 - alpha, n - 1)
        return t, c, t >= c, stats.t.sf(t, n - 1)
    c = stats.t.ppf(alpha, n - 1)
    return t, c, t <= c, stats.t.cdf(t, n - 1)


def interval_confidence(lo_mult, hi_mult, n):
    """Confidence of ybar - lo_mult s/sqrt(n) <= mu <= ybar + hi_mult s/sqrt(n) (Question 7.4.15)."""
    return stats.t.cdf(hi_mult, n - 1) - stats.t.cdf(-lo_mult, n - 1)


def populations():
    """Name -> (sampler(rng, size), mean) for the robustness experiments (Figure 7.4.6, x7.1)."""
    return {
        "normal": (lambda r, size: r.standard_normal(size), 0.0),
        "uniform": (lambda r, size: r.uniform(0, 1, size), 0.5),
        "exponential": (lambda r, size: r.exponential(1.0, size), 1.0),
        "poisson": (lambda r, size: r.poisson(5.0, size).astype(float), 5.0),
        "gamma": (lambda r, size: r.gamma(4.694, 1 / 0.722, size), 4.694 / 0.722),
        "lognormal": (lambda r, size: r.lognormal(0.0, 1.0, size), math.exp(0.5)),
    }


def t_ratios(pop, n, B, seed):
    """B t ratios sqrt(n)(ybar - mu)/s from samples of size n; samples with s = 0 are dropped (NaN)."""
    sampler, mu = populations()[pop]
    rng = np.random.default_rng(seed)
    y = sampler(rng, (B, n))
    s = y.std(1, ddof=1)
    with np.errstate(divide="ignore", invalid="ignore"):
        t = math.sqrt(n) * (y.mean(1) - mu) / s
    return t[np.isfinite(t)]


def true_size(pop, n, alpha=0.05, B=20000, seed=74):
    """(lower tail, upper tail, total) probability that the t ratio falls in the nominal two-sided critical
    region when the data come from `pop`; the nominal values are alpha/2, alpha/2, alpha."""
    t = t_ratios(pop, n, B, seed)
    c = stats.t.ppf(1 - alpha / 2, n - 1)
    lo, hi = float((t <= -c).mean()), float((t >= c).mean())
    return lo, hi, lo + hi


# =========================================================================== Section 7.5
def var_interval(s2, n, conf=0.95):
    """Theorem 7.5.1(a): ((n-1)s^2 / chi2_{1-a/2,n-1}, (n-1)s^2 / chi2_{a/2,n-1})."""
    a = 1 - conf
    return (n - 1) * s2 / stats.chi2.ppf(1 - a / 2, n - 1), (n - 1) * s2 / stats.chi2.ppf(a / 2, n - 1)


def var_test(s2, n, sigma2_0, side="two", alpha=0.05):
    """Theorem 7.5.2: (chi-square statistic, critical value(s), reject, P-value)."""
    x = (n - 1) * s2 / sigma2_0
    F = stats.chi2.cdf(x, n - 1)
    if side == "greater":
        c = stats.chi2.ppf(1 - alpha, n - 1)
        return x, c, x >= c, 1 - F
    if side == "less":
        c = stats.chi2.ppf(alpha, n - 1)
        return x, c, x <= c, F
    lo, hi = stats.chi2.ppf(alpha / 2, n - 1), stats.chi2.ppf(1 - alpha / 2, n - 1)
    return x, (lo, hi), (x <= lo or x >= hi), 2 * min(F, 1 - F)


def expected_width_ratio(n, conf=0.95):
    """E(width of the interval for sigma^2) / sigma^2 = (n-1)(1/chi2_{a/2,n-1} - 1/chi2_{1-a/2,n-1}) (7.5.2)."""
    a = 1 - conf
    return (n - 1) * (1 / stats.chi2.ppf(a / 2, n - 1) - 1 / stats.chi2.ppf(1 - a / 2, n - 1))


def smallest_n_width(conf=0.95, ratio=1.0):
    """Smallest n with expected width <= ratio sigma^2 (Example 7.5.1: n = 39 for ratio 1). The ratio decreases in n."""
    n = 2
    while expected_width_ratio(n, conf) > ratio:
        n += 1
    return n


def equal_height_cutoffs(df_density, df_stat, mass_out):
    """Cut-offs a < b of chi-square(df_stat) such that the chi-square(df_density) density takes the same value at a
    and at b and P(chi2 <= a) + P(chi2 >= b) = mass_out. df_density = df_stat + 2 gives the unbiased test (power has a
    minimum at the null) and df_density = df_stat + 4 the shortest interval for sigma^2."""
    k = df_density
    mode = max(k - 2, 0.0)

    def b_of_a(a):
        h = lambda u: (k / 2 - 1) * math.log(u) - u / 2
        target = h(a)
        return optimize.brentq(lambda u: h(u) - target, mode, 40 * k + 200)

    def excess(a):
        return stats.chi2.cdf(a, df_stat) + stats.chi2.sf(b_of_a(a), df_stat) - mass_out

    a_hi = mode * (1 - 1e-4) if mode > 0 else 1.0
    a = optimize.brentq(excess, 1e-9, a_hi)
    return a, b_of_a(a)


def glrt_cutoffs(n, alpha=0.05):
    """Exact size-alpha generalized likelihood ratio test of H0: sigma^2 = sigma0^2 (Appendix 7.A.3):
    reject if u = (n-1)s^2/sigma0^2 satisfies u e^{-u/n} <= k, i.e. u <= a or u >= b, with a e^{-a/n} = b e^{-b/n}
    and P(chi2_{n-1} <= a) + P(chi2_{n-1} >= b) = alpha."""
    g = lambda u: math.log(u) - u / n

    def b_of_a(a):
        target = g(a)
        return optimize.brentq(lambda u: g(u) - target, n, 60 * n + 200)

    def excess(a):
        return stats.chi2.cdf(a, n - 1) + stats.chi2.sf(b_of_a(a), n - 1) - alpha

    a = optimize.brentq(excess, 1e-9, n * (1 - 1e-4))
    return a, b_of_a(a)


def equal_tail_cutoffs(n, alpha=0.05):
    return stats.chi2.ppf(alpha / 2, n - 1), stats.chi2.ppf(1 - alpha / 2, n - 1)


def unbiased_cutoffs(n, alpha=0.05):
    return equal_height_cutoffs(n + 1, n - 1, alpha)


def shortest_interval_cutoffs(n, conf=0.95):
    """Cut-offs (a, b) of chi2_{n-1} minimising the width of ((n-1)s^2/b, (n-1)s^2/a) at coverage conf."""
    return equal_height_cutoffs(n + 3, n - 1, 1 - conf)


def chi2_power(sigma_ratio2, n, side="less", alpha=0.05):
    """Power of the chi-square test at sigma^2 = sigma_ratio2 * sigma0^2 (one-sided cut-offs)."""
    if side == "less":
        return stats.chi2.cdf(stats.chi2.ppf(alpha, n - 1) / sigma_ratio2, n - 1)
    return stats.chi2.sf(stats.chi2.ppf(1 - alpha, n - 1) / sigma_ratio2, n - 1)


# =========================================================================== Section 7.6
def t_power(d, n, alpha=0.05, side="greater"):
    """Power of the one-sample t test when (mu - mu0)/sigma = d: noncentral t with delta = d sqrt(n)."""
    delta = d * math.sqrt(n)
    nu = n - 1
    if side == "greater":
        return stats.nct.sf(stats.t.ppf(1 - alpha, nu), nu, delta)
    if side == "less":
        return stats.nct.cdf(stats.t.ppf(alpha, nu), nu, delta)
    c = stats.t.ppf(1 - alpha / 2, nu)
    return stats.nct.sf(c, nu, delta) + stats.nct.cdf(-c, nu, delta)


def t_beta(d, n, alpha=0.05, side="greater"):
    return 1 - t_power(d, n, alpha, side)


def z_power(d, n, alpha=0.05, side="greater"):
    """Power of the z test (sigma known) at the same standardised shift."""
    delta = d * math.sqrt(n)
    if side == "greater":
        return N01.sf(N01.isf(alpha) - delta)
    c = N01.isf(alpha / 2)
    return N01.sf(c - delta) + N01.cdf(-c - delta)


def nct_cdf_integral(t, nu, delta):
    """P(T <= t) for T = (Z + delta)/sqrt(U/nu): the integral over u of Phi(t sqrt(u/nu) - delta) f_U(u)."""
    f = lambda u: N01.cdf(t * math.sqrt(u / nu) - delta) * stats.chi2.pdf(u, nu)
    val, _ = integrate.quad(f, 0, np.inf, limit=200)
    return val


def johnson_welch(t, nu, delta):
    """Normal approximation P(T <= t) ~ Phi((t (1 - 1/(4 nu)) - delta) / sqrt(1 + t^2/(2 nu)))."""
    return N01.cdf((t * (1 - 1 / (4 * nu)) - delta) / math.sqrt(1 + t * t / (2 * nu)))


def t_sample_size(d, alpha=0.05, power=0.8, side="greater", nmax=5000):
    """Smallest n whose t test has power >= `power` at standardised shift d."""
    for n in range(2, nmax):
        if t_power(d, n, alpha, side) >= power:
            return n
    return None


def z_sample_size(d, alpha=0.05, power=0.8):
    return math.ceil(((N01.isf(alpha) + N01.isf(1 - power)) / d) ** 2)


def type2_simulation(n=20, mu0=5.0, mu1=6.5, sigma=3.0, dist="normal", reps=200, alpha=0.05, seed=76):
    """The experiment of Section 7.6: the number of samples (out of `reps`) with t = (ybar - mu0)/(s/sqrt n) below
    t_{alpha, n-1}, i.e. the number of Type II errors; dist is normal or the gamma with the same mean and variance."""
    rng = np.random.default_rng(seed)
    if dist == "normal":
        y = rng.normal(mu1, sigma, size=(reps, n))
    else:
        r = (mu1 / sigma) ** 2
        lam = mu1 / sigma ** 2
        y = rng.gamma(r, 1 / lam, size=(reps, n))
    t = (y.mean(1) - mu0) / (y.std(1, ddof=1) / math.sqrt(n))
    return int((t < stats.t.ppf(1 - alpha, n - 1)).sum())


def type2_probability(n=20, mu0=5.0, mu1=6.5, sigma=3.0, dist="gamma", reps=400000, alpha=0.05, seed=77):
    """Probability of a Type II error for the experiment above, from a large simulation."""
    rng = np.random.default_rng(seed)
    cnt = 0
    chunk = 50000
    c = stats.t.ppf(1 - alpha, n - 1)
    left = reps
    while left > 0:
        m = min(chunk, left)
        if dist == "normal":
            y = rng.normal(mu1, sigma, size=(m, n))
        else:
            y = rng.gamma((mu1 / sigma) ** 2, sigma ** 2 / mu1, size=(m, n))
        t = (y.mean(1) - mu0) / (y.std(1, ddof=1) / math.sqrt(n))
        cnt += int((t < c).sum())
        left -= m
    return cnt / reps


# =========================================================================== figures
def _density_fig(ax, x, dens, color, label=None, lw=1.6):
    ax.plot(x, dens, color=color, lw=lw, label=label)


def fig_7_2_1(out=None):
    """Figure 7.2.1: 500 samples of size 4; histograms of (ybar-mu)/(sigma/2) and (ybar-mu)/(S/2) against N(0,1)."""
    z, t = ratios_z_t(4, 500)
    grid = np.linspace(-4, 4, 400)
    fig, axes = plt.subplots(1, 2, figsize=(7.2, 2.7), sharey=True)
    for ax, v, lab, c in ((axes[0], z, r"$(\bar Y-\mu)/(\sigma/\sqrt{4})$", BLUE),
                          (axes[1], t, r"$(\bar Y-\mu)/(S/\sqrt{4})$", RED)):
        ax.hist(np.clip(v, -4, 4), bins=np.linspace(-4, 4, 33), density=True, color=c, alpha=0.35, edgecolor="white")
        ax.plot(grid, N01.pdf(grid), color="k", lw=1.4, label="$f_Z(z)$")
        ax.set_xlim(-4, 4); ax.set_xlabel(lab)
        ax.text(0.97, 0.95, "%d of 500 outside $\\pm4$" % int((np.abs(v) > 4).sum()), transform=ax.transAxes,
                ha="right", va="top", fontsize=8.5, color=GREY)
        ax.legend(loc="upper left", frameon=False)
    axes[0].set_ylabel("density")
    common.panel_label(axes[0], "a", "lower left"); common.panel_label(axes[1], "b", "lower left")
    fig.tight_layout()
    savefig(fig, CH, "fig7-2-1", out)


def fig_7_3_1(out=None):
    """Figure 7.3.1: the F_{3,5} density and its 95th percentile 5.41."""
    q = stats.f.ppf(0.95, 3, 5)
    r = np.linspace(0, 7, 700)
    fig, ax = plt.subplots(figsize=(5.0, 2.9))
    ax.plot(r, f_pdf(r, 3, 5), color=BLUE)
    rr = r[r >= q]
    ax.fill_between(rr, f_pdf(rr, 3, 5), color=BLUE, alpha=0.35)
    ax.axvline(q, color="k", lw=1, ls="--")
    ax.text(q + 0.1, 0.33, "$F_{.95,3,5}=%.2f$" % q, fontsize=9)
    ax.annotate("area = 0.05", (q + 0.6, 0.01), (4.6, 0.17), color=BLUE, arrowprops=dict(arrowstyle="->", color=BLUE))
    ax.text(1.6, 0.30, "area = 0.95", color=BLUE, fontsize=9)
    ax.set_xlabel("r"); ax.set_ylabel("$f_{F_{3,5}}(r)$"); ax.set_xlim(0, 7); ax.set_ylim(0, 0.65)
    savefig(fig, CH, "fig7-3-1", out)


def fig_7_3_2(out=None):
    """Figure 7.3.2: Student t densities with 2 and 10 degrees of freedom against the standard normal."""
    t = np.linspace(-4, 4, 600)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.plot(t, N01.pdf(t), color="k", lw=1.5, label="$f_Z(z)$")
    ax.plot(t, t_pdf(t, 10), color=BLUE, label="$f_{T_{10}}(t)$")
    ax.plot(t, t_pdf(t, 2), color=RED, label="$f_{T_2}(t)$")
    ax.set_xlabel("t"); ax.set_ylabel("density"); ax.set_xlim(-4, 4); ax.set_ylim(0, 0.45); ax.legend(frameon=False)
    savefig(fig, CH, "fig7-3-2", out)


def fig_7_4_2(out=None):
    """Figure 7.4.2: the number t_{alpha,n} with P(T_n >= t_{alpha,n}) = alpha (here n = 10, alpha = 0.05)."""
    n, a = 10, 0.05
    c = stats.t.ppf(1 - a, n)
    t = np.linspace(-4, 4, 600)
    fig, ax = plt.subplots(figsize=(5.0, 2.9))
    ax.plot(t, t_pdf(t, n), color=BLUE)
    tt = t[t >= c]
    ax.fill_between(tt, t_pdf(tt, n), color=BLUE, alpha=0.35)
    ax.axvline(c, color="k", lw=1, ls="--")
    ax.text(c - 0.1, 0.40, "$t_{.05,10}=%.3f$" % c, ha="right", fontsize=9)
    ax.annotate("area = $\\alpha$", (c + 0.4, 0.01), (2.7, 0.14), color=BLUE, arrowprops=dict(arrowstyle="->", color=BLUE))
    ax.set_xlabel("t"); ax.set_ylabel("$f_{T_n}(t)$"); ax.set_xlim(-4, 4); ax.set_ylim(0, 0.45)
    savefig(fig, CH, "fig7-4-2", out)


def fig_7_4_3(out=None):
    """Figure 7.4.3: histogram of the twenty observations of Example 7.4.1 (strong right skew)."""
    y = np.array(book_data("ch07-tables")["example741"])
    fig, ax = plt.subplots(figsize=(4.8, 2.9))
    ax.hist(y, bins=np.arange(0, 13, 1.0), color=BLUE, alpha=0.6, edgecolor="white")
    ax.set_xlabel("y"); ax.set_ylabel("frequency"); ax.set_xlim(0, 12)
    ax.text(0.97, 0.93, "$\\bar y=%.2f$, $s=%.2f$" % (y.mean(), y.std(ddof=1)), transform=ax.transAxes, ha="right", va="top", fontsize=9)
    savefig(fig, CH, "fig7-4-3", out)


def fig_7_4_6(out=None):
    """Figure 7.4.6: t ratios from uniform, exponential and Poisson samples of size 6 and exponential samples of size 15."""
    B = 2000
    spec = [("uniform", 6, "(a) uniform(0,1), $n=6$", 8), ("exponential", 6, "(b) exponential, $n=6$", 9),
            ("poisson", 6, "(c) Poisson(5), $n=6$", 10), ("exponential", 15, "(d) exponential, $n=15$", 11)]
    fig, axes = plt.subplots(2, 2, figsize=(7.2, 5.0))
    for ax, (pop, n, title, sd) in zip(axes.ravel(), spec):
        t = t_ratios(pop, n, B, 740 + sd)
        lo = -7 if pop == "exponential" and n == 6 else -5
        ax.hist(np.clip(t, lo, 5), bins=np.linspace(lo, 5, 45), density=True, color=BLUE, alpha=0.4, edgecolor="white")
        g = np.linspace(lo, 5, 400)
        ax.plot(g, t_pdf(g, n - 1), color=RED, lw=1.5, label="$f_{T_{%d}}$" % (n - 1))
        ax.set_title(title, fontsize=9.5); ax.set_xlabel("t ratio"); ax.legend(frameon=False, loc="upper left", fontsize=8.5)
        ax.set_xlim(lo, 5)
    for ax in axes[:, 0]:
        ax.set_ylabel("density")
    fig.tight_layout()
    savefig(fig, CH, "fig7-4-6", out)


def fig_7_5_1(out=None):
    """Figure 7.5.1: chi-square density with 5 df; 5% of the area lies below 1.145 and 1% above 15.086."""
    a, b = stats.chi2.ppf(0.05, 5), stats.chi2.ppf(0.99, 5)
    u = np.linspace(0, 18, 600)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.plot(u, stats.chi2.pdf(u, 5), color=BLUE)
    ul, ur = u[u <= a], u[u >= b]
    ax.fill_between(ul, stats.chi2.pdf(ul, 5), color=RED, alpha=0.4); ax.fill_between(ur, stats.chi2.pdf(ur, 5), color=GREEN, alpha=0.5)
    ax.annotate("area = 0.05", (a * 0.7, 0.015), (3.0, 0.11), color=RED, arrowprops=dict(arrowstyle="->", color=RED))
    ax.annotate("area = 0.01", (b + 0.5, 0.003), (13.2, 0.07), color=GREEN, arrowprops=dict(arrowstyle="->", color=GREEN))
    ax.text(a, -0.012, "%.3f" % a, ha="center", va="top", fontsize=8.5, color=RED)
    ax.text(b, -0.012, "%.3f" % b, ha="center", va="top", fontsize=8.5, color=GREEN)
    ax.set_xlabel("$y$"); ax.set_ylabel("$f_{\\chi^2_5}(y)$"); ax.set_xlim(0, 18); ax.set_ylim(0, 0.17)
    savefig(fig, CH, "fig7-5-1", out)


def fig_7_5_3(out=None):
    """Figure 7.5.3: chi-square(18) density, rejection region of Case Study 7.5.2 (left 5%, cut-off 9.390)."""
    n = 19
    c = stats.chi2.ppf(0.05, n - 1)
    chi = (n - 1) * 11.28 ** 2 / 11.67 ** 2
    u = np.linspace(0, 38, 700)
    fig, ax = plt.subplots(figsize=(5.4, 3.0))
    ax.plot(u, stats.chi2.pdf(u, 18), color=BLUE)
    ul = u[u <= c]
    ax.fill_between(ul, stats.chi2.pdf(ul, 18), color=RED, alpha=0.4)
    ax.axvline(c, color="k", lw=1, ls="--"); ax.axvline(chi, color=GREEN, lw=1.4)
    ax.text(c - 0.4, 0.07, "reject $H_0$\narea = 0.05", ha="right", fontsize=8.5, color=RED)
    ax.text(c + 0.3, 0.003, "%.3f" % c, fontsize=8.5)
    ax.text(chi + 0.4, 0.075, "observed\n$\\chi^2=%.2f$" % chi, fontsize=8.5, color=GREEN)
    ax.set_xlabel("$y$"); ax.set_ylabel("$f_{\\chi^2_{18}}(y)$"); ax.set_xlim(0, 38); ax.set_ylim(0, 0.10)
    savefig(fig, CH, "fig7-5-3", out)


def fig_7_A_3_1(out=None):
    """Figure 7.A.3.1: y = x e^{-x}, the likelihood ratio in disguise; the rejection set is two tails (n = 19, alpha = 0.05)."""
    n, alpha = 19, 0.05
    a, b = glrt_cutoffs(n, alpha)
    xa, xb = a / n, b / n
    ks = xa * math.exp(-xa)
    x = np.linspace(0, 3.2, 600)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.plot(x, x * np.exp(-x), color=BLUE)
    ax.axhline(ks, color=RED, lw=1, ls="--")
    for v in (xa, xb):
        ax.plot([v, v], [0, ks], color="k", lw=0.9, ls=":")
    ax.text(0.03, ks + 0.012, "$k^*$", color=RED, fontsize=9)
    ax.text(xa + 0.04, 0.03, "$a$", ha="left", va="bottom"); ax.text(xb + 0.04, 0.03, "$b$", ha="left", va="bottom")
    ax.text(0.05, 0.12, "reject", fontsize=8.5, color=RED); ax.text(2.3, 0.2, "reject", fontsize=8.5, color=RED)
    ax.set_xlabel("$x=\\hat\\sigma^2/\\sigma_0^2$"); ax.set_ylabel("$y=xe^{-x}$"); ax.set_xlim(0, 3.2); ax.set_ylim(0, 0.42)
    savefig(fig, CH, "fig7-A-3-1", out)


def fig_7_A_3_2(out=None):
    """Figure 7.A.3.2: the two-sided chi-square rejection region (chi-square with 18 df, equal tails of 2.5%)."""
    a, b = equal_tail_cutoffs(19, 0.05)
    u = np.linspace(0, 50, 700)
    fig, ax = plt.subplots(figsize=(5.4, 3.0))
    ax.plot(u, stats.chi2.pdf(u, 18), color=BLUE)
    ul, ur = u[u <= a], u[u >= b]
    ax.fill_between(ul, stats.chi2.pdf(ul, 18), color=RED, alpha=0.4); ax.fill_between(ur, stats.chi2.pdf(ur, 18), color=RED, alpha=0.4)
    ax.text(a, -0.006, "$\\chi^2_{\\alpha/2,n-1}=%.2f$" % a, ha="center", va="top", fontsize=8.5)
    ax.text(b, -0.006, "$\\chi^2_{1-\\alpha/2,n-1}=%.2f$" % b, ha="center", va="top", fontsize=8.5)
    ax.text(4, 0.03, "reject", color=RED, fontsize=8.5, ha="center"); ax.text(41, 0.02, "reject", color=RED, fontsize=8.5, ha="center")
    ax.set_xlabel("$y$", labelpad=14); ax.set_ylabel("density"); ax.set_xlim(0, 50); ax.set_ylim(0, 0.10)
    savefig(fig, CH, "fig7-A-3-2", out)


def _size_table(B=20000):
    path = os.path.join(CACHE, "ch07-size.json")
    ns = [3, 5, 8, 12, 20, 30, 50, 100]
    pops = ["normal", "uniform", "exponential", "poisson", "lognormal"]
    if os.path.exists(path):
        d = json.load(open(path))
        if d.get("B") == B and d.get("ns") == ns:
            return d
    d = {"B": B, "ns": ns, "pops": pops, "total": {}, "lo": {}, "hi": {}}
    for p in pops:
        d["total"][p], d["lo"][p], d["hi"][p] = [], [], []
        for n in ns:
            lo, hi, tot = true_size(p, n, 0.05, B, seed=700 + n)
            d["lo"][p].append(lo); d["hi"][p].append(hi); d["total"][p].append(tot)
    os.makedirs(CACHE, exist_ok=True)
    json.dump(d, open(path, "w"))
    return d


def fig_x7_1(out=None):
    """Own figure x7.1: the true level of the nominal 5% two-sided t test against n, for five populations."""
    d = _size_table()
    cols = {"normal": "k", "uniform": GREEN, "exponential": RED, "poisson": BLUE, "lognormal": PURPLE}
    labs = {"normal": "normal", "uniform": "uniform", "exponential": "exponential", "poisson": "Poisson(5)", "lognormal": "lognormal ($\\sigma=1$)"}
    fig, ax = plt.subplots(figsize=(5.8, 3.4))
    band = 2 * math.sqrt(0.05 * 0.95 / d["B"])
    ax.axhspan(0.05 - band, 0.05 + band, color=GREY, alpha=0.2, lw=0)
    for p in d["pops"]:
        ax.plot(d["ns"], d["total"][p], "o-", color=cols[p], ms=3.5, label=labs[p])
    ax.axhline(0.05, color="k", lw=0.8, ls="--")
    ax.set_xscale("log"); ax.set_xticks(d["ns"]); ax.set_xticklabels([str(n) for n in d["ns"]])
    ax.set_xlabel("sample size $n$"); ax.set_ylabel("true level of the nominal 0.05 test"); ax.set_ylim(0.0, 0.2)
    ax.legend(frameon=False, ncol=2, fontsize=8.5, loc="upper right")
    savefig(fig, CH, "figx7-1", out)


def fig_x7_2(out=None):
    """Own figure x7.2: power of the one-sided 5% t test against the z test for n = 20, and Example 7.6.1."""
    n = 20
    d = np.linspace(0, 1.1, 200)
    fig, ax = plt.subplots(figsize=(5.6, 3.3))
    ax.plot(d, [z_power(x, n) for x in d], color=BLUE, label="z test ($\\sigma$ known)")
    ax.plot(d, [t_power(x, n) for x in d], color=RED, label="t test ($\\sigma$ unknown)")
    p = t_power(0.5, n)
    ax.plot([0.5], [p], "o", color=RED, ms=5)
    ax.annotate("$d=0.5$: power %.3f,\n$\\beta=%.3f$ (Example 7.6.1)" % (p, 1 - p), (0.5, p), (0.62, 0.35), arrowprops=dict(arrowstyle="->"), fontsize=8.5)
    ax.axhline(0.05, color=GREY, lw=0.8, ls=":")
    ax.set_xlabel("$d=(\\mu_1-\\mu_0)/\\sigma$"); ax.set_ylabel("power"); ax.set_xlim(0, 1.1); ax.set_ylim(0, 1.0); ax.legend(frameon=False, loc="lower right")
    savefig(fig, CH, "figx7-2", out)


def fig_x7_3(out=None):
    """Own figure x7.3: expected width of the 95% interval for sigma^2, equal tails and shortest."""
    ns = np.arange(5, 80)
    eq = np.array([expected_width_ratio(n) for n in ns])
    sh = []
    for n in ns:
        a, b = shortest_interval_cutoffs(int(n), 0.95)
        sh.append((n - 1) * (1 / a - 1 / b))
    fig, ax = plt.subplots(figsize=(5.6, 3.3))
    ax.plot(ns, eq, color=BLUE, label="equal tails (Theorem 7.5.1)")
    ax.plot(ns, sh, color=RED, label="shortest")
    ax.axhline(1.0, color=GREY, lw=0.8, ls="--"); ax.plot([39], [expected_width_ratio(39)], "o", color=BLUE, ms=5)
    ax.annotate("$n=39$", (39, expected_width_ratio(39)), (45, 1.35), arrowprops=dict(arrowstyle="->"), fontsize=9)
    ax.set_xlabel("sample size $n$"); ax.set_ylabel("expected width $/\\ \\sigma^2$"); ax.set_ylim(0, 4); ax.set_xlim(5, 79)
    ax.legend(frameon=False)
    savefig(fig, CH, "figx7-3", out)


# =========================================================================== export for the demos
def demo_reference():
    """Exact (or high-accuracy simulated) numbers that the two browser demonstrations must reproduce."""
    d = {"note": "Reference values for t-test-robustness-demo.html and variance-inference-demo.html."}
    # t-test robustness: true level (lower, upper, total) of the nominal 5% two-sided test
    sizes = {}
    for p in ("normal", "uniform", "exponential", "poisson", "gamma", "lognormal"):
        sizes[p] = {}
        for n in (3, 6, 15, 30):
            lo, hi, tot = true_size(p, n, 0.05, 100000, seed=900 + n)
            sizes[p][str(n)] = {"lo": round(lo, 4), "hi": round(hi, 4), "total": round(tot, 4)}
    d["true_size_two_sided_5pct"] = sizes
    d["t_crit_two_sided_5pct"] = {str(n): round(float(stats.t.ppf(0.975, n - 1)), 4) for n in (3, 6, 15, 30)}
    d["example_7_6_1"] = {"delta": 0.5 * math.sqrt(20), "beta": float(t_beta(0.5, 20)), "z_beta": float(1 - z_power(0.5, 20)),
                          "n_t_80": t_sample_size(0.5, 0.05, 0.8), "n_z_80": z_sample_size(0.5, 0.05, 0.8),
                          "gamma_beta": type2_probability(dist="gamma")}
    # variance inference
    s2 = float(np.var(book_data("ch07-tables")["potassium_argon"], ddof=1))
    d["case_7_5_1"] = {"n": 19, "s2": s2, "ci_sigma": [float(math.sqrt(v)) for v in var_interval(s2, 19)]}
    ret = np.array(book_data("ch07-tables")["global_rock"]["returns"])
    x, c, rej, p = var_test(float(ret.var(ddof=1)), 19, 11.67 ** 2, "less")
    d["case_7_5_2"] = {"n": 19, "s": float(ret.std(ddof=1)), "chi2": float(x), "crit": float(c), "pvalue": float(p)}
    cut = {}
    for n in (5, 10, 19, 30, 60):
        cut[str(n)] = {"equal_tail": [float(v) for v in equal_tail_cutoffs(n)], "glrt": [float(v) for v in glrt_cutoffs(n)],
                       "unbiased": [float(v) for v in unbiased_cutoffs(n)], "shortest_ci": [float(v) for v in shortest_interval_cutoffs(n)]}
    d["cutoffs_5pct"] = cut
    d["width_ratio"] = {str(n): float(expected_width_ratio(n)) for n in (15, 20, 30, 38, 39, 60)}
    d["smallest_n_width_1"] = smallest_n_width()
    return d


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


FIGURES = {
    "7.2.1": fig_7_2_1, "7.3.1": fig_7_3_1, "7.3.2": fig_7_3_2, "7.4.2": fig_7_4_2, "7.4.3": fig_7_4_3,
    "7.4.6": fig_7_4_6, "7.5.1": fig_7_5_1, "7.5.3": fig_7_5_3, "7.A.3.1": fig_7_A_3_1, "7.A.3.2": fig_7_A_3_2,
    "x7.1": fig_x7_1, "x7.2": fig_x7_2, "x7.3": fig_x7_3,
}

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