"""Larsen and Marx (2018), Chapter 4: Special Distributions.

Companion code for Chapter 4 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 (../ch04-special-distributions.html):

* Section 4.2, the Poisson distribution: poisson_limit_table (Tables 4.2.1 and 4.2.2), tv_distance and le_cam_bound
  (how far the binomial is from its Poisson limit), niles_cluster (Case Study 4.2.1), poisson_fit and pearson_fit
  (Case Studies 4.2.2 and 4.2.3, Question 4.2.10), new_madrid (Case Study 4.2.4).
* Section 4.3, the normal distribution: binom_normal (Theorem 4.3.1 with and without the continuity correction),
  uniform_average_exact (the exact law behind Examples 4.3.2 and 4.3.4, the Irwin-Hall distribution),
  ridge_count_table (Case Study 4.3.2), clt_distance (own figure: how fast standardized sums become normal).
* Sections 4.4 and 4.5, geometric and negative binomial: coupon_collector (Example 4.4.2), mellows (Example 4.5.1)
  and mellow_walks_sample (Case Study 4.5.1, Table 4.5.1 and Figure 4.5.4).
* Section 4.6, the gamma distribution: gamma_cdf_poisson (Theorem 4.6.1 as a Poisson tail), fuel_pumps (Example 4.6.1).
* Section 4.7, Monte Carlo: simulate_warranty (the repair-cost simulation behind Figure 4.7.6) and warranty_exact
  (the same quantities in closed form from the compound Poisson structure).
* Browser demonstrations: demo_reference() exports the exact numbers that poisson-limit-demo.html,
  normal-approximation-demo.html and warranty-simulation-demo.html show (../data/ch04-demos.json).

Figures. The book has 25 numbered figures in Chapter 4; those computed from a model, data or a simulation are
reproduced:
  4.2.4 the New Madrid interval histogram with the exponential curve; 4.3.1 the binomial bars and the normal
  curve (n = 20); 4.3.5 and 4.3.6 simulated uniform data and averages of eight; 4.3.7 the breath-analyzer
  areas; 4.3.10 the Mensa cutoff; 4.5.4 one hundred simulated numbers of walks; 4.7.1 and 4.7.2 the repair-interval
  and repair-cost densities; 4.7.6 simulated two-year repair costs.
Skipped, with reasons: 4.2.1 to 4.2.3 (sketches of a time axis, of the grid of wars and of intervals), 4.3.3 (shaded
areas for a diagram), 4.3.4 (the ESP symbols), 4.3.8 and 4.3.9 (fingerprints), 4.4.1, 4.4.2, 4.5.1, 4.5.2, 4.6.1
(sketches of trial sequences), 4.5.3 (a block of random digits), 4.7.3 to 4.7.5 (statistical-package screenshots).
Three figures of our own (figx4-1 to figx4-3) illustrate Sections 4.2, 4.6 and 4.3: the law of small numbers and the
Poisson fits, the gamma family with its waiting-time origin, and the speed of the central limit theorem.
Run `python3 ch04_special_distributions.py --list`, `python3 ch04_special_distributions.py` (all figures, about
20 s) or `python3 ch04_special_distributions.py --fig 4.7.6`. Files go to ../img/ch04/.
"""
import json
import math
import os
from fractions import Fraction

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 = 4
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))
TAB = None


def tables():
    global TAB
    if TAB is None:
        TAB = book_data("ch04-poisson-tables")
    return TAB


# =========================================================================== Section 4.2
def poisson_limit_table(n, p, kmax=None):
    """Tables 4.2.1 and 4.2.2: binomial(n, p) probabilities beside the Poisson(np) limit, for k = 0..kmax."""
    kmax = n if kmax is None else kmax
    k = np.arange(0, kmax + 1)
    return k, stats.binom.pmf(k, n, p), stats.poisson.pmf(k, n * p)


def tv_distance(n, p):
    """Total variation distance sup_A |P(Bin(n,p) in A) - P(Poisson(np) in A)| (exact, by summation)."""
    k = np.arange(0, n + 1)
    return 0.5 * (np.abs(stats.binom.pmf(k, n, p) - stats.poisson.pmf(k, n * p)).sum() + stats.poisson.sf(n, n * p))


