"""Chapter 1 (Introduction) of Larsen and Marx (2018), An Introduction to Mathematical Statistics and Its Applications.

Reproduces / adds
  Figure 1.2.1  the fitted earthquake frequency curve N = 80338.16 exp(-1.981 R) of Case Study 1.2.1
                (log scale, with the extrapolation to R = 10.5). The book's plotted averages are not tabulated, so the
                markers show the fitted values at the book's magnitudes R = 4, 4.5, ..., 7.
  Figure x1.1   (own) Table 1.2.1 of Case Study 1.2.2: admission rates before, during and after the full moon, month by month.
  Figure x1.2   (own) Case Study 1.2.3: sampling distribution of the serial-number estimator (n+1)/n * max - 1 and of the
                moment estimator 2 * mean - 1 for n = 5 tanks.

Skipped: Figure 1.2.1's seismograph table (a picture of raw numbers), Figure 1.3.1 (photograph of an astragalus),
Figure 1.3.2 (a schematic of the six faces of a die) and Figure 1.3.3 (facsimile of the 1665 London bill of mortality).

Also holds the closed forms used in the notes (tank_mean, tank_var, ...), and exports ../data/ch01-tanks.json for the demo.
Run:  python ch01_introduction.py [--fig 1.2.1 x1.1 x1.2]
"""
import json
import os
import numpy as np
import matplotlib.pyplot as plt
from math import comb
from scipy import stats

from common import (savefig, run, book_data, BLUE, RED, GREEN, GREY, ORANGE, HERE)

DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))


# ------------------------------------------------------------------ closed forms (Case Study 1.2.3)
def tank_est(x):
    """Serial-number estimate (n+1)/n * max - 1 (Equation 1.2.2)."""
    x = np.asarray(x)
    n = len(x)
    return (n + 1) / n * x.max() - 1


def tank_mean_max(N, n):
    return n * (N + 1) / (n + 1)


def tank_var_max(N, n):
    return n * (N + 1) * (N - n) / ((n + 1) ** 2 * (n + 2))


def tank_var_est(N, n):
    """Variance of (n+1)/n * M - 1 when n serials are drawn without replacement from 1..N."""
    return (N + 1) * (N - n) / (n * (n + 2))


def tank_var_mom(N, n):
    """Variance of 2 * (sample mean) - 1 under the same sampling."""
    return (N + 1) * (N - n) / (3 * n)


def tank_pmf_max(N, n):
    m = np.arange(n, N + 1)
    return m, np.array([comb(int(k) - 1, n - 1) for k in m], dtype=float) / comb(N, n)


def quake_rate(R, b0=80338.16, b1=-1.981):
    return b0 * np.exp(b1 * np.asarray(R, dtype=float))


def block_anova(Y):
    """Randomized block ANOVA for an (b blocks) x (k treatments) array: returns a dict of sums of squares, F, p."""
    Y = np.asarray(Y, dtype=float)
    b, k = Y.shape
    g = Y.mean()
    ss_t = b * ((Y.mean(0) - g) ** 2).sum()
    ss_b = k * ((Y.mean(1) - g) ** 2).sum()
    ss_tot = ((Y - g) ** 2).sum()
    ss_e = ss_tot - ss_t - ss_b
    df_t, df_b, df_e = k - 1, b - 1, (k - 1) * (b - 1)
    F = (ss_t / df_t) / (ss_e / df_e)
    Fb = (ss_b / df_b) / (ss_e / df_e)
    return dict(ss_t=ss_t, ss_b=ss_b, ss_e=ss_e, ss_tot=ss_tot, df_t=df_t, df_b=df_b, df_e=df_e, F=F, p=stats.f.sf(F, df_t, df_e),
                F_blocks=Fb, p_blocks=stats.f.sf(Fb, df_b, df_e))


def moon_matrix():
    d = book_data("moon")
    return np.column_stack([d["before"], d["during"], d["after"]]), d["months"]


# ------------------------------------------------------------------ figures
def fig_1_2_1(out=None):
    """Figure 1.2.1: fitted earthquake frequency curve, log scale, with the extrapolation to R = 10.5."""
    d = book_data("earthquake")
    fig, axes = plt.subplots(1, 2, figsize=(8.2, 3.2))
    R = np.linspace(3.75, 11, 300)
    Rg = np.array(d["R_grid"])
    ax = axes[0]
    ax.plot(R[R <= 7.5], quake_rate(R[R <= 7.5]), color=BLUE)
    ax.plot(Rg, quake_rate(Rg), "o", color=RED, ms=4, label="fitted value at the book's R")
    ax.set_xlabel("Magnitude on Richter scale, R")
    ax.set_ylabel("Average number of shocks per year, N")
    ax.set_xlim(3.75, 7.5)
    ax.set_ylim(0, 35)
    ax.legend(frameon=False, loc="upper right")
    ax.set_title("$N = 80338.16\\,e^{-1.981R}$")
    ax = axes[1]
    ax.semilogy(R, quake_rate(R), color=BLUE)
    ax.semilogy(Rg, quake_rate(Rg), "o", color=RED, ms=4)
    ax.axvspan(3.75, 7.25, color=GREEN, alpha=0.12, lw=0)
    ax.text(5.5, 3e-6, "range of the data", color=GREEN, ha="center", fontsize=9)
    n105 = float(quake_rate(10.5))
    ax.plot([10.5], [n105], "s", color=ORANGE, ms=6)
    ax.annotate("R = 10.5:\n%.2e per year\n(once in %s years)" % (n105, format(round(1 / n105, -1), ",.0f")), (10.5, n105), (7.4, 1e-2),
                arrowprops=dict(arrowstyle="->", color=GREY), fontsize=8.5)
    ax.set_xlabel("Magnitude on Richter scale, R")
    ax.set_ylabel("N (log scale)")
    ax.set_title("same curve: a straight line on the log scale")
    ax.set_ylim(1e-6, 1e3)
    fig.tight_layout()
    return savefig(fig, 1, "fig1-2-1", out)


