"""Larsen and Marx (2018), Chapter 2: Probability.

Companion code for Chapter 2 of R. J. Larsen and M. L. Marx, An Introduction to Mathematical Statistics
and Its Applications, 6th edition (Pearson, 2018), pp. 15-101, written from scratch with numpy, scipy and
matplotlib. The functions are short and meant to be read next to the lecture notes
(../ch02-probability.html):

* Section 2.1, the frequency view of probability: running_proportion (Figure 2.1.1).
* Sections 2.2-2.3, the sample space of two dice (Figure 2.2.1), inclusion-exclusion and the
  matching problem: incl_excl_partial, derangements, matching_union (Theorem 2.3.7, Example 2.6.24).
* Section 2.4, conditional probability and Bayes: posterior, monty_hall_posterior (Case Study 2.4.1 with
  a host who has a preference), screening_table (Tables 2.4.2 and 2.4.3), two_sided_chip (Example 2.4.10).
* Section 2.5, independence: craps_point and craps_win (Example 2.5.12), duel_andy (Example 2.5.14),
  relay (Example 2.5.13), caesar_breath (Example 2.5.15), bernstein_events.
* Section 2.6, combinatorics: multinomial, stirling, password_space (Example 2.6.18), pascal_rows
  (Figure 2.6.17), compositions.
* Section 2.7, combinatorial probability: birthday_match and birthday_nonuniform (Example 2.7.6, Table
  2.7.1), one_pair_birthday (Question 2.7.15), poker_counts (Example 2.7.7, Table 2.7.2),
  powerball_table (Example 2.7.9, Table 2.7.3), walk_pmf (Example 2.7.8).
* Section 2.8, Monte Carlo: chip_trials (Table 2.8.1, data typed in from the book), mc_standard_error.
* JSRandom: the seeded generator of the browser demonstrations (DK.rng in courses/demo-kit.js), and the
  three demonstrations' simulations (demo_birthday, demo_poker, demo_lottery, demo_matching, demo_independent), so that the
  numbers on the pages can be rerun here.

Figures. Three of the book's figures in this chapter are computed or can be (the rest are Venn diagrams, tree
diagrams, wiring diagrams, urn pictures and counting schematics); all three are reproduced:
  2.1.1   running proportion of heads, here from a simulation (reproduced);
  2.2.1   the 6 by 6 sample space of two dice, with the event "sum is 7" (reproduced);
  2.6.17  Pascal's triangle (reproduced).
Skipped as schematic drawings: 2.2.2 to 2.2.8 (Venn diagrams), 2.3.1 to 2.3.3 (Venn diagrams), 2.4.1 to 2.4.4,
2.4.6 to 2.4.9 (sample-space, urn and tree pictures), 2.4.5 (urn compositions), 2.5.1 (circuit), 2.5.2 and
2.5.3 (relay and duel pictures), 2.5.4 (molecules in a box), 2.6.1 to 2.6.16 and 2.6.18 (counting
diagrams, dials, braille cells, a chessboard, routes), 2.7.1 to 2.7.9 (urn and card pictures, Venn-like
diagrams of the birthday sequences), 2.8.1 (two ways of conceptualizing the chip game).
Three figures of our own illustrate the notes:
  x2-1  the birthday problem: exact probability, the exponential approximation, a seasonal
        distribution of births, simulated frequencies, and the number of people needed against the number
        of days (Table 2.7.1, Section 2.7);
  x2-2  how little a positive screening test says about a rare condition (Tables 2.4.2 and 2.4.3,
        Question 2.4.48);
  x2-3  Monte Carlo for the two-sided chip: the 100 trials of Table 2.8.1 and simulated paths (Section 2.8).
Run `python3 ch02_probability.py --list`, `python3 ch02_probability.py` (all figures, a few seconds) or
`python3 ch02_probability.py --fig 2.2.1`. Files go to ../img/ch02/; the demonstrations read
../data/ch02-birthday.json and ../data/ch02-combinatorics.json (written by export_json()).
"""
import json
import math
import os
from fractions import Fraction
from itertools import combinations

import numpy as np

import common
from common import BLUE, GREEN, GREY, MAGENTA, ORANGE, PURPLE, RED, savefig, book_data

import matplotlib.pyplot as plt

CH = 2
M32 = 0xFFFFFFFF
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))


# --------------------------------------------------------------------------- JS-compatible random numbers
def _imul(a, b):
    """Math.imul as an unsigned number: the low 32 bits of the product (the bit pattern is what matters
    for the XORs and the logical shifts that follow)."""
    return (a * b) & M32