def le_cam_bound(n, p):
    """Le Cam's bound n p^2 on the distance (Filling the gap 4.1)."""
    return n * p * p


def niles_cluster():
    """Case Study 4.2.1: P(8 or more leukemia cases among 7076 children) with p = 0.000248, exactly and by Poisson."""
    n, p = 7076, 286 / 1152695 * 1.0
    p_book = 0.000248
    return {"mean": n * p_book, "binomial": float(stats.binom.sf(7, n, p_book)), "poisson": float(stats.poisson.sf(7, n * p_book)),
            "rate_per_100000": p * 1e5}


def poisson_fit(freq, last_is_open=True):
    """Case Studies 4.2.2 and 4.2.3: the sample mean and the fitted Poisson proportions.

    freq[k] = number of units with k events; the last cell counts 'k or more' and is valued at its label.
    Returns (kbar, observed proportions, fitted probabilities with the tail lumped into the last cell)."""
    freq = np.asarray(freq, dtype=float)
    k = np.arange(len(freq))
    n = freq.sum()
    kbar = (freq * k).sum() / n
    pm = stats.poisson.pmf(k, kbar)
    if last_is_open:
        pm[-1] = stats.poisson.sf(len(freq) - 2, kbar)
    return kbar, freq / n, pm


def pearson_fit(freq, last_is_open=True, min_expected=5.0):
    """Pearson's statistic sum (O-E)^2/E for the fitted Poisson, with the upper cells pooled until every expected
    count is at least min_expected. Returns (statistic, degrees of freedom = cells - 2, p-value of chi-square)."""
    freq = np.asarray(freq, dtype=float)
    kbar, prop, pm = poisson_fit(freq, last_is_open)
    n = freq.sum()
    O, E = list(freq), list(n * pm)
    while len(E) > 2 and E[-1] < min_expected:
        o_last, e_last = O.pop(), E.pop()
        O[-1] += o_last; E[-1] += e_last
    O, E = np.array(O), np.array(E)
    X2 = float(((O - E) ** 2 / E).sum())
    df = len(E) - 2
    return X2, df, float(stats.chi2.sf(X2, df))


def new_madrid():
    """Case Study 4.2.4 (Table 4.2.5): density-scaled histogram and the fitted exponential rate."""
    t = tables()["new_madrid"]
    freq = np.array(t["freq"], float)
    width = t["width"]
    lam = 1 / t["mean_interval_days"]
    dens = freq / (freq.sum() * width)
    return np.array(t["lower"]), width, freq, dens, lam


# =========================================================================== Section 4.3
def binom_normal(n, p, a, b, cc=True):
    """P(a <= X <= b) for X ~ Bin(n, p): exact, and the normal approximation with or without the continuity correction."""
    mu, sd = n * p, math.sqrt(n * p * (1 - p))
    ex = float(stats.binom.cdf(b, n, p) - stats.binom.cdf(a - 1, n, p))
    h = 0.5 if cc else 0.0
    ap = float(stats.norm.cdf((b + h - mu) / sd) - stats.norm.cdf((a - h - mu) / sd))
    return ex, ap


def irwin_hall_cdf(x, n):
    """Exact P(U_1 + ... + U_n <= x) for independent Uniform(0,1) variables (rational arithmetic, any n)."""
    x = Fraction(x)
    if x <= 0:
        return Fraction(0)
    if x >= n:
        return Fraction(1)
    s = Fraction(0)
    for k in range(0, int(math.floor(x)) + 1):
        s += (-1) ** k * math.comb(n, k) * (x - k) ** n
    return s / math.factorial(n)


