"""Larsen and Marx (2018), Chapter 10: Goodness-of-Fit Tests.

Companion code for Chapter 10 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 (../ch10-goodness-of-fit.html):

* Section 10.2, the multinomial law: multinomial_pmf (Theorem 10.2.1), compositions (every outcome of a
  multinomial experiment, for exact calculations), multinomial_cov (the covariance matrix n(diag p - p p^T)).
* Section 10.3, all parameters known: pearson (the statistic d of Theorem 10.3.1), pearson_mean_var (exact mean
  t - 1 and variance), pearson_exact (the exact null distribution of D by enumeration, and the exact size of the
  chi-square test), glr_stat (the likelihood ratio statistic that D approximates), complement_basis (an orthonormal
  basis of the plane orthogonal to (sqrt p_1, ..., sqrt p_t), the geometry behind t - 1 degrees of freedom),
  benford, pareto_first_digit (Case Study 10.3.2 and its "About the Data").
* Section 10.4, parameters estimated: cell probability functions for the binomial, pooled Poisson, grouped normal
  and grouped exponential models; raw_mle and grouped_mle (Fisher scoring on the multinomial likelihood of the
  counts); grouped_info and cl_lambdas (the Chernoff-Lehmann weights, which say how far the raw-data estimate moves
  the null law of D1 from chi-square with t - 1 - s degrees of freedom); simulate_null.
* Section 10.5, contingency tables: contingency (estimated expected counts, d2, (r - 1)(c - 1) df), two_by_two
  (closed form and the equivalent two-proportion z), fisher_exact_2x2 (the exact conditional test).
* Section 10.6, outliers: dixon_r and dixon_null (Dixon's ratio and its null distribution by simulation).
* Browser demonstrations: demo_reference() exports the numbers that pearson-geometry-demo.html and
  estimated-parameters-demo.html show (../data/ch10-gof.json).

Figures. The book has eight numbered figures in Chapter 10. Those computed from a model are reproduced: 10.2.2 (the
density 6y(1 - y) cut into four ranges), 10.3.2 (the chi-square density with 1 df and its 0.05 critical region),
10.3.3 (two Pareto densities) and 10.3.4 (the chi-square density with 3 df and Mendel's d = 0.47). Skipped, with
reasons: 10.2.1 (a schematic of n trials with t outcomes each) and 10.3.1 (a drawing of the two forms of the
crustacean). Three figures of our own: x10.1, the geometry of Pearson's statistic (the residual vector lives in a
plane, so t = 3 classes give 2 degrees of freedom) and the exact size of the test for small expected counts;
x10.2, the null distributions of D1 with known, grouped-MLE and raw-data-MLE parameters for the designs of Case
Studies 10.4.2 and 10.4.3 and for a coarse grouping; x10.3, the null distribution of Dixon's ratio for n = 20.
Run `python3 ch10_goodness_of_fit.py --list`, `python3 ch10_goodness_of_fit.py` (all figures, about a minute the
first time, a few seconds afterwards: simulations are cached in cache/) or `python3 ch10_goodness_of_fit.py --fig
10.3.4`. Files go to ../img/ch10/.
"""
import itertools
import json
import math
import os

import numpy as np
from scipy import special, stats

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

CH = 10
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))
CACHE = os.path.join(HERE, "cache")
TABLES = book_data("ch10-tables")


# =========================================================================== Section 10.2
def multinomial_pmf(k, p):
    """Theorem 10.2.1: n! / (k_1! ... k_t!) p_1^k_1 ... p_t^k_t, computed on the log scale."""
    k = np.asarray(k, dtype=float)
    p = np.asarray(p, dtype=float)
    n = k.sum(axis=-1)
    with np.errstate(divide="ignore", invalid="ignore"):
        logp = np.where(k > 0, k * np.log(p), 0.0).sum(axis=-1)
    return np.exp(special.gammaln(n + 1) - special.gammaln(k + 1).sum(axis=-1) + logp)


def compositions(n, t):
    """Every vector (k_1, ..., k_t) of non-negative integers with sum n (stars and bars), as an array (M, t)."""
    bars = np.array(list(itertools.combinations(range(n + t - 1), t - 1)), dtype=np.int64).reshape(-1, t - 1)
    edges = np.hstack([np.full((len(bars), 1), -1), bars, np.full((len(bars), 1), n + t - 1)])
    return np.diff(edges, axis=1) - 1


def multinomial_cov(n, p):
    """Covariance matrix of a multinomial vector: n (diag p - p p^T)."""
    p = np.asarray(p, dtype=float)
    return n * (np.diag(p) - np.outer(p, p))


def grade_table(mu=80.0, sigma=5.0, n=50):
    """Example 10.2.3: probabilities, means and variances of the counts of A, B, C, D, F."""
    cuts = [(90, np.inf), (80, 90), (70, 80), (60, 70), (-np.inf, 60)]
    p = np.array([stats.norm.cdf(b, mu, sigma) - stats.norm.cdf(a, mu, sigma) for a, b in cuts])
    return p, n * p, n * p * (1 - p)


# =========================================================================== Section 10.3
def pearson(k, e):
    """Pearson's statistic sum (k_i - e_i)^2 / e_i (d of Theorem 10.3.1, d1 of 10.4.1, d2 of 10.5.1)."""
    k = np.asarray(k, dtype=float)
    e = np.asarray(e, dtype=float)
    return float(((k - e) ** 2 / e).sum())


