"""Larsen and Marx (2018), Chapter 3: Random Variables.

Companion code for Chapter 3 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 (../ch03-random-variables.html):

* Section 3.2, binomial and hypergeometric probabilities: hyper_pmf, binom_pmf, series_length_pmf (Example 3.2.3,
  with the best-fitting success probability for Table 3.2.3), oc_curve (Case Study 3.2.1, Figure 3.2.2),
  hyper_ratio (the recursion of Example 3.2.8) and fpc (the variance factor of Example 3.9.10).
* Section 3.3, discrete random variables: poisson_fit (Case Study 3.3.1), benford_pmf (Example 3.3.3),
  negbin2_pmf (Example 3.3.8) and pepys (Question 3.2.9).
* Section 3.4, continuous random variables: geometric_vs_exponential (Figures 3.4.1 and 3.4.2), the density-scaled
  histogram (Figures 3.4.6 and 3.4.7) and the V805 tubes (Case Study 3.4.1, Figure 3.4.8).
* Section 3.5, expected values: pooled_tests (Example 3.5.4), st_petersburg_truncated (Question 3.5.19),
  newsvendor_optimum (Example 3.5.13) and world_series (Question 3.5.23).
* Section 3.7, joint densities: meeting_probability (Example 3.7.5, Figure 3.7.2) and the joint densities of the
  chapter (joint_moments), computed by numerical integration.
* Section 3.8, transforming random variables: the densities of Questions 3.8.9 and 3.8.13 and of Examples
  3.8.4 to 3.8.6.
* Section 3.10, order statistics: order_pdf (Theorem 3.10.2), order_cdf, range_cdf_uniform (Example 3.10.6) and
  flood_height (Example 3.10.5).
* Section 3.11, conditional densities: example_3_11_1 (Figure 3.11.1).
* Section 3.12, moment-generating functions: mgf_moments (symbolic derivatives with sympy).
* Browser demonstrations: demo_reference() exports the exact numbers that order-statistics-demo.html,
  hypergeometric-binomial-demo.html and joint-density-slices-demo.html show (../data/ch03-demos.json).

Figures. The book has 30 numbered figures in Chapter 3; those computed from a model or from data are reproduced:
  3.2.2 the operating characteristic curve of the apple sampling plan; 3.4.1, 3.4.2 the geometric probability
  function and the exponential curve; 3.4.3 the uniform density; 3.4.4 the density 3t^2; 3.4.5 three normal
  densities; 3.4.6, 3.4.7 the frequency histogram and the density-scaled histogram of Table 3.4.1; 3.4.8 the V805
  lifetimes with the exponential fit; 3.4.9 the density 6y(1-y); 3.7.2 the meeting region; 3.10.1 the densities
  of one observation and of the smallest of three exponential observations; 3.11.1 the three conditional
  probability functions of Example 3.11.1.
Skipped, with reasons: 3.2.1 (a drawing of two striation patterns), 3.3.1 (a tree of free throws), 3.5.1 to
3.5.5 (schematic drawings of a mean, a fulcrum, a lottery ticket, two waves and a segment), 3.6.1 (a rotating rod),
3.7.1, 3.7.3, 3.7.4 (sketches of regions and of a ring on a grid), 3.8.1, 3.8.2 (sketches of integration regions),
3.9.1 (a circuit diagram), 3.10.2 to 3.10.4 (sketches of how observations fall into groups).
Three figures of our own (figx3-1 to figx3-3) illustrate Sections 3.2, 3.3, 3.10: the book's two goodness-of-fit
tables against the model, hypergeometric against binomial, and the Beta densities of the order statistics.
Run `python3 ch03_random_variables.py --list`, `python3 ch03_random_variables.py` (all figures, about 20 s) or
`python3 ch03_random_variables.py --fig 3.4.8`. Files go to ../img/ch03/.
"""
import json
import math
import os

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

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

CH = 3
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))


# =========================================================================== Section 3.2
def binom_pmf(k, n, p):
    """Theorem 3.2.1."""
    return stats.binom.pmf(k, n, p)


def hyper_pmf(k, N, r, n):
    """Theorem 3.2.2: P(k red chips) when n of N chips (r red) are drawn without replacement."""
    return stats.hypergeom.pmf(k, N, r, n)


