"""Larsen and Marx (2018), Chapter 13: Randomized Block Designs.

Companion code for Chapter 13 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 (../ch13-randomized-block-designs.html):

* Section 13.2, the F test for a randomized block design: rbd_anova (the three sums of squares of Theorem 13.2.1
  and the two F ratios of Theorems 13.2.3 and 13.2.4, from the definitions and from the computing formulas
  13.2.2 to 13.2.4), rbd_fit (the fitted values and residuals of Table 13.2.5 and the least-squares estimates of
  Question 13.2.12), oneway_error_ignoring_blocks (what the one-way analysis would use as "error"), tukey_rbd
  (Theorem 13.2.5), contrast_rbd (the single-degree-of-freedom F of Section 13.2), power_rbd and power_oneway
  (power of the two designs through the non-central F law) and the case studies.
* Section 13.3, the paired t test: paired_t (Theorem 13.3.1 and the confidence interval of Question 13.3.6),
  sign_flip_pvalue (the exact randomization test of a paired experiment), block_F_two_levels (for k = 2 the block F
  ratio is the ratio of the variance of the pair sums to that of the pair differences).
* Section 13.4, paired or two-sample: power_paired, power_two_sample, breakeven_rho (how large the within-pair
  correlation must be for pairing to win) and crit_ratio_rho (the critical-value ratio that the book's Table 13.4.4
  illustrates).
* Browser demonstration: demo_reference() exports the exact numbers shown by block-design-demo.html
  (../data/ch13-demos.json).

Figures. Chapter 13 of the book has one figure that is a drawing (13.1.1, two layouts of a corn field: schematic,
not redrawn) and one that is a printed ANOVA table (13.2.1, an ordinary table, reproduced as text in the notes),
so no book figure is computed. Three figures of our own illustrate the chapter: x13.1, the acrophobia data of
Case Study 13.2.2 as one line per block (the lines are nearly parallel, which is what makes blocking pay); x13.2, the
power of the randomized block F test and of the one-way F test as the block variance grows; x13.3, the power of the
paired t test against the within-pair correlation, with the two-sample t test as the horizontal comparison.
Run `python3 ch13_randomized_block_designs.py --list`, `python3 ch13_randomized_block_designs.py` (all figures,
a few seconds) or `python3 ch13_randomized_block_designs.py --fig x13.2`. Files go to ../img/ch13/.
"""
import json
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 = 13
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))
T = book_data("ch13-tables")


# =========================================================================== Section 13.2
def rbd_anova(Y):
    """Randomized block ANOVA of a b x k table (rows = blocks, columns = treatments).

    Returns a dict with the sums of squares, degrees of freedom, mean squares, F ratios and P-values of
    Table 13.2.2. The sums of squares are computed from their definitions (equation 13.2.1).
    """
    Y = np.asarray(Y, float)
    b, k = Y.shape
    g = Y.mean()
    sstr = b * ((Y.mean(0) - g) ** 2).sum()
    ssb = k * ((Y.mean(1) - g) ** 2).sum()
    resid = Y - Y.mean(1, keepdims=True) - Y.mean(0, keepdims=True) + g
    sse = (resid ** 2).sum()
    sstot = ((Y - g) ** 2).sum()
    dfe = (b - 1) * (k - 1)
    mse = sse / dfe
    Ft, Fb = sstr / (k - 1) / mse, ssb / (b - 1) / mse
    return dict(b=b, k=k, sstr=sstr, ssb=ssb, sse=sse, sstot=sstot, df_tr=k - 1, df_b=b - 1, df_e=dfe,
                mstr=sstr / (k - 1), msb=ssb / (b - 1), mse=mse, F_tr=Ft, F_b=Fb,
                p_tr=stats.f.sf(Ft, k - 1, dfe), p_b=stats.f.sf(Fb, b - 1, dfe))


def rbd_computing_formulas(Y):
    """The computing formulas 13.2.2 to 13.2.4: C = T..^2/(bk), SSTR, SSB, SSTOT (and SSE by subtraction)."""
    Y = np.asarray(Y, float)
    b, k = Y.shape
    C = Y.sum() ** 2 / (b * k)
    sstr = (Y.sum(0) ** 2).sum() / b - C
    ssb = (Y.sum(1) ** 2).sum() / k - C
    sstot = (Y ** 2).sum() - C
    return dict(C=C, sstr=sstr, ssb=ssb, sstot=sstot, sse=sstot - sstr - ssb)