class JSRandom:
    """The seeded random numbers of the browser demos (DK.rng in courses/demo-kit.js): u() is mulberry32."""

    def __init__(self, seed):
        self.a = int(seed) & M32

    def u(self):
        a = (self.a + 0x6D2B79F5) & M32
        self.a = a
        t = _imul(a ^ (a >> 15), 1 | a)
        t = ((t + _imul(t ^ (t >> 7), 61 | t)) & M32) ^ t
        return ((t ^ (t >> 14)) & M32) / 4294967296.0


# --------------------------------------------------------------------------- Section 2.1 and 2.3
def running_proportion(n, rng, p=0.5):
    """Proportion of heads after 1, 2, ..., n tosses of a coin with P(head) = p (Figure 2.1.1)."""
    x = rng.random(n) < p
    return np.cumsum(x) / np.arange(1, n + 1)


def incl_excl_partial(inter_sums):
    """Partial sums S_1, S_1 - S_2, S_1 - S_2 + S_3, ... of Theorem 2.3.7, where inter_sums[j-1] is the sum
    of the probabilities of all j-fold intersections. The partial sums alternate around P(union)."""
    out, acc = [], 0.0
    for j, s in enumerate(inter_sums, start=1):
        acc += (-1) ** (j + 1) * s
        out.append(acc)
    return out


def derangements(n):
    """Number of permutations of n objects with no fixed point (the recursion D_n = (n-1)(D_{n-1} + D_{n-2}))."""
    d = [1, 0]
    for m in range(2, n + 1):
        d.append((m - 1) * (d[m - 1] + d[m - 2]))
    return d[n]


def matching_union(n):
    """P(at least one of n letters lands in its own envelope) = sum_{j=1}^n (-1)^(j+1)/j! and its
    inclusion-exclusion terms S_j = 1/j! (the j-fold intersections have probability (n-j)!/n!)."""
    s = [Fraction(math.comb(n, j) * math.factorial(n - j), math.factorial(n)) for j in range(1, n + 1)]
    p = sum(Fraction((-1) ** (j + 1)) * s[j - 1] for j in range(1, n + 1))
    return p, s


# --------------------------------------------------------------------------- Section 2.4
def posterior(prior, sens, fpr):
    """P(A | B) by Bayes' theorem, for an event A of prior probability `prior`, P(B|A) = sens, P(B|A^c) = fpr."""
    return prior * sens / (prior * sens + (1 - prior) * fpr)


def monty_hall_posterior(q):
    """Case Study 2.4.1 generalised. You pick door 2. If the prize is behind door 2 the host opens door 3 with
    probability q (the book takes q = 1/2). Given that he opens door 3: P(prize behind 2) and P(prize behind 1)."""
    stay = Fraction(1, 3) * q / (Fraction(1, 3) * q + Fraction(1, 3))
    return stay, 1 - stay


def screening_table():
    """Tables 2.4.2 and 2.4.3 of the book, recomputed: rows (P(A1), P(B|A1^c), P(A1|B)) with P(B|A1) = 0.9, and
    the burglar-alarm sensitivities with P(A1|B)."""
    t242 = [(pi, f, posterior(pi, 0.9, f)) for pi, f in
            [(1e-4, 1e-3), (1e-4, 1e-4), (1e-3, 1e-3), (1e-3, 1e-4), (1e-2, 1e-3), (1e-2, 1e-4)]]
    t243 = [(s, posterior(2e-4, s, 5 / 730)) for s in (0.95, 0.97, 0.99, 0.999)]
    return t242, t243


def two_sided_chip(n, rng):
    """Example 2.4.10 played n times: draw one of the chips red/red, blue/blue, red/blue at random and a
    random side up. Returns the colours showing (0 = red, 1 = blue) and the colours underneath."""
    chip = rng.integers(0, 3, n)                # 0 red/red, 1 blue/blue, 2 mixed
    flip = rng.integers(0, 2, n)                # which side is up (matters for the mixed chip)
    top = np.where(chip == 0, 0, np.where(chip == 1, 1, flip))
    under = np.where(chip == 0, 0, np.where(chip == 1, 1, 1 - flip))
    return top, under


def chip_trials():
    """The 100 trials of Table 2.8.1: (top, under) as arrays of 0 (red) and 1 (blue)."""
    d = book_data("ch02-chip-trials")
    return (np.array([c == "B" for c in d["top"]], dtype=int), np.array([c == "B" for c in d["under"]], dtype=int))