def hyper_ratio(k, N, r, n):
    """P(X=k+1)/P(X=k) = (n-k)(r-k) / ((k+1)(w-n+k+1)), the recursion of Example 3.2.8 (Question 3.2.30)."""
    w = N - r
    return (n - k) * (r - k) / ((k + 1) * (w - n + k + 1))


def fpc(N, n):
    """Finite population correction (N-n)/(N-1) of the hypergeometric variance (Example 3.9.10)."""
    return (N - n) / (N - 1)


def series_length_pmf(p, first_to=4):
    """Example 3.2.3: P(series lasts 4, 5, 6, 7 games) when team A wins each game with probability p."""
    q = 1 - p
    out = []
    for g in range(first_to, 2 * first_to):
        j = g - first_to           # games lost by the winner
        out.append(math.comb(g - 1, first_to - 1) * (p ** first_to * q ** j + q ** first_to * p ** j))
    return np.array(out)


def fit_series_p():
    """The p in (0.5, 1) that maximises the likelihood of the 68 observed series lengths (Table 3.2.3)."""
    c = np.array(book_data("ch03-stanley-cup")["count"], dtype=float)
    f = lambda p: -(c * np.log(series_length_pmf(p))).sum()
    r = optimize.minimize_scalar(f, bounds=(0.5, 0.99), method="bounded")
    return r.x


def oc_curve(N=144, n=15, c=2, d=None):
    """Case Study 3.2.1: P(at most c substandard apples in the sample) when d of N are substandard."""
    d = np.arange(0, N + 1) if d is None else np.asarray(d)
    return d, stats.hypergeom.cdf(c, N, d, n)


def pepys():
    """Question 3.2.9: P(at least k sixes) in 6k dice, k = 1, 2, 3."""
    return [stats.binom.sf(k - 1, 6 * k, 1 / 6) for k in (1, 2, 3)]


# =========================================================================== Section 3.3
def poisson_fit():
    """Case Study 3.3.1: observed proportions of days and the Poisson(0.82) probabilities (Table 3.3.1)."""
    d = book_data("ch03-deaths")
    s = np.array(d["s"])
    days = np.array(d["days"], dtype=float)
    return s, days / days.sum(), stats.poisson.pmf(s, d["lambda"])


def benford_pmf():
    """Example 3.3.3: P(first significant digit = s) = log10(1 + 1/s), s = 1..9."""
    s = np.arange(1, 10)
    return s, np.log10(1 + 1 / s)


def negbin2_pmf(k, p=0.65):
    """Example 3.3.8: P(second basket on throw k) = (k-1)(1-p)^(k-2) p^2, k = 2, 3, ..."""
    return (k - 1) * (1 - p) ** (k - 2) * p ** 2


# =========================================================================== Section 3.4
def geometric_vs_exponential(q=0.095, kmax=21):
    """Figures 3.4.1 and 3.4.2: the geometric probability function (success prob q at each hour) and the
    exponential curve 0.1 exp(-0.1 x) that approximates it."""
    k = np.arange(1, kmax + 1)
    return k, (1 - q) ** (k - 1) * q


def density_scaled(y, edges):
    """Heights of a histogram whose total area is 1: count / (n * width) (Figure 3.4.7)."""
    c, _ = np.histogram(y, bins=edges)
    return c, c / (len(y) * np.diff(edges))


def v805():
    """Case Study 3.4.1: grouped lifetimes of 903 tubes; classes (lower, upper, count, density)."""
    d = book_data("ch03-v805")
    lo = np.array(d["lower"], dtype=float)
    hi = np.array([np.nan if u is None else u for u in d["upper"]], dtype=float)
    cnt = np.array(d["count"], dtype=float)
    return lo, hi, cnt


# =========================================================================== Section 3.5
def pooled_tests(p, n=50):
    """Example 3.5.4: E(number of tests) = 1 + n (1 - (1-p)^n) when n samples are pooled."""
    return 1 + n * (1 - (1 - p) ** n)


def st_petersburg_truncated(cap_k=10, cap=1000):
    """Question 3.5.19: expected payoff when the prize 2^k is cut off at 'cap' (k >= cap_k pays cap)."""
    k = np.arange(1, cap_k)
    return float((2.0 ** k / 2.0 ** k).sum() + cap * 0.5 ** (cap_k - 1))


def newsvendor_expected(x, lam, m, n):
    """Example 3.5.13: expected profit lam (m+n)(1 - exp(-x/lam)) - n x when x items are made."""
    return lam * (m + n) * (1 - np.exp(-x / lam)) - n * x


