"""Larsen and Marx (2018), Chapter 14: Nonparametric Statistics.

Companion code for Chapter 14 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 (../ch14-nonparametric-statistics.html):

* Section 14.2, the sign test: sign_test (the count k, the Z ratio of Theorem 14.2.1 and the exact binomial
  P-value), randomized_crit (the critical value and randomisation probability that give an exact level alpha).
* Section 14.3, Wilcoxon tests: signed_rank (w with midranks), signed_rank_counts (the coefficients c(w) of the
  generating function prod (1 + e^{it}) of Theorem 14.3.1), signed_rank_pmf, signed_rank_conditional (the exact
  null law given the (mid)ranks, for data with ties), rank_sum and rank_sum_counts (the rank-sum statistic and the
  Gaussian-binomial generating function of its null law), rank_sum_conditional (the same with ties), tie-corrected
  variances, mann_whitney (the pair count U = W' - n(n + 1)/2).
* Section 14.4, the Kruskal-Wallis test: kruskal_wallis (b, with and without the tie correction).
* Section 14.5, the Friedman test: friedman (g from within-block midranks).
* Section 14.6, runs up and down: runs_up_down (w), runs_exact (the exact null law of W by a recursion over
  relative ranks), runs_mean_var (Theorem 14.6.1).
* Section 14.7, parametric against nonparametric: efficacies and asymptotic relative efficiencies (2/pi and 3/pi at
  the normal), sim_power (power of the t, sign and signed-rank tests by simulation), sim_kw_f (the Monte Carlo
  experiment of Figures 14.7.1 to 14.7.6).
* Browser demonstrations: demo_reference() exports the numbers that rank-null-demo.html and
  rank-test-power-demo.html show (../data/ch14-demos.json).

Figures. Reproduced: 14.2.1 (the binomial pdf for n = 8 with the two-sided critical region of Case Study 14.2.2),
14.4.1 (average draft-lottery selection number by month, from the rank totals of Table 14.4.2) and 14.7.1 to 14.7.6
(the Monte Carlo comparison of the F test and the Kruskal-Wallis test, here with 10,000 replications instead of the
book's 100, so the histograms are smooth and the rejection rates are accurate). Skipped, with reasons: the chapter
opener (power curves of the t and sign tests for populations described only by two cumulants from an outside
study; the populations are not specified well enough to recompute, and own figure x14.2 shows the same comparison
for named populations), 14.5.1 (a drawing of two base paths) and 14.6.1 (a schematic of the sign sequence).
Three figures of our own: x14.1, exact null distributions of the signed-rank and rank-sum statistics from their
generating functions, against the normal approximation; x14.2, power curves of the t, sign and signed-rank tests
for normal, Laplace and uniform data, with the local power predicted by the asymptotic relative efficiencies;
x14.3, the exact null distribution of the number of runs up and down for n = 25 (Case Study 14.6.1) against the
normal approximation of Theorem 14.6.1.
Run `python3 ch14_nonparametric_statistics.py --list`, `python3 ch14_nonparametric_statistics.py` (all figures,
about half a minute the first time; simulations are cached in cache/) or
`python3 ch14_nonparametric_statistics.py --fig 14.4.1`. Files go to ../img/ch14/.
"""
import json
import math
import os

import numpy as np
from scipy import integrate, stats

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

CH = 14
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))
CACHE = os.path.join(HERE, "cache")
TABLES = book_data("ch14-tables")


def midranks(a):
    """Ranks 1..n with tied values given the average of the ranks they share (the book's convention)."""
    return stats.rankdata(np.asarray(a, dtype=float), method="average")


def tie_sizes(a):
    """Sizes t of the groups of tied values (groups of size 1 included)."""
    _, c = np.unique(np.round(np.asarray(a, dtype=float), 10), return_counts=True)
    return c


# =========================================================================== Section 14.2
def sign_test(y, m0):
    """Theorem 14.2.1. Returns n (values equal to m0 dropped), k = #(y > m0), the Z ratio and exact P-values."""
    y = np.asarray(y, dtype=float)
    y = y[y != m0]
    n, k = len(y), int(np.sum(y > m0))
    z = (k - n / 2) / math.sqrt(n / 4)
    lower, upper = stats.binom.cdf(k, n, 0.5), stats.binom.sf(k - 1, n, 0.5)
    return dict(n=n, k=k, z=z, p_lower=lower, p_upper=upper, p_two=min(1.0, 2 * min(lower, upper)))


def randomized_crit(pmf, alpha):
    """For a statistic with null pmf on 0, 1, ..., return (c, gamma) such that the test 'reject if T > c, and with
    probability gamma if T = c' has size exactly alpha (one-sided, upper tail)."""
    pmf = np.asarray(pmf, dtype=float)
    tail = np.cumsum(pmf[::-1])[::-1]               # tail[t] = P(T >= t)
    c = int(np.argmax(tail <= alpha + 1e-15)) - 1   # smallest c with P(T > c) <= alpha
    above = tail[c + 1] if c + 1 < len(tail) else 0.0
    gamma = (alpha - above) / pmf[c]
    return c, gamma


