"""Larsen and Marx (2018), Chapter 6: Hypothesis Testing.

Companion code for Chapter 6 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 (../ch06-hypothesis-testing.html):

* Section 6.2, the decision rule: z_stat, z_crit, z_pvalue (Theorem 6.2.1, Definition 6.2.4) and the gas
  mileage example (critical value 25.718, Figures 6.2.2 to 6.2.6).
* Section 6.3, binomial data: large_sample_ok (inequality 6.3.1), binom_z (Theorem 6.3.1), binom_pvalue_exact
  (the exact test, with the "smallest probabilities" rule for two sides), randomized_gamma (Question 6.3.8) and
  the two case studies (Case Studies 6.3.1 and 6.3.2) and Example 6.3.1 (Figure 6.3.1).
* Section 6.4, Type I and Type II errors: power_z, beta_z, sample_size_z (Example 6.4.1), the largest
  observation of a uniform sample (Example 6.4.2), Poisson sums (Example 6.4.3), the number of runs in a
  sequence of six letters (Case Study 6.4.1: exact distribution runs_pmf, exact p-value of the ten-pair
  experiment) and the power curves (Figures 6.4.4, 6.4.6, 6.4.7, 6.4.8).
* Section 6.5, the generalized likelihood ratio: glr_uniform, glrt_power_uniform (the GLRT of Section 6.5 is exactly
  the test of Example 6.4.2) and glr_normal_mean (Question 6.5.3).
* Section 6.6, statistical versus practical significance: the power curves of Figures 6.6.1 and 6.6.2 and the
  sample size needed to detect a trivial effect.
* Browser demonstrations: demo_reference() exports the exact numbers that glr-uniform-demo.html and
  practical-significance-demo.html show (../data/ch06-demos.json).

Figures. The book has 20 numbered figures and three tables of data in Chapter 6. Those computed from a model are
reproduced: 6.2.2 to 6.2.6 (the gas mileage tail areas, the critical value z_alpha, the two-sided region and the
P-value of Example 6.2.1), 6.3.1 (the binomial probabilities of Example 6.3.1), 6.4.2 to 6.4.4 (Type I and Type
II errors and the power curve), 6.4.6 and 6.4.7 (the effect of alpha and of sigma), 6.4.8 (Example 6.4.2),
6.4.9 and 6.4.10 (the Poisson probabilities of Example 6.4.3), 6.5.1 (the density of the likelihood ratio,
which is exactly flat for the uniform parameter) and 6.6.1, 6.6.2 (the power curves for n = 30, 60, 900).
Skipped, with reasons: 6.2.1 (a sketch of a number line), 6.4.1 (the two-by-two table of decisions and
states of nature), 6.4.5 (two hypothetical power curves, a schematic) and the two Monte Carlo tables 6.2.1 and
6.4.2 (random draws that cannot be reproduced; the exact distribution of Table 6.4.2 is computed instead).
Three figures of our own illustrate Sections 6.3 to 6.5: x6.1, the true size of the large-sample binomial test
against p_0; x6.2, the exact null distribution of the number of runs and of the mean of ten sequences; x6.3,
the power of the likelihood ratio test of Section 6.5 against a test based on the sample mean.
Run `python3 ch06_hypothesis_testing.py --list`, `python3 ch06_hypothesis_testing.py` (all figures, about 30 s)
or `python3 ch06_hypothesis_testing.py --fig 6.4.4`. Files go to ../img/ch06/.
"""
import itertools
import json
import math
import os

import numpy as np
from scipy import stats

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

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


# =========================================================================== Section 6.2
def z_stat(ybar, mu0, sigma, n):
    """The observed z = (ybar - mu0) / (sigma / sqrt(n)) of Theorem 6.2.1."""
    return (ybar - mu0) / (sigma / math.sqrt(n))


def z_crit(alpha, side="greater"):
    """Critical value of Theorem 6.2.1: z_alpha for one side, z_{alpha/2} for 'two'."""
    return N01.isf(alpha / 2) if side == "two" else N01.isf(alpha)


def z_pvalue(z, side="greater"):
    """P-value of Definition 6.2.4 for the Z test."""
    if side == "greater":
        return N01.sf(z)
    if side == "less":
        return N01.cdf(z)
    return 2 * N01.sf(abs(z))


def ystar(mu0, sigma, n, alpha, z=None):
    """Critical sample mean mu0 + z_alpha sigma / sqrt(n) (equation 6.2.1). z overrides the exact quantile."""
    return mu0 + (N01.isf(alpha) if z is None else z) * sigma / math.sqrt(n)


# the running example of Sections 6.2 to 6.6
MU0, SIGMA, N_CARS = 25.0, 2.4, 30


def gas_tail(ystar_value):
    """P(Ybar >= y*) when mu = 25.0, n = 30, sigma = 2.4 (Figures 6.2.2 and 6.2.3)."""
    return N01.sf((ystar_value - MU0) / (SIGMA / math.sqrt(N_CARS)))


