"""Larsen and Marx (2018), Chapter 5: Estimation.

Companion code for Chapter 5 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 (../ch05-estimation.html):

* Section 5.2, maximum likelihood and the method of moments: geometric_fit (Case Study 5.2.1),
  truncated_poisson_mle (Example 5.2.3, Equation 5.2.1), negbin_moments (Example 5.2.7 and Case Study 5.2.2),
  negbin_fixed_s_mle (Case Study 5.2.2's companion, Case Study 5.8.2) and poisson_grouped_fit (Question 5.2.9).
* Section 5.3, interval estimation: z_interval (Example 5.3.1, Case Study 5.3.1), wald_interval (Theorem 5.3.1),
  margin_of_error (Definition 5.3.1), sample_size (Theorem 5.3.2), poll_win_probability (Example 5.3.3).
* Sections 5.4 and 5.5, properties of estimators and the Cramer-Rao bound: ESTIMATORS, a table of exact means and
  variances of the unbiased estimators the chapter compares, with crlb() and simulate_estimators().
* Section 5.6, sufficiency: conditional_given_statistic, the law of a Bernoulli or Poisson sample given the value
  of a statistic (the test behind Definition 5.6.1).
* Section 5.7, consistency: ymax_sample_size (Example 5.7.1).
* Section 5.8, Bayesian estimation: discrete_posterior (Example 5.8.1), beta_binomial_update,
  gamma_poisson_update (Example 5.8.3, Case Study 5.8.1) and bayes_estimates (Theorem 5.8.1, Example 5.8.5).
* Section 5.9, the bootstrap: parametric_bootstrap_se (Tables 5.9.1 and 5.9.2).
* Browser demonstrations: demo_reference() exports the exact numbers that unbiased-estimators-demo.html,
  sufficiency-demo.html and bayes-updating-demo.html show (../data/ch05-demos.json).

Figures. The book has 13 numbered figures in Chapter 5; those computed from a model or from data are reproduced:
  5.1.1 two Poisson probability functions; 5.1.2 the likelihood p^2(1-p) of HHT; 5.2.1 the shifted exponential
  density with a sample (and, added, its likelihood); 5.2.2 the earthquake histogram of Case Study 5.2.2 (with the
  fitted negative binomial added); 5.3.1 the central 95% of the standard Normal; 5.3.2 the fifty simulated 95%
  intervals of Table 5.3.1; 5.3.3 and 5.3.4 the distributions of p behind Max's poll (n = 1000 and n = 5000);
  5.4.1 the laws of X/10 and X/100; 5.7.1 the density of Ymax concentrating near theta; 5.8.1 the Beta(2, 4)
  density.
Skipped, with reasons: 5.4.2 and 5.4.3 (schematic drawings of the densities of two hypothetical estimators, not
computed from any model; Figure x5.2 shows a concrete version of the same comparison).
Three figures of our own (figx5-1 to figx5-3): the chapter's fitted count models against their tables; the two
unbiased estimators of Examples 5.4.2 and 5.4.6 against the bound of Example 5.5.2; the hurricane prior and
posterior of Case Study 5.8.1 and the parametric bootstrap of Section 5.9.
Run `python3 ch05_estimation.py --list`, `python3 ch05_estimation.py` (all figures, about 15 s) or
`python3 ch05_estimation.py --fig 5.3.2`. Files go to ../img/ch05/.
"""
import json
import math
import os

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

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

CH = 5
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))
LIGHT = "#9db8e8"


def tables():
    return book_data("ch05-tables")


# =========================================================================== Section 5.2
def geometric_fit():
    """Case Study 5.2.1: p_e = n / sum(k) = 1 / k-bar and the expected frequencies (last class takes the rest)."""
    t = tables()["dow_geometric"]
    k = np.array(t["k"]); o = np.array(t["observed"], dtype=float)
    n = o.sum(); p = n / (k * o).sum()
    e = n * (1 - p) ** (k - 1) * p
    e[-1] = n - e[:-1].sum()
    return p, o, e


def truncated_poisson_pmf(k, lam):
    """p(k) = lam^k / ((e^lam - 1) k!), k = 1, 2, ... (Example 5.2.3)."""
    k = np.asarray(k, dtype=float)
    return np.exp(k * np.log(lam) - np.log(np.expm1(lam)) - special.gammaln(k + 1))


def truncated_poisson_mean(lam):
    """The mean of the zero-truncated Poisson, lam e^lam / (e^lam - 1): the left side of Equation 5.2.1."""
    return lam / (-np.expm1(-lam))


def truncated_poisson_mle(kbar):
    """Solve lam e^lam / (e^lam - 1) = k-bar (Equation 5.2.1); a root exists and is unique iff k-bar > 1."""
    if kbar <= 1:
        raise ValueError("no maximum: k-bar must exceed 1")
    return optimize.brentq(lambda l: truncated_poisson_mean(l) - kbar, 1e-9, 10 * kbar + 10)


def hurricane_fit(lam=None):
    """Example 5.2.3: the root of (5.2.1) and the grouped expected frequencies of Table 5.2.3 (classes 1, 2, 3, 4+)."""
    t = tables()["hurricanes_truncated"]
    k = np.array(t["k"]); o = np.array(t["observed"], dtype=float)
    n = o.sum(); kbar = (k * o).sum() / n
    lam = truncated_poisson_mle(kbar) if lam is None else lam
    e = n * truncated_poisson_pmf(np.array([1, 2, 3]), lam)
    return kbar, lam, np.r_[o[:3], o[3:].sum()], np.r_[e, n - e.sum()]