def fig_x1_1(out=None):
    """Figure x1.1 (own): Table 1.2.1, admission rates before, during and after the full moon."""
    Y, months = moon_matrix()
    fig, axes = plt.subplots(1, 2, figsize=(8.2, 3.3), gridspec_kw=dict(width_ratios=[1.5, 1]))
    ax = axes[0]
    x = np.arange(len(months))
    for j, (lab, c) in enumerate(zip(["before", "during", "after"], [GREY, RED, BLUE])):
        ax.plot(x, Y[:, j], "o-" if j == 1 else "o--", color=c, ms=3.5, lw=1.4 if j == 1 else 1, label=lab)
    ax.set_xticks(x)
    ax.set_xticklabels(months, fontsize=8)
    ax.set_ylabel("admissions per day")
    ax.legend(frameon=False, ncol=3, fontsize=8.5, loc="upper left")
    ax.set_title("every month, in order (Aug to Jul)")
    ax = axes[1]
    diff = Y[:, 1] - Y[:, 0]
    ax.axhline(0, color="k", lw=0.8)
    ax.plot(np.zeros(12) + np.linspace(-0.08, 0.08, 12), diff, "o", color=RED, ms=4)
    ax.errorbar([0.35], [diff.mean()], yerr=[diff.std(ddof=1) / np.sqrt(12)], fmt="s", color="k", ms=5, capsize=4)
    ax.set_xlim(-0.5, 0.7)
    ax.set_xticks([0, 0.35])
    ax.set_xticklabels(["12 months", "mean $\\pm$ s.e."])
    ax.set_ylabel("during minus before")
    ax.set_title("paired difference")
    fig.tight_layout()
    return savefig(fig, 1, "figx1-1", out)


def fig_x1_2(out=None, R=40000, seed=1):
    """Figure x1.2 (own): sampling distribution of the two tank estimators, n = 5 tanks out of N = 360."""
    rng = np.random.default_rng(seed)
    N, n = 360, 5
    X = np.array([rng.choice(N, n, replace=False) + 1 for _ in range(R)])
    est1 = (n + 1) / n * X.max(1) - 1
    est2 = 2 * X.mean(1) - 1
    fig, ax = plt.subplots(1, 2, figsize=(8.2, 3.2), sharey=True)
    bins = np.arange(0, 800, 12)
    for a, e, lab, c in [(ax[0], est1, "$(n+1)/n\\cdot x_{\\max}-1$", BLUE), (ax[1], est2, "$2\\bar x-1$", RED)]:
        a.hist(e, bins=bins, density=True, color=c, alpha=0.55)
        a.axvline(N, color="k", lw=1.2)
        a.set_title(lab + ":  mean %.0f, sd %.0f" % (e.mean(), e.std()))
        a.set_xlabel("estimate of the production total")
    ax[0].set_ylabel("density")
    ax[0].text(N - 8, ax[0].get_ylim()[1] * 0.92, "true N = 360", fontsize=8.5, ha="right")
    ax[0].axvline(tank_est([92, 14, 28, 300, 146]), color=ORANGE, ls="--")
    ax[0].text(N - 8, ax[0].get_ylim()[1] * 0.74, "captured serials\n(Equation 1.2.2): 359", fontsize=8, color=ORANGE, ha="right")
    fig.tight_layout()
    return savefig(fig, 1, "figx1-2", out)


def export_demo_data():
    """Small table of the exact standard deviations for the demo (N = 360)."""
    rows = []
    for n in (2, 3, 5, 10, 20, 50, 100):
        rows.append(dict(n=n, sd_max=float(np.sqrt(tank_var_est(360, n))), sd_mom=float(np.sqrt(tank_var_mom(360, n)))))
    os.makedirs(DATA_OUT, exist_ok=True)
    with open(os.path.join(DATA_OUT, "ch01-tanks.json"), "w") as f:
        json.dump(dict(N=360, rows=rows), f, indent=1)


FIGURES = {"1.2.1": fig_1_2_1, "x1.1": fig_x1_1, "x1.2": fig_x1_2}

if __name__ == "__main__":
    export_demo_data()
    run(FIGURES, 1)