# =========================================================================== Section 6.3
def large_sample_ok(n, p0):
    """Inequality (6.3.1): 0 < n p0 - 3 sd and n p0 + 3 sd < n."""
    sd = math.sqrt(n * p0 * (1 - p0))
    return 0 < n * p0 - 3 * sd and n * p0 + 3 * sd < n


def n_threshold(p0):
    """Closed form of (6.3.1): it holds exactly when n > 9 max(p0/(1-p0), (1-p0)/p0)."""
    return 9 * max(p0 / (1 - p0), (1 - p0) / p0)


def binom_z(k, n, p0):
    """The statistic of Theorem 6.3.1."""
    return (k - n * p0) / math.sqrt(n * p0 * (1 - p0))


def binom_pvalue_exact(k, n, p0, side="two"):
    """Exact P-value. 'greater': P(X >= k); 'less': P(X <= k); 'two': the total probability of the outcomes
    that are no more likely than the observed one (the rule used by most software)."""
    d = stats.binom(n, p0)
    if side == "greater":
        return d.sf(k - 1)
    if side == "less":
        return d.cdf(k)
    pk = d.pmf(k)
    allp = d.pmf(np.arange(n + 1))
    return float(allp[allp <= pk * (1 + 1e-9)].sum())


def binom_size_zregion(n, p0, alpha=0.05):
    """Exact size of the two-sided large-sample test of Theorem 6.3.1(c): P(|Z| >= z_{alpha/2}) when p = p0."""
    k = np.arange(n + 1)
    z = (k - n * p0) / math.sqrt(n * p0 * (1 - p0))
    return float(stats.binom.pmf(k, n, p0)[np.abs(z) >= z_crit(alpha, "two")].sum())


def randomized_gamma(n, p0, alpha, k_edge):
    """Question 6.3.8: reject for X >= k_edge + 1, and reject with probability gamma when X = k_edge, where gamma
    solves P(X > k_edge) + gamma P(X = k_edge) = alpha. Returns gamma."""
    d = stats.binom(n, p0)
    return (alpha - d.sf(k_edge)) / d.pmf(k_edge)


def example_6_3_1():
    """Example 6.3.1: the critical region {k <= 13} or {k = 19} for H0: p = 0.85, n = 19."""
    d = stats.binom(19, 0.85)
    return d.cdf(13), d.pmf(19), d.cdf(13) + d.pmf(19)


# =========================================================================== Section 6.4
def power_z(mu, mu0, sigma, n, alpha, side="greater", z=None):
    """Power of the Z test of Theorem 6.2.1 at the true mean mu. z overrides the critical value z_alpha."""
    d = (mu - mu0) * math.sqrt(n) / sigma if np.isscalar(mu) else (np.asarray(mu) - mu0) * math.sqrt(n) / sigma
    if side == "greater":
        za = N01.isf(alpha) if z is None else z
        return N01.cdf(d - za)
    if side == "less":
        za = N01.isf(alpha) if z is None else z
        return N01.cdf(-d - za)
    zh = N01.isf(alpha / 2) if z is None else z
    return N01.cdf(-zh + d) + N01.cdf(-zh - d)


def beta_z(mu, mu0, sigma, n, alpha, side="greater", z=None):
    return 1 - power_z(mu, mu0, sigma, n, alpha, side, z)


def sample_size_z(mu, mu0, sigma, alpha, power, side="greater"):
    """Smallest integer n with power at least `power` at the alternative mu, and the unrounded value.
    one-sided: n = ((z_alpha + z_beta) sigma / (mu - mu0))^2 (equations 6.4.1 and 6.4.2)."""
    za = N01.isf(alpha) if side != "two" else N01.isf(alpha / 2)
    zb = N01.isf(1 - power)
    raw = ((za + zb) * sigma / (mu - mu0)) ** 2
    n = max(1, int(math.ceil(raw)))
    if side == "two":          # the far tail adds a little power: search the exact smallest n
        while n > 1 and power_z(mu, mu0, sigma, n - 1, alpha, "two") >= power:
            n -= 1
        while power_z(mu, mu0, sigma, n, alpha, "two") < power:
            n += 1
    return n, raw


def uniform_max_critical(theta0, n, alpha):
    """Example 6.4.2: reject H0: theta = theta0 against theta < theta0 when Ymax <= theta0 alpha^(1/n)."""
    return theta0 * alpha ** (1.0 / n)


def uniform_power(theta, theta0, n, alpha):
    """P(Ymax <= c | theta) = min(1, (c/theta)^n) with c = theta0 alpha^(1/n): the power of the test of Example
    6.4.2 and of the GLRT of Section 6.5 (they are the same test)."""
    c = uniform_max_critical(theta0, n, alpha)
    th = np.asarray(theta, dtype=float)
    return np.minimum(1.0, (c / th) ** n)


def poisson_sum_test(lam0=0.8, lam1=1.2, n=4, c=6):
    """Example 6.4.3: reject when the sum of n Poisson(lambda) counts is at least c."""
    return stats.poisson.sf(c - 1, n * lam0), stats.poisson.sf(c - 1, n * lam1)


def example_6_4_4():
    """Example 6.4.4: p = P(Y >= 0.9) under 3y^2 on (0,1) and the size of 'reject if X >= 4' with 7 observations."""
    p = 1 - 0.9 ** 3
    return p, stats.binom.sf(3, 7, p)