def negbin_pmf(k, r, p):
    """p(k) = C(k+r-1, k) (1-p)^k p^r, k = 0, 1, ... (the form of Example 5.2.7; scipy's nbinom(r, p))."""
    return stats.nbinom.pmf(k, r, p)


def negbin_moments(mean, var):
    """Example 5.2.7: method-of-moments p_e = mean/var, r_e = mean^2/(var - mean); needs var > mean."""
    if var <= mean:
        raise ValueError("no solution: the moment equations need var > mean (overdispersion)")
    return mean / var, mean ** 2 / (var - mean)


def earthquake_fit():
    """Case Study 5.2.2: moment estimates from the book's mean 19.83 and variance 50.69 and the class probabilities."""
    t = tables()["earthquakes_grouped"]
    p, r = negbin_moments(t["mean"], t["var_mle"])
    up = [u for u in t["upper"] if u is not None]
    F = stats.nbinom.cdf(up, r, p)
    probs = np.r_[F[0], np.diff(F), 1 - F[-1]]
    return p, r, np.array(t["observed"], dtype=float), 100 * probs


def negbin_fixed_s_mle(n, s, sum_w):
    """MLE of p in C(w+s-1, w) p^s (1-p)^w with s known: p = n s / (n s + sum w) (not n s / sum w)."""
    return n * s / (n * s + sum_w)


def coordination_fit(s=0.8):
    """Case Study 5.8.2: the book's p = 0.106, the correct MLE for sum w = 3821, and the p its printed column uses."""
    t = tables()["coordination_errors"]
    n = sum(t["observed"]); pred = np.array(t["book_predicted"])
    p_book_formula = n * s / t["sum_w"]
    p_mle = negbin_fixed_s_mle(n, s, t["sum_w"])

    def expected(p):
        e = n * stats.nbinom.pmf(np.arange(31), s, p)
        return np.r_[e, n * stats.nbinom.sf(30, s, p)]
    p_printed = optimize.minimize_scalar(lambda p: np.sum((expected(p)[:31] - pred[:31]) ** 2), bounds=(0.05, 0.2), method="bounded").x
    return dict(n=n, p_book_formula=p_book_formula, p_mle=p_mle, p_printed=p_printed, expected=expected,
                observed=np.array(t["observed"], dtype=float), book=pred)


def poisson_grouped_fit():
    """Question 5.2.9: lambda_e = k-bar (4+ counted as 4) and expected frequencies, last class the tail."""
    t = tables()["no_hitters"]
    k = np.array(t["k"]); o = np.array(t["observed"], dtype=float)
    n = o.sum(); lam = (k * o).sum() / n
    e = n * stats.poisson.pmf(k[:-1], lam)
    return lam, o, np.r_[e, n - e.sum()]


def gamma2_mle(y):
    """Example 5.2.2: theta_e = sum(y) / (2n) for the density y e^{-y/theta} / theta^2."""
    y = np.asarray(y, dtype=float)
    return y.sum() / (2 * len(y))


# =========================================================================== Section 5.3
def z_interval(ybar, sigma, n, conf=0.95):
    """y-bar -/+ z_{alpha/2} sigma / sqrt(n) (Example 5.3.1 and the Comment after Case Study 5.3.1)."""
    z = stats.norm.ppf(0.5 + conf / 2)
    h = z * sigma / math.sqrt(n)
    return ybar - h, ybar + h


def wald_interval(k, n, conf=0.95, z=None):
    """Theorem 5.3.1: k/n -/+ z sqrt((k/n)(1-k/n)/n)."""
    z = stats.norm.ppf(0.5 + conf / 2) if z is None else z
    ph = k / n
    h = z * math.sqrt(ph * (1 - ph) / n)
    return ph - h, ph + h


def margin_of_error(n, conf=0.95, N=None):
    """Definition 5.3.1, d = z / (2 sqrt n); with a population of N, times sqrt((N-n)/(N-1)) (Question 5.3.21)."""
    d = stats.norm.ppf(0.5 + conf / 2) / (2 * math.sqrt(n))
    return d if N is None else d * math.sqrt((N - n) / (N - 1))


def sample_size(d, conf=0.95, p=None):
    """Theorem 5.3.2: n = z^2 / (4 d^2), or z^2 p(1-p) / d^2 if p (a bound on p(1-p)'s argument) is given."""
    z = stats.norm.ppf(0.5 + conf / 2)
    return z ** 2 / (4 * d ** 2) if p is None else z ** 2 * p * (1 - p) / d ** 2


def poll_win_probability(k, n, how="book"):
    """Example 5.3.3: P(p > 1/2) for the poll k of n.

    how = "book": Normal with sd = margin/1.96 = 1/(2 sqrt n), as the book does; "plugin": sd from k/n;
    "beta": the exact posterior Beta(k+1, n-k+1) under a flat prior (the reading of Filling the gap 5.8)."""
    ph = k / n
    if how == "beta":
        return stats.beta.sf(0.5, k + 1, n - k + 1)
    sd = 1 / (2 * math.sqrt(n)) if how == "book" else math.sqrt(ph * (1 - ph) / n)
    return stats.norm.sf((0.5 - ph) / sd)