def rbd_fit(Y):
    """Least-squares fit of Y_ij = mu + beta_i + tau_j + e_ij with sum beta = sum tau = 0 (Question 13.2.12).

    Returns mu_hat, beta_hat, tau_hat, the fitted values (Table 13.2.5, second entry) and the residuals (third entry).
    """
    Y = np.asarray(Y, float)
    mu = Y.mean()
    beta = Y.mean(1) - mu
    tau = Y.mean(0) - mu
    fitted = mu + beta[:, None] + tau[None, :]
    return mu, beta, tau, fitted, Y - fitted


def oneway_error_ignoring_blocks(Y):
    """What a one-way analysis of the same table would call error: SSB + SSE on k(b-1) degrees of freedom.

    Returns (SS, df, MS, F, P) for the one-way F ratio that ignores the blocks (equation 13.2.1).
    """
    a = rbd_anova(Y)
    b, k = a["b"], a["k"]
    ss, df = a["ssb"] + a["sse"], k * (b - 1)
    F = a["mstr"] / (ss / df)
    return ss, df, ss / df, F, stats.f.sf(F, k - 1, df)


def tukey_rbd(Y, alpha=0.05):
    """Theorem 13.2.5: Tukey intervals for all pairwise differences of treatment means.

    Returns (Q, D, radius, list of (s, t, difference, lower, upper)), s < t as column indices.
    """
    a = rbd_anova(Y)
    b, k, dfe = a["b"], a["k"], a["df_e"]
    Q = stats.studentized_range.isf(alpha, k, dfe)
    D = Q / math.sqrt(b)
    rad = D * math.sqrt(a["mse"])
    m = np.asarray(Y, float).mean(0)
    out = [(s, t, m[s] - m[t], m[s] - m[t] - rad, m[s] - m[t] + rad) for s in range(k) for t in range(s + 1, k)]
    return Q, D, rad, out


def contrast_rbd(Y, c):
    """F test of H0: sum c_j mu_j = 0 in a randomized block design: (C_hat, SSC, F, P) with 1 and (b-1)(k-1) df."""
    Y = np.asarray(Y, float)
    c = np.asarray(c, float)
    a = rbd_anova(Y)
    chat = float(c @ Y.mean(0))
    ssc = chat ** 2 / ((c ** 2).sum() / a["b"])
    F = ssc / a["mse"]
    return chat, ssc, F, stats.f.sf(F, 1, a["df_e"])


def power_rbd(k, b, ss_tau, sigma2=1.0, alpha=0.05):
    """Power of the randomized block F test when sum_j (mu_j - mubar)^2 = ss_tau and the error variance is sigma2.

    The non-centrality is lambda = b * ss_tau / sigma2 (gap 13.4); the degrees of freedom are k-1 and (b-1)(k-1).
    """
    d1, d2 = k - 1, (b - 1) * (k - 1)
    return float(stats.ncf.sf(stats.f.isf(alpha, d1, d2), d1, d2, b * ss_tau / sigma2))


def power_oneway(k, b, ss_tau, sigma2=1.0, sigma_b2=0.0, alpha=0.05):
    """Power of the one-way F test with b units per treatment, drawn from blocks whose effects have variance sigma_b2.

    The error variance is sigma2 + sigma_b2 and the degrees of freedom are k-1 and k(b-1) (gap 13.6).
    """
    d1, d2 = k - 1, k * (b - 1)
    return float(stats.ncf.sf(stats.f.isf(alpha, d1, d2), d1, d2, b * ss_tau / (sigma2 + sigma_b2)))


def breakeven_block_ratio(k, b, ss_tau, sigma2=1.0, alpha=0.05):
    """The value of sigma_b2/sigma2 above which the block design has the higher power (gap 13.6)."""
    f = lambda r: power_rbd(k, b, ss_tau, sigma2, alpha) - power_oneway(k, b, ss_tau, sigma2, r * sigma2, alpha)
    return optimize.brentq(f, 0.0, 50.0)


# =========================================================================== Section 13.3
def paired_t(x, y, alpha=0.05):
    """Theorem 13.3.1 and the interval of Question 13.3.6 for d_i = x_i - y_i: (dbar, s_D, t, df, P two-sided, lo, hi)."""
    d = np.asarray(x, float) - np.asarray(y, float)
    b = len(d)
    dbar, sd = d.mean(), d.std(ddof=1)
    t = dbar / (sd / math.sqrt(b))
    q = stats.t.isf(alpha / 2, b - 1)
    return dbar, sd, t, b - 1, 2 * stats.t.sf(abs(t), b - 1), dbar - q * sd / math.sqrt(b), dbar + q * sd / math.sqrt(b)