def pearson_known(k, p0, alpha=0.05):
    """Theorem 10.3.1: d, df = t - 1, critical value and p-value."""
    k = np.asarray(k, dtype=float)
    p0 = np.asarray(p0, dtype=float)
    d = pearson(k, k.sum() * p0)
    df = len(k) - 1
    return dict(d=d, df=df, crit=stats.chi2.isf(alpha, df), p=stats.chi2.sf(d, df))


def pearson_mean_var(n, p):
    """Exact mean and variance of D under H0 (any n): t - 1 and 2(t - 1) + (sum 1/p_i - t^2 - 2t + 2)/n."""
    p = np.asarray(p, dtype=float)
    t = len(p)
    return t - 1.0, 2.0 * (t - 1) + ((1 / p).sum() - t * t - 2 * t + 2) / n


def pearson_exact(n, p, alpha=0.05):
    """Exact null distribution of D by enumerating every outcome; returns values, probabilities and the exact size
    P(D >= chi2_{1-alpha, t-1}) of the chi-square test."""
    p = np.asarray(p, dtype=float)
    K = compositions(n, len(p))
    e = n * p
    d = ((K - e) ** 2 / e).sum(axis=1)
    w = multinomial_pmf(K, p)
    crit = stats.chi2.isf(alpha, len(p) - 1)
    return d, w, float(w[d >= crit - 1e-9].sum())


def glr_stat(k, e):
    """-2 ln(lambda) = 2 sum k_i ln(k_i / e_i) for the multinomial (empty cells contribute 0)."""
    k = np.asarray(k, dtype=float)
    e = np.asarray(e, dtype=float)
    with np.errstate(divide="ignore", invalid="ignore"):
        return float(2 * np.where(k > 0, k * np.log(k / e), 0.0).sum())


def complement_basis(p):
    """Rows: an orthonormal basis of the (t - 1)-dimensional subspace orthogonal to u = (sqrt p_1, ..., sqrt p_t).
    Gram-Schmidt on u, e_1, ..., e_t; the first row of the full orthogonal matrix (u itself) is dropped."""
    u = np.sqrt(np.asarray(p, dtype=float))
    vecs = [u]
    for j in range(len(u)):
        v = np.eye(len(u))[j]
        for w in vecs:
            v = v - (v @ w) * w
        nv = np.linalg.norm(v)
        if nv > 1e-8:
            vecs.append(v / nv)
        if len(vecs) == len(u):
            break
    return np.array(vecs[1:])


def pearson_residuals(K, p):
    """U = (X - n p) / sqrt(n p) for each row of counts K (all with the same n)."""
    K = np.atleast_2d(np.asarray(K, dtype=float))
    n = K.sum(axis=1, keepdims=True)
    return (K - n * p) / np.sqrt(n * p)


def benford(d=None):
    """Benford's law (10.3.1): P(first digit = d) = log10(d + 1) - log10(d)."""
    d = np.arange(1, 10) if d is None else np.asarray(d)
    return np.log10(d + 1.0) - np.log10(d)


def pareto_first_digit(a):
    """Exact first-digit law of the Pareto density a y^(-a-1), y >= 1: (d^-a - (d+1)^-a) / (1 - 10^-a)."""
    d = np.arange(1, 10, dtype=float)
    return (d ** -a - (d + 1) ** -a) / (1 - 10.0 ** -a)


def example_10_3_1():
    """Example 10.3.1: classes of width 0.2 for f(y) = 6y(1 - y), then the two outer pairs merged."""
    y = np.array(TABLES["sample_ex_10_3_1"]["y"])
    F = lambda x: 3 * x ** 2 - 2 * x ** 3
    e5 = np.array([0, .2, .4, .6, .8, 1.0])
    k5 = np.histogram(y, e5 + np.array([0, 0, 0, 0, 0, 1e-9]))[0]
    p5 = np.diff(F(e5))
    k3 = np.array([k5[0] + k5[1], k5[2], k5[3] + k5[4]])
    p3 = np.array([p5[0] + p5[1], p5[2], p5[3] + p5[4]])
    return dict(k5=k5, p5=p5, k3=k3, p3=p3, d3=pearson(k3, 40 * p3), d5=pearson(k5, 40 * p5))


# =========================================================================== Section 10.4: cell probabilities
def cells_binomial(m):
    """Cells 0, 1, ..., m of a Binomial(m, p) count; theta = (p,)."""
    return lambda th: stats.binom.pmf(np.arange(m + 1), m, th[0])


def cells_poisson(last):
    """Cells 0, 1, ..., last - 1 and 'last or more' of a Poisson count; theta = (lambda,)."""
    def f(th):
        p = stats.poisson.pmf(np.arange(last), th[0])
        return np.append(p, max(1.0 - p.sum(), 1e-300))
    return f


def cells_normal(edges):
    """Cells between the given finite edges, open-ended at both sides; theta = (mu, sigma)."""
    e = np.concatenate([[-np.inf], np.asarray(edges, dtype=float), [np.inf]])
    return lambda th: np.maximum(np.diff(stats.norm.cdf(e, th[0], th[1])), 1e-300)