def interval_counts():
    """Table 5.3.1: how many of the 50 intervals contain mu = 10, and the Bin(50, 0.95) law of that count."""
    lo = np.array(tables()["ci_simulation"]["lower"]); hi = lo + 2 * 1.96 * 0.8 / 2
    hit = (lo < 10) & (hi > 10)
    return lo, hi, hit


# =========================================================================== Sections 5.4 and 5.5
# Exact sampling means and variances of the unbiased estimators the chapter compares, as functions of (theta, n).
# Each model: a sampler, the estimators (name -> (function of the sorted sample matrix, exact variance)),
# and the Cramer-Rao bound 1/(n I(theta)) when the regularity conditions hold (None when they do not).
ESTIMATORS = {
    "tri": {   # f(y; theta) = 2y/theta^2 on [0, theta]  (Examples 5.4.2, 5.4.6, 5.5.2)
        "draw": lambda rng, th, R, n: th * np.sqrt(rng.random((R, n))),
        "est": {"3/2 Ybar": (lambda Y: 1.5 * Y.mean(1), lambda th, n: th ** 2 / (8 * n)),
                "(2n+1)/(2n) Ymax": (lambda Y: (2 * Y.shape[1] + 1) / (2 * Y.shape[1]) * Y.max(1), lambda th, n: th ** 2 / (4 * n * (n + 1)))},
        "crlb": None, "formal_bound": lambda th, n: th ** 2 / (4 * n)},
    "unif": {  # Uniform(0, theta)  (Questions 5.4.18, 5.4.21, 5.5.4)
        "draw": lambda rng, th, R, n: th * rng.random((R, n)),
        "est": {"(n+1)/n Ymax": (lambda Y: (Y.shape[1] + 1) / Y.shape[1] * Y.max(1), lambda th, n: th ** 2 / (n * (n + 2))),
                "2 Ybar": (lambda Y: 2 * Y.mean(1), lambda th, n: th ** 2 / (3 * n)),
                "(n+1) Ymin": (lambda Y: (Y.shape[1] + 1) * Y.min(1), lambda th, n: n * th ** 2 / (n + 2))},
        "crlb": None, "formal_bound": lambda th, n: th ** 2 / n},
    "expo": {  # f(y; theta) = e^{-y/theta}/theta  (Questions 5.4.19, 5.5.1)
        "draw": lambda rng, th, R, n: rng.exponential(th, (R, n)),
        "est": {"Ybar": (lambda Y: Y.mean(1), lambda th, n: th ** 2 / n),
                "n Ymin": (lambda Y: Y.shape[1] * Y.min(1), lambda th, n: th ** 2),
                "Y1": (lambda Y: Y[:, 0], lambda th, n: th ** 2)},
        "crlb": lambda th, n: th ** 2 / n},
    "pois": {  # Poisson(lambda)  (Questions 5.4.20, 5.5.2)
        "draw": lambda rng, th, R, n: rng.poisson(th, (R, n)).astype(float),
        "est": {"Xbar": (lambda Y: Y.mean(1), lambda th, n: th / n),
                "(X1+X2)/2": (lambda Y: Y[:, :2].mean(1), lambda th, n: th / 2),
                "X1": (lambda Y: Y[:, 0], lambda th, n: th)},
        "crlb": lambda th, n: th / n},
    "norm3": {  # Normal(mu, 1), weights (Example 5.4.5); theta = mu
        "draw": lambda rng, th, R, n: th + rng.standard_normal((R, n)),
        "est": {"Ybar": (lambda Y: Y.mean(1), lambda th, n: 1.0 / n),
                "weighted 1/4,1/2,1/4": (lambda Y: Y[:, :3] @ np.array([0.25, 0.5, 0.25]), lambda th, n: 3 / 8),
                "median": (lambda Y: np.median(Y, 1), None)},
        "crlb": lambda th, n: 1.0 / n},
}


def crlb(model, th, n):
    m = ESTIMATORS[model]
    return None if m["crlb"] is None else m["crlb"](th, n)


def simulate_estimators(model, th, n, R=20000, seed=5):
    """Simulated mean and variance of each estimator of ESTIMATORS[model]."""
    rng = np.random.default_rng(seed)
    Y = ESTIMATORS[model]["draw"](rng, th, R, n)
    return {k: (f(Y).mean(), f(Y).var(), f(Y)) for k, (f, v) in ESTIMATORS[model]["est"].items()}


def fisher_info_numeric(logf, th, lo, hi, h=1e-5):
    """E[(d/dtheta log f)^2] by quadrature, for checking closed forms (continuous models with fixed support)."""
    from scipy import integrate

    def integrand(y):
        s = (logf(y, th + h) - logf(y, th - h)) / (2 * h)
        return s * s * math.exp(logf(y, th))
    return integrate.quad(integrand, lo, hi, limit=200)[0]


# =========================================================================== Section 5.6
def conditional_given_statistic(n, stat, p, model="bern", kmax=None):
    """P(sample | T = t) for every value t of the statistic T = stat(sample), Bernoulli(p) or Poisson(p) data.

    Returns {t: {sample: probability}}. For a sufficient T the result does not depend on p (Definition 5.6.1)."""
    import itertools
    if model == "bern":
        pts = list(itertools.product((0, 1), repeat=n))
        prob = lambda s: np.prod([p if x else 1 - p for x in s])
    else:
        kmax = kmax or 12
        pts = list(itertools.product(range(kmax + 1), repeat=n))
        prob = lambda s: np.prod([stats.poisson.pmf(x, p) for x in s])
    out = {}
    for s in pts:
        out.setdefault(stat(s), {})[s] = prob(s)
    for t, d in out.items():
        tot = sum(d.values())
        for s in d:
            d[s] /= tot
    return out