def newsvendor_optimum(lam, m, n):
    """x* = lam ln((m+n)/n)."""
    return lam * math.log((m + n) / n)


def world_series():
    """Question 3.5.23: the series-length distribution for p = 1/2 and its mean 5.8125."""
    pm = series_length_pmf(0.5)
    return pm, float((np.arange(4, 8) * pm).sum())


# =========================================================================== Section 3.7
def meeting_probability(T=60.0, w=15.0):
    """Example 3.7.5: two independent arrival times in [0, T], each waits w; P(meet) = 1 - (1 - w/T)^2."""
    return 1 - (1 - w / T) ** 2


def joint_moments(f, region=(0, 1, 0, 1)):
    """E X, E Y, E XY, Var X, Var Y, Cov, by numerical integration of a joint density on a rectangle.
    Used for the joint densities of Examples 3.7.11 and 3.9.8 and Questions 3.7.13, 3.7.47."""
    a, b, c, d = region
    I = lambda g: integrate.dblquad(lambda y, x: g(x, y) * f(x, y), a, b, c, d)[0]
    m0 = I(lambda x, y: 1)
    ex, ey = I(lambda x, y: x), I(lambda x, y: y)
    exx, eyy, exy = I(lambda x, y: x * x), I(lambda x, y: y * y), I(lambda x, y: x * y)
    return dict(mass=m0, ex=ex, ey=ey, vx=exx - ex ** 2, vy=eyy - ey ** 2, cov=exy - ex * ey)


# =========================================================================== Section 3.8
def pdf_w_sq(w):
    """Question 3.8.9: Y has density 6y(1-y); W = Y^2 has density 3(1 - sqrt w), 0 < w < 1."""
    return 3 * (1 - np.sqrt(w))


def pdf_y_over_x(w):
    """Question 3.8.13: X ~ x e^{-x}, Y ~ e^{-y} independent; W = Y/X has density 2/(1+w)^3, w > 0."""
    return 2 / (1 + np.asarray(w, dtype=float)) ** 3


# =========================================================================== Section 3.10
def order_pdf(i, n, f, F, y):
    """Theorem 3.10.2: density of the i-th smallest of n iid observations with density f and cdf F."""
    Fy = F(y)
    return math.factorial(n) / (math.factorial(i - 1) * math.factorial(n - i)) * Fy ** (i - 1) * (1 - Fy) ** (n - i) * f(y)


def order_cdf(i, n, F, y):
    """P(i-th smallest <= y) = P(at least i of the n observations are <= y), a binomial tail."""
    return stats.binom.sf(i - 1, n, F(y))


def range_cdf_uniform(r, n):
    """Example 3.10.6 generalised: P(range <= r) = n r^(n-1) - (n-1) r^n for Uniform(0,1) samples."""
    r = np.asarray(r, dtype=float)
    return n * r ** (n - 1) - (n - 1) * r ** n


def flood_height(prob=0.30, n=33, i=32, lo=20.0, hi=40.0):
    """Example 3.10.5: the height h with P(Y'_i > h) = prob for n Uniform(lo, hi) annual maxima."""
    g = lambda h: stats.beta.sf((h - lo) / (hi - lo), i, n - i + 1) - prob
    return optimize.brentq(g, lo, hi - 1e-9)


# =========================================================================== Section 3.11
def example_3_11_1():
    """Example 3.11.1: Y = heads in five tosses, X = heads in the last two; p_{Y|x}(y) = C(3, y-x)/8."""
    out = {}
    for x in (0, 1, 2):
        out[x] = {y: math.comb(3, y - x) / 8 for y in range(x, x + 4)}
    return out


# =========================================================================== Section 3.12
def mgf_moments(M, t, kmax=4):
    """Raw moments E(W^k), k = 1..kmax, as the derivatives at 0 of a sympy mgf M(t) (Theorem 3.12.1)."""
    import sympy as sp
    return [sp.simplify(sp.diff(M, t, k).subs(t, 0)) for k in range(1, kmax + 1)]