# ---- Case Study 6.4.1: runs in a sequence of six letters
def n_runs(seq):
    return 1 + sum(a != b for a, b in zip(seq, seq[1:]))


def runs_pmf(L=6):
    """Exact null distribution of the number of runs in L independent fair A/B letters: 1 + Binomial(L-1, 1/2)."""
    k = np.arange(1, L + 1)
    return k, stats.binom.pmf(k - 1, L - 1, 0.5)


def runs_moments(L=6):
    """mean 1 + (L-1)/2 and variance (L-1)/4 (the book estimates 3.49 and 1.17 by simulation for L = 6)."""
    return 1 + (L - 1) / 2, (L - 1) / 4


def runs_z(runs=None, n=10, L=6, mu0=None, var0=None):
    """The Z ratio of Case Study 6.4.1 with exact (or supplied) null moments."""
    d = book_data("ch06-spawning")
    runs = np.array(d["runs"] if runs is None else runs, dtype=float)
    m, v = runs_moments(L)
    m = m if mu0 is None else mu0
    v = v if var0 is None else var0
    return (runs.mean() - m) / math.sqrt(v / len(runs))


def runs_sum_pvalue(total=50, n=10, L=6):
    """Exact two-sided P-value of the ten-pair experiment: the sum of n independent run counts is
    n + Binomial(n (L-1), 1/2), so P(sum >= total) is a binomial tail."""
    m = n + n * (L - 1) / 2
    upper = stats.binom.sf(total - n - 1, n * (L - 1), 0.5)
    lower = stats.binom.cdf(2 * m - total - n, n * (L - 1), 0.5)
    return upper, min(1.0, upper + lower)


# =========================================================================== Section 6.5
def glr_uniform(ymax, theta0, n):
    """The generalized likelihood ratio lambda = (ymax / theta0)^n of Section 6.5."""
    return (ymax / theta0) ** n


def glr_uniform_critical(theta0, n, alpha):
    """w* = alpha^(1/n) for W = Ymax / theta0, i.e. lambda* = alpha: the GLR is exactly Uniform(0, 1) under H0."""
    return alpha ** (1.0 / n)


def glr_normal_mean(ybar, mu0, sigma, n):
    """Question 6.5.3: lambda = exp(-z^2 / 2) with z = sqrt(n) (ybar - mu0) / sigma."""
    z = z_stat(ybar, mu0, sigma, n)
    return math.exp(-0.5 * z * z)


def glr_binomial_half(k, n):
    """Question 6.5.5: lambda = 2^(-n) / [(k/n)^k (1-k/n)^(n-k)] for H0: p = 1/2, written through
    k ln k + (n-k) ln(n-k), which is symmetric about k = n/2."""
    k = np.asarray(k, dtype=float)
    kl = np.where(k > 0, k * np.log(np.where(k > 0, k, 1.0)), 0.0) + np.where(n - k > 0, (n - k) * np.log(np.where(n - k > 0, n - k, 1.0)), 0.0)
    return np.exp(-n * math.log(2) + n * math.log(n) - kl)


# =========================================================================== Section 6.6
def power_curve_mpg(mu, n, alpha=0.05):
    """Power of the one-sided Z test of H0: mu = 25 at sigma = 2.4 (Figures 6.4.4, 6.6.1, 6.6.2)."""
    return power_z(mu, MU0, SIGMA, n, alpha)


def n_for_effect(delta, sigma=SIGMA, alpha=0.05, power=0.9):
    """Sample size needed to detect a mean shift delta with the one-sided Z test (the 25.001 mpg thought experiment)."""
    return sample_size_z(MU0 + delta, MU0, sigma, alpha, power)


# =========================================================================== figures
def _two_densities(ax, mu_a, mu_b, sd, ystar_v, xlim, labels=("$H_0$ true", "$H_1$ true"), shade=True):
    x = np.linspace(*xlim, 600)
    ax.plot(x, N01.pdf(x, mu_a, sd), color=BLUE, label=labels[0])
    ax.plot(x, N01.pdf(x, mu_b, sd), color=RED, label=labels[1])
    if shade:
        xr = x[x >= ystar_v]
        ax.fill_between(xr, N01.pdf(xr, mu_a, sd), color=BLUE, alpha=.35)
        xl = x[x <= ystar_v]
        ax.fill_between(xl, N01.pdf(xl, mu_b, sd), color=RED, alpha=.30)
    ax.axvline(ystar_v, color="k", lw=1, ls="--")
    ax.set_xlim(*xlim); ax.set_ylim(bottom=0)


