"""Larsen and Marx (2018), Chapter 8: Types of Data, a Brief Overview.

Companion code for Chapter 8 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 (../ch08-types-of-data.html):

* Section 8.1: the tables of Case Studies 8.1.1 and 8.1.2 and the logistic curve of Figure 8.1.2
  (fit_logistic); decomposition of a block design into block, treatment and error sums of squares (rb_decompose).
* Section 8.2, classifying data: the five questions of the book as a function (classify), the model equations of
  the eight designs as simulators (sim_paired, sim_two_sample), the between and within sums of squares of a
  k-sample design (ksample_ss), the paired and randomized-block F statistics (paired_t, rb_F, ksample_F; for two
  levels F = t^2), the power of the paired and of the two-sample t test (power_paired, power_unpaired), the least
  squares slope through the origin for Hubble's law (hubble_H, hubble_age_years), the bivariate normal density of
  Figure 8.2.2 and the contingency-table statistic of Case Study 8.2.7 (chi2_2d).

Figures. Chapter 8 has seven numbered figures. Reproduced: 8.1.2 (the ICBM stockpile and its S-shaped logistic
curve; the book does not print the equation of its dashed curve, so the curve here is a least squares fit of our
own), 8.2.2 (the bivariate normal surface) and 8.2.3 (Hubble's data with the line v = H d).
Skipped, with reasons: 8.1.1 (an empty table layout), 8.1.3 (a diagram of the 2 x 2 recording scheme), 8.2.1
(an illustration of a random run order) and 8.2.4 and 8.2.5 (flow charts: the five questions are given as a table
and as the function classify instead).
Two figures of our own: x8.1, the profile of every block across the treatment levels for the bait data and the
blood-doping data (a block effect is a vertical shift of a whole profile), and x8.2, the power of the paired and of
the two-sample t test against the size of the shared pair effect (the break-even of Filling the gap 8.2).
Run `python3 ch08_types_of_data.py --list`, `python3 ch08_types_of_data.py` (all figures, about 10 s) or
`python3 ch08_types_of_data.py --fig 8.2.3`. Files go to ../img/ch08/.
"""
import math
import os

import numpy as np
from scipy import optimize, stats

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

CH = 8
HERE = os.path.dirname(os.path.abspath(__file__))
T = None


def tables():
    """The tables typed in from the book (code/data/ch08-tables.json)."""
    global T
    if T is None:
        T = book_data("ch08-tables")
    return T


# =========================================================================== Section 8.2: the five questions
def classify(quantitative, similar_units, n_factors=1, n_levels=1, dependent=False):
    """The design that the five questions of Section 8.2 lead to (the flow chart of Figure 8.2.4).

    Questions: quantitative or qualitative? similar or dissimilar units? one factor or more than one? how many
    factor levels (1, 2 or more)? dependent or independent samples? Returns the name of the data model.
    """
    if not quantitative:
        return "categorical"
    if not similar_units:
        return "regression/correlation"
    if n_factors >= 2:
        return "factorial"
    if n_levels == 1:
        return "one-sample"
    if n_levels == 2:
        return "paired" if dependent else "two-sample"
    return "randomized block" if dependent else "k-sample"


def overlaps(design):
    """The two overlaps of the flow chart (page 440): paired = RB with k = 2, two-sample = k-sample with k = 2."""
    return {"paired": "randomized block", "randomized block": "paired",
            "two-sample": "k-sample", "k-sample": "two-sample"}.get(design)


# =========================================================================== sums of squares and F statistics
def ksample_ss(groups):
    """Between-group and within-group sums of squares of a k-sample design (list of 1-d arrays)."""
    groups = [np.asarray(g, float) for g in groups]
    allv = np.concatenate(groups)
    m = allv.mean()
    ssb = sum(len(g) * (g.mean() - m) ** 2 for g in groups)
    ssw = sum(((g - g.mean()) ** 2).sum() for g in groups)
    return ssb, ssw, ((allv - m) ** 2).sum()