# =========================================================================== demo reference numbers
def demo_reference():
    """Exact numbers shown by the three demonstrations (the same formulas run in the browser)."""
    out = {}
    # order statistics: a few reference cases
    cases = {}
    cases["min3exp"] = dict(P_lt_1=1 - math.exp(-3), P_single_lt_1=1 - math.exp(-1))
    cases["median5unif"] = dict(mean=3 / 6, var=3 * 3 / (36 * 7))
    cases["flood"] = dict(h=flood_height(), mean=20 + 20 * 32 / 34)
    cases["range3"] = dict(mean=0.5, F_half=float(range_cdf_uniform(0.5, 3)))
    out["order"] = cases
    # hypergeometric / binomial
    hb = {}
    hb["apples_good"] = dict(N=144, d=10, n=15, c=2, accept=float(stats.hypergeom.cdf(2, 144, 10, 15)),
                             accept_binom=float(stats.binom.cdf(2, 15, 10 / 144)))
    hb["apples_bad"] = dict(N=144, d=30, n=15, c=2, accept=float(stats.hypergeom.cdf(2, 144, 30, 15)),
                            accept_binom=float(stats.binom.cdf(2, 15, 30 / 144)))
    hb["audit"] = dict(N=470, d=10, n=19, tail3=float(stats.hypergeom.sf(2, 470, 10, 19)),
                       tail3_binom=float(stats.binom.sf(2, 19, 10 / 470)))
    hb["fantasy5"] = dict(N=36, d=12, n=5, p3=float(stats.hypergeom.pmf(3, 36, 12, 5)))
    hb["jury"] = dict(N=25, d=2, n=12, hung=float(1 - stats.hypergeom.pmf(0, 25, 2, 12)))
    out["hyper"] = hb
    # joint densities
    j = {}
    j["xplusy"] = dict(p_x_lt_2y=19 / 24, cov=-1 / 144, ex=7 / 12)
    j["q347"] = dict(p_box=5 / 32, p_prod=3 / 16)
    j["indep"] = dict(cov=0.0)
    out["joint"] = j
    return out


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


# =========================================================================== figures
def _out(a):
    return a if a else None


def fig_3_2_2(out=None):
    """Figure 3.2.2: P(sample passes inspection) against the presumed percentage of defectives."""
    d, pr = oc_curve()
    fig, ax = plt.subplots(figsize=(5.2, 3.2))
    ax.plot(100 * d / 144, pr, color=BLUE)
    for dd, col in ((10, GREEN), (30, RED)):
        v = stats.hypergeom.cdf(2, 144, dd, 15)
        ax.plot([100 * dd / 144], [v], "o", color=col)
        ax.annotate("%.3f" % v, (100 * dd / 144, v), textcoords="offset points", xytext=(8, 5), color=col)
    ax.set_xlabel("Presumed percent defective"); ax.set_ylabel("P(sample passes)")
    ax.set_xlim(0, 100); ax.set_ylim(0, 1.02); ax.grid(alpha=.25)
    savefig(fig, CH, "fig3-2-2", out)


def fig_3_4_1(out=None):
    """Figure 3.4.1: p_X(k), the hour at which the monitor first fails."""
    k, p = geometric_vs_exponential()
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.bar(k, p, width=1.0, color="#9db8e8", edgecolor="white")
    ax.set_xlabel("Hour when monitor first fails, k"); ax.set_ylabel("$p_X(k)$"); ax.set_xlim(0, 22)
    savefig(fig, CH, "fig3-4-1", out)


def fig_3_4_2(out=None):
    """Figure 3.4.2: the same bars with the curve 0.1 exp(-0.1 x)."""
    k, p = geometric_vs_exponential()
    x = np.linspace(0, 22, 300)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.bar(k, p, width=1.0, color="#9db8e8", edgecolor="white")
    ax.plot(x, 0.1 * np.exp(-0.1 * x), color=RED, label="$y=0.1e^{-0.1x}$")
    ax.set_xlabel("Hour when monitor first fails, k"); ax.set_ylabel("$p_X(k)$"); ax.set_xlim(0, 22); ax.legend()
    savefig(fig, CH, "fig3-4-2", out)


def fig_3_4_3(out=None):
    """Figure 3.4.3: the uniform density 1/(b-a) and the probability of a subinterval (Example 3.4.1)."""
    a, b, c, d = 2.0, 6.0, 3.0, 4.5
    fig, ax = plt.subplots(figsize=(4.6, 2.8))
    ax.plot([a - 1, a, a, b, b, b + 1], [0, 0, 1 / (b - a), 1 / (b - a), 0, 0], color=BLUE)
    ax.fill_between([c, d], 0, 1 / (b - a), color="#9db8e8")
    ax.text((c + d) / 2, 0.08, "$P(c\\leq Y\\leq d)$\n$=(d-c)/(b-a)$", ha="center", fontsize=8.5)
    ax.set_xticks([a, c, d, b]); ax.set_xticklabels(["a", "c", "d", "b"]); ax.set_ylim(0, 0.32)
    ax.set_xlabel("t"); ax.set_ylabel("$f(t)=1/(b-a)$")
    savefig(fig, CH, "fig3-4-3", out)