def uniform_average_exact():
    """Exact values behind Examples 4.3.2 and 4.3.4 (Filling the gap 4.10)."""
    # Example 4.3.2: mean of 8 observations from Uniform(0,10) between 4.5 and 5.5, i.e. sum of 8 Uniform(0,1) in [3.6, 4.4]
    e2 = float(irwin_hall_cdf(Fraction(44, 10), 8) - irwin_hall_cdf(Fraction(36, 10), 8))
    a2 = float(stats.norm.cdf(0.5 / math.sqrt(25 / 24)) - stats.norm.cdf(-0.5 / math.sqrt(25 / 24)))
    # Example 4.3.4: 100 rounding errors Uniform(-50, 50): P(|S| > 500) is P(|T - 50| > 5) for T the sum of 100 Uniform(0,1)
    e4 = float(1 - (irwin_hall_cdf(55, 100) - irwin_hall_cdf(45, 100)))
    a4 = float(2 * stats.norm.sf(math.sqrt(3)))
    return {"ex432_exact": e2, "ex432_clt": a2, "ex434_exact": e4, "ex434_clt": a4}


def mean_beta13(n=15):
    """P(1/8 <= mean <= 3/8) for the mean of n observations from f(y) = 3(1-y)^2 (Example 4.3.3). The sum of n
    such variables has no simple closed form, so its density is found by the discrete convolution theorem (fast
    Fourier transform) on a fine grid."""
    m = 2 ** 17
    L = float(n)
    dx = L * 1.0 / m
    y = (np.arange(m) + 0.5) * dx
    f = np.where(y <= 1, 3 * (1 - np.clip(y, 0, 1)) ** 2, 0.0)
    F = np.fft.rfft(f * dx) ** n          # the discrete convolution theorem
    g = np.fft.irfft(F, m) / dx
    cdf = np.cumsum(g) * dx
    lo, hi = n / 8.0, 3 * n / 8.0
    return float(np.interp(hi, y, cdf) - np.interp(lo, y, cdf))


def ridge_count_table(ns=(25, 50, 75, 100, 150, 200), cc=True):
    """Case Study 4.3.2: p = P(ridge count >= 270) and P(X >= 2 | X >= 1) for n suspects (Table 4.3.2)."""
    p = float(stats.norm.sf((269.5 - 146) / 52)) if cc else float(stats.norm.sf((270 - 146) / 52))
    out = []
    for n in ns:
        q = 1 - p
        out.append((n, (1 - q ** n - n * p * q ** (n - 1)) / (1 - q ** n)))
    return p, out


def clt_distance(n, dist="exp"):
    """Kolmogorov distance between the cdf of the standardized sum of n iid variables and the standard normal cdf.
    dist = 'exp' (sum is Gamma(n,1), exact) or 'unif' (Irwin-Hall, evaluated on a grid in floating point for n <= 12)."""
    if dist == "exp":
        z = np.linspace(-6, 6, 12001)
        F = stats.gamma.cdf(n + math.sqrt(n) * z, n)
        return float(np.max(np.abs(F - stats.norm.cdf(z))))
    raise ValueError(dist)


# =========================================================================== Sections 4.4 and 4.5
def coupon_collector(m=6):
    """Example 4.4.2 for m equally likely letters: E(X), Var(X) of the number of purchases to see all m."""
    p = np.array([(m - i) / m for i in range(m)])
    return float((1 / p).sum()), float(((1 - p) / p ** 2).sum())


def mellows(p_strike=0.5):
    """Example 4.5.1: the probability a batter strikes out, the law of the walks W in an inning (a negative
    binomial shifted by 3), and E(R) for R = (W - 3)^+ , the runs walked in."""
    # strikeout: three strikes before four balls. P(X = k) = C(k-1,2) s^3 (1-s)^(k-3), k = 3..6, with s = P(strike)
    s = p_strike
    q = float(sum(math.comb(kk - 1, 2) * s ** 3 * (1 - s) ** (kk - 3) for kk in range(3, 7)))
    w = np.arange(0, 600)
    pw = stats.nbinom.pmf(w, 3, q)
    ER = float(((w - 3).clip(0) * pw).sum())
    return {"q": q, "EW": 3 * (1 - q) / q, "pw": pw[:12], "ER": ER, "game": 9 * ER}