def fig_6_2_2(out=None):
    """Figure 6.2.2: P(Ybar >= 25.25 | mu = 25) = 0.2843."""
    se = SIGMA / math.sqrt(N_CARS)
    x = np.linspace(23.5, 26.5, 600)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.plot(x, N01.pdf(x, MU0, se), color=BLUE)
    xr = x[x >= 25.25]; ax.fill_between(xr, N01.pdf(xr, MU0, se), color=BLUE, alpha=.35)
    ax.axvline(25.25, color="k", lw=1, ls="--")
    ax.text(25.3, 0.35, "area = %.4f" % gas_tail(25.25), color=BLUE)
    ax.text(25.29, 0.05, "reject $H_0$", fontsize=8.5); ax.text(24.2, 0.05, "do not reject", fontsize=8.5)
    ax.set_xlabel("$\\bar y$ (distribution of $\\bar Y$ when $\\mu=25.0$)"); ax.set_ylabel("density"); ax.set_xlim(23.5, 26.5); ax.set_ylim(bottom=0)
    ax.set_title("$y^*=25.25$", fontsize=9.5)
    savefig(fig, CH, "fig6-2-2", out)


def fig_6_2_3(out=None):
    """Figure 6.2.3: P(Ybar >= 26.50 | mu = 25) = 0.0003."""
    se = SIGMA / math.sqrt(N_CARS)
    x = np.linspace(23.5, 27, 600)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.plot(x, N01.pdf(x, MU0, se), color=BLUE)
    xr = x[x >= 26.5]; ax.fill_between(xr, N01.pdf(xr, MU0, se), color=BLUE, alpha=.6)
    ax.axvline(26.5, color="k", lw=1, ls="--")
    ax.annotate("area = %.4f" % gas_tail(26.5), (26.55, 0.01), (26.0, 0.35), color=BLUE, arrowprops=dict(arrowstyle="->", color=BLUE))
    ax.set_xlabel("$\\bar y$ (distribution of $\\bar Y$ when $\\mu=25.0$)"); ax.set_ylabel("density"); ax.set_xlim(23.5, 27); ax.set_ylim(bottom=0)
    ax.set_title("$y^*=26.50$", fontsize=9.5)
    savefig(fig, CH, "fig6-2-3", out)


def fig_6_2_4(out=None):
    """Figure 6.2.4: the number z_alpha with P(Z >= z_alpha) = alpha, for alpha = 0.05."""
    z = np.linspace(-3.5, 3.5, 600)
    fig, ax = plt.subplots(figsize=(5.0, 2.9))
    ax.plot(z, N01.pdf(z), color=BLUE)
    zr = z[z >= 1.6449]; ax.fill_between(zr, N01.pdf(zr), color=BLUE, alpha=.35)
    ax.axvline(1.6449, color="k", lw=1, ls="--")
    ax.annotate("area = 0.05", (2.2, 0.03), (2.3, 0.17), color=BLUE, arrowprops=dict(arrowstyle="->", color=BLUE))
    ax.text(1.55, 0.43, "$z_{.05}=1.64$", fontsize=9, ha="right")
    ax.set_xlabel("z"); ax.set_ylabel("$f_Z(z)$"); ax.set_xlim(-3.5, 3.5); ax.set_ylim(0, 0.45)
    savefig(fig, CH, "fig6-2-4", out)


def fig_6_2_5(out=None):
    """Figure 6.2.5: two-sided 0.05 critical region and the observed z = 0.60 of Example 6.2.1."""
    z = np.linspace(-3.5, 3.5, 600)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.plot(z, N01.pdf(z), color=BLUE)
    for sgn in (1, -1):
        zz = z[sgn * z >= 1.96]; ax.fill_between(zz, N01.pdf(zz), color=RED, alpha=.4)
    ax.axvline(0.60, color=GREEN, lw=1.6); ax.text(0.72, 0.43, "observed $z=0.60$", color=GREEN, fontsize=9)
    ax.text(2.0, 0.07, "0.025", color=RED); ax.text(-3.0, 0.07, "0.025", color=RED)
    ax.text(2.2, 0.20, "reject $H_0$", color=RED, fontsize=8.5); ax.text(-3.4, 0.20, "reject $H_0$", color=RED, fontsize=8.5)
    ax.set_xticks([-1.96, 0, 1.96]); ax.set_xticklabels(["$-1.96$", "0", "1.96"]); ax.set_xlabel("z"); ax.set_ylabel("$f_Z(z)$"); ax.set_xlim(-3.5, 3.5); ax.set_ylim(0, 0.48)
    savefig(fig, CH, "fig6-2-5", out)


def fig_6_2_6(out=None):
    """Figure 6.2.6: the two-sided P-value 0.5486 for z = 0.60."""
    z = np.linspace(-3.5, 3.5, 600)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.plot(z, N01.pdf(z), color=BLUE)
    for sgn in (1, -1):
        zz = z[sgn * z >= 0.60]; ax.fill_between(zz, N01.pdf(zz), color=ORANGE, alpha=.45)
    ax.text(1.35, 0.06, "%.4f" % N01.sf(0.6), color="#a05000"); ax.text(-2.45, 0.06, "%.4f" % N01.sf(0.6), color="#a05000")
    ax.text(0, 0.43, "P-value = %.4f" % z_pvalue(0.60, "two"), ha="center", fontsize=9.5)
    ax.set_xticks([-0.6, 0, 0.6]); ax.set_xticklabels(["$-0.60$", "0", "0.60"]); ax.set_xlabel("z"); ax.set_ylabel("$f_Z(z)$"); ax.set_xlim(-3.5, 3.5); ax.set_ylim(0, 0.48)
    savefig(fig, CH, "fig6-2-6", out)