def cells_exponential(edges):
    """Cells [0, e_1), [e_1, e_2), ..., [e_last, infinity) of an exponential variable; theta = (rate,)."""
    e = np.concatenate([[0.0], np.asarray(edges, dtype=float), [np.inf]])
    return lambda th: np.maximum(np.diff(1 - np.exp(-th[0] * e)), 1e-300)


def jacobian(cellf, th, h=1e-6):
    """Numerical derivative of the cell probabilities: a (t, s) matrix with entries dp_j / d theta_r."""
    th = np.asarray(th, dtype=float)
    cols = []
    for r in range(len(th)):
        step = h * max(1.0, abs(th[r]))
        a, b = th.copy(), th.copy()
        a[r] += step
        b[r] -= step
        cols.append((cellf(a) - cellf(b)) / (2 * step))
    return np.array(cols).T


def grouped_mle(k, cellf, th0, iters=50):
    """Maximum likelihood estimate from the counts alone (the multinomial likelihood sum k_j log p_j(theta)),
    by Fisher scoring started at th0. This is the estimate Theorem 10.4.1 needs for t - 1 - s df exactly."""
    k = np.asarray(k, dtype=float)
    n = k.sum()
    th = np.asarray(th0, dtype=float).copy()
    for _ in range(iters):
        p = cellf(th)
        J = jacobian(cellf, th)
        score = J.T @ (k / p)
        info = n * (J.T / p) @ J
        step = np.linalg.solve(info, score)
        th_new = th + step
        if len(th) > 1:                          # keep a scale parameter positive
            th_new[-1] = max(th_new[-1], 0.5 * th[-1])
        th_new[0] = th_new[0] if len(th) > 1 else max(th_new[0], 1e-9)
        if np.max(np.abs(th_new - th)) < 1e-12 * max(1.0, np.max(np.abs(th))):
            th = th_new
            break
        th = th_new
    return th


def grouped_info(cellf, th):
    """Fisher information per observation carried by the counts: J = sum_j (grad p_j)(grad p_j)^T / p_j."""
    p = cellf(th)
    G = jacobian(cellf, th)
    return (G.T / p) @ G


def full_info(model, th):
    """Fisher information per observation of the ungrouped data."""
    if model == "poisson":
        return np.array([[1.0 / th[0]]])
    if model == "binomial4":
        return np.array([[4.0 / (th[0] * (1 - th[0]))]])
    if model == "normal":
        return np.diag([1.0 / th[1] ** 2, 2.0 / th[1] ** 2])
    if model == "exponential":
        return np.array([[1.0 / th[0] ** 2]])
    raise ValueError(model)


def cl_lambdas(model, cellf, th):
    """Chernoff-Lehmann weights: eigenvalues of I_s - I^(-1/2) J I^(-1/2), each in [0, 1). With the raw-data MLE,
    D1 tends to chi2_{t-1-s} + sum_j lambda_j Z_j^2 instead of chi2_{t-1-s}."""
    I = full_info(model, th)
    J = grouped_info(cellf, th)
    w, V = np.linalg.eigh(I)
    Ih = V @ np.diag(w ** -0.5) @ V.T
    return np.sort(np.linalg.eigvalsh(np.eye(len(th)) - Ih @ J @ Ih))


def cl_cdf(x, df, lams, m=200000, seed=10):
    """cdf of chi2_df + sum lambda_j Z_j^2, by simulation (used for the Chernoff-Lehmann p-value ranges)."""
    r = np.random.default_rng(seed)
    s = r.chisquare(df, m) if df > 0 else np.zeros(m)
    for lam in lams:
        s = s + lam * r.standard_normal(m) ** 2
    s.sort()
    return np.searchsorted(s, x, side="right") / m


# =========================================================================== Section 10.4: the case studies
def fit_hits():
    """Case Study 10.4.1: binomial model for hits in four at-bats (cells = values, so grouped MLE = raw MLE)."""
    k = np.array(TABLES["hits_cs_10_4_1"]["observed"], dtype=float)
    n = k.sum()
    p = (k * np.arange(5)).sum() / (4 * n)
    cellf = cells_binomial(4)
    e = n * cellf([p])
    e_book = n * cellf([0.251])
    d1 = pearson(k, e)
    return dict(model="binomial4", k=k, n=n, raw=np.array([p]), grouped=grouped_mle(k, cellf, [p]), e=e,
                e_book=e_book, d1=d1, d1_book_p=pearson(k, e_book), s=1, t=5, df=3, p=stats.chi2.sf(d1, 3),
                cellf=cellf, lams=cl_lambdas("binomial4", cellf, [p]))


def fit_deaths():
    """Case Study 10.4.2: Poisson model for daily deaths; MLE = mean of the raw counts, cells 0..6 and 7+."""
    k11 = np.array(TABLES["deaths_cs_10_4_2"]["observed"], dtype=float)
    n = k11.sum()
    lam = (k11 * np.arange(11)).sum() / n
    k = np.append(k11[:7], k11[7:].sum())
    cellf = cells_poisson(7)
    e = n * cellf([lam])
    d1 = pearson(k, e)
    g = grouped_mle(k, cellf, [lam])
    return dict(model="poisson", k=k, n=n, raw=np.array([lam]), grouped=g, e=e, d1=d1, s=1, t=8, df=6,
                p=stats.chi2.sf(d1, 6), d1_grouped=pearson(k, n * cellf(g)), cellf=cellf,
                lams=cl_lambdas("poisson", cellf, [lam]))