def sufficiency_gap(n, stat, p1, p2, model="bern", kmax=None):
    """max over t of the total variation distance between the conditional laws under p1 and p2."""
    a = conditional_given_statistic(n, stat, p1, model, kmax)
    b = conditional_given_statistic(n, stat, p2, model, kmax)
    return max(0.5 * sum(abs(a[t][s] - b[t][s]) for s in a[t]) for t in a)


# =========================================================================== Section 5.7
def ymax_sample_size(theta, eps, delta):
    """Example 5.7.1: the smallest n with 1 - ((theta - eps)/theta)^n >= 1 - delta."""
    return math.ceil(math.log(delta) / math.log((theta - eps) / theta))


# =========================================================================== Section 5.8
def discrete_posterior(x, values=(8, 10), prior=(0.25, 0.75)):
    """Example 5.8.1: posterior of a Poisson rate on two values after one observation x."""
    lik = np.array([stats.poisson.pmf(x, v) for v in values]) * np.array(prior)
    return lik / lik.sum()


def beta_binomial_update(r, s, k, n):
    """Example 5.8.2: Beta(r, s) prior, k successes in n -> Beta(k + r, n - k + s)."""
    return k + r, n - k + s


def gamma_poisson_update(s, mu, w, n):
    """Example 5.8.3: Gamma(shape s, rate mu) prior, total w in n Poisson counts -> Gamma(w + s, mu + n)."""
    return w + s, mu + n


def bayes_estimates(dist, c=1.0, d=1.0):
    """Theorem 5.8.1 and Example 5.8.5: posterior mean (squared loss), median (absolute loss), and the
    c/(c+d) quantile, which minimises the loss c(theta - t) for t < theta and d(t - theta) for t > theta."""
    return dist.mean(), dist.median(), dist.ppf(c / (c + d))


def asymmetric_risk(dist, t, c, d):
    """Posterior expected loss of Example 5.8.5 (per customer), by quadrature."""
    from scipy import integrate
    lo, hi = dist.ppf(1e-12), dist.ppf(1 - 1e-12)
    a = integrate.quad(lambda th: c * (th - t) * dist.pdf(th), max(t, lo), hi, limit=200)[0] if t < hi else 0.0
    b = integrate.quad(lambda th: d * (t - th) * dist.pdf(th), lo, min(t, hi), limit=200)[0] if t > lo else 0.0
    return a + b


# =========================================================================== Section 5.9
def parametric_bootstrap_se(y, B=200, seed=59):
    """Section 5.9: theta_e = y-bar/2, then B samples of size n from y e^{-y/theta_e}/theta_e^2 (Gamma(2, theta_e));
    the bootstrap standard error is the sample sd of the B re-estimates. Returns (theta_e, se_boot, estimates)."""
    y = np.asarray(y, dtype=float)
    n = len(y); th = gamma2_mle(y)
    rng = np.random.default_rng(seed)
    est = rng.gamma(2.0, th, (B, n)).mean(1) / 2
    return th, est.std(ddof=1), est


# =========================================================================== figures
def fig_5_1_1(out=None):
    """Figure 5.1.1: the Poisson probability functions for lambda = 1 and lambda = 4."""
    fig, axes = common.panel_grid(1, 2, size=(3.2, 2.5))
    for ax, lam, kmax, lab in zip(axes[0], (1, 4), (8, 12), "ab"):
        k = np.arange(0, kmax + 1)
        ax.bar(k, stats.poisson.pmf(k, lam), 0.55, color=BLUE)
        ax.set_xlabel("k"); ax.set_ylabel("$p_X(k)$"); ax.set_ylim(0, 0.42)
        ax.set_title(r"$\lambda = %d$" % lam, fontsize=10); common.panel_label(ax, lab, "upper right")
    fig.tight_layout()
    savefig(fig, CH, "fig5-1-1", out)


def fig_5_1_2(out=None):
    """Figure 5.1.2: the probability p^2(1-p) of the sample HHT as a function of p, maximal at 2/3."""
    p = np.linspace(0, 1, 400)
    fig, ax = plt.subplots(figsize=(4.4, 2.8))
    ax.plot(p, p ** 2 * (1 - p), color=BLUE)
    ax.axvline(2 / 3, color=RED, ls="--", lw=1.1); ax.plot([2 / 3], [4 / 27], "o", color=RED)
    ax.annotate(r"$p = 2/3$, height $4/27$", (2 / 3, 4 / 27), (0.08, 0.13), fontsize=9, arrowprops=dict(arrowstyle="->", lw=0.8))
    ax.set_xlabel("p"); ax.set_ylabel(r"$p^2(1-p)$"); ax.set_xlim(0, 1); ax.set_ylim(0, 0.17)
    fig.tight_layout()
    savefig(fig, CH, "fig5-1-2", out)