def digit_ranges(pw, last=7):
    """Table 4.5.1: the two-digit numbers 00..99 handed to w = 0, 1, ..., last (each probability rounded to hundredths,
    so w gets round(100 p_W(w)) numbers); whatever is left goes to the last row, 'w >= last + 1'."""
    sizes = np.round(np.asarray(pw[: last + 1]) * 100).astype(int)
    lo = np.concatenate([[0], np.cumsum(sizes)[:-1]])
    rows = [(int(a), int(a + s - 1)) for a, s in zip(lo, sizes)]
    rows.append((int(sizes.sum()), 99))
    return rows


def mellow_walks_sample(n=100, seed=2018):
    """Case Study 4.5.1: n innings of walks by the table-lookup method (a random two-digit number is mapped to w
    through the ranges of Table 4.5.1; digits in the last row are recorded as w = 8)."""
    rng = np.random.default_rng(seed)
    pw = mellows()["pw"]
    rows = digit_ranges(pw)
    digits = rng.integers(0, 100, size=n)
    w = np.empty(n, dtype=int)
    for j, (a, b) in enumerate(rows):
        w[(digits >= a) & (digits <= b)] = j
    return w, pw


# =========================================================================== Section 4.6
def gamma_cdf_poisson(y, r, lam):
    """Theorem 4.6.1: P(Gamma(r, lam) <= y) = P(Poisson(lam y) >= r), for integer r."""
    return float(stats.poisson.sf(r - 1, lam * y))


def fuel_pumps(lam=0.01, t=50.0, r=2):
    """Example 4.6.1: P(the second of two pumps fails before t hours)."""
    return gamma_cdf_poisson(t, r, lam)


# =========================================================================== Section 4.7
def simulate_warranty(nsim, rate=0.75, years=2.0, mu=100.0, sd=20.0, rng=None):
    """Section 4.7: total repair cost over the warranty period for each of nsim customers.

    Repair times are the arrival times of a Poisson process (exponential gaps, Theorem 4.2.3); each repair costs an
    independent Normal(mu, sd^2) amount. Returns the array of costs and the array of the numbers of repairs."""
    rng = rng or np.random.default_rng(2018)
    cost = np.zeros(nsim)
    nrep = np.zeros(nsim, dtype=int)
    for i in range(nsim):
        t = rng.exponential(1 / rate)
        while t <= years:
            nrep[i] += 1
            cost[i] += rng.normal(mu, sd)
            t += rng.exponential(1 / rate)
    return cost, nrep


def warranty_exact(rate=0.75, years=2.0, mu=100.0, sd=20.0, price=200.0):
    """The compound Poisson law of the total cost W = C_1 + ... + C_N, N ~ Poisson(rate * years) (Filling the gap 4.21)."""
    m = rate * years
    k = np.arange(0, int(m + 12 * math.sqrt(m) + 30))
    pk = stats.poisson.pmf(k, m)

    def sf(x):
        s = 0.0
        for kk in k:
            if kk == 0:
                s += pk[0] * (0.0 > x)
            else:
                s += pk[kk] * stats.norm.sf(x, loc=mu * kk, scale=sd * math.sqrt(kk))
        return float(s)

    from scipy import optimize
    med = float(optimize.brentq(lambda x: (1 - sf(x)) - 0.5, 1e-6, 10 * mu * m + 10))
    return {"mean": m * mu, "var": m * (sd ** 2 + mu ** 2), "sd": math.sqrt(m * (sd ** 2 + mu ** 2)), "p_none": float(pk[0]),
            "p_exceed_price": sf(price), "p_exceed_2price": sf(2 * price), "median": med}


# =========================================================================== figures
def _norm_pdf(x, mu=0.0, sd=1.0):
    return stats.norm.pdf(x, mu, sd)