def ksample_F(groups):
    """The one-way F ratio (Chapter 12): (SSB/(k-1)) / (SSW/(n-k))."""
    ssb, ssw, _ = ksample_ss(groups)
    k = len(groups)
    n = sum(len(g) for g in groups)
    return (ssb / (k - 1)) / (ssw / (n - k))


def rb_decompose(Y):
    """Randomized block table Y (b blocks x k levels): SST, SS_blocks, SS_treatments, SS_error."""
    Y = np.asarray(Y, float)
    b, k = Y.shape
    m = Y.mean()
    sst = ((Y - m) ** 2).sum()
    ssb = k * ((Y.mean(1) - m) ** 2).sum()
    sstr = b * ((Y.mean(0) - m) ** 2).sum()
    return sst, ssb, sstr, sst - ssb - sstr


def rb_F(Y):
    """The randomized block F ratio (Chapter 13) for the treatment effect."""
    Y = np.asarray(Y, float)
    b, k = Y.shape
    _, _, sstr, sse = rb_decompose(Y)
    return (sstr / (k - 1)) / (sse / ((b - 1) * (k - 1)))


def paired_t(x, y):
    """The paired t statistic d_bar / (s_d / sqrt(n)) of Chapter 13."""
    d = np.asarray(x, float) - np.asarray(y, float)
    return d.mean() / (d.std(ddof=1) / math.sqrt(len(d)))


def pooled_t(x, y):
    """The pooled two-sample t statistic of Chapter 9."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    n, m = len(x), len(y)
    sp2 = ((n - 1) * x.var(ddof=1) + (m - 1) * y.var(ddof=1)) / (n + m - 2)
    return (x.mean() - y.mean()) / math.sqrt(sp2 * (1 / n + 1 / m))


def chi2_2d(table):
    """Pearson's statistic sum (O - E)^2 / E of an R x C table, its degrees of freedom and expected counts."""
    O = np.asarray(table, float)
    E = O.sum(1, keepdims=True) * O.sum(0, keepdims=True) / O.sum()
    return ((O - E) ** 2 / E).sum(), (O.shape[0] - 1) * (O.shape[1] - 1), E


# =========================================================================== model simulators (Section 8.2)
def sim_paired(rng, n, mu_x, mu_y, sd_pair, sd_x, sd_y):
    """X_i = mu_x + P_i + e_i, Y_i = mu_y + P_i + e'_i with P_i ~ N(0, sd_pair^2) (the paired model, p. 432)."""
    P = rng.normal(0, sd_pair, n)
    return mu_x + P + rng.normal(0, sd_x, n), mu_y + P + rng.normal(0, sd_y, n)


def sim_two_sample(rng, n, mu_x, mu_y, sd_x, sd_y):
    """The two-sample model: independent samples with their own spreads."""
    return rng.normal(mu_x, sd_x, n), rng.normal(mu_y, sd_y, n)


def breakeven_ratio(n, level=0.05):
    """sigma_P^2 / sigma^2 above which the paired t test has the shorter interval (Filling the gap 8.2)."""
    q = 1 - level / 2
    return (stats.t.ppf(q, n - 1) / stats.t.ppf(q, 2 * n - 2)) ** 2 - 1


def power_crossing(n, delta_over_sigma, level=0.05):
    """The ratio sigma_P^2 / sigma^2 at which the two tests have the same power."""
    pp = power_paired(n, delta_over_sigma, level)
    return optimize.brentq(lambda r: power_unpaired(n, delta_over_sigma, r, level) - pp, 0.0, 3.0)


def power_paired(n, delta_over_sigma, level=0.05):
    """Power of the two-sided paired t test: sigma_P cancels. delta = mu_X - mu_Y, sigma = sd of eps (both equal)."""
    nc = delta_over_sigma * math.sqrt(n / 2.0)
    c = stats.t.ppf(1 - level / 2, n - 1)
    return stats.nct.sf(c, n - 1, nc) + stats.nct.cdf(-c, n - 1, nc)