def fig_6_3_1(out=None):
    """Figure 6.3.1: the Bin(19, 0.85) probabilities of Example 6.3.1 and the critical region {k <= 13} or {k = 19}."""
    k = np.arange(6, 20)
    p = stats.binom.pmf(k, 19, 0.85)
    crit = (k <= 13) | (k == 19)
    fig, ax = plt.subplots(figsize=(5.4, 3.0))
    ax.bar(k, p, color=np.where(crit, RED, "#9db8e8"), edgecolor="white")
    ax.annotate("$P(X\\leq13)=%.4f$" % stats.binom.cdf(13, 19, .85), (12.5, 0.02), (7.2, 0.12), color=RED, fontsize=9, arrowprops=dict(arrowstyle="->", color=RED))
    ax.annotate("$P(X=19)=%.4f$" % stats.binom.pmf(19, 19, .85), (19, 0.046), (17.6, 0.27), color=RED, fontsize=9, arrowprops=dict(arrowstyle="->", color=RED))
    ax.set_xlabel("k"); ax.set_ylabel("$p_X(k)$"); ax.set_xlim(5.4, 20.4); ax.set_ylim(0, 0.31)
    ax.set_title("n = 19, $p_0=0.85$: red = critical region, $\\alpha=%.4f$" % sum(example_6_3_1()[:2]), fontsize=9.5)
    savefig(fig, CH, "fig6-3-1", out)


def _alpha_beta_panel(ax, mu1, ystar_v, sd, xlim, ylab=True, sig=None):
    x = np.linspace(*xlim, 700)
    ax.plot(x, N01.pdf(x, MU0, sd), color=BLUE, label="$\\bar Y$ when $H_0$ is true")
    ax.plot(x, N01.pdf(x, mu1, sd), color=RED, label="$\\bar Y$ when $\\mu=%s$" % ("%g" % mu1))
    xr = x[x >= ystar_v]; ax.fill_between(xr, N01.pdf(xr, MU0, sd), color=BLUE, alpha=.40)
    xl = x[x <= ystar_v]; ax.fill_between(xl, N01.pdf(xl, mu1, sd), color=RED, alpha=.30)
    ax.axvline(ystar_v, color="k", lw=1, ls="--")
    ax.set_xlim(*xlim); ax.set_ylim(bottom=0); ax.set_xlabel("$\\bar y$")
    if ylab:
        ax.set_ylabel("density")


def fig_6_4_2(out=None):
    """Figure 6.4.2: alpha = 0.05 and beta = 0.4721 when mu = 25.75 (critical value 25.718)."""
    se = SIGMA / math.sqrt(N_CARS)
    fig, ax = plt.subplots(figsize=(5.4, 3.1))
    _alpha_beta_panel(ax, 25.75, 25.718, se, (23.8, 27.0))
    b = float(N01.cdf((25.718 - 25.75) / (SIGMA / math.sqrt(N_CARS))))
    ax.text(0.02, 0.97, "blue area $\\alpha=0.05$\nred area $\\beta=%.3f$" % b, transform=ax.transAxes, va="top", fontsize=9)
    ax.legend(fontsize=8, loc="upper right")
    savefig(fig, CH, "fig6-4-2", out)


def fig_6_4_3(out=None):
    """Figure 6.4.3: alpha = 0.05 and beta = 0.0068 when mu = 26.8."""
    se = SIGMA / math.sqrt(N_CARS)
    fig, ax = plt.subplots(figsize=(5.4, 3.1))
    _alpha_beta_panel(ax, 26.8, 25.718, se, (23.8, 28.0))
    b = float(N01.cdf((25.718 - 26.8) / (SIGMA / math.sqrt(N_CARS))))
    ax.text(0.02, 0.97, "blue area $\\alpha=0.05$\nred area $\\beta=%.4f$" % b, transform=ax.transAxes, va="top", fontsize=9)
    ax.legend(fontsize=8, loc="upper right")
    savefig(fig, CH, "fig6-4-3", out)


def fig_6_4_4(out=None):
    """Figure 6.4.4: the power curve of the one-sided test, n = 30, alpha = 0.05."""
    mu = np.linspace(25, 27.2, 400)
    fig, ax = plt.subplots(figsize=(5.2, 3.2))
    ax.plot(mu, power_curve_mpg(mu, 30), color=BLUE)
    for m, col in ((25.75, RED), (26.8, GREEN), (26.0, GREY), (25.5, GREY)):
        v = float(power_curve_mpg(m, 30))
        ax.plot([m], [v], "o", color=col, ms=5); ax.annotate("%.2f" % v, (m, v), textcoords="offset points", xytext=(6, -12), fontsize=8.5, color=col)
    ax.axhline(0.05, color="k", lw=.8, ls=":"); ax.text(26.6, 0.07, "$\\alpha=0.05$", fontsize=8.5)
    ax.set_xlabel("presumed value of $\\mu$"); ax.set_ylabel("power $1-\\beta$"); ax.set_xlim(25, 27.2); ax.set_ylim(0, 1.03); ax.grid(alpha=.25)
    savefig(fig, CH, "fig6-4-4", out)