def paired_t_summary(b, dbar, sd, alpha=0.05):
    """The same from summary statistics: (t, df, two-sided P, lo, hi)."""
    t = dbar / (sd / math.sqrt(b))
    q = stats.t.isf(alpha / 2, b - 1)
    return t, b - 1, 2 * stats.t.sf(abs(t), b - 1), dbar - q * sd / math.sqrt(b), dbar + q * sd / math.sqrt(b)


def sign_flip_pvalue(d):
    """Exact two-sided randomization P-value of a paired experiment: every sign pattern of the differences is equally
    likely when the treatments are assigned at random within each pair and have no effect (gap 13.12).
    The statistic is |sum d|, which is equivalent to |t| because sum d^2 does not change when signs are flipped."""
    d = np.asarray(d, float)
    b = len(d)
    bits = ((np.arange(2 ** b)[:, None] >> np.arange(b)) & 1) * 2 - 1
    s = np.abs(bits @ d)
    return float(np.mean(s >= abs(d.sum()) - 1e-9))


def block_F_two_levels(x, y):
    """For k = 2 the block F ratio equals s_S^2 / s_D^2 (variance of the pair sums over variance of the differences),
    on (b-1, b-1) degrees of freedom (gap 13.10). Returns (F, df, P)."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    F = (x + y).var(ddof=1) / (x - y).var(ddof=1)
    b = len(x)
    return F, b - 1, stats.f.sf(F, b - 1, b - 1)


# =========================================================================== Section 13.4
def power_paired(b, delta_over_sigma, rho, alpha=0.05):
    """Two-sided power of the paired t test when each observation has standard deviation sigma and the two
    observations of a pair have correlation rho: the non-centrality is (delta/sigma) sqrt(b / (2 (1 - rho)))."""
    nu = b - 1
    nc = delta_over_sigma * math.sqrt(b / (2 * (1 - rho)))
    c = stats.t.isf(alpha / 2, nu)
    return float(stats.nct.sf(c, nu, nc) + stats.nct.cdf(-c, nu, nc))


def power_two_sample(b, delta_over_sigma, alpha=0.05):
    """Two-sided power of the pooled two-sample t test with b subjects per group (2b - 2 df), same sigma."""
    nu = 2 * b - 2
    nc = delta_over_sigma * math.sqrt(b / 2)
    c = stats.t.isf(alpha / 2, nu)
    return float(stats.nct.sf(c, nu, nc) + stats.nct.cdf(-c, nu, nc))


def crit_ratio_rho(b, alpha=0.05):
    """1 - (t_{2b-2}/t_{b-1})^2: the within-pair correlation above which the paired interval is shorter, in expectation,
    than the two-sample interval (the book's Table 13.4.4 gives the two critical values for b = 5)."""
    return 1 - (stats.t.isf(alpha / 2, 2 * b - 2) / stats.t.isf(alpha / 2, b - 1)) ** 2


def breakeven_rho(b, delta_over_sigma, alpha=0.05):
    """The correlation at which the paired t test and the two-sample t test have the same power."""
    f = lambda r: power_paired(b, delta_over_sigma, r, alpha) - power_two_sample(b, delta_over_sigma, alpha)
    return optimize.brentq(f, -0.9, 0.99)


# =========================================================================== case studies
def case_study_numbers():
    """The numbers of the case studies, from the printed data."""
    out = {}
    out["wine"] = rbd_anova(T["cs1321_wine"]["y"])
    out["acro"] = rbd_anova(T["cs1322_acro"]["y"])
    out["moon"] = rbd_anova(T["cs1323_moon"]["y"])
    h = T["cs1331_hemoglobin"]
    out["hemo"] = paired_t(h["before"], h["after"])
    s = T["cs1332_stings"]
    out["stings"] = paired_t(s["stung"], s["fresh"])
    return out


# =========================================================================== figures
def fig_x13_1(out_dir=None):
    """Own figure x13.1: the acrophobia data (Case Study 13.2.2) as one line per block."""
    d = T["cs1322_acro"]
    Y = np.array(d["y"], float)
    fig, ax = plt.subplots(figsize=(5.4, 3.6))
    cols = [RED, ORANGE, GREEN, BLUE, PURPLE]
    for i, row in enumerate(Y):
        ax.plot(range(3), row, "o-", color=cols[i], lw=1.3, ms=4, label="Block " + "ABCDE"[i])
    ax.plot(range(3), Y.mean(0), "s--", color="black", lw=2.0, ms=6, label="Mean of the blocks")
    ax.set_xticks(range(3))
    ax.set_xticklabels(["Contact\ndesensitization", "Demonstration\nparticipation", "Live\nmodeling"])
    ax.set_ylabel("Change in HAT score")
    ax.legend(ncol=2, frameon=False, fontsize=8)
    ax.set_xlim(-0.25, 2.25)
    return savefig(fig, CH, "figx13-1", out_dir)


def fig_x13_2(out_dir=None):
    """Own figure x13.2: power of the block F test and the one-way F test against the block variance."""
    k, b = 3, 5
    ss = 0.8                    # sum of squared treatment deviations, error variance 1 (lambda = 4)
    r = np.linspace(0, 4, 201)
    fig, ax = plt.subplots(figsize=(5.4, 3.4))
    ax.plot(r, [power_rbd(k, b, ss)] * len(r), color=BLUE, label="Randomized block F (2 and 8 df)")
    ax.plot(r, [power_oneway(k, b, ss, 1.0, x) for x in r], color=RED, label="One-way F (2 and 12 df)")
    r0 = breakeven_block_ratio(k, b, ss)
    ax.axvline(r0, color=GREY, ls=":")
    ax.annotate("break-even %.2f" % r0, (r0, 0.12), xytext=(r0 + 0.1, 0.12), fontsize=8, color=GREY)
    ax.set_xlabel(r"block variance over error variance, $\sigma_B^2/\sigma^2$")
    ax.set_ylabel("power at level 0.05")
    ax.legend(frameon=False, fontsize=8, loc="center right")
    ax.set_ylim(0, 0.45)
    return savefig(fig, CH, "figx13-2", out_dir)


def fig_x13_3(out_dir=None):
    """Own figure x13.3: power of the paired t test against the within-pair correlation."""
    rho = np.linspace(-0.3, 0.95, 200)
    fig, ax = plt.subplots(figsize=(5.4, 3.4))
    for b, delta, col in [(5, 2.0, BLUE), (10, 1.2, GREEN)]:
        ax.plot(rho, [power_paired(b, delta, x) for x in rho], color=col, label="paired t, %d pairs (delta/sigma = %.1f)" % (b, delta))
        ax.axhline(power_two_sample(b, delta), color=col, ls="--", lw=1.2,
                   label="two-sample t, %d + %d subjects" % (b, b))
        be = breakeven_rho(b, delta)
        ax.plot([be], [power_two_sample(b, delta)], "o", color=col, ms=4)
    ax.set_xlabel(r"within-pair correlation $\rho$")
    ax.set_ylabel("power at level 0.05")
    ax.legend(frameon=False, fontsize=7.5, loc="lower right")
    ax.set_ylim(0, 1.02)
    return savefig(fig, CH, "figx13-3", out_dir)


FIGURES = {"x13.1": fig_x13_1, "x13.2": fig_x13_2, "x13.3": fig_x13_3}


# =========================================================================== browser demonstration
def demo_reference():
    """Write ../data/ch13-demos.json: the exact powers that block-design-demo.html compares with its simulation."""
    pre = []
    for k, b, lam, rb in [(3, 5, 4.0, 0.0), (3, 5, 4.0, 1.0), (3, 5, 4.0, 4.0), (4, 6, 6.0, 2.0), (3, 10, 6.0, 0.3)]:
        ss = lam / b
        pre.append(dict(k=k, b=b, lam=lam, rb=rb, rbd=power_rbd(k, b, ss), oneway=power_oneway(k, b, ss, 1.0, rb),
                        crit_rbd=float(stats.f.isf(0.05, k - 1, (b - 1) * (k - 1))), crit_oneway=float(stats.f.isf(0.05, k - 1, k * (b - 1)))))
    os.makedirs(DATA_OUT, exist_ok=True)
    path = os.path.join(DATA_OUT, "ch13-demos.json")
    with open(path, "w", encoding="utf-8") as f:
        json.dump({"source": "Own computations for Chapter 13 (gap 13.6).", "presets": pre}, f, indent=1)
    return path


if __name__ == "__main__":
    common.run(FIGURES, CH)
    print("wrote", os.path.relpath(demo_reference(), os.getcwd()))