# =========================================================================== Section 14.3
def signed_rank(y, m0=0.0):
    """Wilcoxon signed-rank statistic w = sum of the (mid)ranks of |y - m0| over the positive deviations.
    Zero deviations are dropped (as in Question 14.3.4). Returns w, the ranks and the signs."""
    d = np.asarray(y, dtype=float) - m0
    d = d[np.abs(d) > 1e-12]
    r = midranks(np.abs(d))
    return float(np.sum(r[d > 0])), r, (d > 0).astype(int)


def signed_rank_counts(n):
    """Theorem 14.3.1: c(w), w = 0..n(n+1)/2, the coefficients of prod_{i=1}^n (1 + x^i) (x = e^t)."""
    c = np.zeros(n * (n + 1) // 2 + 1, dtype=np.int64)
    c[0] = 1
    top = 0
    for i in range(1, n + 1):
        c[i:top + i + 1] += c[0:top + 1].copy()       # multiply by (1 + x^i)
        top += i
    return c


def signed_rank_pmf(n):
    return signed_rank_counts(n) / 2.0 ** n


def signed_rank_critical(n, alpha_tail):
    """Largest w* with P(W <= w*) <= alpha_tail (the lower critical value of Table A.6); by symmetry the upper one
    is n(n+1)/2 - w*. Returns (w*, P(W <= w*))."""
    cdf = np.cumsum(signed_rank_pmf(n))
    ok = np.nonzero(cdf <= alpha_tail + 1e-12)[0]
    if len(ok) == 0:
        return None, 0.0
    return int(ok[-1]), float(cdf[ok[-1]])


def signed_rank_conditional(r):
    """Exact null law of W = sum r_i Z_i, Z_i iid Bernoulli(1/2), for given (mid)ranks r (ties allowed).
    Returns (values, probabilities)."""
    r2 = np.rint(2 * np.asarray(r)).astype(int)            # midranks are multiples of 1/2
    tot = int(r2.sum())
    p = np.zeros(tot + 1)
    p[0] = 1.0
    for v in r2:
        q = 0.5 * p.copy()
        q[v:] += 0.5 * p[:tot + 1 - v]
        p = q
    vals = np.arange(tot + 1) / 2.0
    keep = p > 0
    return vals[keep], p[keep]


def signed_rank_mean_var(n):
    """Theorem 14.3.2."""
    return n * (n + 1) / 4, n * (n + 1) * (2 * n + 1) / 24


def signed_rank_var_ties(r):
    """Null variance of W given the (mid)ranks: sum r_i^2 / 4 (equals n(n+1)(2n+1)/24 without ties)."""
    r = np.asarray(r, dtype=float)
    return float(np.sum(r ** 2) / 4)


def rank_sum(x, y):
    """Wilcoxon rank-sum statistic w' = sum of the ranks of the x's in the pooled sample (midranks for ties)."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    r = midranks(np.concatenate([x, y]))
    return float(r[:len(x)].sum()), r


def rank_sum_counts(N, n):
    """Number of n-subsets of {1, ..., N} with sum s, for s = 0..max; the coefficients of the Gaussian binomial
    generating function. Recursion: c(N, n, s) = c(N - 1, n, s) + c(N - 1, n - 1, s - N)."""
    smax = n * (2 * N - n + 1) // 2
    c = np.zeros((n + 1, smax + 1), dtype=float)
    c[0, 0] = 1.0
    for v in range(1, N + 1):
        for j in range(min(n, v), 0, -1):              # in place, j decreasing: each value used at most once
            c[j, v:] += c[j - 1, :smax + 1 - v]
    return c[n]


def rank_sum_pmf(N, n):
    cnt = rank_sum_counts(N, n)
    return cnt / math.comb(N, n)


def rank_sum_conditional(ranks, n):
    """Exact null law of the sum of n ranks drawn without replacement from the given (mid)ranks."""
    r2 = np.rint(2 * np.asarray(ranks)).astype(int)
    smax = int(np.sort(r2)[::-1][:n].sum())
    c = np.zeros((n + 1, smax + 1))
    c[0, 0] = 1.0
    for v in r2:
        for j in range(n, 0, -1):
            if v <= smax:
                c[j, v:] += c[j - 1, :smax + 1 - v]
    p = c[n] / math.comb(len(r2), n)
    vals = np.arange(smax + 1) / 2.0
    keep = p > 0
    return vals[keep], p[keep]


def rank_sum_mean_var(n, m):
    """Theorem 14.3.4."""
    N = n + m
    return n * (N + 1) / 2, n * m * (N + 1) / 12


def rank_sum_var_ties(pooled, n, m):
    """Null variance of W' with midranks: nm/12 [N + 1 - sum(t^3 - t) / (N(N - 1))]."""
    N = n + m
    t = tie_sizes(pooled).astype(float)
    return n * m / 12 * (N + 1 - np.sum(t ** 3 - t) / (N * (N - 1)))


def mann_whitney(x, y):
    """U = #{(i, j): x_i > y_j} + 0.5 #{x_i = y_j}; equals W' - n(n + 1)/2."""
    x, y = np.asarray(x, float)[:, None], np.asarray(y, float)[None, :]
    return float(np.sum(x > y) + 0.5 * np.sum(x == y))


# =========================================================================== Section 14.4
def kruskal_wallis(groups, ties=False):
    """Theorem 14.4.1: b = 12/(n(n + 1)) sum R_j^2 / n_j - 3(n + 1); with ties=True divided by
    1 - sum(t^3 - t)/(n^3 - n). Returns b, the rank sums, df, the chi-square P-value."""
    sizes = [len(g) for g in groups]
    pooled = np.concatenate([np.asarray(g, float) for g in groups])
    r = midranks(pooled)
    n = len(pooled)
    Rj = np.array([s.sum() for s in np.split(r, np.cumsum(sizes)[:-1])])
    b = 12 / (n * (n + 1)) * np.sum(Rj ** 2 / np.array(sizes)) - 3 * (n + 1)
    if ties:
        t = tie_sizes(pooled).astype(float)
        b /= 1 - np.sum(t ** 3 - t) / (n ** 3 - n)
    k = len(groups)
    return dict(b=float(b), R=Rj, df=k - 1, p=float(stats.chi2.sf(b, k - 1)))


def kw_from_totals(R, sizes):
    R, sizes = np.asarray(R, float), np.asarray(sizes, float)
    n = sizes.sum()
    return float(12 / (n * (n + 1)) * np.sum(R ** 2 / sizes) - 3 * (n + 1))


# =========================================================================== Section 14.5
def friedman(Y, ties=False):
    """Theorem 14.5.1: Y is b x k (blocks in rows); ranks within each row (midranks for ties).
    g = 12/(b k (k + 1)) sum r_j^2 - 3 b (k + 1); with ties=True divided by 1 - sum(t^3 - t)/(b (k^3 - k))."""
    Y = np.asarray(Y, dtype=float)
    b, k = Y.shape
    r = np.vstack([midranks(row) for row in Y])
    rj = r.sum(axis=0)
    g = 12 / (b * k * (k + 1)) * np.sum(rj ** 2) - 3 * b * (k + 1)
    if ties:
        t = np.concatenate([tie_sizes(row) for row in Y]).astype(float)
        g /= 1 - np.sum(t ** 3 - t) / (b * (k ** 3 - k))
    return dict(g=float(g), r=rj, df=k - 1, p=float(stats.chi2.sf(g, k - 1)))


# =========================================================================== Section 14.6
def runs_up_down(y):
    """Number of runs up and down: 1 + number of sign changes in sgn(y_i - y_{i-1}) (no ties assumed)."""
    s = np.sign(np.diff(np.asarray(y, float)))
    s = s[s != 0]
    return int(1 + np.sum(s[1:] != s[:-1]))


def runs_mean_var(n):
    """Theorem 14.6.1."""
    return (2 * n - 1) / 3, (16 * n - 29) / 90


def runs_exact(n):
    """Exact null law of W (number of runs up and down) for n iid continuous observations, n >= 2.
    State after i observations: relative rank j of the last one (1..i), direction of the last step, number of runs.
    A new observation with relative rank j' in 1..i+1 is a step up exactly when j' > j. Returns P(W = w), w = 0..n-1."""
    R = n                                           # runs index 0..n-1
    # f[d, j, w]: d = 0 last step down, 1 up; j = 0..i-1 (relative rank - 1)
    f = np.zeros((2, n, R))
    f[1, 1, 1] = 0.5                                # (y1 < y2): last has rank 2, one run (up)
    f[0, 0, 1] = 0.5                                # (y1 > y2): last has rank 1, one run (down)
    for i in range(2, n):                           # add observation i + 1
        g = np.zeros_like(f)
        for d in (0, 1):
            cs = np.cumsum(f[d, :i], axis=0)        # cs[j] = sum_{l <= j} f[d, l]
            tot = cs[-1]
            for jn in range(i + 1):                 # new relative rank jn (0-based) among i + 1
                up = cs[jn - 1] if jn >= 1 else np.zeros(R)     # previous last had relative rank l < jn
                down = tot - (cs[jn - 1] if jn >= 1 else 0)     # previous last had relative rank l >= jn
                if d == 1:      # last step was up: going up continues the run, down starts a new run
                    g[1, jn] += up
                    g[0, jn, 1:] += down[:-1]
                else:
                    g[0, jn] += down
                    g[1, jn, 1:] += up[:-1]
        f = g / (i + 1)
    return f.sum(axis=(0, 1))


# =========================================================================== Section 14.7
# Populations scaled to mean (median) 0 and variance 1 where the variance exists.
POPS = {
    "normal": dict(rv=stats.norm(), label="normal"),
    "uniform": dict(rv=stats.uniform(-math.sqrt(3), 2 * math.sqrt(3)), label="uniform"),
    "logistic": dict(rv=stats.logistic(scale=math.sqrt(3) / math.pi), label="logistic"),
    "laplace": dict(rv=stats.laplace(scale=1 / math.sqrt(2)), label="Laplace"),
    "t3": dict(rv=stats.t(3, scale=1 / math.sqrt(3)), label="t, 3 df"),
    "cauchy": dict(rv=stats.cauchy(), label="Cauchy"),
}


def int_f2(rv, lo=-np.inf, hi=np.inf):
    return integrate.quad(lambda x: rv.pdf(x) ** 2, lo, hi, limit=200)[0]


def are_table():
    """Asymptotic relative efficiencies for a symmetric population with density f and variance sigma^2:
    sign vs t: 4 f(0)^2 sigma^2; signed rank vs t: 12 sigma^2 (int f^2)^2; sign vs signed rank: f(0)^2 / (3 (int f^2)^2)."""
    out = {}
    for k, P in POPS.items():
        rv = P["rv"]
        lo, hi = (-math.sqrt(3), math.sqrt(3)) if k == "uniform" else (-np.inf, np.inf)
        f0, I2 = rv.pdf(0.0), int_f2(rv, lo, hi)
        var = rv.var() if k != "cauchy" else np.inf
        out[k] = dict(f0=f0, int_f2=I2, var=var,
                      sign_t=4 * f0 ** 2 * var if np.isfinite(var) else np.inf,
                      wilcoxon_t=12 * var * I2 ** 2 if np.isfinite(var) else np.inf,
                      sign_wilcoxon=f0 ** 2 / (3 * I2 ** 2))
    return out


def sim_power(pop, n, thetas, alpha=0.05, reps=20000, seed=14):
    """Power of the one-sided (H1: centre > 0) t test, randomized exact sign test and randomized exact signed-rank
    test of size alpha, for data theta + X, X from POPS[pop]. Returns dict of arrays over thetas."""
    rng = np.random.default_rng(seed)
    rv = POPS[pop]["rv"]
    tcrit = stats.t.ppf(1 - alpha, n - 1)
    cs, gs = randomized_crit(stats.binom.pmf(np.arange(n + 1), n, 0.5), alpha)
    pw = signed_rank_pmf(n)
    cw, gw = randomized_crit(pw, alpha)
    X = rv.rvs(size=(reps, n), random_state=rng)
    U1, U2 = rng.random(reps), rng.random(reps)
    res = {"t": [], "sign": [], "wilcoxon": []}
    ranks0 = None
    for th in thetas:
        D = X + th
        t = D.mean(1) / (D.std(1, ddof=1) / math.sqrt(n))
        res["t"].append(np.mean(t > tcrit))
        K = np.sum(D > 0, axis=1)
        res["sign"].append(np.mean((K > cs) | ((K == cs) & (U1 < gs))))
        A = np.abs(D)
        ranks0 = np.argsort(np.argsort(A, axis=1), axis=1) + 1
        W = np.sum(ranks0 * (D > 0), axis=1)
        res["wilcoxon"].append(np.mean((W > cw) | ((W == cw) & (U2 < gw))))
    return {k: np.array(v) for k, v in res.items()}


def local_power(eff, n, theta, alpha=0.05):
    """Asymptotic power 1 - Phi(z_alpha - sqrt(n) theta sqrt(efficacy)) at the local alternative theta."""
    return stats.norm.sf(stats.norm.isf(alpha) - math.sqrt(n) * np.asarray(theta) * math.sqrt(eff))


def efficacies(pop):
    """Efficacies (per observation) of the t, sign and signed-rank tests: 1/sigma^2, 4 f(0)^2, 12 (int f^2)^2."""
    a = are_table()[pop]
    return dict(t=1 / a["var"] if np.isfinite(a["var"]) else 0.0, sign=4 * a["f0"] ** 2, wilcoxon=12 * a["int_f2"] ** 2)


def kw_stat_batch(X):
    """Kruskal-Wallis b for each row of X (reps x k x nj), no ties (continuous data)."""
    reps, k, nj = X.shape
    n = k * nj
    flat = X.reshape(reps, n)
    r = np.argsort(np.argsort(flat, axis=1), axis=1) + 1.0
    Rj = r.reshape(reps, k, nj).sum(2)
    return 12 / (n * (n + 1)) * np.sum(Rj ** 2 / nj, axis=1) - 3 * (n + 1)


def f_stat_batch(X):
    reps, k, nj = X.shape
    m = X.mean(2)
    g = X.mean((1, 2))
    sstr = nj * np.sum((m - g[:, None]) ** 2, axis=1)
    sse = np.sum((X - m[:, :, None]) ** 2, axis=(1, 2))
    return (sstr / (k - 1)) / (sse / (k * nj - k))


def sim_kw_f(reps=10000, seed=147, k=4, nj=5):
    """The Monte Carlo experiment of Section 14.7 (Figures 14.7.1 to 14.7.6), cached."""
    path = os.path.join(CACHE, "ch14-kwf-%d.npz" % reps)
    if os.path.exists(path):
        d = np.load(path)
        return {key: d[key] for key in d.files}
    rng = np.random.default_rng(seed)
    out = {}
    Xn = rng.standard_normal((reps, k, nj))
    out["F_null_normal"], out["B_null_normal"] = f_stat_batch(Xn), kw_stat_batch(Xn)
    Xe = rng.exponential(1.0, (reps, k, nj))
    out["F_null_expo"], out["B_null_expo"] = f_stat_batch(Xe), kw_stat_batch(Xe)
    Xs = rng.standard_normal((reps, k, nj))
    Xs[:, 3, :] += 1.0
    out["F_shift"], out["B_shift"] = f_stat_batch(Xs), kw_stat_batch(Xs)
    os.makedirs(CACHE, exist_ok=True)
    np.savez_compressed(path, **out)
    return out


def kw_exact_null_mc(sizes, reps=200000, seed=144):
    """Permutation (exact) null distribution of B by Monte Carlo over random rank assignments."""
    rng = np.random.default_rng(seed)
    n = sum(sizes)
    P = np.argsort(rng.random((reps, n)), axis=1) + 1.0
    idx = np.cumsum(sizes)[:-1]
    R = np.stack([s.sum(1) for s in np.split(P, idx, axis=1)], axis=1)
    return 12 / (n * (n + 1)) * np.sum(R ** 2 / np.array(sizes), axis=1) - 3 * (n + 1)


# =========================================================================== figures
def fig_14_2_1(out_dir=None):
    """Figure 14.2.1: the binomial pdf, n = 8, p = 1/2, with the two-sided critical region of Case Study 14.2.2."""
    x = np.arange(9)
    p = stats.binom.pmf(x, 8, 0.5)
    crit = (x <= 1) | (x >= 7)
    fig, ax = plt.subplots(figsize=(6.0, 3.2))
    ax.bar(x[~crit], p[~crit], width=0.55, color=BLUE, alpha=0.8, label="$P(X=x)$")
    ax.bar(x[crit], p[crit], width=0.55, color=RED, alpha=0.9, label="critical region for $k=7$")
    for xi, pi in zip(x, p):
        ax.text(xi, pi + 0.006, "%.6f" % (pi + 1e-12), ha="center", va="bottom", fontsize=7.5, rotation=0)
    ax.set_xlabel("$x$ (number of brands above 3.55)")
    ax.set_ylabel("$P(X=x)$")
    ax.set_xticks(x)
    ax.set_ylim(0, 0.32)
    ax.set_title("Binomial pdf, $n=8$, $p=1/2$: P-value $=P(X\\geq7)+P(X\\leq1)=0.0703$")
    ax.legend(loc="upper right", frameon=False)
    savefig(fig, CH, "fig14-2-1", out_dir)


def fig_14_4_1(out_dir=None):
    """Figure 14.4.1: average draft-lottery selection number by month (1969), from the rank totals of Table 14.4.2."""
    L = TABLES["lottery_cs_14_4_1"]
    avg = np.array(L["rank_totals"]) / np.array(L["days"])
    fig, ax = plt.subplots(figsize=(6.2, 3.3))
    ax.plot(range(12), avg, "o-", color=RED, ms=5)
    ax.axhline(183.5, color=GREY, ls="--", lw=1)
    ax.text(11.2, 186, "183.5 = (1 + 2 + ... + 366)/366", ha="right", va="bottom", fontsize=8.5, color=GREY)
    ax.set_xticks(range(12))
    ax.set_xticklabels([m[0] for m in L["months"]])
    ax.set_ylim(100, 240)
    ax.set_ylabel("Average selection number")
    ax.set_xlabel("Birth month")
    ax.set_title("1969 draft lottery: later months were drawn earlier")
    savefig(fig, CH, "fig14-4-1", out_dir)


def _hist(ax, v, pdf, xmax, label, cut=None, color=BLUE, bins=40):
    v = np.asarray(v)
    ax.hist(v[v <= xmax], bins=np.linspace(0, xmax, bins + 1), density=True, color=color, alpha=0.45,
            edgecolor="white", lw=0.4, weights=None)
    xx = np.linspace(1e-3, xmax, 400)
    ax.plot(xx, pdf(xx), color="k", lw=1.5, label=label)
    ax.set_xlim(0, xmax)
    ax.set_ylabel("Density")
    if cut:
        for c, lab in cut:
            ax.axvline(c, color=RED, ls="--", lw=1.1)
            ax.text(c, ax.get_ylim()[1] * 0.92, " " + lab, color=RED, fontsize=8, ha="left", va="top")


def _fig_147(key, out_dir, name, kind, xmax, title, cuts=False):
    S = sim_kw_f()
    v = S[key]
    fig, ax = plt.subplots(figsize=(5.4, 3.0))
    if kind == "F":
        pdf, lab = (lambda x: stats.f.pdf(x, 3, 16)), "$F_{3,16}$ pdf"
        cut = [(stats.f.ppf(0.95, 3, 16), "$F_{0.95,3,16}=3.24$"), (stats.f.ppf(0.99, 3, 16), "$F_{0.99,3,16}=5.29$")] if cuts else None
        ax.set_xlabel("Observed F ratio")
        crits = (stats.f.ppf(0.95, 3, 16), stats.f.ppf(0.99, 3, 16))
    else:
        pdf, lab = (lambda x: stats.chi2.pdf(x, 3)), "$\\chi^2_3$ pdf"
        cut = [(stats.chi2.ppf(0.95, 3), "7.815"), (stats.chi2.ppf(0.99, 3), "11.345")] if cuts else None
        ax.set_xlabel("Observed $b$")
        crits = (stats.chi2.ppf(0.95, 3), stats.chi2.ppf(0.99, 3))
    _hist(ax, v, pdf, xmax, lab, None, color=BLUE if kind == "F" else GREEN)
    if cut:
        for c, labc in cut:
            ax.axvline(c, color=RED, ls="--", lw=1.1)
            ax.text(c, ax.get_ylim()[1] * 0.95, " " + labc, color=RED, fontsize=8, ha="left", va="top")
    r05, r01 = np.mean(v > crits[0]), np.mean(v > crits[1])
    ax.set_title(title + "\n%d replications: %.1f%% above the 0.05 cut-off, %.1f%% above the 0.01 cut-off"
                 % (len(v), 100 * r05, 100 * r01), fontsize=9)
    ax.legend(loc="center right", frameon=False)
    savefig(fig, CH, name, out_dir)


def fig_14_7_1(out_dir=None):
    """Figure 14.7.1: F ratios, normal data, H0 true (k = 4, n_j = 5)."""
    _fig_147("F_null_normal", out_dir, "fig14-7-1", "F", 6, "F test, normal data, $H_0$ true")


def fig_14_7_2(out_dir=None):
    """Figure 14.7.2: Kruskal-Wallis b, normal data, H0 true."""
    _fig_147("B_null_normal", out_dir, "fig14-7-2", "B", 12, "Kruskal-Wallis, normal data, $H_0$ true")


def fig_14_7_3(out_dir=None):
    """Figure 14.7.3: Kruskal-Wallis b, exponential data, H0 true."""
    _fig_147("B_null_expo", out_dir, "fig14-7-3", "B", 12, "Kruskal-Wallis, exponential data, $H_0$ true")


def fig_14_7_4(out_dir=None):
    """Figure 14.7.4: F ratios, exponential data, H0 true."""
    _fig_147("F_null_expo", out_dir, "fig14-7-4", "F", 8, "F test, exponential data, $H_0$ true")


def fig_14_7_5(out_dir=None):
    """Figure 14.7.5: Kruskal-Wallis b, normal data, fourth mean shifted by one standard deviation."""
    _fig_147("B_shift", out_dir, "fig14-7-5", "B", 14, "Kruskal-Wallis, normal data, $\\mu_4=1$", cuts=True)


def fig_14_7_6(out_dir=None):
    """Figure 14.7.6: F ratios, normal data, fourth mean shifted by one standard deviation."""
    _fig_147("F_shift", out_dir, "fig14-7-6", "F", 12, "F test, normal data, $\\mu_4=1$", cuts=True)


def fig_x14_1(out_dir=None):
    """Own figure x14.1: exact null laws of the signed-rank and rank-sum statistics against the normal curve."""
    fig, axs = plt.subplots(1, 3, figsize=(11.4, 3.1))
    # (a) n = 4, Table 14.3.1
    p4 = signed_rank_pmf(4)
    axs[0].bar(np.arange(len(p4)), p4 * 16, width=0.6, color=BLUE)
    axs[0].set_xlabel("$w$")
    axs[0].set_ylabel("$c(w)=16\\,p_W(w)$")
    axs[0].set_title("(a) signed rank, $n=4$: coefficients of\n$(1+x)(1+x^2)(1+x^3)(1+x^4)$", fontsize=9)
    axs[0].set_yticks([0, 1, 2])
    # (b) n = 14 with the normal approximation and Case Study 14.3.2
    n = 14
    p = signed_rank_pmf(n)
    m, v = signed_rank_mean_var(n)
    w = np.arange(len(p))
    axs[1].vlines(w, 0, p, color=BLUE, lw=1.2)
    xx = np.linspace(0, len(p) - 1, 400)
    axs[1].plot(xx, stats.norm.pdf(xx, m, math.sqrt(v)), color=RED, lw=1.4, label="normal approximation")
    axs[1].axvline(95, ymax=0.68, color=ORANGE, ls="--", lw=1.2)
    axs[1].set_ylim(0, max(p) * 1.45)
    axs[1].text(104, max(p) * 1.42, "$w=95$\nexact $P(W\\geq95)$\n$=%.4f$ " % p[95:].sum(), fontsize=8, color=ORANGE, ha="right", va="top")
    axs[1].set_xlabel("$w$")
    axs[1].set_title("(b) signed rank, $n=14$ (Case Study 14.3.2)", fontsize=9)
    axs[1].legend(loc="upper left", frameon=False, fontsize=7.5)
    # (c) rank sum n = 14, m = 12
    nn, mm = 14, 12
    pr = rank_sum_pmf(nn + mm, nn)
    s = np.arange(len(pr))
    keep = pr > 0
    mr, vr = rank_sum_mean_var(nn, mm)
    axs[2].vlines(s[keep], 0, pr[keep], color=GREEN, lw=0.8)
    xx = np.linspace(s[keep][0], s[keep][-1], 400)
    axs[2].plot(xx, stats.norm.pdf(xx, mr, math.sqrt(vr)), color=RED, lw=1.4, label="normal approximation")
    axs[2].axvline(240.5, ymax=0.68, color=ORANGE, ls="--", lw=1.2)
    axs[2].set_ylim(0, max(pr) * 1.45)
    axs[2].text(272, max(pr) * 1.42, "$w'=240.5$\nexact $P(W'\\geq w')$\n$=%.4f$ " % pr[241:].sum(), fontsize=8, color=ORANGE, ha="right", va="top")
    axs[2].set_xlabel("$w'$")
    axs[2].set_title("(c) rank sum, $n=14$, $m=12$ (Case Study 14.3.4)", fontsize=9)
    axs[2].legend(loc="upper left", frameon=False, fontsize=7.5)
    fig.tight_layout()
    savefig(fig, CH, "figx14-1", out_dir)


def power_curves(n=20, reps=20000):
    path = os.path.join(CACHE, "ch14-power-%d-%d.json" % (n, reps))
    if os.path.exists(path):
        with open(path) as f:
            return json.load(f)
    thetas = np.round(np.linspace(0, 1.0, 11), 3)
    out = {"thetas": thetas.tolist()}
    for pop in ("normal", "laplace", "uniform"):
        r = sim_power(pop, n, thetas, reps=reps, seed=1400 + len(pop))
        out[pop] = {k: v.tolist() for k, v in r.items()}
    os.makedirs(CACHE, exist_ok=True)
    with open(path, "w") as f:
        json.dump(out, f)
    return out


def fig_x14_2(out_dir=None):
    """Own figure x14.2: power of the t, sign and signed-rank tests (n = 20, one-sided, exact size 0.05)."""
    n = 20
    P = power_curves(n)
    th = np.array(P["thetas"])
    A = are_table()
    fig, axs = plt.subplots(1, 3, figsize=(11.4, 3.2), sharey=True)
    cols = {"t": BLUE, "sign": RED, "wilcoxon": GREEN}
    labs = {"t": "$t$ test", "sign": "sign test", "wilcoxon": "signed-rank test"}
    xx = np.linspace(0, 1, 200)
    for ax, pop in zip(axs, ("normal", "laplace", "uniform")):
        e = efficacies(pop)
        for key in ("t", "sign", "wilcoxon"):
            ax.plot(th, P[pop][key], "o", color=cols[key], ms=3.5)
            ax.plot(xx, local_power(e[key], n, xx), color=cols[key], lw=1.2, label=labs[key])
        a = A[pop]
        ax.set_title("%s: ARE sign/$t$ = %.3f, signed rank/$t$ = %.3f" % (POPS[pop]["label"], a["sign_t"], a["wilcoxon_t"]), fontsize=8.6)
        ax.set_xlabel("shift $\\theta$ (in standard deviations)")
        ax.set_ylim(0, 1.02)
    axs[0].set_ylabel("power")
    axs[0].legend(loc="lower right", frameon=False, fontsize=8)
    fig.tight_layout()
    savefig(fig, CH, "figx14-2", out_dir)


def fig_x14_3(out_dir=None):
    """Own figure x14.3: exact null law of the number of runs up and down, n = 25, against the normal approximation."""
    n = 25
    p = runs_exact(n)
    m, v = runs_mean_var(n)
    w = np.arange(len(p))
    fig, ax = plt.subplots(figsize=(6.2, 3.2))
    ax.bar(w, p, width=0.6, color=BLUE, alpha=0.8, label="exact $P(W=w)$")
    xx = np.linspace(5, 24, 300)
    ax.plot(xx, stats.norm.pdf(xx, m, math.sqrt(v)), color=RED, lw=1.4, label="normal, mean 16.33, var 4.12")
    ax.axvline(18, color=ORANGE, ls="--", lw=1.2)
    ax.text(18.3, max(p) * 0.95, "$w=18$ (Case Study 14.6.1)", fontsize=8.5, color=ORANGE, va="top")
    ax.set_xlim(7, 24.5)
    ax.set_xlabel("number of runs up and down, $w$")
    ax.set_ylabel("probability")
    ax.set_title("Runs up and down, $n=25$: exact null law and Theorem 14.6.1", fontsize=9.5)
    ax.legend(loc="upper left", frameon=False, fontsize=8)
    savefig(fig, CH, "figx14-3", out_dir)


# =========================================================================== demo export
def demo_reference():
    """The numbers the two browser demonstrations show (../data/ch14-demos.json)."""
    T = TABLES
    sh = T["sharks_cs_14_3_1"]
    w_sh, r_sh, _ = signed_rank(sh["ratio"], sh["mu0"])
    q = T["qscores_cs_14_3_2"]
    w_q, r_q, _ = signed_rank(q["y"], q["mu0"])
    ev = T["evaluations_cs_14_3_3"]
    w_ev, r_ev, _ = signed_rank(np.array(ev["inclass"]) - np.array(ev["online"]))
    bb = T["baseball_cs_14_3_4"]
    w_bb, r_bb = rank_sum(bb["AL"], bb["NL"])
    en = T["energy_q_14_3_1"]
    w_en, r_en, _ = signed_rank(np.array(en["winter"]) - np.array(en["summer"]))
    rank_presets = [
        dict(name="n = 4: Table 14.3.1", kind="signed", n=4, alt="two", alpha=0.10, w=None),
        dict(name="n = 7, two-sided, alpha = 0.05", kind="signed", n=7, alt="two", alpha=0.05, w=None),
        dict(name="Sharks (Case Study 14.3.1)", kind="signed", n=10, alt="two", alpha=0.05, w=w_sh, ranks=r_sh.tolist()),
        dict(name="Cyclazocine (Case Study 14.3.2)", kind="signed", n=14, alt="upper", alpha=0.05, w=w_q, ranks=r_q.tolist()),
        dict(name="Game times (Case Study 14.3.4)", kind="ranksum", n=14, m=12, alt="two", alpha=0.05, w=w_bb, ranks=r_bb.tolist()),
    ]
    ref = []
    for P in rank_presets:
        if P["kind"] == "signed":
            pmf = signed_rank_pmf(P["n"])
            m, v = signed_rank_mean_var(P["n"])
            vals = np.arange(len(pmf)).astype(float)
        else:
            pmf = rank_sum_pmf(P["n"] + P["m"], P["n"])
            m, v = rank_sum_mean_var(P["n"], P["m"])
            vals = np.arange(len(pmf)).astype(float)
        cdf = np.cumsum(pmf)
        a_tail = P["alpha"] / 2 if P["alt"] == "two" else P["alpha"]
        lo_ok = np.nonzero(cdf <= a_tail + 1e-12)[0]
        lo = int(vals[lo_ok[-1]]) if len(lo_ok) else None
        R = dict(P, mean=m, var=v, lower_crit=lo, lower_size=float(cdf[lo_ok[-1]]) if len(lo_ok) else 0.0)
        if P["w"] is not None:
            w = P["w"]
            R["p_exact_upper"] = float(pmf[vals >= w - 1e-9].sum())
            R["p_exact_lower"] = float(pmf[vals <= w + 1e-9].sum())
            R["z"] = (w - m) / math.sqrt(v)
            if P["kind"] == "signed":
                cv, cp = signed_rank_conditional(P["ranks"])
                R["var_ties"] = signed_rank_var_ties(P["ranks"])
            else:
                cv, cp = rank_sum_conditional(P["ranks"], P["n"])
                R["var_ties"] = float(rank_sum_var_ties(np.concatenate([bb["AL"], bb["NL"]]), P["n"], P["m"]))
            R["p_cond_upper"] = float(cp[cv >= w - 1e-9].sum())
            R["p_cond_lower"] = float(cp[cv <= w + 1e-9].sum())
        ref.append(R)
    A = are_table()
    are = {k: {kk: (None if not np.isfinite(vv) else float(vv)) for kk, vv in a.items()} for k, a in A.items()}
    crit = {}
    for n in (10, 20, 50):
        cs, gs = randomized_crit(stats.binom.pmf(np.arange(n + 1), n, 0.5), 0.05)
        cw, gw = randomized_crit(signed_rank_pmf(n), 0.05)
        crit[str(n)] = dict(sign_c=cs, sign_gamma=gs, wil_c=cw, wil_gamma=gw, t_crit=float(stats.t.ppf(0.95, n - 1)))
    S = sim_kw_f()
    kw = dict(chi2_95=float(stats.chi2.ppf(0.95, 3)), chi2_99=float(stats.chi2.ppf(0.99, 3)),
              f_95=float(stats.f.ppf(0.95, 3, 16)), f_99=float(stats.f.ppf(0.99, 3, 16)))
    for key in S:
        c = (kw["f_95"], kw["f_99"]) if key.startswith("F") else (kw["chi2_95"], kw["chi2_99"])
        kw[key] = dict(r05=float(np.mean(S[key] > c[0])), r01=float(np.mean(S[key] > c[1])))
    return dict(rank=ref, are=are, crit=crit, kw=kw, energy=dict(w=w_en), evaluations=dict(w=w_ev))


def export_json():
    os.makedirs(DATA_OUT, exist_ok=True)
    path = os.path.join(DATA_OUT, "ch14-demos.json")

    def conv(o):
        if isinstance(o, (np.floating, np.integer)):
            return o.item()
        if isinstance(o, np.ndarray):
            return o.tolist()
        raise TypeError(type(o))
    with open(path, "w", encoding="utf-8") as f:
        json.dump(demo_reference(), f, indent=1, default=conv)
    print("wrote", os.path.relpath(path, os.getcwd()))


FIGURES = {
    "14.2.1": fig_14_2_1, "14.4.1": fig_14_4_1,
    "14.7.1": fig_14_7_1, "14.7.2": fig_14_7_2, "14.7.3": fig_14_7_3,
    "14.7.4": fig_14_7_4, "14.7.5": fig_14_7_5, "14.7.6": fig_14_7_6,
    "x14.1": fig_x14_1, "x14.2": fig_x14_2, "x14.3": fig_x14_3,
}

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