def fig_4_2_4(out=None):
    """Figure 4.2.4: intervals between New Madrid earthquakes with the exponential density (Case Study 4.2.4)."""
    lo, w, freq, dens, lam = new_madrid()
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.bar(lo, dens, width=w, align="edge", color="#9db8e8", edgecolor="white")
    y = np.linspace(0, 270, 300)
    ax.plot(y, lam * np.exp(-lam * y), color=RED, label=r"$f_Y(y)=0.0152\,e^{-0.0152y}$")
    ax.set_xlabel("interval between earthquakes (days)"); ax.set_ylabel("density"); ax.legend(frameon=False)
    ax.set_xlim(0, 270)
    fig.tight_layout()
    savefig(fig, CH, "fig4-2-4", out)


def fig_4_3_1(out=None):
    """Figure 4.3.1: the Binomial(20, 1/2) probabilities and the normal curve of Theorem 4.3.1."""
    n, p = 20, 0.5
    k = np.arange(5, 16)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.bar(k, stats.binom.pmf(k, n, p), width=1.0, color="#9db8e8", edgecolor="white", label=r"$p_X(k)$")
    x = np.linspace(4.5, 15.5, 300)
    ax.plot(x, _norm_pdf(x, n * p, math.sqrt(n * p * (1 - p))), color=RED, ls="--", label="normal curve")
    ax.set_xlabel("k"); ax.set_ylabel("probability / density"); ax.set_xticks(k); ax.legend(frameon=False)
    sec = ax.secondary_xaxis("top", functions=(lambda v: (v - 10) / math.sqrt(5), lambda z: 10 + math.sqrt(5) * z))
    sec.set_xlabel("z = (k - 10)/sqrt(5)")
    fig.tight_layout()
    savefig(fig, CH, "fig4-3-1", out)


def fig_4_3_5(out=None):
    """Figure 4.3.5: a sample of 100 observations from the uniform density on [0, 10) (Example 4.3.2)."""
    rng = np.random.default_rng(2018)
    y = rng.uniform(0, 10, 100)
    fig, ax = plt.subplots(figsize=(5.0, 2.8))
    ax.hist(y, bins=np.arange(0, 10.5, 1), density=True, color="#9db8e8", edgecolor="white", label="data histogram")
    ax.hlines(0.1, 0, 10, color=RED, label=r"$f_Y(y)=1/10$")
    ax.set_ylim(0, 0.2); ax.set_xlabel("y"); ax.set_ylabel("density"); ax.legend(frameon=False)
    fig.tight_layout()
    savefig(fig, CH, "fig4-3-5", out)


def fig_4_3_6(out=None):
    """Figure 4.3.6: fifty averages of eight Uniform[0, 10) observations and the normal curve of the CLT."""
    rng = np.random.default_rng(2019)
    ybar = rng.uniform(0, 10, (50, 8)).mean(axis=1)
    fig, ax = plt.subplots(figsize=(5.0, 2.8))
    ax.hist(ybar, bins=np.arange(2, 8.01, 0.5), density=True, color="#9db8e8", edgecolor="white", label="50 averages, n = 8")
    x = np.linspace(1.5, 8.5, 300)
    ax.plot(x, _norm_pdf(x, 5, math.sqrt(25 / 3 / 8)), color=RED, ls="--", label=r"$N(5,\,25/24)$")
    ax.set_xlabel("sample average"); ax.set_ylabel("density"); ax.legend(frameon=False)
    fig.tight_layout()
    savefig(fig, CH, "fig4-3-6", out)


def fig_4_3_7(out=None):
    """Figure 4.3.7: the breath-analyzer error, P(Y >= 0.080) for Y ~ N(0.075, 0.004^2), and the matching z area."""
    fig, axes = plt.subplots(1, 2, figsize=(6.2, 2.7))
    ax = axes[0]
    y = np.linspace(0.060, 0.090, 300)
    ax.plot(y, _norm_pdf(y, 0.075, 0.004), color=BLUE)
    yy = np.linspace(0.080, 0.090, 100)
    ax.fill_between(yy, _norm_pdf(yy, 0.075, 0.004), color=RED, alpha=0.5)
    ax.set_xlabel("y (%)"); ax.set_ylabel(r"$f_Y(y)$"); ax.set_title("area 0.1056", fontsize=9)
    ax = axes[1]
    z = np.linspace(-3, 3, 300)
    ax.plot(z, _norm_pdf(z), color=BLUE)
    zz = np.linspace(1.25, 3, 100)
    ax.fill_between(zz, _norm_pdf(zz), color=RED, alpha=0.5)
    ax.set_xlabel("z"); ax.set_ylabel(r"$f_Z(z)$"); ax.set_title("area 0.1056", fontsize=9)
    fig.tight_layout()
    savefig(fig, CH, "fig4-3-7", out)