CHEST_EDGES = np.arange(34.5, 46.0, 1.0)      # 12 finite edges: 13 cells y < 34.5, ..., y >= 45.5


def fit_chest():
    """Case Study 10.4.3: normal model for chest circumferences, 13 cells, mu and sigma estimated."""
    v = np.array(TABLES["chest_cs_10_4_3"]["inches"], dtype=float)
    f = np.array(TABLES["chest_cs_10_4_3"]["observed"], dtype=float)
    n = f.sum()
    mu = (v * f).sum() / n
    sd = math.sqrt(((v - mu) ** 2 * f).sum() / (n - 1))
    sd_mle = math.sqrt(((v - mu) ** 2 * f).sum() / n)
    k = np.concatenate([[f[:2].sum()], f[2:13], [f[13:].sum()]])
    cellf = cells_normal(CHEST_EDGES)
    e = n * cellf([mu, sd])
    e_book = n * cellf([39.8, 2.044])
    d1 = pearson(k, e)
    g = grouped_mle(k, cellf, [mu, sd_mle])
    return dict(model="normal", k=k, n=n, raw=np.array([mu, sd]), sd_mle=sd_mle, grouped=g, e=e, e_book=e_book,
                d1=d1, d1_book_par=pearson(k, e_book), d1_grouped=pearson(k, n * cellf(g)), s=2, t=13, df=10,
                p=stats.chi2.sf(d1, 10), cellf=cellf, lams=cl_lambdas("normal", cellf, [mu, sd_mle]))


COARSE_EDGES = np.array([-0.6744897501960817, 0.0, 0.6744897501960817])   # quartiles of N(0, 1)


def coarse_normal_lams():
    """A coarse grouping (4 equally likely cells at the quartiles of the normal): where the raw-data MLE matters."""
    cellf = cells_normal(COARSE_EDGES)
    return cl_lambdas("normal", cellf, [0.0, 1.0]), grouped_info(cellf, [0.0, 1.0])


# =========================================================================== Section 10.4: null simulations
def _bin_raw(model, Y, cfg):
    if model == "binomial4":
        return np.stack([(Y == j).sum(axis=1) for j in range(5)], axis=1)
    if model == "poisson":
        return np.stack([(Y == j).sum(axis=1) for j in range(7)] + [(Y >= 7).sum(axis=1)], axis=1)
    edges = cfg["edges"]
    idx = np.searchsorted(edges, Y, side="right")
    return np.stack([(idx == j).sum(axis=1) for j in range(len(edges) + 1)], axis=1)


def simulate_null(model, n, th, reps, seed, edges=None, chunk=200):
    """Simulate `reps` data sets of size n from the model at th; return D (true th), D1 with the grouped MLE and
    D1 with the raw-data MLE. Normal data are continuous (no rounding)."""
    r = np.random.default_rng(seed)
    if model == "binomial4":
        cellf = cells_binomial(4)
    elif model == "poisson":
        cellf = cells_poisson(7)
    else:
        cellf = cells_normal(edges)
    cfg = dict(edges=edges)
    out = {"D": [], "Dg": [], "Dr": []}
    p_true = cellf(th)
    done = 0
    while done < reps:
        m = min(chunk, reps - done)
        if model == "binomial4":
            Y = r.binomial(4, th[0], size=(m, n))
        elif model == "poisson":
            Y = r.poisson(th[0], size=(m, n))
        else:
            Y = r.normal(th[0], th[1], size=(m, n))
        K = _bin_raw(model, Y, cfg)
        for i in range(m):
            k = K[i].astype(float)
            if model == "binomial4":
                raw = np.array([Y[i].mean() / 4])
            elif model == "poisson":
                raw = np.array([Y[i].mean()])
            else:
                raw = np.array([Y[i].mean(), Y[i].std()])
            g = grouped_mle(k, cellf, raw)
            out["D"].append(pearson(k, n * p_true))
            out["Dg"].append(pearson(k, n * cellf(g)))
            out["Dr"].append(pearson(k, n * cellf(raw)))
        done += m
    return {kk: np.array(v) for kk, v in out.items()}


def cached_null(name, *args, **kw):
    os.makedirs(CACHE, exist_ok=True)
    path = os.path.join(CACHE, "ch10-%s.npz" % name)
    if os.path.exists(path):
        z = np.load(path)
        return {k: z[k] for k in z.files}
    res = simulate_null(*args, **kw)
    np.savez(path, **res)
    return res


# =========================================================================== Section 10.5
def contingency(T, alpha=0.05):
    """Theorem 10.5.1(b): estimated expected counts R_i C_j / n, d2, (r - 1)(c - 1) df, p-value."""
    T = np.asarray(T, dtype=float)
    n = T.sum()
    E = np.outer(T.sum(axis=1), T.sum(axis=0)) / n
    d2 = pearson(T, E)
    df = (T.shape[0] - 1) * (T.shape[1] - 1)
    return dict(E=E, d2=d2, df=df, p=stats.chi2.sf(d2, df), crit=stats.chi2.isf(alpha, df))