def fig_3_4_4(out=None):
    """Figure 3.4.4: f(t) = 3 t^2 on [0, 1], with the areas 1/27 and 19/27 (Example 3.4.2)."""
    t = np.linspace(0, 1, 300)
    fig, ax = plt.subplots(figsize=(4.4, 3.0))
    ax.plot(t, 3 * t ** 2, color=BLUE)
    s1 = t <= 1 / 3; s2 = t >= 2 / 3
    ax.fill_between(t[s1], 0, 3 * t[s1] ** 2, color="#9db8e8"); ax.fill_between(t[s2], 0, 3 * t[s2] ** 2, color="#9db8e8")
    ax.text(0.17, 0.35, "1/27", ha="center", fontsize=8.5); ax.text(0.84, 1.15, "19/27", ha="center", fontsize=8.5)
    ax.set_xlabel("t"); ax.set_ylabel("$f(t)=3t^2$"); ax.set_xlim(0, 1.02); ax.set_ylim(0, 3.2)
    savefig(fig, CH, "fig3-4-4", out)


def fig_3_4_5(out=None):
    """Figure 3.4.5: three normal densities (mu = -4, 0, 3; sigma = 0.5, 1.5, 1)."""
    t = np.linspace(-8, 6, 600)
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    for (m, s), col in zip(((-4, .5), (0, 1.5), (3, 1)), (RED, BLUE, GREEN)):
        ax.plot(t, stats.norm.pdf(t, m, s), color=col, label="$\\mu=%g,\\ \\sigma=%g$" % (m, s))
    ax.set_xlabel("t"); ax.set_ylabel("f(t)"); ax.legend(fontsize=8)
    savefig(fig, CH, "fig3-4-5", out)


def fig_3_4_6(out=None):
    """Figure 3.4.6: frequency histogram of the forty observations of Table 3.4.1."""
    y = np.array(book_data("ch03-uniform-sample")["y"])
    edges = np.arange(20, 71, 10)
    fig, ax = plt.subplots(figsize=(4.8, 3.0))
    ax.hist(y, bins=edges, color="#9db8e8", edgecolor="white")
    ax.set_xlabel("y"); ax.set_ylabel("Frequency"); ax.set_xticks(edges)
    savefig(fig, CH, "fig3-4-6", out)


def fig_3_4_7(out=None):
    """Figure 3.4.7: density-scaled histogram of Table 3.4.1 with the Uniform(20, 70) density 1/50."""
    y = np.array(book_data("ch03-uniform-sample")["y"])
    edges = np.arange(20, 71, 10)
    c, h = density_scaled(y, edges)
    fig, ax = plt.subplots(figsize=(4.8, 3.0))
    ax.bar(edges[:-1], h, width=10, align="edge", color="#9db8e8", edgecolor="white")
    ax.plot([20, 70], [1 / 50, 1 / 50], color=RED, label="uniform density $1/50$"); ax.set_ylim(0, 0.03)
    ax.set_xlabel("y"); ax.set_ylabel("Density"); ax.set_xticks(edges); ax.legend(fontsize=8)
    savefig(fig, CH, "fig3-4-7", out)


def fig_3_4_8(out=None):
    """Figure 3.4.8: V805 lifetimes, density-scaled histogram and the exponential model with lambda = 0.0056."""
    lo, hi, cnt = v805()
    width = np.array([80] * 7 + [140, 140.0])        # the book draws the last class 700 to 840, so 700+ keeps density 0.0002
    dens = cnt / cnt.sum() / width
    lam = book_data("ch03-v805")["lambda_book"]
    t = np.linspace(0, 840, 500)
    fig, ax = plt.subplots(figsize=(5.4, 3.1))
    ax.bar(lo, dens, width=width, align="edge", color="#9db8e8", edgecolor="white")
    ax.plot(t, lam * np.exp(-lam * t), color=RED, label="$f(t)=0.0056e^{-0.0056t}$")
    s = t >= 500
    ax.fill_between(t[s], 0, lam * np.exp(-lam * t[s]), color=ORANGE, alpha=.45)
    ax.text(600, 0.0014, "area $=e^{-2.8}=%.4f$" % math.exp(-2.8), fontsize=8.5)
    ax.set_xlabel("V805 lifetimes (hrs)"); ax.set_ylabel("Probability density"); ax.legend(fontsize=8)
    savefig(fig, CH, "fig3-4-8", out)