def fig_5_2_1(out=None):
    """Figure 5.2.1: the threshold density e^{-(y-theta)} with a sample; added: the likelihood L(theta)."""
    rng = np.random.default_rng(521)
    th0 = 1.0; y = np.sort(th0 + rng.exponential(1.0, 8))
    fig, axes = common.panel_grid(1, 2, size=(3.4, 2.6))
    ax = axes[0, 0]; t = np.linspace(th0, 5.5, 300)
    ax.plot(t, np.exp(-(t - th0)), color=BLUE); ax.plot([0, th0], [0, 0], color=BLUE); ax.plot([th0, th0], [0, 1], color=BLUE, ls=":")
    ax.plot(y, np.zeros_like(y), "|", color=RED, ms=14, mew=1.6)
    ax.annotate(r"$y'_1 = y_{\min}$", (y[0], 0), (y[0] + 1.2, 0.55), fontsize=8.5, arrowprops=dict(arrowstyle="->", lw=0.8))
    ax.set_xlabel("y"); ax.set_ylabel(r"$f_Y(y;\theta)$"); ax.set_xticks([th0]); ax.set_xticklabels([r"$\theta$"]); ax.set_xlim(0, 5.5)
    common.panel_label(ax, "a", "upper right")
    ax = axes[0, 1]; g = np.linspace(0, 2.6, 600)
    L = np.where(g <= y[0], np.exp(-(y - 0).sum() + len(y) * g), 0.0)
    ax.plot(g, L / L.max(), color=PURPLE); ax.axvline(y[0], color=RED, ls="--", lw=1)
    ax.set_xlabel(r"$\theta$"); ax.set_ylabel(r"$L(\theta)$ (scaled)"); ax.set_xticks([0, y[0]]); ax.set_xticklabels(["0", r"$y_{\min}$"])
    common.panel_label(ax, "b", "upper left")
    fig.tight_layout()
    savefig(fig, CH, "fig5-2-1", out)


def fig_5_2_2(out=None):
    """Figure 5.2.2: the earthquake histogram of Case Study 5.2.2, with the moment-fitted negative binomial added."""
    p, r, o, e = earthquake_fit()
    fig, ax = plt.subplots(figsize=(4.8, 2.9))
    left = np.arange(0, 45, 5)
    ax.bar(left + 2.5, o, 5, color="#d6d6d6", edgecolor="black", lw=0.7, label="observed (Table 5.2.4)")
    k = np.arange(0, 51)
    ax.plot(k, 100 * 5 * stats.nbinom.pmf(k, r, p), color=RED, lw=1.4, label=r"$100\times5\,p_X(k)$, $r_e=%.2f$, $p_e=%.3f$" % (r, p))
    ax.set_xlabel("number of earthquakes in a year"); ax.set_ylabel("years"); ax.set_xlim(0, 47); ax.set_ylim(0, 31)
    ax.legend(fontsize=7.5, loc="upper right")
    fig.tight_layout()
    savefig(fig, CH, "fig5-2-2", out)


def fig_5_3_1(out=None):
    """Figure 5.3.1: the standard Normal density with the central area 0.95 between -1.96 and 1.96."""
    z = np.linspace(-3.5, 3.5, 400)
    fig, ax = plt.subplots(figsize=(4.4, 2.5))
    ax.plot(z, stats.norm.pdf(z), color=BLUE)
    m = np.abs(z) <= 1.96
    ax.fill_between(z[m], stats.norm.pdf(z[m]), color=LIGHT, alpha=0.8)
    ax.text(0, 0.15, "area = 0.95", ha="center", fontsize=9)
    ax.set_xticks([-1.96, 0, 1.96]); ax.set_yticks([]); ax.set_ylim(0, 0.43)
    ax.set_xlabel(r"$z = (\bar y-\mu)/(0.8/\sqrt{4})$"); ax.set_ylabel(r"$f_Z(z)$")
    fig.tight_layout()
    savefig(fig, CH, "fig5-3-1", out)


def fig_5_3_2(out=None):
    """Figure 5.3.2 (with the data of Table 5.3.1): fifty 95% intervals for mu = 10; three miss."""
    lo, hi, hit = interval_counts()
    fig, ax = plt.subplots(figsize=(5.2, 3.2))
    j = np.arange(1, len(lo) + 1)
    for jj, a, b, h in zip(j, lo, hi, hit):
        ax.plot([jj, jj], [a, b], color=BLUE if h else RED, lw=1.6 if h else 2.2)
        ax.plot([jj], [(a + b) / 2], ".", color=BLUE if h else RED, ms=3)
    ax.axhline(10, color="black", lw=0.9, ls="--")
    ax.set_xlabel("sample (row of Table 5.3.1)"); ax.set_ylabel("95% interval for $\\mu$"); ax.set_xlim(0, 51)
    ax.set_title("%d of 50 intervals contain $\\mu = 10$ (dashed); misses in red" % hit.sum(), fontsize=9.5)
    fig.tight_layout()
    savefig(fig, CH, "fig5-3-2", out)