def fig_6_4_6(out=None):
    """Figure 6.4.6: raising alpha from 0.05 to 0.10 lowers beta and raises the power (mu = 25.75)."""
    se = SIGMA / math.sqrt(N_CARS)
    fig, axes = common.panel_grid(2, 1, size=(5.2, 2.5), sharex=True)
    for ax, a, ys in zip(axes[:, 0], (0.05, 0.10), (25.718, 25.561)):
        _alpha_beta_panel(ax, 25.75, ys, se, (23.8, 27.0))
        pw = float(power_z(25.75, MU0, SIGMA, N_CARS, a, z=(ys - MU0) * math.sqrt(N_CARS) / SIGMA))
        ax.set_title("$\\alpha=%.2f$: critical value %.3f, power %.3f" % (a, ys, pw), fontsize=9.2)
    axes[0, 0].legend(fontsize=7.5, loc="upper right")
    fig.tight_layout()
    savefig(fig, CH, "fig6-4-6", out)


def fig_6_4_7(out=None):
    """Figure 6.4.7: halving sigma from 2.4 to 1.2 (alpha = 0.05, mu = 25.75)."""
    fig, axes = common.panel_grid(2, 1, size=(5.2, 2.5), sharex=True)
    for ax, s, ys in zip(axes[:, 0], (2.4, 1.2), (25.718, 25.359)):
        se = s / math.sqrt(N_CARS)
        _alpha_beta_panel(ax, 25.75, ys, se, (23.8, 27.0))
        pw = float(power_z(25.75, MU0, s, N_CARS, 0.05, z=(ys - MU0) * math.sqrt(N_CARS) / s))
        ax.set_title("$\\sigma=%.1f$: critical value %.3f, power %.3f" % (s, ys, pw), fontsize=9.2)
    axes[0, 0].legend(fontsize=7.5, loc="upper right")
    fig.tight_layout()
    savefig(fig, CH, "fig6-4-7", out)


def fig_6_4_8(out=None):
    """Figure 6.4.8: the density of the largest of 8 observations when theta = 2.0 and theta = 1.7 (Example 6.4.2)."""
    c = uniform_max_critical(2.0, 8, 0.10)
    y2 = np.linspace(0, 2, 500); y17 = np.linspace(0, 1.7, 500)
    fig, ax = plt.subplots(figsize=(5.4, 3.1))
    ax.plot(y2, 8 * y2 ** 7 / 2.0 ** 8, color=BLUE, label="$\\theta=2.0$ ($H_0$ true)")
    ax.plot(y17, 8 * y17 ** 7 / 1.7 ** 8, color=RED, label="$\\theta=1.7$ ($H_1$ true)")
    yl = y2[y2 <= c]; ax.fill_between(yl, 8 * yl ** 7 / 2.0 ** 8, color=BLUE, alpha=.4)
    yr = y17[y17 >= c]; ax.fill_between(yr, 8 * yr ** 7 / 1.7 ** 8, color=RED, alpha=.3)
    ax.axvline(c, color="k", lw=1, ls="--")
    ax.text(1.12, 0.6, "$\\alpha=0.10$", color=BLUE); ax.text(1.60, 4.1, "$\\beta=%.2f$" % (1 - float(uniform_power(1.7, 2.0, 8, 0.10))), color=RED, ha="right")
    ax.text(c - 0.02, 5.0, "$c=%.2f$" % c, ha="right", fontsize=9)
    ax.set_xlabel("largest observation $y_{\\max}$"); ax.set_ylabel("density"); ax.set_xlim(0, 2.1); ax.set_ylim(0, 5.6); ax.legend(fontsize=8, loc="upper left")
    savefig(fig, CH, "fig6-4-8", out)


def _poisson_fig(lam, name, title, color, out):
    k = np.arange(0, 17 if lam < 4 else 21)
    p = stats.poisson.pmf(k, lam)
    fig, ax = plt.subplots(figsize=(5.4, 3.0))
    ax.bar(k, p, color=np.where(k >= 6, color, "#9db8e8"), edgecolor="white")
    ax.set_xlabel("$\\sum k_i$"); ax.set_ylabel("probability"); ax.set_title(title % stats.poisson.sf(5, lam), fontsize=9.5)
    ax.set_xlim(-0.6, k[-1] + 0.6)
    savefig(fig, CH, name, out)


def fig_6_4_9(out=None):
    """Figure 6.4.9: Poisson(3.2), the law of the sum of four counts under H0 (alpha = 0.1054)."""
    _poisson_fig(3.2, "fig6-4-9", "Poisson(3.2), $H_0$ true: $P(\\sum k_i\\geq6)=%.4f=\\alpha$", RED, out)


def fig_6_4_10(out=None):
    """Figure 6.4.10: Poisson(4.8), the law of the sum when lambda = 1.2 (power 0.3490)."""
    _poisson_fig(4.8, "fig6-4-10", "Poisson(4.8), $\\lambda=1.2$: $P(\\sum k_i\\geq6)=%.4f=1-\\beta$", GREEN, out)