def two_by_two(T):
    """For a 2 x 2 table [[a, b], [c, d]]: n(ad - bc)^2 / (R1 R2 C1 C2), and the pooled two-proportion z comparing
    the columns (a / C1 against b / C2), whose square is the same number."""
    (a, b), (c, d) = np.asarray(T, dtype=float)
    n = a + b + c + d
    R1, R2, C1, C2 = a + b, c + d, a + c, b + d
    closed = n * (a * d - b * c) ** 2 / (R1 * R2 * C1 * C2)
    pbar = R1 / n
    z = (a / C1 - b / C2) / math.sqrt(pbar * (1 - pbar) * (1 / C1 + 1 / C2))
    return closed, z


def fisher_exact_2x2(T):
    """Exact conditional test given both margins: the top-left count is hypergeometric; two-sided p-value sums the
    probabilities not larger than that of the observed table."""
    (a, b), (c, d) = np.asarray(T, dtype=int)
    R1, C1, n = a + b, a + c, a + b + c + d
    lo, hi = max(0, R1 + C1 - n), min(R1, C1)
    xs = np.arange(lo, hi + 1)
    pm = stats.hypergeom.pmf(xs, n, C1, R1)
    p_obs = stats.hypergeom.pmf(a, n, C1, R1)
    return float(pm[pm <= p_obs * (1 + 1e-7)].sum()), xs, pm


def suicide_table(xcut=None, ycut=None):
    """Case Study 10.5.2: dichotomise each city at the sample means; rows (high, low suicide), cols (low, high mobility)."""
    x = np.array(TABLES["suicide_cs_10_5_2"]["x"])
    y = np.array(TABLES["suicide_cs_10_5_2"]["y"])
    xc = x.mean() if xcut is None else xcut
    yc = y.mean() if ycut is None else ycut
    hi, lo = x >= xc, x < xc
    return np.array([[(hi & (y < yc)).sum(), (hi & (y >= yc)).sum()], [(lo & (y < yc)).sum(), (lo & (y >= yc)).sum()]])


# =========================================================================== Section 10.6
def dixon_r(y):
    """Dixon's ratio for the largest observation: (y_(n) - y_(n-1)) / (y_(n) - y_(1))."""
    y = np.sort(np.asarray(y, dtype=float))
    return (y[-1] - y[-2]) / (y[-1] - y[0])