def _poll_panel(ax, n, k, xr=(0.42, 0.54), ymax=60):
    ph = k / n; d = margin_of_error(n); sd = d / 1.96
    x = np.linspace(*xr, 600)
    f = stats.norm.pdf(x, ph, sd)
    ax.plot(x, f, color=BLUE, ls="--")
    for a, b in ((xr[0], ph - d), (ph + d, xr[1])):
        m = (x >= a) & (x <= b); ax.fill_between(x[m], f[m], color=LIGHT)
    m = x >= 0.5; ax.fill_between(x[m], f[m], color=RED, alpha=0.45)
    ax.axvline(0.5, color="black", lw=0.8)
    ax.set_xticks([round(ph - d, 3), ph, round(ph + d, 3), 0.5]); ax.tick_params(axis="x", labelsize=7.5, rotation=45)
    ax.set_ylim(0, ymax); ax.set_xlim(*xr)
    ax.set_title("n = %d: d = %.3f, P(p > 0.5) = %.4f" % (n, d, poll_win_probability(k, n)), fontsize=9)
    ax.text(0.03, 0.9, "peak $1/(\\sqrt{2\\pi}\\sigma_p)$ = %.2f" % (1 / (math.sqrt(2 * math.pi) * sd)), fontsize=8, transform=ax.transAxes)
    ax.set_xlabel("p, the proportion of all voters for Max")


def fig_5_3_3(out=None):
    """Figure 5.3.3: the Normal curve for p implied by the poll of 1000 with 48% for Max (Example 5.3.3)."""
    fig, ax = plt.subplots(figsize=(4.6, 2.8))
    _poll_panel(ax, 1000, 480)
    fig.tight_layout()
    savefig(fig, CH, "fig5-3-3", out)


def fig_5_3_4(out=None):
    """Figure 5.3.4: the same for 2400 of 5000 (the book's figure is labelled n = 3,000 by mistake)."""
    fig, ax = plt.subplots(figsize=(4.6, 2.8))
    _poll_panel(ax, 5000, 2400)
    fig.tight_layout()
    savefig(fig, CH, "fig5-3-4", out)


def fig_5_4_1(out=None):
    """Figure 5.4.1: the law of X/10 (exact) and of X/100 (Normal approximation) for p = 0.6."""
    fig, ax = plt.subplots(figsize=(5.0, 2.9))
    k = np.arange(11); pk = stats.binom.pmf(k, 10, 0.6)
    ax.bar(k / 10, pk * 10, 0.06, color=[RED if 5 <= kk <= 7 else LIGHT for kk in k], label=r"$X/10$ (probability $\times 10$)")
    x = np.linspace(0, 1, 500); sd = math.sqrt(0.24 / 100)
    ax.plot(x, stats.norm.pdf(x, 0.6, sd), color=BLUE, label=r"$X/100$ (Normal density)")
    m = (x >= 0.5) & (x <= 0.7); ax.fill_between(x[m], stats.norm.pdf(x[m], 0.6, sd), color=BLUE, alpha=0.18)
    pa = stats.binom.cdf(7, 10, 0.6) - stats.binom.cdf(4, 10, 0.6)
    pb = 2 * stats.norm.cdf(0.1 / sd) - 1
    ax.text(0.02, 7.0, "area %.4f (n = 10, red bars)\narea %.4f (n = 100, shaded)" % (pa, pb), fontsize=8.5)
    ax.set_xlabel("values of X/n"); ax.set_xlim(0, 1); ax.legend(fontsize=7.5, loc="upper right")
    fig.tight_layout()
    savefig(fig, CH, "fig5-4-1", out)


def fig_5_7_1(out=None):
    """Figure 5.7.1: the density of Ymax for Uniform(0, theta) concentrating near theta; P(|Ymax - theta| < eps) vs n."""
    th, eps, delta = 4.0, 0.1, 0.2
    fig, axes = common.panel_grid(1, 2, size=(3.4, 2.7))
    ax = axes[0, 0]; y = np.linspace(0, th, 500)
    for n, c in zip((1, 2, 3, 10, 64), (GREY, GREEN, ORANGE, PURPLE, BLUE)):
        ax.plot(y, n * y ** (n - 1) / th ** n, color=c, label="n = %d" % n)
    ax.axvspan(th - eps, th, color=RED, alpha=0.15)
    ax.set_ylim(0, 3.5); ax.set_xlabel("y"); ax.set_ylabel(r"$f_{Y_{\max}}(y)$"); ax.legend(fontsize=7, loc="upper left")
    common.panel_label(ax, "a", "upper center")
    ax = axes[0, 1]; n = np.arange(1, 121)
    ax.plot(n, 1 - ((th - eps) / th) ** n, color=BLUE)
    n0 = ymax_sample_size(th, eps, delta)
    ax.axhline(1 - delta, color=RED, ls="--", lw=1); ax.axvline(n0, color=RED, ls=":", lw=1)
    ax.text(n0 + 3, 0.3, r"$n(\varepsilon,\delta) = %d$" % n0, fontsize=8.5)
    ax.set_xlabel("n"); ax.set_ylabel(r"$P(|\hat\theta_n-\theta|<\varepsilon)$"); ax.set_ylim(0, 1.02)
    common.panel_label(ax, "b", "lower right")
    fig.tight_layout()
    savefig(fig, CH, "fig5-7-1", out)


def fig_5_8_1(out=None):
    """Figure 5.8.1: the Beta(2, 4) density."""
    t = np.linspace(0, 1, 400)
    fig, ax = plt.subplots(figsize=(4.2, 2.6))
    ax.plot(t, stats.beta.pdf(t, 2, 4), color=BLUE)
    ax.set_xlabel(r"$\theta$"); ax.set_ylabel(r"$f_\Theta(\theta)$"); ax.set_ylim(0, 2.4); ax.set_xlim(0, 1)
    fig.tight_layout()
    savefig(fig, CH, "fig5-8-1", out)