def fig_4_3_10(out=None):
    """Figure 4.3.10: the IQ cutoff y_L that leaves the top 2% (Mensa), for N(100, 16^2)."""
    yL = 100 + 16 * stats.norm.isf(0.02)
    fig, ax = plt.subplots(figsize=(5.0, 2.8))
    y = np.linspace(40, 160, 400)
    ax.plot(y, _norm_pdf(y, 100, 16), color=BLUE)
    yy = np.linspace(yL, 160, 100)
    ax.fill_between(yy, _norm_pdf(yy, 100, 16), color=RED, alpha=0.5)
    ax.axvline(yL, color=GREY, ls=":")
    ax.text(yL + 2, 0.0045, "y_L = %.1f\ntop 2%% of IQs" % yL, fontsize=9)
    ax.set_xlabel("IQ"); ax.set_ylabel(r"$f_Y(y)$")
    fig.tight_layout()
    savefig(fig, CH, "fig4-3-10", out)


def fig_4_5_4(out=None):
    """Figure 4.5.4: the numbers of walks in 100 simulated innings (Table 4.5.1 lookup) against the negative binomial law."""
    w, pw = mellow_walks_sample(100)
    k = np.arange(0, 9)
    fig, ax = plt.subplots(figsize=(5.2, 2.9))
    ax.bar(k, np.bincount(w, minlength=9)[:9] / 100.0, width=0.6, color="#9db8e8", label="100 simulated innings")
    ax.plot(k, pw[:9], "o-", color=RED, label=r"$p_W(w)$")
    ax.set_xlabel("number of walks, w"); ax.set_ylabel("probability"); ax.legend(frameon=False); ax.set_xticks(k)
    fig.tight_layout()
    savefig(fig, CH, "fig4-5-4", out)


def fig_4_7_1(out=None):
    """Figure 4.7.1: the exponential density of the years between repairs, rate 0.75."""
    fig, ax = plt.subplots(figsize=(4.6, 2.7))
    y = np.linspace(0, 6, 300)
    ax.plot(y, 0.75 * np.exp(-0.75 * y), color=BLUE)
    ax.set_xlabel("y (years between repairs)"); ax.set_ylabel(r"$f_Y(y)=0.75e^{-0.75y}$")
    fig.tight_layout()
    savefig(fig, CH, "fig4-7-1", out)


def fig_4_7_2(out=None):
    """Figure 4.7.2: the density N(100, 20^2) of the cost of one repair visit."""
    fig, ax = plt.subplots(figsize=(4.6, 2.7))
    c = np.linspace(30, 170, 300)
    ax.plot(c, _norm_pdf(c, 100, 20), color=BLUE)
    for v, lab in ((40, r"$\mu-3\sigma$"), (100, r"$\mu$"), (160, r"$\mu+3\sigma$")):
        ax.axvline(v, color=GREY, ls=":", lw=0.8); ax.text(v, -0.003, lab, ha="center", va="top", fontsize=8)
    ax.set_xlabel("c (dollars)", labelpad=14); ax.set_ylabel(r"$f_C(c)$")
    fig.tight_layout()
    savefig(fig, CH, "fig4-7-2", out)