def fig_3_4_9(out=None):
    """Figure 3.4.9: f_Y(y) = 6y(1-y) on [0, 1] (Example 3.4.5)."""
    y = np.linspace(0, 1, 200)
    fig, ax = plt.subplots(figsize=(4.4, 3.0))
    ax.plot(y, 6 * y * (1 - y), color=BLUE); ax.fill_between(y, 0, 6 * y * (1 - y), color="#dbe5f7")
    ax.set_xlabel("y"); ax.set_ylabel("$f_Y(y)=6y(1-y)$")
    savefig(fig, CH, "fig3-4-9", out)


def fig_3_7_2(out=None):
    """Figure 3.7.2: the region |x - y| <= 15 in the 60 by 60 square (the two friends meet)."""
    fig, ax = plt.subplots(figsize=(4.0, 4.0))
    ax.fill([0, 15, 60, 60, 45, 0], [0, 0, 45, 60, 60, 15], color="#9db8e8", alpha=.8)
    ax.plot([0, 60, 60, 0, 0], [0, 0, 60, 60, 0], color="k", lw=1)
    ax.plot([0, 45], [15, 60], color=RED, lw=1); ax.plot([15, 60], [0, 45], color=RED, lw=1)
    ax.text(30, 30, "M", ha="center", va="center", fontsize=14)
    ax.text(10, 50, "x - y = -15", fontsize=8, color=RED, rotation=0); ax.text(35, 8, "x - y = 15", fontsize=8, color=RED)
    ax.set_xlabel("x (minutes after 12:00)"); ax.set_ylabel("y"); ax.set_aspect("equal"); ax.set_xticks([0, 15, 45, 60]); ax.set_yticks([0, 15, 45, 60])
    ax.set_title("P(M) = %.4f" % meeting_probability(), fontsize=9.5)
    savefig(fig, CH, "fig3-7-2", out)


def fig_3_10_1(out=None):
    """Figure 3.10.1: f_Y(y) = e^{-y} and the density 3 e^{-3y} of the smallest of three observations."""
    y = np.linspace(0, 5, 400)
    fig, ax = plt.subplots(figsize=(5.0, 3.0))
    ax.plot(y, np.exp(-y), color=BLUE, label="$f_{Y_1}(y)=e^{-y}$")
    ax.plot(y, 3 * np.exp(-3 * y), color=RED, label="$f_{Y_1'}(y)=3e^{-3y}$")
    ax.set_xlabel("y"); ax.set_ylabel("Probability density"); ax.legend(fontsize=8.5)
    savefig(fig, CH, "fig3-10-1", out)


def fig_3_11_1(out=None):
    """Figure 3.11.1: p_{Y|x}(y) for x = 0, 1, 2 (Example 3.11.1)."""
    pm = example_3_11_1()
    fig, ax = plt.subplots(figsize=(5.0, 3.0))
    for x, col, off in ((0, RED, -0.27), (1, BLUE, 0.0), (2, GREEN, 0.27)):
        ys = list(pm[x]); ax.bar(np.array(ys) + off, [pm[x][y] for y in ys], width=0.25, color=col, label="$x=%d$" % x)
    ax.set_xlabel("y"); ax.set_ylabel("$p_{Y|x}(y)$"); ax.set_xticks(range(0, 6)); ax.legend(fontsize=8.5)
    savefig(fig, CH, "fig3-11-1", out)