def mc_standard_error(p, m):
    """Standard error sqrt(p(1-p)/m) of a Monte Carlo estimate of a probability p from m replications."""
    return math.sqrt(p * (1 - p) / m)


# --------------------------------------------------------------------------- Section 2.5
def craps_point(point):
    """Probability of making the point 4, 5, 6, 8, 9 or 10 (Example 2.5.12): the point first, then the same sum
    before a 7. With a = P(sum = point) and s = P(sum = 7) the answer is a * a / (a + s) (first-step analysis)."""
    ways = {2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1}
    a, s = Fraction(ways[point], 36), Fraction(6, 36)
    return a * a / (a + s)


def craps_win():
    """P(shooter wins) = P(7 or 11 first) + the sum of the six point probabilities = 244/495."""
    return Fraction(8, 36) + sum(craps_point(p) for p in (4, 5, 6, 8, 9, 10))


def duel_andy(hit_a=0.3, hit_c=0.5):
    """Example 2.5.14: Andy's survival probability if he shoots at Bob and hits (so Charley and Andy duel,
    Charley first), against 'deliberately miss'. Returns (hit, miss)."""
    q = (1 - hit_c) * (1 - hit_a)
    hit = (1 - hit_c) * hit_a / (1 - q)
    return hit, hit_a


def relay(prior_plus=0.6, flip=0.25, stages=3):
    """Example 2.5.13: P(+ sent | + received) after `stages` relay stations that each reverse a signal
    with probability `flip`. Returns (P(+ received | + sent), P(+ received | - sent), posterior)."""
    # probability that the signal is unchanged after the stages: (1 + (1 - 2 flip)^stages) / 2
    keep = (1 + (1 - 2 * flip) ** stages) / 2
    p_b_a, p_b_ac = keep, 1 - keep
    return p_b_a, p_b_ac, prior_plus * p_b_a / (prior_plus * p_b_a + (1 - prior_plus) * p_b_ac)


def caesar_breath(n_total=10 ** 44, k=2 * 10 ** 22):
    """Example 2.5.15. P(at least one of Caesar's k molecules in a breath of k) = 1 - prod (N-k-i)/(N-i); returns
    the value, the book's exponential approximation 1 - exp(-k^2/N), and the sandwich bounds of Filling the gap 2.14."""
    from mpmath import mp, mpf, log, exp
    mp.dps = 60
    N, K = mpf(n_total), mpf(k)
    approx = 1 - exp(-K * K / N)
    # the product prod_{i<k} (1 - K/(N-i)) lies between (1 - K/(N-K))^K and (1 - K/N)^K
    upper = 1 - (1 - K / (N - K)) ** K          # lower bound for the product gives upper bound for P
    lower = 1 - (1 - K / N) ** K
    return float(approx), float(lower), float(upper)


def bernstein_events():
    """Question 2.5.15: red/green dice, A odd red, B odd green, C odd sum: pairwise independent, not mutually."""
    omega = [(r, g) for r in range(1, 7) for g in range(1, 7)]
    A = {w for w in omega if w[0] % 2 == 1}
    B = {w for w in omega if w[1] % 2 == 1}
    C = {w for w in omega if (w[0] + w[1]) % 2 == 1}
    P = lambda E: Fraction(len(E), 36)
    return dict(PA=P(A), PB=P(B), PC=P(C), PAB=P(A & B), PAC=P(A & C), PBC=P(B & C), PABC=P(A & B & C))


# --------------------------------------------------------------------------- Section 2.6
def multinomial(*ks):
    """n! / (k_1! ... k_r!) with n = sum k_i (Theorem 2.6.2)."""
    out = math.factorial(sum(ks))
    for k in ks:
        out //= math.factorial(k)
    return out


def stirling(n):
    """sqrt(2 pi) n^(n+1/2) e^(-n), the approximation to n! of the Comment after Example 2.6.9."""
    return math.sqrt(2 * math.pi) * n ** (n + 0.5) * math.exp(-n)


def password_space():
    """Example 2.6.18: number of admissible passwords, and the probability of being hacked in 6 months."""
    n = 10 ** 4 * 8 ** 2 * 26 ** 4 * 2 ** 4 * multinomial(4, 4, 2)
    per_month = 3 * 10 ** 9 * 60 * 60 * 24 * 30
    return n, per_month, 1 - (1 - per_month / n) ** 6