def fig_4_7_6(out=None):
    """Figure 4.7.6: total repair costs in 100 simulated two-year warranty periods."""
    cost, nrep = simulate_warranty(100, rng=np.random.default_rng(2018))
    ex = warranty_exact()
    fig, ax = plt.subplots(figsize=(5.4, 3.0))
    bins = np.arange(0, 651, 50)
    ax.hist(cost, bins=bins, color="#9db8e8", edgecolor="white")
    ax.axvline(200, color=RED, lw=1.6, label="warranty price $200")
    ax.axvline(float(np.median(cost)), color=GREEN, ls="--", label="median $%.0f" % np.median(cost))
    ax.axvline(float(cost.mean()), color=PURPLE, ls="-.", label="mean $%.0f" % cost.mean())
    ax.set_xlabel("simulated repair costs in two years (dollars)"); ax.set_ylabel("frequency"); ax.legend(frameon=False, fontsize=8)
    ax.yaxis.set_major_locator(plt.MaxNLocator(integer=True))
    ax.text(0.97, 0.55, "%d of 100 with no repair\n%d of 100 above $200" % ((nrep == 0).sum(), (cost > 200).sum()), transform=ax.transAxes, ha="right", fontsize=8)
    fig.tight_layout()
    savefig(fig, CH, "fig4-7-6", out)


def fig_x4_1(out=None):
    """Own figure: the Poisson limit (Tables 4.2.1, 4.2.2) and the Poisson fits of Case Studies 4.2.2 and 4.2.3."""
    fig, axes = common.panel_grid(2, 2, size=(3.3, 2.5))
    for ax, (n, p), lab in ((axes[0, 0], (5, 0.2), "a"), (axes[0, 1], (100, 0.01), "b")):
        k, b, po = poisson_limit_table(n, p, 7)
        ax.bar(k - 0.2, b, width=0.4, color=BLUE, label="binomial"); ax.bar(k + 0.2, po, width=0.4, color=ORANGE, label="Poisson(1)")
        ax.set_title("n=%d, p=%g:  distance %.3f" % (n, p, tv_distance(n, p)), fontsize=9); ax.set_xlabel("k"); common.panel_label(ax, lab, "upper right")
    axes[0, 0].legend(fontsize=7.5, loc="center right")
    for ax, key, lab, title in ((axes[1, 0], "rutherford_geiger", "c", "alpha particles per 1/8 minute"), (axes[1, 1], "wars", "d", "new wars per year")):
        freq = tables()[key]["freq"]
        kbar, prop, pm = poisson_fit(freq)
        k = np.arange(len(freq))
        ax.bar(k - 0.2, prop, width=0.4, color=BLUE, label="observed"); ax.bar(k + 0.2, pm, width=0.4, color=ORANGE, label="Poisson(%.2f)" % kbar)
        ax.set_title(title, fontsize=9); ax.set_xlabel("k"); ax.legend(fontsize=7.5); common.panel_label(ax, lab, "upper right")
    fig.tight_layout()
    savefig(fig, CH, "figx4-1", out)


def fig_x4_2(out=None):
    """Own figure: gamma densities, and the waiting time for the third event of a Poisson process against Gamma(3, 1)."""
    rng = np.random.default_rng(4)
    fig, axes = common.panel_grid(1, 2, size=(3.5, 2.8))
    ax = axes[0, 0]
    y = np.linspace(0.001, 14, 500)
    for r, c in ((0.5, PURPLE), (1, RED), (2, ORANGE), (5, GREEN), (10, BLUE)):
        ax.plot(y, stats.gamma.pdf(y, r), color=c, label="r = %g" % r)
    ax.set_ylim(0, 1.0); ax.set_xlabel("y"); ax.set_ylabel("density, $\\lambda=1$"); ax.legend(fontsize=7.5); common.panel_label(ax, "a", "upper center")
    ax = axes[0, 1]
    gaps = rng.exponential(1.0, (40000, 3)).sum(axis=1)
    ax.hist(gaps, bins=60, density=True, color="#9db8e8", edgecolor="white")
    t = np.linspace(0, 12, 300)
    ax.plot(t, stats.gamma.pdf(t, 3), color=RED, label=r"$\frac{y^2}{2}e^{-y}$")
    ax.set_xlabel("time of the 3rd event"); ax.legend(fontsize=8); common.panel_label(ax, "b", "upper right")
    fig.tight_layout()
    savefig(fig, CH, "figx4-2", out)