def fig_6_5_1(out=None):
    """Figure 6.5.1: the density of the GLR under H0 for the uniform model. It is exactly flat on (0, 1)."""
    fig, ax = plt.subplots(figsize=(5.0, 2.8))
    lam = np.linspace(0, 1, 200)
    ax.plot(lam, np.ones_like(lam), color=BLUE)
    a = 0.10
    ax.fill_between(lam[lam <= a], 1, color=RED, alpha=.4); ax.axvline(a, color="k", lw=1, ls="--")
    ax.text(a + .02, 0.45, "$\\lambda^*=\\alpha$", fontsize=9.5); ax.text(0.01, 1.08, "reject $H_0$: area $\\alpha$", color=RED, fontsize=8.5)
    ax.set_xlabel("$\\lambda$"); ax.set_ylabel("$f_\\Lambda(\\lambda\\mid H_0)$"); ax.set_xlim(0, 1); ax.set_ylim(0, 1.3)
    ax.set_title("uniform model, any $n$: $\\Lambda=(Y_{\\max}/\\theta_0)^n\\sim$ Uniform(0,1)", fontsize=9.2)
    savefig(fig, CH, "fig6-5-1", out)


def fig_6_6_1(out=None):
    """Figure 6.6.1: the power curve of the gas-mileage test with n = 30."""
    mu = np.linspace(25, 26.6, 300)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.plot(mu, power_curve_mpg(mu, 30), color=BLUE)
    v = float(power_curve_mpg(25.75, 30)); ax.plot([25.75], [v], "o", color=RED); ax.annotate("(25.75, %.2f)" % v, (25.75, v), xytext=(25.82, v - .1), color=RED, fontsize=9)
    ax.set_xlabel("$\\mu$"); ax.set_ylabel("$1-\\beta$"); ax.set_xlim(25, 26.6); ax.set_ylim(0, 1.03); ax.grid(alpha=.25)
    ax.text(26.0, 0.12, "n = 30", color=BLUE)
    savefig(fig, CH, "fig6-6-1", out)


def fig_6_6_2(out=None):
    """Figure 6.6.2: power curves for n = 30, 60 and 900."""
    mu = np.linspace(25, 26.6, 400)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    for n, col in ((30, BLUE), (60, GREEN), (900, RED)):
        ax.plot(mu, power_curve_mpg(mu, n), color=col, label="n = %d" % n)
    ax.plot([25.25] * 3, [float(power_curve_mpg(25.25, n)) for n in (30, 60, 900)], "ko", ms=4)
    ax.set_xlabel("$\\mu$"); ax.set_ylabel("$1-\\beta$"); ax.set_xlim(25, 26.6); ax.set_ylim(0, 1.03); ax.grid(alpha=.25); ax.legend(fontsize=8.5, loc="center right")
    savefig(fig, CH, "fig6-6-2", out)


def fig_x6_1(out=None):
    """Own figure: the true size of the two-sided large-sample binomial test against p0, and the region where (6.3.1) holds."""
    p0 = np.linspace(0.03, 0.97, 941)
    fig, axes = common.panel_grid(1, 2, size=(3.5, 2.9))
    ax = axes[0, 0]
    for n, col in ((25, ORANGE), (100, BLUE)):
        ax.plot(p0, [binom_size_zregion(n, p) for p in p0], color=col, lw=.9, label="n = %d" % n)
    ax.axhline(0.05, color="k", lw=.8, ls=":"); ax.set_xlabel("$p_0$"); ax.set_ylabel("true size, nominal 0.05"); ax.set_ylim(0, 0.13); ax.legend(fontsize=8)
    common.panel_label(ax, "a", "upper center")
    ax = axes[0, 1]
    q = np.linspace(0.02, 0.98, 300)
    ax.plot(q, [n_threshold(p) for p in q], color=PURPLE)
    ax.fill_between(q, [n_threshold(p) for p in q], 1500, color=PURPLE, alpha=.12)
    ax.set_yscale("log"); ax.set_ylim(9, 1500); ax.set_xlabel("$p_0$"); ax.set_ylabel("n"); ax.text(0.5, 40, "(6.3.1) holds", ha="center", fontsize=8.5)
    ax.plot([0.25], [747], "o", color=GREEN, ms=4); ax.plot([0.85], [19], "o", color=RED, ms=4)
    ax.text(0.28, 800, "Case Study 6.3.2", fontsize=7.5, color=GREEN); ax.text(0.62, 10.5, "Example 6.3.1", fontsize=7.5, color=RED, ha="left")
    common.panel_label(ax, "b", "upper center")
    fig.tight_layout()
    savefig(fig, CH, "figx6-1", out)