def dixon_null(n=20, reps=400000, seed=106):
    """Null distribution of Dixon's ratio for n normal observations (free of mu and sigma), by simulation."""
    path = os.path.join(CACHE, "ch10-dixon-%d-%d.npy" % (n, reps))
    if os.path.exists(path):
        return np.load(path)
    r = np.random.default_rng(seed)
    out = []
    for _ in range(reps // 50000):
        Z = np.sort(r.standard_normal((50000, n)), axis=1)
        out.append((Z[:, -1] - Z[:, -2]) / (Z[:, -1] - Z[:, 0]))
    res = np.concatenate(out)
    os.makedirs(CACHE, exist_ok=True)
    np.save(path, res)
    return res


# =========================================================================== figures
def fig_10_2_2(out=None):
    """The density 6y(1 - y) cut into four ranges r1 to r4 (Example 10.2.2)."""
    fig, ax = plt.subplots(figsize=(6.0, 2.9))
    y = np.linspace(0, 1, 400)
    f = 6 * y * (1 - y)
    ax.plot(y, f, color=BLUE, ls="--", lw=1.6)
    cols = ["#dbe7fb", "#f3dada", "#f3dada", "#dbe7fb"]
    labs = ["$p_1=5/32$", "$p_2=11/32$", "$p_3=11/32$", "$p_4=5/32$"]
    for j, (a, b) in enumerate([(0, .25), (.25, .5), (.5, .75), (.75, 1)]):
        m = (y >= a) & (y <= b)
        ax.fill_between(y[m], 0, f[m], color=cols[j], lw=0)
        ax.vlines([a, b], 0, [6 * a * (1 - a), 6 * b * (1 - b)], color=GREY, lw=0.8)
        ax.text((a + b) / 2, 0.55 if j in (0, 3) else 0.75, labs[j], ha="center", fontsize=9)
        ax.text((a + b) / 2, -0.32, "$r_%d$" % (j + 1), ha="center", fontsize=10)
    pts = [0.17, 0.53, 0.58, 0.70, 0.92]
    ax.plot(pts, [0.03] * 5, "o", color="black", ms=6, clip_on=False, zorder=5)
    ax.annotate("$f_Y(y)=6y(1-y)$", xy=(0.8, 6 * .8 * .2), xytext=(0.86, 1.45), fontsize=9,
                arrowprops=dict(arrowstyle="-", color=GREY, lw=0.8))
    ax.set_xlim(0, 1.0)
    ax.set_ylim(0, 1.9)
    ax.set_xticks([0, .25, .5, .75, 1])
    ax.set_ylabel("probability density")
    ax.set_title("Five observations: one in $r_1$, none in $r_2$, three in $r_3$, one in $r_4$", fontsize=9.5)
    return savefig(fig, CH, "fig10-2-2", out)


def _chi2_panel(ax, df, x_max, shade_from=None, mark=None, mark_lab=None, area_lab=None, ymax=None):
    x = np.linspace(1e-4 if df > 1 else 0.02, x_max, 600)
    f = stats.chi2.pdf(x, df)
    ax.plot(x, f, color=BLUE)
    if shade_from is not None:
        m = x >= shade_from
        ax.fill_between(x[m], 0, f[m], color=RED, alpha=0.35, lw=0)
        ax.axvline(shade_from, color=RED, lw=1.0)
    if mark is not None:
        ax.annotate(mark_lab, xy=(mark, 0), xytext=(mark + 0.6, (ymax or f.max()) * 0.25), fontsize=9,
                    arrowprops=dict(arrowstyle="->", color=GREEN, lw=1.2), color=GREEN)
    ax.set_xlim(0, x_max)
    ax.set_ylim(0, ymax or f.max() * 1.1)
    ax.set_xlabel("$x$")
    ax.set_ylabel("density")


def fig_10_3_2(out=None):
    """The chi-square density with 1 df and the 0.05 critical region beyond 3.841 (Case Study 10.3.1)."""
    fig, ax = plt.subplots(figsize=(5.2, 2.9))
    c = stats.chi2.isf(0.05, 1)
    _chi2_panel(ax, 1, 8.0, shade_from=c, ymax=0.5)
    ax.text(c - 0.15, 0.16, "reject $H_0$ to the right\nof %.3f: area = 0.05" % c, fontsize=9, color=RED, ha="right")
    ax.axvline(5.94, color=GREEN, lw=1.4, ls="--")
    ax.text(5.94 + 0.12, 0.30, "$d=5.94$", color=GREEN, fontsize=9)
    ax.set_title(r"$\chi^2_1$ density (crustaceans: $d=5.94$)", fontsize=10)
    return savefig(fig, CH, "fig10-3-2", out)


def fig_10_3_3(out=None):
    """Two Pareto densities a y^(-a-1), y >= 1, for a = 1 and a = 2."""
    fig, ax = plt.subplots(figsize=(5.0, 2.9))
    y = np.linspace(1, 4, 400)
    for a, c in [(2, RED), (1, BLUE)]:
        ax.plot(y, a * y ** (-a - 1), color=c, label="$a=%d$" % a)
    ax.set_xlim(0, 4.2)
    ax.set_ylim(0, 2.15)
    ax.set_xlabel("$y$")
    ax.set_ylabel("density")
    ax.legend(frameon=False)
    ax.set_title(r"Pareto densities $f_Y(y)=a\,y^{-a-1}$, $1\leq y<\infty$", fontsize=10)
    return savefig(fig, CH, "fig10-3-3", out)


def fig_10_3_4(out=None):
    """The chi-square density with 3 df and Mendel's statistic d = 0.47 (Case Study 10.3.3)."""
    fig, ax = plt.subplots(figsize=(5.2, 2.9))
    _chi2_panel(ax, 3, 11.0, ymax=0.3)
    x = np.linspace(1e-4, 0.47, 100)
    ax.fill_between(x, 0, stats.chi2.pdf(x, 3), color=GREEN, alpha=0.45, lw=0)
    ax.annotate("$d=0.47$\n$P(\\chi^2_3\\leq0.47)=0.075$", xy=(0.4, 0.02), xytext=(5.2, 0.13), fontsize=9,
                arrowprops=dict(arrowstyle="->", color=GREEN, lw=1.2), color=GREEN)
    lo = stats.chi2.ppf(0.05, 3)
    ax.axvline(lo, color=RED, lw=1.0, ls=":")
    ax.text(lo + 0.08, 0.27, r"$\chi^2_{0.05,3}=%.3f$" % lo, color=RED, fontsize=8.5)
    ax.set_title(r"$\chi^2_3$ density and Mendel's $d$", fontsize=10)
    return savefig(fig, CH, "fig10-3-4", out)


def frizzle_cloud(n=93, p=(0.25, 0.5, 0.25), reps=4000, seed=1003):
    r = np.random.default_rng(seed)
    K = r.multinomial(n, p, size=reps)
    U = pearson_residuals(K, np.asarray(p))
    Q = complement_basis(p)
    return K, U, U @ Q.T, U @ np.sqrt(np.asarray(p))


def exact_size_curve(p, ns, alpha=0.05):
    return np.array([pearson_exact(n, p, alpha)[2] for n in ns])


def fig_x10_1(out=None):
    """Own figure: the geometry of Pearson's statistic for t = 3 and the exact size for small expected counts."""
    fig, axes = plt.subplots(1, 3, figsize=(10.2, 3.2), gridspec_kw=dict(width_ratios=[1, 1.05, 1.15]))
    p = np.array([0.25, 0.5, 0.25])
    K, U, W, along = frizzle_cloud()
    ax = axes[0]
    ax.scatter(W[:, 0], W[:, 1], s=4, color=BLUE, alpha=0.25, lw=0)
    c = math.sqrt(stats.chi2.isf(0.05, 2))
    th = np.linspace(0, 2 * np.pi, 300)
    ax.plot(c * np.cos(th), c * np.sin(th), color=RED, lw=1.4)
    ax.set_aspect("equal")
    ax.set_xlim(-4.2, 4.2)
    ax.set_ylim(-4.2, 4.2)
    ax.set_xlabel("$W_1$")
    ax.set_ylabel("$W_2$")
    ax.set_title("(a) residual vector in the plane $\\perp u$", fontsize=9.5)
    ax.text(0, -3.9, "reject outside the circle\n$W_1^2+W_2^2\\geq5.991$", ha="center", fontsize=8, color=RED)
    ax = axes[1]
    D = (U ** 2).sum(axis=1)
    ax.hist(D, bins=np.arange(0, 14, 0.5), density=True, color=BLUE, alpha=0.4)
    x = np.linspace(0.01, 14, 400)
    ax.plot(x, stats.chi2.pdf(x, 2), color=ORANGE, lw=2, label="$\\chi^2_2$")
    ax.plot(x, stats.chi2.pdf(x, 3), color=GREY, lw=1.4, ls="--", label="$\\chi^2_3$")
    ax.set_xlim(0, 14)
    ax.set_xlabel("$D$")
    ax.set_ylabel("density")
    ax.legend(frameon=False)
    ax.set_title("(b) $D=\\|U\\|^2$, 1:2:1 with $n=93$", fontsize=9.5)
    ax = axes[2]
    ns = np.arange(10, 61, 5)
    p5 = np.array([0.104, 0.248, 0.296, 0.248, 0.104])
    p3 = np.array([0.352, 0.296, 0.352])
    s5 = exact_size_curve(p5, ns)
    s3 = exact_size_curve(p3, ns)
    ax.plot(ns, s5, "o-", color=RED, ms=3.5, label="5 classes (Table 10.3.5)")
    ax.plot(ns, s3, "s-", color=BLUE, ms=3.5, label="3 classes (Table 10.3.6)")
    ax.axhline(0.05, color=GREY, ls=":", lw=1)
    ax.axvline(40, color=GREEN, ls="--", lw=1)
    ax.text(41, 0.071, "$n=40$", color=GREEN, fontsize=8.5)
    ax.set_ylim(0.03, 0.075)
    ax.set_xlabel("$n$")
    ax.set_ylabel("exact P(reject $H_0$)")
    ax.legend(frameon=False, fontsize=8, loc="lower right")
    ax.set_title("(c) exact size of the 0.05 test", fontsize=9.5)
    fig.tight_layout()
    return savefig(fig, CH, "figx10-1", out)


def null_sims():
    """The three simulation designs of Figure x10.2 (cached)."""
    deaths = fit_deaths()
    chest = fit_chest()
    sims = {
        "poisson": cached_null("poisson", "poisson", int(deaths["n"]), deaths["raw"], 2000, 1042),
        "chest": cached_null("chest", "normal", int(chest["n"]), np.array([chest["raw"][0], chest["sd_mle"]]), 1000,
                             1043, edges=CHEST_EDGES),
        "coarse": cached_null("coarse", "normal", 200, np.array([0.0, 1.0]), 4000, 1044, edges=COARSE_EDGES),
    }
    return sims


def _ecdf(ax, v, **kw):
    v = np.sort(v)
    ax.step(v, np.arange(1, len(v) + 1) / len(v), where="post", **kw)


def fig_x10_2(out=None):
    """Own figure: null distribution of D1 with known, grouped-MLE and raw-data-MLE parameters."""
    sims = null_sims()
    fig, axes = plt.subplots(1, 3, figsize=(10.4, 3.2))
    specs = [("poisson", 8, 1, 16, "(a) Poisson, cells 0..6, 7+ ($n=1096$)"),
             ("chest", 13, 2, 26, "(b) normal, 13 cells ($n=5738$)"),
             ("coarse", 4, 2, 10, "(c) normal, 4 cells ($n=200$)")]
    for ax, (key, t, s, xm, title) in zip(axes, specs):
        S = sims[key]
        x = np.linspace(0, xm, 400)
        ax.plot(x, stats.chi2.cdf(x, t - 1), color=GREY, lw=1.4, ls="--", label="$\\chi^2_{%d}$ ($t-1$)" % (t - 1))
        ax.plot(x, stats.chi2.cdf(x, t - 1 - s), color=ORANGE, lw=2.2, label="$\\chi^2_{%d}$ ($t-1-s$)" % (t - 1 - s))
        _ecdf(ax, S["Dg"], color=BLUE, lw=1.2, label="$D_1$, grouped MLE")
        _ecdf(ax, S["Dr"], color=RED, lw=1.2, ls="-.", label="$D_1$, raw-data MLE")
        if key == "coarse":
            lams, _ = coarse_normal_lams()
            ax.plot(x, cl_cdf(x, t - 1 - s, lams), color=PURPLE, lw=1.2, ls=":",
                    label="Chernoff-Lehmann limit")
        ax.set_xlim(0, xm)
        ax.set_ylim(0, 1.01)
        ax.set_xlabel("value")
        ax.set_title(title, fontsize=9.2)
    axes[0].set_ylabel("cumulative probability")
    axes[2].legend(frameon=False, fontsize=7.6, loc="lower right")
    fig.tight_layout()
    return savefig(fig, CH, "figx10-2", out)


def fig_x10_3(out=None):
    """Own figure: the null distribution of Dixon's ratio for n = 20 normal observations."""
    r = dixon_null()
    obs = dixon_r(TABLES["outlier_sec_10_6"]["y"])
    q95, q98 = np.quantile(r, [0.95, 0.98])
    fig, ax = plt.subplots(figsize=(5.6, 2.9))
    ax.hist(r, bins=np.linspace(0, 0.7, 71), density=True, color=BLUE, alpha=0.45)
    for q, lab, c, yv, ha, dx in [(q95, "95th percentile %.3f" % q95, ORANGE, 4.4, "right", -0.008),
                                   (q98, "98th percentile %.3f" % q98, RED, 3.2, "left", 0.008)]:
        ax.axvline(q, color=c, lw=1.2, ls="--")
        ax.text(q + dx, yv, lab, color=c, fontsize=8.5, ha=ha)
    ax.axvline(obs, color=GREEN, lw=2)
    ax.text(obs + 0.008, 5.6, "observed $r=0.321$", color=GREEN, fontsize=8.5)
    ax.set_xlim(0, 0.7)
    ax.set_xlabel("$r=(y'_{20}-y'_{19})/(y'_{20}-y'_1)$")
    ax.set_ylabel("density")
    ax.set_title("Dixon's ratio for $n=20$ normal observations (400 000 simulated samples)", fontsize=9.5)
    return savefig(fig, CH, "figx10-3", out)


# =========================================================================== demo reference
def demo_reference():
    """Numbers shown by the two browser demonstrations (written to ../data/ch10-gof.json)."""
    out = {"_note": "Exact and fitted numbers for pearson-geometry-demo.html and estimated-parameters-demo.html, "
                    "from ch10_goodness_of_fit.py. Data: Larsen and Marx (2018), Chapter 10 case studies."}
    geo = []
    for name, n, p in [("frizzle", 93, [0.25, 0.5, 0.25]), ("small", 12, [0.25, 0.5, 0.25]),
                       ("ex1031five", 40, [0.104, 0.248, 0.296, 0.248, 0.104]),
                       ("mendel", 556, [9 / 16, 3 / 16, 3 / 16, 1 / 16])]:
        m, v = pearson_mean_var(n, p)
        size = pearson_exact(n, p)[2] if math.comb(n + len(p) - 1, len(p) - 1) <= 2000000 else None
        geo.append(dict(name=name, n=n, p=p, mean=m, var=v, exact_size=size, crit=stats.chi2.isf(0.05, len(p) - 1)))
    m, v = pearson_mean_var(355, benford())
    geo.append(dict(name="benford", n=355, p=list(benford()), mean=m, var=v, exact_size=None,
                    crit=stats.chi2.isf(0.05, 8)))
    out["geometry"] = geo
    obs = {"frizzle": TABLES["frizzle_q_10_3_10"]["observed"], "mendel": TABLES["mendel_cs_10_3_3"]["observed"],
           "benford": TABLES["benford_cs_10_3_2"]["observed"]}
    out["geometry_observed"] = {k: dict(k=v, d=pearson(v, np.sum(v) * np.asarray(g["p"])))
                                for k, v in obs.items() for g in geo if g["name"] == k}
    hits, deaths, chest = fit_hits(), fit_deaths(), fit_chest()
    lam_c, _ = coarse_normal_lams()
    out["estimated"] = {
        "hits": dict(k=list(hits["k"]), n=int(hits["n"]), raw=list(hits["raw"]), grouped=list(hits["grouped"]),
                     d1=hits["d1"], df=3, p=hits["p"], lams=list(hits["lams"]), labels=["0", "1", "2", "3", "4"]),
        "deaths": dict(k=list(deaths["k"]), n=int(deaths["n"]), raw=list(deaths["raw"]),
                       grouped=list(deaths["grouped"]), d1=deaths["d1"], d1_grouped=deaths["d1_grouped"], df=6,
                       p=deaths["p"], lams=list(deaths["lams"]),
                       labels=["0", "1", "2", "3", "4", "5", "6", "7+"]),
        "chest": dict(k=list(chest["k"]), n=int(chest["n"]), raw=[chest["raw"][0], chest["sd_mle"]],
                      raw_sd_book=chest["raw"][1], grouped=list(chest["grouped"]),
                      d1=pearson(chest["k"], chest["n"] * chest["cellf"]([chest["raw"][0], chest["sd_mle"]])),
                      d1_sd_n_minus_1=chest["d1"],
                      d1_grouped=chest["d1_grouped"], df=10, p=chest["p"], lams=list(chest["lams"]),
                      edges=list(CHEST_EDGES), labels=["<34.5"] + ["%d" % v for v in range(35, 46)] + ["45.5+"]),
        "coarse": dict(edges=list(COARSE_EDGES), lams=list(lam_c), n=200),
    }
    return out


def export_json():
    os.makedirs(DATA_OUT, exist_ok=True)
    path = os.path.join(DATA_OUT, "ch10-gof.json")

    def conv(o):
        if isinstance(o, (np.floating, np.integer)):
            return o.item()
        raise TypeError(type(o))
    with open(path, "w", encoding="utf-8") as f:
        json.dump(demo_reference(), f, indent=1, default=conv)
    print("wrote", os.path.relpath(path, os.getcwd()))


FIGURES = {
    "10.2.2": fig_10_2_2, "10.3.2": fig_10_3_2, "10.3.3": fig_10_3_3, "10.3.4": fig_10_3_4,
    "x10.1": fig_x10_1, "x10.2": fig_x10_2, "x10.3": fig_x10_3,
}

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