def fig_x4_3(out=None):
    """Own figure: how fast the standardized sum of n Exponential(1) variables approaches N(0,1)."""
    fig, axes = common.panel_grid(1, 2, size=(3.5, 2.8))
    ax = axes[0, 0]
    z = np.linspace(-4, 4, 600)
    for n, c in ((1, PURPLE), (2, ORANGE), (5, GREEN), (30, BLUE)):
        ax.plot(z, math.sqrt(n) * stats.gamma.pdf(n + math.sqrt(n) * z, n), color=c, label="n = %d" % n)
    ax.plot(z, _norm_pdf(z), color="black", ls="--", lw=1.2, label="N(0,1)")
    ax.set_ylim(0, 0.9); ax.set_xlabel("z"); ax.set_ylabel("density"); ax.legend(fontsize=7.5); common.panel_label(ax, "a", "upper left")
    ax = axes[0, 1]
    ns = np.unique(np.round(np.logspace(0, 3, 25)).astype(int))
    d = np.array([clt_distance(int(n)) for n in ns])
    ax.loglog(ns, d, "o-", color=BLUE, ms=3, label="exact distance")
    ax.loglog(ns, d[0] / np.sqrt(ns) * 1.0, color=RED, ls="--", label=r"$c/\sqrt{n}$")
    ax.set_xlabel("n"); ax.set_ylabel("largest cdf gap"); ax.legend(fontsize=7.5); common.panel_label(ax, "b", "lower left")
    fig.tight_layout()
    savefig(fig, CH, "figx4-3", out)


# =========================================================================== data for the demos
def demo_reference():
    """The exact numbers that the three browser demonstrations show for their presets."""
    ref = {}
    ref["poisson"] = {}
    for key, (n, p) in {"tab421": (5, 0.2), "tab422": (100, 0.01), "irs": (65000, 1735 / 137.8e6), "niles": (7076, 0.000248), "bug": (1000, 0.006)}.items():
        ref["poisson"][key] = {"n": n, "p": p, "tv": tv_distance(n, p) if n <= 7000 else None, "bound": le_cam_bound(n, p)}
    ref["poisson"]["niles"]["tail8_binom"] = float(stats.binom.sf(7, 7076, 0.000248))
    ref["poisson"]["niles"]["tail8_poisson"] = float(stats.poisson.sf(7, 7076 * 0.000248))
    ref["poisson"]["irs"]["tail3_poisson"] = float(stats.poisson.sf(2, 65000 * 1735 / 137.8e6))
    cases = {"overbook": (178, 0.9, 169, 178), "esp": (60000, 0.2, 12489, 60000), "voters_tie": (400, 0.55, 200, 200), "voters_upset": (400, 0.55, 0, 199),
             "n20": (20, 0.5, 10, 10), "nevada": (3000, 0.001, 8, 3000), "small": (10, 0.7, 4, 8)}
    ref["normal"] = {}
    for key, (n, p, a, b) in cases.items():
        ex, ap = binom_normal(n, p, a, b, True)
        ex2, ap0 = binom_normal(n, p, a, b, False)
        ref["normal"][key] = {"n": n, "p": p, "a": a, "b": b, "exact": ex, "cc": ap, "plain": ap0}
    ref["warranty"] = warranty_exact()
    return ref


def export_json():
    os.makedirs(DATA_OUT, exist_ok=True)
    path = os.path.join(DATA_OUT, "ch04-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 = {
    "4.2.4": fig_4_2_4, "4.3.1": fig_4_3_1, "4.3.5": fig_4_3_5, "4.3.6": fig_4_3_6, "4.3.7": fig_4_3_7, "4.3.10": fig_4_3_10,
    "4.5.4": fig_4_5_4, "4.7.1": fig_4_7_1, "4.7.2": fig_4_7_2, "4.7.6": fig_4_7_6,
    "x4.1": fig_x4_1, "x4.2": fig_x4_2, "x4.3": fig_x4_3,
}

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