def power_unpaired(n, delta_over_sigma, ratio, level=0.05):
    """Power of the pooled two-sample t test on the same data, ratio = sigma_P^2 / sigma^2 (pairing ignored)."""
    nc = delta_over_sigma * math.sqrt(n / (2.0 * (1 + ratio)))
    c = stats.t.ppf(1 - level / 2, 2 * n - 2)
    return stats.nct.sf(c, 2 * n - 2, nc) + stats.nct.cdf(-c, 2 * n - 2, nc)


# =========================================================================== Hubble and the logistic curve
def hubble_H(d, v):
    """Least squares slope of the line through the origin v = H d: H = sum(d v) / sum(d^2)."""
    d, v = np.asarray(d, float), np.asarray(v, float)
    return float((d * v).sum() / (d ** 2).sum())


MILES_PER_MLY = 5.87850e18          # miles in a million light years (as in the book)
SECONDS_PER_YEAR = 365.25 * 86400.0


def hubble_age_years(H):
    """1/H in years, H in (thousand miles per second) per million light years."""
    H_per_s = H * 1000.0 / MILES_PER_MLY
    return 1.0 / H_per_s / SECONDS_PER_YEAR


def logistic(x, K, x0, s):
    return K / (1.0 + np.exp(-(x - x0) / s))


def fit_logistic(x, y):
    """Least squares fit of y = K / (1 + exp(-(x - x0)/s)); returns (K, x0, s)."""
    p, _ = optimize.curve_fit(logistic, np.asarray(x, float), np.asarray(y, float), p0=[1050.0, 4.0, 1.0])
    return tuple(float(a) for a in p)


# =========================================================================== figures
def fig_8_1_2(out=None):
    """Figure 8.1.2: ICBM stockpile 1960-1969 and an S-shaped (logistic) curve."""
    t = tables()["icbm"]
    x, y = np.array(t["years_after_1959"], float), np.array(t["n_icbm"], float)
    K, x0, s = fit_logistic(x, y)
    xx = np.linspace(0.5, 10.5, 300)
    fig, ax = plt.subplots(figsize=(5.2, 3.3))
    ax.plot(xx, logistic(xx, K, x0, s), "--", color=GREY, label="logistic fit: K = %.0f, midpoint %.2f, scale %.2f" % (K, x0, s))
    ax.plot(x, y, "o", color=BLUE)
    ax.set_xlabel("Years after 1959, x")
    ax.set_ylabel("No. of ICBMs, y")
    ax.set_xlim(0, 11)
    ax.legend(loc="upper left", frameon=False)
    return savefig(fig, CH, "fig8-1-2", out)


def bvn_pdf(x, y, rho):
    """Standard bivariate normal density with correlation rho."""
    q = (x ** 2 - 2 * rho * x * y + y ** 2) / (1 - rho ** 2)
    return np.exp(-q / 2) / (2 * np.pi * math.sqrt(1 - rho ** 2))


def fig_8_2_2(out=None):
    """Figure 8.2.2: a bivariate normal density (surface and contours)."""
    g = np.linspace(-3, 3, 61)
    X, Y = np.meshgrid(g, g)
    Z = bvn_pdf(X, Y, 0.6)
    fig = plt.figure(figsize=(6.4, 3.4))
    ax = fig.add_subplot(1, 2, 1, projection="3d")
    ax.plot_wireframe(X, Y, Z, rstride=3, cstride=3, color=BLUE, linewidth=0.5)
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.set_zlabel("density")
    ax.view_init(elev=30, azim=-60)
    ax2 = fig.add_subplot(1, 2, 2)
    ax2.contour(X, Y, Z, levels=8, colors=BLUE, linewidths=0.8)
    ax2.set_aspect("equal")
    ax2.set_xlabel("x")
    ax2.set_ylabel("y")
    ax2.set_title("contours, correlation 0.6")
    return savefig(fig, CH, "fig8-2-2", out)