def fig_x5_1(out=None):
    """Own figure: the fitted count models of the chapter against their tables (Case Studies 5.2.1, 5.8.2, Example 5.2.3)."""
    fig, axes = common.panel_grid(1, 3, size=(2.7, 2.6))
    p, o, e = geometric_fit(); k = np.arange(1, 7); w = 0.38
    ax = axes[0, 0]
    ax.bar(k - w / 2, o, w, color=LIGHT, label="observed"); ax.bar(k + w / 2, e, w, color=RED, alpha=.8, label="geometric, p = %.3f" % p)
    ax.set_xlabel("days down before a rise"); ax.set_xticks(k); ax.set_xticklabels(["1", "2", "3", "4", "5", "6+"]); ax.legend(fontsize=6.5)
    common.panel_label(ax, "a", "upper center")
    kbar, lam, og, eg = hurricane_fit()
    ax = axes[0, 1]; k = np.arange(1, 5)
    ax.bar(k - w / 2, og, w, color=LIGHT, label="observed"); ax.bar(k + w / 2, eg, w, color=RED, alpha=.8, label=r"truncated Poisson, $\lambda$ = %.3f" % lam)
    ax.set_xlabel("hurricanes in a year"); ax.set_xticks(k); ax.set_xticklabels(["1", "2", "3", "4+"]); ax.legend(fontsize=6.5)
    common.panel_label(ax, "b", "upper center")
    cf = coordination_fit()
    ax = axes[0, 2]; ww = np.arange(31)
    ax.bar(ww, cf["observed"][:31], 0.8, color=LIGHT, label="observed")
    ax.plot(ww, cf["book"][:31], "o", ms=2.6, color="black", label="book's column")
    ax.plot(ww, cf["expected"](cf["p_mle"])[:31], color=RED, label="p = %.4f (MLE)" % cf["p_mle"])
    ax.plot(ww, cf["expected"](cf["p_book_formula"])[:31], color=GREEN, ls="--", label="p = %.3f (book)" % cf["p_book_formula"])
    ax.set_xlabel("errors, w"); ax.legend(fontsize=6.2); common.panel_label(ax, "c", "lower left")
    fig.tight_layout()
    savefig(fig, CH, "figx5-1", out)


def fig_x5_2(out=None):
    """Own figure: two unbiased estimators for theta in 2y/theta^2 (Examples 5.4.2, 5.4.6) and the bound of Example 5.5.2."""
    th = 1.0; n = 5
    sim = simulate_estimators("tri", th, n, R=40000, seed=546)
    fig, axes = common.panel_grid(1, 2, size=(3.4, 2.7))
    ax = axes[0, 0]; bins = np.linspace(0.4, 1.6, 61)
    for (k, (m, v, x)), c in zip(sim.items(), (ORANGE, BLUE)):
        lab = r"$\frac{3}{2}\bar Y$" if k.startswith("3/2") else r"$\frac{2n+1}{2n}Y_{\max}$"
        ax.hist(x, bins=bins, density=True, histtype="stepfilled", alpha=0.45, color=c, label="%s, var %.4f" % (lab, v))
    ax.axvline(th, color="black", lw=0.8, ls="--"); ax.set_xlabel(r"estimate of $\theta = 1$, $n = 5$"); ax.legend(fontsize=7, loc="upper left")
    common.panel_label(ax, "a", "upper right")
    ax = axes[0, 1]; nn = np.arange(1, 41)
    ax.semilogy(nn, th ** 2 / (8 * nn), color=ORANGE, label=r"Var $\frac{3}{2}\bar Y = \theta^2/(8n)$")
    ax.semilogy(nn, th ** 2 / (4 * nn * (nn + 1)), color=BLUE, label=r"Var $\frac{2n+1}{2n}Y_{\max} = \theta^2/(4n(n+1))$")
    ax.semilogy(nn, th ** 2 / (4 * nn), color=RED, ls="--", label=r"formal bound $\theta^2/(4n)$")
    ax.set_xlabel("n"); ax.set_ylabel(r"variance ($\theta = 1$)"); ax.legend(fontsize=6.5, loc="lower left")
    common.panel_label(ax, "b", "upper right")
    fig.tight_layout()
    savefig(fig, CH, "figx5-2", out)


def fig_x5_3(out=None):
    """Own figure: Case Study 5.8.1 (prior and posterior for the hurricane rate) and the bootstrap of Section 5.9."""
    fig, axes = common.panel_grid(1, 2, size=(3.4, 2.7))
    ax = axes[0, 0]; t = np.linspace(1.0, 2.6, 400)
    pri = stats.gamma(88, scale=1 / 50); a, b = gamma_poisson_update(88, 50, 164, 100); post = stats.gamma(a, scale=1 / b)
    ax.plot(t, pri.pdf(t), color=GREY, ls="--", label="prior Gamma(88, 50)")
    ax.plot(t, post.pdf(t), color=BLUE, label="posterior Gamma(252, 150)")
    ax.axvline(164 / 100, color=RED, lw=1, ls=":", label="MLE 1.64")
    ax.axvline(post.mean(), color=BLUE, lw=1, label="posterior mean %.2f" % post.mean())
    ax.set_ylim(0, 6.2); ax.set_xlabel(r"hurricanes per year, $\theta$"); ax.legend(fontsize=6.3, loc="upper right"); common.panel_label(ax, "a", "upper left")
    ax = axes[0, 1]
    y = tables()["bootstrap_sample"]["y"]
    th, se, est = parametric_bootstrap_se(y, B=200, seed=59)
    ax.hist(est, bins=24, density=True, color=LIGHT, edgecolor="white", label="200 bootstrap estimates")
    g = np.linspace(est.min() - 1, est.max() + 1, 300)
    ax.plot(g, stats.gamma.pdf(g, 2 * len(y), scale=th / (2 * len(y))), color=RED, label="exact law at $\\theta_e$")
    ax.axvline(th, color="black", ls="--", lw=0.8)
    ax.set_xlabel(r"bootstrap $\theta_e$; se %.2f (target %.2f)" % (se, th / math.sqrt(2 * len(y))), fontsize=8.5)
    ax.legend(fontsize=6.5, loc="upper right"); common.panel_label(ax, "b", "upper left")
    fig.tight_layout()
    savefig(fig, CH, "figx5-3", out)