def compositions(n, r):
    """Number of solutions of x_1 + ... + x_r = n in positive integers: C(n-1, r-1) (Question 2.6.56)."""
    return math.comb(n - 1, r - 1)


def pascal_rows(m):
    return [[math.comb(n, k) for k in range(n + 1)] for n in range(m + 1)]


# --------------------------------------------------------------------------- Section 2.7
def birthday_match(k, d=365):
    """P(at least two of k people share a birthday) with d equally likely days (Example 2.7.6)."""
    if k > d:
        return 1.0
    p = 1.0
    for j in range(k):
        p *= (d - j) / d
    return 1.0 - p


def birthday_approx(k, d=365):
    """1 - exp(-k(k-1)/(2d)): the number of pairs, C(k,2), times the chance 1/d that a pair matches."""
    return 1.0 - math.exp(-k * (k - 1) / (2.0 * d))


def birthday_threshold(d, q=0.5):
    """Smallest k with P(match) >= q."""
    p, k = 1.0, 0
    while 1 - p < q:
        p *= (d - k) / d
        k += 1
    return k


def elementary_symmetric(w, kmax):
    """e_0..e_kmax of the numbers w (coefficients of prod (1 + w_i t))."""
    e = np.zeros(kmax + 1)
    e[0] = 1.0
    for x in w:
        e[1:] = e[1:] + x * e[:-1]
    return e


def birthday_nonuniform(k, w):
    """P(some two of k people share a birthday) when day i has probability w_i (sum 1): 1 - k! e_k(w).
    The classical result (proved in Filling the gap 2.19) is that this is at least birthday_match(k, len(w))."""
    if k > len(w):
        return 1.0
    e = elementary_symmetric(np.asarray(w, dtype=float), k)
    return float(1.0 - math.factorial(k) * e[k])


def seasonal_weights(d=365, amp=0.6, peak=230):
    """A smooth seasonal distribution of births: w_i proportional to 1 + amp cos(2 pi (i - peak)/d)."""
    i = np.arange(d)
    w = 1 + amp * np.cos(2 * np.pi * (i - peak) / d)
    return w / w.sum()


def one_pair_birthday(k, d=365):
    """Question 2.7.15: P(exactly one pair of the k people share a birthday, everyone else distinct)."""
    if k < 2 or k > d:
        return 0.0
    num = math.comb(k, 2) * d
    for j in range(k - 2):
        num *= (d - 1 - j)
    return num / d ** k


def poker_counts():
    """Numbers of five-card hands of each type (Example 2.7.7 and Table 2.7.2); they add up to C(52, 5)."""
    C = math.comb
    return {
        "royal flush": 4,
        "straight flush": 36,
        "four of a kind": 13 * 48,
        "full house": 13 * C(4, 3) * 12 * C(4, 2),
        "flush": 4 * (C(13, 5) - 10),
        "straight": 10 * (4 ** 5 - 4),
        "three of a kind": 13 * C(4, 3) * C(12, 2) * 4 ** 2,
        "two pairs": C(13, 2) * C(4, 2) ** 2 * 44,
        "one pair": 13 * C(4, 2) * C(12, 3) * 4 ** 3,
        "no pair": (C(13, 5) - 10) * (4 ** 5 - 4),
    }


POKER_ORDER = ["no pair", "one pair", "two pairs", "three of a kind", "straight", "flush", "full house",
               "four of a kind", "straight flush", "royal flush"]