def fig_8_2_3(out=None):
    """Figure 8.2.3: Hubble's distance and velocity data with the line v = H d."""
    t = tables()["hubble"]
    d, v = np.array(t["d"], float), np.array(t["v"], float)
    H = hubble_H(d, v)
    fig, ax = plt.subplots(figsize=(5.0, 3.4))
    ax.plot(d, v, "o", color=BLUE)
    dd = np.linspace(0, 1150, 50)
    ax.plot(dd, H * dd, "-", color=RED, label="v = %.5f d" % H)
    ax.set_xlabel("Distance (millions of light-years), d")
    ax.set_ylabel("Velocity (thousand miles/sec), v")
    ax.legend(loc="upper left", frameon=False)
    return savefig(fig, CH, "fig8-2-3", out)


def fig_x8_1(out=None):
    """Own figure x8.1: profiles of the blocks of Tables 8.1.2 and 8.2.5 across the factor levels."""
    t = tables()
    fig, axes = plt.subplots(1, 2, figsize=(7.4, 3.2))
    for ax, Y, labs, title, yl in (
            (axes[0], np.array(t["bait"]["surveys"]), t["bait"]["flavours"], "Bait acceptance (Table 8.1.2)", "% of baits taken"),
            (axes[1], np.array(t["blood_doping"]["times"]), t["blood_doping"]["levels"], "Blood doping (Table 8.2.5)", "10 000 m time (min)")):
        cols = plt.cm.viridis(np.linspace(0.05, 0.9, Y.shape[0]))
        for i, row in enumerate(Y):
            ax.plot(range(Y.shape[1]), row, "o-", color=cols[i], lw=1.2, ms=3.5, label="block %d" % (i + 1))
        ax.plot(range(Y.shape[1]), Y.mean(0), "k-", lw=2.4, alpha=0.7, label="level means")
        ax.set_xticks(range(Y.shape[1]))
        ax.set_xticklabels(labs, rotation=15, fontsize=8)
        ax.set_title(title)
        ax.set_ylabel(yl)
        ax.legend(fontsize=6.5, frameon=False, ncol=2)
    fig.tight_layout()
    return savefig(fig, CH, "figx8-1", out)


def fig_x8_2(out=None):
    """Own figure x8.2: power of the paired and of the two-sample t test against sigma_P^2 / sigma^2 (n = 12)."""
    n, dl = 12, 1.0
    r = np.linspace(0, 3, 121)
    pu = np.array([power_unpaired(n, dl, x) for x in r])
    pp = power_paired(n, dl)
    be = power_crossing(n, dl)
    fig, ax = plt.subplots(figsize=(5.2, 3.3))
    ax.plot(r, pu, color=ORANGE, label="two-sample t test (pairing ignored)")
    ax.axhline(pp, color=BLUE, label="paired t test (does not depend on the pair effect)")
    ax.axvline(be, color=GREY, ls=":", lw=1)
    ax.text(be + 0.05, 0.12, "equal power at %.3f" % be, fontsize=8, color=GREY)
    ax.set_xlabel(r"shared pair effect relative to noise, $\sigma_P^2/\sigma^2$")
    ax.set_ylabel("power")
    ax.set_title(r"n = 12 pairs, true difference $= \sigma$, level 0.05", fontsize=9)
    ax.set_ylim(0, 1)
    ax.legend(loc="center right", frameon=False, fontsize=8)
    return savefig(fig, CH, "figx8-2", out)


FIGURES = {"8.1.2": fig_8_1_2, "8.2.2": fig_8_2_2, "8.2.3": fig_8_2_3, "x8.1": fig_x8_1, "x8.2": fig_x8_2}

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