# =========================================================================== demo export
def demo_reference():
    """Numbers the three browser demos show, written to ../data/ch05-demos.json (small)."""
    out = {"source": "Larsen and Marx (2018), Chapter 5; computed by ch05_estimation.py"}
    # unbiased-estimators-demo: exact variances and bounds at the presets
    pres = [("tri", 1.0, 5), ("tri", 1.0, 20), ("unif", 3.0, 5), ("expo", 2.0, 10), ("norm3", 0.0, 3)]
    rows = []
    for model, th, n in pres:
        m = ESTIMATORS[model]
        r = {"model": model, "theta": th, "n": n, "var": {k: (v(th, n) if v else None) for k, (f, v) in m["est"].items()},
             "crlb": crlb(model, th, n)}
        if "formal_bound" in m:
            r["formal_bound"] = m["formal_bound"](th, n)
        rows.append(r)
    out["estimators"] = rows
    # sufficiency-demo: conditional laws
    S = {"sum": lambda s: sum(s), "x1": lambda s: s[0], "w123": lambda s: s[0] + 2 * s[1] + 3 * s[2], "max": lambda s: max(s)}
    suf = []
    for key, n, p1, p2 in (("sum", 3, 0.2, 0.7), ("x1", 3, 0.2, 0.7), ("w123", 3, 0.2, 0.7), ("max", 3, 0.2, 0.7)):
        a = conditional_given_statistic(n, S[key], p1)
        suf.append({"stat": key, "n": n, "p1": p1, "p2": p2, "gap": sufficiency_gap(n, S[key], p1, p2),
                    "cond_t1_p1": {"".join(map(str, s)): v for s, v in a[1].items()}})
    pa = conditional_given_statistic(2, lambda s: s[0] + s[1], 1.0, "pois", 14)
    pb = conditional_given_statistic(2, lambda s: s[0] + s[1], 3.0, "pois", 14)
    suf.append({"stat": "poisson-sum", "n": 2, "t": 4, "p1": 1.0, "p2": 3.0,
                "cond_p1": [pa[4][(j, 4 - j)] for j in range(5)], "cond_p2": [pb[4][(j, 4 - j)] for j in range(5)]})
    out["sufficiency"] = suf
    # bayes-updating-demo
    bay = []
    for lab, kind, a0, b0, x, n, c, d in (("hurricanes", "gp", 88, 50, 164, 100, 1, 1), ("video", "bb", 4, 102, 7, 100, 1, 1),
                                         ("inventory", "bb", 4, 102, 7, 100, 3, 1), ("poll", "bb", 135, 135, 480, 1000, 1, 1),
                                         ("flat", "bb", 1, 1, 2, 10, 1, 1)):
        if kind == "gp":
            a, b = gamma_poisson_update(a0, b0, x, n); dist = stats.gamma(a, scale=1 / b); mle = x / n; pm = a0 / b0; wt = n / (b0 + n)
        else:
            a, b = beta_binomial_update(a0, b0, x, n); dist = stats.beta(a, b); mle = x / n; pm = a0 / (a0 + b0); wt = n / (a0 + b0 + n)
        mean, med, q = bayes_estimates(dist, c, d)
        bay.append({"lab": lab, "kind": kind, "prior": [a0, b0], "x": x, "n": n, "post": [a, b], "mean": mean, "median": med,
                    "quantile": q, "c": c, "d": d, "mle": mle, "prior_mean": pm, "weight_mle": wt,
                    "ci95": list(dist.ppf([0.025, 0.975])), "p_gt_half": float(dist.sf(0.5)) if kind == "bb" else None})
    out["bayes"] = bay
    os.makedirs(DATA_OUT, exist_ok=True)
    path = os.path.join(DATA_OUT, "ch05-demos.json")
    with open(path, "w", encoding="utf-8") as f:
        json.dump(out, f, indent=1, default=float)
    print("wrote", os.path.relpath(path, os.getcwd()))
    return out


FIGURES = {
    "5.1.1": fig_5_1_1, "5.1.2": fig_5_1_2, "5.2.1": fig_5_2_1, "5.2.2": fig_5_2_2, "5.3.1": fig_5_3_1,
    "5.3.2": fig_5_3_2, "5.3.3": fig_5_3_3, "5.3.4": fig_5_3_4, "5.4.1": fig_5_4_1, "5.7.1": fig_5_7_1,
    "5.8.1": fig_5_8_1, "x5.1": fig_x5_1, "x5.2": fig_x5_2, "x5.3": fig_x5_3,
}

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