def fig_x6_2(out=None):
    """Own figure: the exact distribution of the number of runs in six letters and of the mean of ten such counts."""
    k, p = runs_pmf(6)
    d = book_data("ch06-spawning")
    fig, axes = common.panel_grid(1, 2, size=(3.6, 2.9))
    ax = axes[0, 0]
    ax.bar(k - 0.2, p, width=0.4, color=BLUE, label="exact")
    ax.bar(np.array(d["mc_k"]) + 0.2, np.array(d["mc_freq"]) / d["mc_total"], width=0.4, color=ORANGE, label="Table 6.4.2 (500 draws)")
    ax.set_xlabel("number of runs k"); ax.set_ylabel("probability"); ax.set_ylim(0, 0.43); ax.legend(fontsize=7.5, loc="upper center"); common.panel_label(ax, "a", "upper left")
    ax = axes[0, 1]
    s = np.arange(10, 61); ps = stats.binom.pmf(s - 10, 50, 0.5)
    ax.bar(s / 10, ps * 10, width=0.1, color="#9db8e8")
    m, v = runs_moments(6); xs = np.linspace(2, 5.2, 300)
    ax.plot(xs, N01.pdf(xs, m, math.sqrt(v / 10)), color=RED, lw=1.2)
    ax.axvline(5.0, color=GREEN, lw=1.5); ax.text(4.9, 0.55, "observed 5.0", color=GREEN, fontsize=8, ha="right")
    ax.set_xlabel("mean number of runs, 10 sequences"); ax.set_ylabel("density"); ax.set_xlim(2, 5.3); common.panel_label(ax, "b", "upper left")
    fig.tight_layout()
    savefig(fig, CH, "figx6-2", out)


def sim_mean_test_power(theta, theta0, n, alpha, reps=40000, seed=6):
    """Simulated power of 'reject if the sample mean is at most c', with c the simulated alpha quantile under H0."""
    rng = np.random.default_rng(seed)
    null = (rng.random((reps, n)) * theta0).mean(axis=1)
    c = np.quantile(null, alpha)
    out = []
    for th in np.atleast_1d(theta):
        out.append(float(((rng.random((reps, n)) * th).mean(axis=1) <= c).mean()))
    return np.array(out), c


def fig_x6_3(out=None):
    """Own figure: the power of the likelihood ratio test (largest observation) against a test based on the sample mean."""
    th = np.linspace(0.9, 2.0, 40)
    pm, _ = sim_mean_test_power(th, 2.0, 8, 0.10)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.plot(th, uniform_power(th, 2.0, 8, 0.10), color=BLUE, label="likelihood ratio test (largest observation)")
    ax.plot(th, pm, color=RED, ls="--", label="test based on the sample mean")
    ax.axhline(0.10, color="k", lw=.8, ls=":")
    ax.set_xlabel("true $\\theta$ ($H_0$: $\\theta=2$)"); ax.set_ylabel("power"); ax.set_ylim(0, 1.03); ax.legend(fontsize=8, loc="upper right"); ax.grid(alpha=.25)
    ax.set_title("n = 8, $\\alpha=0.10$; the sample-mean curve is simulated", fontsize=9)
    savefig(fig, CH, "figx6-3", out)


# =========================================================================== demo reference numbers
def demo_reference():
    """Exact numbers shown by the two demonstrations (the same formulas run in the browser)."""
    out = {}
    out["mpg"] = dict(
        ystar=ystar(25, 2.4, 30, .05), se=2.4 / math.sqrt(30),
        power_25_75=float(power_curve_mpg(25.75, 30)), power_25_25=[float(power_curve_mpg(25.25, n)) for n in (30, 60, 900)],
        n_for_25_001=n_for_effect(0.001)[0], n_for_0_5=n_for_effect(0.5)[0], n_for_0_25=n_for_effect(0.25)[0])
    out["uniform"] = dict(
        c=uniform_max_critical(2.0, 8, .1), power_1_7=float(uniform_power(1.7, 2.0, 8, .1)),
        power_1_9=float(uniform_power(1.9, 2.0, 8, .1)), power_1_5=float(uniform_power(1.5, 2.0, 8, .1)),
        n20_c=uniform_max_critical(2.0, 20, .05), n20_power_1_9=float(uniform_power(1.9, 2.0, 20, .05)))
    pm, cmean = sim_mean_test_power([1.7, 1.9], 2.0, 8, .10, reps=200000)
    out["uniform"]["mean_test_power_1_7_sim"] = float(pm[0]); out["uniform"]["mean_test_power_1_9_sim"] = float(pm[1])
    return out


def export_json():
    os.makedirs(DATA_OUT, exist_ok=True)
    path = os.path.join(DATA_OUT, "ch06-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 = {
    "6.2.2": fig_6_2_2, "6.2.3": fig_6_2_3, "6.2.4": fig_6_2_4, "6.2.5": fig_6_2_5, "6.2.6": fig_6_2_6,
    "6.3.1": fig_6_3_1, "6.4.2": fig_6_4_2, "6.4.3": fig_6_4_3, "6.4.4": fig_6_4_4, "6.4.6": fig_6_4_6,
    "6.4.7": fig_6_4_7, "6.4.8": fig_6_4_8, "6.4.9": fig_6_4_9, "6.4.10": fig_6_4_10, "6.5.1": fig_6_5_1,
    "6.6.1": fig_6_6_1, "6.6.2": fig_6_6_2,
    "x6.1": fig_x6_1, "x6.2": fig_x6_2, "x6.3": fig_x6_3,
}

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