def fig_x3_1(out=None):
    """Own figure: the book's two goodness-of-fit tables against their models (Table 3.3.1 and Table 3.2.3)."""
    s, obs, mod = poisson_fit()
    c = np.array(book_data("ch03-stanley-cup")["count"], dtype=float); prop = c / c.sum()
    pfit = fit_series_p()
    fig, axes = common.panel_grid(1, 2, size=(3.3, 2.7))
    ax = axes[0, 0]
    w = 0.38
    ax.bar(s - w / 2, obs, w, color="#9db8e8", label="observed"); ax.bar(s + w / 2, mod, w, color=RED, alpha=.8, label="Poisson(0.82)")
    ax.set_xlabel("deaths in a day, s"); ax.set_ylabel("proportion of days"); ax.set_ylim(0, 0.55); ax.legend(fontsize=7.5); common.panel_label(ax, "a", "upper right")
    ax = axes[0, 1]
    g = np.arange(4, 8); w = 0.27
    ax.bar(g - w, prop, w, color="#9db8e8", label="observed"); ax.bar(g, series_length_pmf(.5), w, color=RED, alpha=.8, label="p = 0.5")
    ax.bar(g + w, series_length_pmf(pfit), w, color=GREEN, alpha=.8, label="p = %.2f" % pfit)
    ax.set_xlabel("games in the series"); ax.set_ylim(0, 0.46); ax.legend(fontsize=7, ncol=3, loc="upper center"); common.panel_label(ax, "b", "upper left")
    fig.tight_layout()
    savefig(fig, CH, "figx3-1", out)


def fig_x3_2(out=None):
    """Own figure: sampling without replacement (hypergeometric) against with replacement (binomial)."""
    fig, axes = common.panel_grid(1, 3, size=(2.6, 2.6))
    for ax, (N, r, n), lab in zip(axes[0, :2], ((20, 8, 10), (200, 80, 10)), "ab"):
        k = np.arange(0, n + 1); w = 0.38
        ax.bar(k - w / 2, hyper_pmf(k, N, r, n), w, color=BLUE, label="hypergeometric")
        ax.bar(k + w / 2, binom_pmf(k, n, r / N), w, color=ORANGE, label="binomial")
        ax.set_title("N=%d, r=%d, n=%d" % (N, r, n), fontsize=9); ax.set_xlabel("k"); common.panel_label(ax, lab, "upper left")
    axes[0, 0].legend(fontsize=7, loc="upper right")
    ax = axes[0, 2]; NN = 100; nn = np.arange(1, NN + 1)
    ax.plot(nn / NN, fpc(NN, nn), color=PURPLE); ax.set_xlabel("n / N"); ax.set_ylabel("Var(hypergeom) / Var(binomial)"); common.panel_label(ax, "c", "upper right")
    ax.set_ylim(0, 1.05)
    fig.tight_layout()
    savefig(fig, CH, "figx3-2", out)


def fig_x3_3(out=None):
    """Own figure: the densities of the five order statistics of a Uniform(0,1) sample of size 5 (Beta(i, 6-i))."""
    rng = np.random.default_rng(2018)
    Y = np.sort(rng.random((40000, 5)), axis=1)
    y = np.linspace(0, 1, 400)
    fig, axes = common.panel_grid(1, 2, size=(3.4, 2.8))
    ax = axes[0, 0]
    cols = [RED, ORANGE, GREEN, BLUE, PURPLE]
    for i in range(1, 6):
        ax.plot(y, order_pdf(i, 5, lambda t: np.ones_like(t), lambda t: t, y), color=cols[i - 1], label="$Y'_%d$" % i)
    ax.set_xlabel("y"); ax.set_ylabel("density"); ax.legend(fontsize=7.5, ncol=2); common.panel_label(ax, "a", "upper center")
    ax = axes[0, 1]
    ax.hist(Y[:, 2], bins=40, density=True, color="#9db8e8", edgecolor="white")
    ax.plot(y, order_pdf(3, 5, lambda t: np.ones_like(t), lambda t: t, y), color=RED, label="$30y^2(1-y)^2$"); ax.set_xlabel("y"); ax.legend(fontsize=8)
    ax.set_title("median of 5, 40 000 samples", fontsize=9); common.panel_label(ax, "b", "upper left")
    fig.tight_layout()
    savefig(fig, CH, "figx3-3", out)


FIGURES = {
    "3.2.2": fig_3_2_2, "3.4.1": fig_3_4_1, "3.4.2": fig_3_4_2, "3.4.3": fig_3_4_3, "3.4.4": fig_3_4_4,
    "3.4.5": fig_3_4_5, "3.4.6": fig_3_4_6, "3.4.7": fig_3_4_7, "3.4.8": fig_3_4_8, "3.4.9": fig_3_4_9,
    "3.7.2": fig_3_7_2, "3.10.1": fig_3_10_1, "3.11.1": fig_3_11_1,
    "x3.1": fig_x3_1, "x3.2": fig_x3_2, "x3.3": fig_x3_3,
}

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