def poker_classify(cards):
    """Hand type of five cards given as integers 0..51 (rank = c % 13 with 12 = ace, suit = c // 13)."""
    ranks = sorted(c % 13 for c in cards)
    suits = {c // 13 for c in cards}
    counts = sorted([ranks.count(r) for r in set(ranks)], reverse=True)
    straight = (len(set(ranks)) == 5 and (ranks[4] - ranks[0] == 4 or ranks == [0, 1, 2, 3, 12]))
    flush = len(suits) == 1
    if straight and flush:
        return "royal flush" if ranks == [8, 9, 10, 11, 12] else "straight flush"
    if counts == [4, 1]:
        return "four of a kind"
    if counts == [3, 2]:
        return "full house"
    if flush:
        return "flush"
    if straight:
        return "straight"
    if counts == [3, 1, 1]:
        return "three of a kind"
    if counts == [2, 2, 1]:
        return "two pairs"
    if counts == [2, 1, 1, 1]:
        return "one pair"
    return "no pair"


def powerball_table(white=59, picks=5, extra=35):
    """Example 2.7.9 and Table 2.7.3: for every (number of white matches w, Powerball matched b) the number of
    tickets C(picks, w) C(white - picks, picks - w) (1 or extra - 1) out of C(white, picks) extra."""
    total = math.comb(white, picks) * extra
    rows = {}
    for w in range(picks + 1):
        for b in (1, 0):
            rows[(w, b)] = math.comb(picks, w) * math.comb(white - picks, picks - w) * (1 if b else extra - 1)
    return total, rows


def walk_pmf(n, r):
    """Example 2.7.8: P(net advance r after n equally likely forward/backward steps); 0 unless n + r is even."""
    if abs(r) > n or (n + r) % 2:
        return 0.0
    return math.comb(n, (n + r) // 2) / 2 ** n


# --------------------------------------------------------------------------- demonstrations (JS reproduction)
def demo_birthday(k, d, weights, R, seed):
    """birthday-problem-demo.html: R simulated groups of k people; returns the proportion with a shared
    birthday and the proportion with exactly one shared pair of people (Y = number of matching pairs).
    weights is None (uniform) or a list of d probabilities; a birthday is drawn by inverting the cdf."""
    rng = JSRandom(seed * 7919 + k)
    if weights is None:
        cum = None
    else:
        cum, s = [], 0.0
        for x in weights:
            s += x
            cum.append(s)
    any_match, pair_counts = 0, {}
    for _ in range(R):
        seen = {}
        for _i in range(k):
            u = rng.u()
            if cum is None:
                day = int(u * d)
            else:
                lo, hi = 0, d - 1
                while lo < hi:
                    mid = (lo + hi) >> 1
                    if cum[mid] > u:
                        hi = mid
                    else:
                        lo = mid + 1
                day = lo
            seen[day] = seen.get(day, 0) + 1
        y = sum(v * (v - 1) // 2 for v in seen.values())
        if y > 0:
            any_match += 1
        pair_counts[y] = pair_counts.get(y, 0) + 1
    return any_match / R, pair_counts


def demo_poker(R, seed):
    """combinatorial-probability-demo.html (poker): R hands, each the first five cards of a Fisher-Yates
    shuffle of 52 cards; returns the counts of hand types."""
    rng = JSRandom(seed * 7919 + 5)
    counts = {h: 0 for h in POKER_ORDER}
    for _ in range(R):
        deck = list(range(52))
        for i in range(5):
            j = i + int(rng.u() * (52 - i))
            deck[i], deck[j] = deck[j], deck[i]
        counts[poker_classify(deck[:5])] += 1
    return counts


def demo_lottery(white, picks, extra, R, seed):
    """combinatorial-probability-demo.html (lottery): R tickets against a fixed drawing; returns counts of
    (white matches, extra ball matched). The drawing is the first `picks` numbers of 1..white and the extra
    ball 1; each ticket is a random subset (Fisher-Yates) and a random extra number."""
    rng = JSRandom(seed * 7919 + 59)
    counts = {}
    for _ in range(R):
        deck = list(range(white))
        for i in range(picks):
            j = i + int(rng.u() * (white - i))
            deck[i], deck[j] = deck[j], deck[i]
        w = sum(1 for x in deck[:picks] if x < picks)
        b = 1 if int(rng.u() * extra) == 0 else 0
        counts[(w, b)] = counts.get((w, b), 0) + 1
    return counts


def demo_matching(n, R, seed):
    """inclusion-exclusion-demo.html: R random permutations of n letters; returns the number with at least one
    fixed point and the histogram of the number of fixed points."""
    rng = JSRandom(seed * 7919 + n)
    hit, hist = 0, {}
    for _ in range(R):
        a = list(range(n))
        for i in range(n - 1, 0, -1):
            j = int(rng.u() * (i + 1))
            a[i], a[j] = a[j], a[i]
        f = sum(1 for i in range(n) if a[i] == i)
        if f > 0:
            hit += 1
        hist[f] = hist.get(f, 0) + 1
    return hit, hist


def demo_independent(n, p, R, seed):
    """inclusion-exclusion-demo.html (independent events): R trials of n independent events, each of
    probability p; returns the number of trials with at least one event and the histogram of the number
    of events that occur."""
    rng = JSRandom(seed * 7919 + n)
    hit, hist = 0, {}
    for _ in range(R):
        c = 0
        for _i in range(n):
            if rng.u() < p:
                c += 1
        if c > 0:
            hit += 1
        hist[c] = hist.get(c, 0) + 1
    return hit, hist


# --------------------------------------------------------------------------- figures
def fig_2_1_1(out_dir=None):
    """Figure 2.1.1: the running proportion m/n of heads tends to 1/2 (simulated here)."""
    rng = np.random.default_rng(2110)
    n = 1000
    fig, ax = plt.subplots(figsize=(6.4, 3.3))
    t = np.arange(1, n + 1)
    for i, c in enumerate((BLUE, RED, GREEN, ORANGE)):
        ax.plot(t, running_proportion(n, rng), color=c, lw=1.1)
    ax.axhline(0.5, color="black", lw=0.8)
    ax.plot(t, 0.5 + 1 / np.sqrt(t), color=GREY, lw=0.9, ls="--")
    ax.plot(t, 0.5 - 1 / np.sqrt(t), color=GREY, lw=0.9, ls="--")
    ax.set_xscale("log")
    ax.set_ylim(0, 1)
    ax.set_xlabel("number of tosses $n$")
    ax.set_ylabel("proportion of heads $m/n$")
    ax.text(1.3, 0.54, "$1/2$", fontsize=9)
    ax.text(120, 0.14, "dashed: $1/2\\pm 1/\\sqrt{n}$, two standard deviations", fontsize=8, color=GREY, ha="center")
    return savefig(fig, CH, "fig2-1-1", out_dir)


def fig_2_2_1(out_dir=None):
    """Figure 2.2.1: the 36 outcomes of rolling a red and a green die; the event A: the sum is 7."""
    fig, ax = plt.subplots(figsize=(4.2, 4.2))
    for r in range(1, 7):
        for g in range(1, 7):
            hit = r + g == 7
            ax.add_patch(plt.Rectangle((g - 0.5, 6.5 - r), 1, 1, fc="#f3b7b7" if hit else "white", ec="black", lw=0.7))
            ax.text(g, 7 - r, "(%d,%d)" % (r, g), ha="center", va="center", fontsize=8, color="black")
    ax.set_xlim(0.5, 6.5)
    ax.set_ylim(0.5, 6.5)
    ax.set_aspect("equal")
    ax.set_xticks(range(1, 7))
    ax.set_yticks(range(1, 7))
    ax.set_yticklabels(range(6, 0, -1))
    ax.xaxis.tick_top()
    ax.xaxis.set_label_position("top")
    ax.set_xlabel("face showing on the green die")
    ax.set_ylabel("face showing on the red die")
    ax.tick_params(length=0)
    return savefig(fig, CH, "fig2-2-1", out_dir)


def fig_2_6_17(out_dir=None):
    """Figure 2.6.17: Pascal's triangle, with C(n+1, k) = C(n, k) + C(n, k-1) (Equation 2.6.1) marked."""
    rows = pascal_rows(8)
    fig, ax = plt.subplots(figsize=(6.2, 3.6))
    for n, row in enumerate(rows):
        for k, v in enumerate(row):
            x, y = k - n / 2, -n
            mark = (n, k) in ((4, 1), (4, 2), (5, 2))
            ax.text(x, y, str(v), ha="center", va="center", fontsize=10,
                    bbox=dict(boxstyle="round,pad=0.25", fc="#f3b7b7" if mark else "white", ec=GREY, lw=0.6))
    for n in range(9):
        ax.text(-4.9, -n, "row %d" % n, ha="left", va="center", fontsize=8, color=GREY)
    ax.set_xlim(-5, 4.6)
    ax.set_ylim(-8.6, 0.6)
    ax.axis("off")
    return savefig(fig, CH, "fig2-6-17", out_dir)


def fig_x2_1(out_dir=None):
    """Own figure x2-1: the birthday problem, exact against approximations and simulation."""
    rng = np.random.default_rng(2711)
    ks = np.arange(1, 81)
    exact = np.array([birthday_match(int(k)) for k in ks])
    appr = np.array([birthday_approx(int(k)) for k in ks])
    w = seasonal_weights()
    seas = np.array([birthday_nonuniform(int(k), w) for k in ks])
    fig, (ax, bx) = plt.subplots(1, 2, figsize=(8.8, 3.5), gridspec_kw=dict(width_ratios=[1.25, 1]))
    ax.plot(ks, exact, color=BLUE, lw=2, label="exact, 365 equally likely days")
    ax.plot(ks, appr, color=GREY, lw=1.3, ls="--", label=r"$1-e^{-k(k-1)/730}$")
    ax.plot(ks, seas, color=ORANGE, lw=1.5, label="seasonal births (peak in August)")
    for k in (15, 22, 23, 40, 50, 70):
        ax.plot([k], [birthday_match(k)], "o", color=BLUE, ms=4)
    sim_k = [10, 20, 23, 30, 40, 60]
    sim = []
    for k in sim_k:
        hit = 0
        for _ in range(4000):
            b = rng.integers(0, 365, k)
            hit += len(set(b.tolist())) < k
        sim.append(hit / 4000)
    ax.plot(sim_k, sim, "s", mfc="none", mec=RED, ms=6, label="simulation, 4000 groups")
    ax.axhline(0.5, color="black", lw=0.5, ls=":")
    ax.axvline(23, color="black", lw=0.5, ls=":")
    ax.set_xlabel("number of people $k$")
    ax.set_ylabel("P(at least two share a birthday)")
    ax.set_xlim(0, 80)
    ax.set_ylim(0, 1.02)
    ax.legend(loc="lower right", fontsize=8)
    ds = np.unique(np.round(np.logspace(0.7, 6, 40)).astype(int))
    ths = [birthday_threshold(int(d)) for d in ds]
    bx.loglog(ds, ths, "o", color=BLUE, ms=3, label="smallest $k$ with $P\\geq 1/2$")
    bx.loglog(ds, np.sqrt(2 * np.log(2) * ds), color=GREY, ls="--", label=r"$\sqrt{2\ln 2\;d}$")
    bx.plot([365], [23], "s", mfc="none", mec=RED, ms=7)
    bx.set_xlabel("number of equally likely days $d$")
    bx.set_ylabel("people needed")
    bx.legend(fontsize=8, loc="upper left")
    ax.set_title("(a)", loc="left", fontsize=9)
    bx.set_title("(b)", loc="left", fontsize=9)
    return savefig(fig, CH, "figx2-1", out_dir)


def fig_x2_2(out_dir=None):
    """Own figure x2-2: the posterior probability of a rare condition after a positive screening result."""
    fig, (ax, bx) = plt.subplots(1, 2, figsize=(8.8, 3.4))
    pi = np.logspace(-5, -0.5, 200)
    for f, c in ((1e-2, RED), (1e-3, ORANGE), (1e-4, BLUE)):
        ax.semilogx(pi, posterior(pi, 0.9, f), color=c, lw=1.6, label="false positive rate %g" % f)
    ax.plot([1e-4], [posterior(1e-4, 0.9, 1e-3)], "ko", ms=4)
    ax.annotate("Example 2.4.13: 0.08", (1e-4, posterior(1e-4, 0.9, 1e-3)), (2e-5, 0.35), fontsize=8,
                arrowprops=dict(arrowstyle="-", lw=0.6))
    ax.plot([1 / 90], [posterior(1 / 90, 0.9, 0.03)], "s", color=MAGENTA, ms=5)
    ax.annotate("Question 2.4.48: 0.25", (1 / 90, posterior(1 / 90, 0.9, 0.03)), (4e-2, 0.08), fontsize=8,
                arrowprops=dict(arrowstyle="-", lw=0.6))
    ax.set_xlabel("prevalence $P(A_1)$")
    ax.set_ylabel("$P(A_1\\mid B)$ (sensitivity 0.9)")
    ax.set_ylim(0, 1.02)
    ax.legend(fontsize=8, loc="upper left")
    s = np.linspace(0.5, 1, 100)
    bx.plot(s, posterior(2e-4, s, 5 / 730), color=BLUE, lw=1.8)
    bx.axhline(posterior(2e-4, 1.0, 5 / 730), color=GREY, ls="--", lw=0.9)
    for sv in (0.95, 0.97, 0.99, 0.999):
        bx.plot([sv], [posterior(2e-4, sv, 5 / 730)], "ko", ms=4)
    bx.set_ylim(0, 0.035)
    bx.set_xlabel("sensitivity $P(B\\mid A_1)$ of the alarm")
    bx.set_ylabel("$P(A_1\\mid B)$")
    bx.text(0.52, 0.0295, "ceiling at sensitivity 1: 0.0284", fontsize=8, color=GREY)
    ax.set_title("(a)", loc="left", fontsize=9)
    bx.set_title("(b) Example 2.4.14, Table 2.4.3", loc="left", fontsize=9)
    return savefig(fig, CH, "figx2-2", out_dir)


def fig_x2_3(out_dir=None):
    """Own figure x2-3: Monte Carlo for the two-sided chip (Section 2.8)."""
    rng = np.random.default_rng(2813)
    top, under = chip_trials()
    blue = top == 1
    m = np.cumsum(blue)[blue]
    run = np.cumsum(under[blue] == 1) / np.arange(1, blue.sum() + 1)
    fig, (ax, bx) = plt.subplots(1, 2, figsize=(8.8, 3.4))
    mm = np.arange(1, 3001)
    for c in (BLUE, GREEN, ORANGE, PURPLE):
        t, u = two_sided_chip(9000, rng)
        sel = u[t == 1][:3000]
        ax.plot(mm, np.cumsum(sel) / mm, color=c, lw=0.9, alpha=0.9)
    ax.fill_between(mm, 2 / 3 - 2 * np.sqrt(2 / 9 / mm), 2 / 3 + 2 * np.sqrt(2 / 9 / mm), color=GREY, alpha=0.18, lw=0)
    ax.plot(np.arange(1, blue.sum() + 1), run, color="black", lw=1.6, drawstyle="steps-post",
            label="the book's 100 trials (52 with blue on top)")
    ax.axhline(2 / 3, color=RED, lw=0.8)
    ax.axhline(1 / 2, color=RED, lw=0.8, ls="--")
    ax.text(1500, 2 / 3 + 0.012, "2/3", color=RED, fontsize=9)
    ax.text(1500, 0.5 + 0.012, "1/2", color=RED, fontsize=9)
    ax.set_xscale("log")
    ax.set_ylim(0.2, 1.0)
    ax.set_xlabel("number of trials with blue showing")
    ax.set_ylabel("proportion with blue underneath")
    ax.legend(fontsize=8, loc="lower right")
    est = []
    for _ in range(8000):
        t, u = two_sided_chip(100, rng)
        sel = u[t == 1]
        est.append(sel.mean() if len(sel) else np.nan)
    est = np.array(est)
    bx.hist(est[~np.isnan(est)], bins=np.linspace(0.3, 1.0, 36), color="#9fc3f0", ec="white", density=True)
    bx.axvline(36 / 52, color="black", lw=1.4)
    bx.axvline(2 / 3, color=RED, lw=0.9)
    bx.axvline(0.5, color=RED, lw=0.9, ls="--")
    bx.text(36 / 52 + 0.012, bx.get_ylim()[1] * 0.9, "book: 36/52", fontsize=8)
    bx.set_xlabel("estimate from 100 trials")
    bx.set_ylabel("density over 8000 repetitions")
    ax.set_title("(a)", loc="left", fontsize=9)
    bx.set_title("(b)", loc="left", fontsize=9)
    return savefig(fig, CH, "figx2-3", out_dir)


# --------------------------------------------------------------------------- data for the demonstrations
def export_json(out_dir=None):
    """Write the small data files read by the demonstrations."""
    out = out_dir or DATA_OUT
    os.makedirs(out, exist_ok=True)
    w = seasonal_weights()
    ks = list(range(1, 101))
    bd = {
        "note": "Birthday problem: exact P(at least two of k share a birthday) with 365 equally likely days and with a seasonal "
                "distribution w_i proportional to 1 + 0.6 cos(2 pi (i - 230)/365); Table 2.7.1 of Larsen and Marx (2018).",
        "k": ks,
        "exact365": [round(birthday_match(k), 10) for k in ks],
        "seasonal365": [round(birthday_nonuniform(k, w), 10) for k in ks],
        "table_2_7_1": {str(k): round(birthday_match(k), 3) for k in (15, 22, 23, 40, 50, 70)},
    }
    with open(os.path.join(out, "ch02-birthday.json"), "w") as f:
        json.dump(bd, f)
    total, rows = powerball_table()
    comb = {
        "note": "Hand counts for five-card poker (Example 2.7.7, Table 2.7.2) and Powerball ticket counts (Example 2.7.9, Table 2.7.3).",
        "poker": poker_counts(),
        "poker_total": math.comb(52, 5),
        "powerball_total": total,
        "powerball": {"%d,%d" % k: v for k, v in rows.items()},
    }
    with open(os.path.join(out, "ch02-combinatorics.json"), "w") as f:
        json.dump(comb, f)
    print("wrote", os.path.join(out, "ch02-birthday.json"), "and ch02-combinatorics.json")


FIGURES = {
    "2.1.1": fig_2_1_1,
    "2.2.1": fig_2_2_1,
    "2.6.17": fig_2_6_17,
    "x2-1": fig_x2_1,
    "x2-2": fig_x2_2,
    "x2-3": fig_x2_3,
}

if __name__ == "__main__":
    common.run(FIGURES, CH)
    export_json()
