"""Larsen and Marx (2018), Chapter 11: Regression.

Companion code for Chapter 11 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 (../ch11-regression.html):

* Section 11.2, least squares: ols (Theorem 11.2.1, with the residuals of Definition 11.2.1 and the sums of squares
  used throughout), ols_sums (the formula of the theorem written with raw sums, as in the book), ols_origin,
  ols_known_slope and ols_known_intercept (Questions 11.2.14 and 11.2.16), and the three linearised models of
  Table 11.2.9: fit_exponential, fit_power and fit_logistic (equations 11.2.1 to 11.2.5), with doubling_time.
* Section 11.3, the linear model: mle_normal_loglik (the likelihood of Theorem 11.3.1, maximised numerically),
  var_beta0 / var_beta1 / cov_b0_b1 (Theorem 11.3.2), slope_test and ci_slope (Theorems 11.3.4 to 11.3.6),
  ci_intercept (equation 11.3.6), ci_sigma2 (the chi-squared interval), ci_mean and pred_int (Theorems 11.3.7 and
  11.3.8), wh_halfwidth (the simultaneous band of Working and Hotelling, our own addition), two_slopes
  (Theorem 11.3.9) and slope_pivot_sim, which simulates the model to check each distributional claim.
* Section 11.4, covariance and correlation: sample_r (equation 11.4.1), r_from_slope (Question 11.4.9),
  r_squared (equation 11.4.3), rho_discrete and rho_x_x2 (Questions 11.4.1 and 11.4.6).
* Section 11.5, the bivariate normal: bvn_pdf (Definition 11.5.1), bvn_cond (Theorem 11.5.1), bvn_mle
  (Theorem 11.5.2, in closed form), t_rho (Theorem 11.5.3), fisher_z_ci (the comment after Example 11.5.1).
* Browser demonstrations: demo_reference() exports the exact numbers that least-squares-fit-demo.html and
  regression-estimators-demo.html show (../data/ch11-demos.json).

Figures. The book has nineteen numbered figures in Chapter 11. Those computed from data or from a model are
reproduced: 11.2.1 to 11.2.6, 11.2.8, 11.2.10 to 11.2.12 (the rod, Social Security, calcium oxide, Moore's law,
ant and red shank data), 11.3.1 (the regression curve of Example 11.3.1 with three conditional densities), 11.3.3
to 11.3.5 (the Camry, cigarette and fruit fly data) and 11.4.1 (SAT scores). Skipped, with reasons:
11.2.7 and 11.2.9 (sketches of the shapes of y = a e^(bx) and y = a x^b with no data), 11.3.2 (a schematic of the
simple linear model with its normal conditional densities; our x11.3 and Figure 11.3.1 show the same idea with
real numbers) and 11.6.1 (a sketch of a curved scatter plot; our figure x11.1 replaces it with computed
examples). Three figures of our own illustrate the chapter: x11.1, four ways in which r can mislead; x11.2,
regression towards the mean for a bivariate normal pair (both regression lines); x11.3, how the placement of the
x values controls the sampling distribution of the slope.
Run `python3 ch11_regression.py --list`, `python3 ch11_regression.py` (all figures, about 20 s)
or `python3 ch11_regression.py --fig 11.3.4`. Files go to ../img/ch11/.
"""
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 = 11
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_OUT = os.path.normpath(os.path.join(HERE, "..", "data"))
N01 = stats.norm
T = book_data("ch11-tables")


# =========================================================================== Section 11.2
def ols(x, y):
    """Least squares line y = b0 + b1 x (Theorem 11.2.1) and everything built from it.

    Returns a dict with n, xbar, ybar, sxx = sum (x - xbar)^2, sxy, syy, b0, b1, fitted, resid (Definition 11.2.1),
    sse = sum of squared residuals, s2 = sse / (n - 2) (the unbiased estimator of sigma^2, Corollary 11.3.1), s,
    sst = syy, ssr = sst - sse, r (equation 11.4.1) and r2 (equation 11.4.3).
    """
    x, y = np.asarray(x, float), np.asarray(y, float)
    n = len(x)
    xbar, ybar = x.mean(), y.mean()
    sxx = float(((x - xbar) ** 2).sum())
    sxy = float(((x - xbar) * (y - ybar)).sum())
    syy = float(((y - ybar) ** 2).sum())
    b1 = sxy / sxx
    b0 = ybar - b1 * xbar
    fitted = b0 + b1 * x
    resid = y - fitted
    sse = float((resid ** 2).sum())
    s2 = sse / (n - 2) if n > 2 else float("nan")
    r = sxy / math.sqrt(sxx * syy)
    return dict(n=n, x=x, y=y, xbar=float(xbar), ybar=float(ybar), sxx=sxx, sxy=sxy, syy=syy, b0=float(b0), b1=float(b1),
                fitted=fitted, resid=resid, sse=sse, s2=s2, s=math.sqrt(s2) if n > 2 else float("nan"),
                sst=syy, ssr=syy - sse, r=r, r2=r * r)


def ols_sums(x, y):
    """The slope and intercept of Theorem 11.2.1 written with the raw sums, exactly as the book prints them."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    n = len(x)
    sx, sy, sxx, sxy = x.sum(), y.sum(), (x * x).sum(), (x * y).sum()
    b = (n * sxy - sx * sy) / (n * sxx - sx ** 2)
    a = (sy - b * sx) / n
    return float(a), float(b)


def ols_origin(x, y):
    """Question 11.2.14: the best line through the origin, y = b x, has b = sum x_i y_i / sum x_i^2."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    return float((x * y).sum() / (x * x).sum())


def ols_known_slope(x, y, b):
    """Question 11.2.16(a): with the slope known to be b, the least squares intercept is ybar - b xbar."""
    return float(np.mean(y) - b * np.mean(x))


def ols_known_intercept(x, y, a):
    """Question 11.2.16(b): with the intercept known to be a, the least squares slope is sum x (y - a) / sum x^2."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    return float((x * (y - a)).sum() / (x * x).sum())


def fit_exponential(x, y):
    """y = a exp(b x), fitted by least squares on ln y (equations 11.2.1 and 11.2.2). Returns (a, b)."""
    f = ols(x, np.log(np.asarray(y, float)))
    return float(math.exp(f["b0"])), f["b1"]


def doubling_time(b):
    """If y = a exp(b x), y doubles every ln(2) / b units of x (Case Study 11.2.4)."""
    return math.log(2) / b


def fit_power(x, y):
    """y = a x^b, fitted by least squares on (log10 x, log10 y). Returns (a, b)."""
    f = ols(np.log10(np.asarray(x, float)), np.log10(np.asarray(y, float)))
    return float(10 ** f["b0"]), f["b1"]


def fit_logistic(x, y, L):
    """y = L / (1 + exp(a + b x)), fitted by least squares on ln((L - y) / y) against x (equation 11.2.5).
    Returns (a, b)."""
    y = np.asarray(y, float)
    f = ols(x, np.log((L - y) / y))
    return f["b0"], f["b1"]


# =========================================================================== Section 11.3
def mle_normal_loglik(par, x, y):
    """Minus the log-likelihood of the simple linear model, parametrised by (b0, b1, log sigma^2) (Theorem 11.3.1)."""
    b0, b1, ls2 = par
    s2 = math.exp(ls2)
    e = np.asarray(y, float) - b0 - b1 * np.asarray(x, float)
    n = len(e)
    return 0.5 * n * math.log(2 * math.pi * s2) + 0.5 * (e ** 2).sum() / s2


def var_beta1(sigma2, x):
    """Theorem 11.3.2(c): Var(beta1_hat) = sigma^2 / sum (x_i - xbar)^2."""
    x = np.asarray(x, float)
    return sigma2 / ((x - x.mean()) ** 2).sum()


def var_beta0(sigma2, x):
    """Theorem 11.3.2(d): Var(beta0_hat) = sigma^2 sum x_i^2 / (n sum (x_i - xbar)^2)."""
    x = np.asarray(x, float)
    return sigma2 * (x ** 2).sum() / (len(x) * ((x - x.mean()) ** 2).sum())


def cov_b0_b1(sigma2, x):
    """Cov(beta0_hat, beta1_hat) = - sigma^2 xbar / sum (x_i - xbar)^2 (Filling the gap 11.6)."""
    x = np.asarray(x, float)
    return -sigma2 * x.mean() / ((x - x.mean()) ** 2).sum()


def slope_test(f, b1_null=0.0):
    """Theorems 11.3.4 and 11.3.5: t = (b1_hat - b1') / (s / sqrt(Sxx)) on n - 2 degrees of freedom, and the two-sided
    P-value. f is the dict returned by ols."""
    t = (f["b1"] - b1_null) / (f["s"] / math.sqrt(f["sxx"]))
    return t, 2 * stats.t.sf(abs(t), f["n"] - 2)


def ci_slope(f, level=0.95):
    """Theorem 11.3.6: b1_hat -/+ t_{alpha/2, n-2} s / sqrt(Sxx)."""
    tq = stats.t.ppf(1 - (1 - level) / 2, f["n"] - 2)
    w = tq * f["s"] / math.sqrt(f["sxx"])
    return f["b1"] - w, f["b1"] + w


def ci_intercept(f, level=0.95):
    """Equation 11.3.6 inverted: b0_hat -/+ t s sqrt(sum x^2) / (sqrt(n) sqrt(Sxx))."""
    n = f["n"]
    tq = stats.t.ppf(1 - (1 - level) / 2, n - 2)
    sx2 = float((f["x"] ** 2).sum())
    w = tq * f["s"] * math.sqrt(sx2) / (math.sqrt(n) * math.sqrt(f["sxx"]))
    return f["b0"] - w, f["b0"] + w


def ci_sigma2(f, level=0.95):
    """The interval ((n-2)s^2 / chi2_{1-alpha/2, n-2}, (n-2)s^2 / chi2_{alpha/2, n-2}) of Section 11.3."""
    a = 1 - level
    k = f["n"] - 2
    return k * f["s2"] / stats.chi2.ppf(1 - a / 2, k), k * f["s2"] / stats.chi2.ppf(a / 2, k)


def ci_mean(f, x0, level=0.95):
    """Theorem 11.3.7: the confidence interval for E(Y | x0). Returns (yhat, halfwidth)."""
    n = f["n"]
    tq = stats.t.ppf(1 - (1 - level) / 2, n - 2)
    yhat = f["b0"] + f["b1"] * x0
    return yhat, tq * f["s"] * math.sqrt(1 / n + (x0 - f["xbar"]) ** 2 / f["sxx"])


def pred_int(f, x0, level=0.95):
    """Theorem 11.3.8: the prediction interval for a new Y at x0. Returns (yhat, halfwidth)."""
    n = f["n"]
    tq = stats.t.ppf(1 - (1 - level) / 2, n - 2)
    yhat = f["b0"] + f["b1"] * x0
    return yhat, tq * f["s"] * math.sqrt(1 + 1 / n + (x0 - f["xbar"]) ** 2 / f["sxx"])


def wh_halfwidth(f, x0, level=0.95):
    """Working-Hotelling: a band for the whole line, half-width sqrt(2 F_{level; 2, n-2}) s sqrt(1/n + (x - xbar)^2 / Sxx).
    (Filling the gap 11.11; this is not in the book.)"""
    n = f["n"]
    c = math.sqrt(2 * stats.f.ppf(level, 2, n - 2))
    return c * f["s"] * math.sqrt(1 / n + (x0 - f["xbar"]) ** 2 / f["sxx"])


def two_slopes(x1, y1, x2, y2):
    """Theorem 11.3.9: the pooled standard deviation s, t statistic and degrees of freedom n + m - 4 for H0: b1 = b1*."""
    f1, f2 = ols(x1, y1), ols(x2, y2)
    n, m = f1["n"], f2["n"]
    s = math.sqrt((f1["sse"] + f2["sse"]) / (n + m - 4))
    t = (f1["b1"] - f2["b1"]) / (s * math.sqrt(1 / f1["sxx"] + 1 / f2["sxx"]))
    return s, t, n + m - 4


def two_slopes_summary(b1, sse1, sxx1, n1, b2, sse2, sxx2, n2):
    """Theorem 11.3.9 from summary numbers (Question 11.3.21): returns (s, t, df)."""
    s = math.sqrt((sse1 + sse2) / (n1 + n2 - 4))
    return s, (b1 - b2) / (s * math.sqrt(1 / sxx1 + 1 / sxx2)), n1 + n2 - 4


def simulate_model(rng, x, b0, b1, sigma, reps):
    """reps data sets y = b0 + b1 x + sigma Z from the simple linear model with the given x values; returns
    arrays (b0_hat, b1_hat, s2, ybar) of length reps (vectorised least squares)."""
    x = np.asarray(x, float)
    n = len(x)
    Y = b0 + b1 * x + sigma * rng.standard_normal((reps, n))
    xc = x - x.mean()
    sxx = (xc ** 2).sum()
    ybar = Y.mean(1)
    bh1 = (Y * xc).sum(1) / sxx
    bh0 = ybar - bh1 * x.mean()
    sse = ((Y - bh0[:, None] - bh1[:, None] * x) ** 2).sum(1)
    return bh0, bh1, sse / (n - 2), ybar


# =========================================================================== Section 11.4
def sample_r(x, y):
    """The sample correlation coefficient, equation 11.4.1."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    return float(((x - x.mean()) * (y - y.mean())).sum() / math.sqrt(((x - x.mean()) ** 2).sum() * ((y - y.mean()) ** 2).sum()))


def r_from_slope(f):
    """Question 11.4.9: r = b1_hat sqrt(Sxx / Syy)."""
    return f["b1"] * math.sqrt(f["sxx"] / f["syy"])


def r_squared(f):
    """Equation 11.4.3: (SST - SSE) / SST."""
    return (f["sst"] - f["sse"]) / f["sst"]


def rho_discrete(pmf):
    """Correlation of a discrete pair given as {(x, y): probability} (Questions 11.4.1 and 11.4.4)."""
    ex = sum(p * x for (x, y), p in pmf.items())
    ey = sum(p * y for (x, y), p in pmf.items())
    vx = sum(p * x * x for (x, y), p in pmf.items()) - ex ** 2
    vy = sum(p * y * y for (x, y), p in pmf.items()) - ey ** 2
    cov = sum(p * x * y for (x, y), p in pmf.items()) - ex * ey
    return cov, cov / math.sqrt(vx * vy)


def rho_x_x2(n):
    """Question 11.4.6: X uniform on 1..n and Y = X^2; the exact correlation."""
    k = np.arange(1, n + 1, dtype=float)
    return float(np.corrcoef(k, k ** 2)[0, 1])


# =========================================================================== Section 11.5
def bvn_pdf(x, y, mx, sx, my, sy, rho):
    """Definition 11.5.1: the bivariate normal density."""
    zx, zy = (x - mx) / sx, (y - my) / sy
    q = (zx ** 2 - 2 * rho * zx * zy + zy ** 2) / (1 - rho ** 2)
    return np.exp(-0.5 * q) / (2 * math.pi * sx * sy * math.sqrt(1 - rho ** 2))


def bvn_cond(x, mx, sx, my, sy, rho):
    """Theorem 11.5.1(c), (d): the mean and standard deviation of Y given X = x."""
    return my + rho * sy / sx * (x - mx), sy * math.sqrt(1 - rho ** 2)


def bvn_mle(x, y):
    """Theorem 11.5.2: the maximum likelihood estimates (xbar, ybar, sigma_x^2, sigma_y^2, r), divisors n."""
    x, y = np.asarray(x, float), np.asarray(y, float)
    return x.mean(), y.mean(), x.var(), y.var(), sample_r(x, y)


def t_rho(r, n):
    """Theorem 11.5.3: t = sqrt(n-2) r / sqrt(1 - r^2) on n - 2 degrees of freedom, and the two-sided P-value."""
    t = math.sqrt(n - 2) * r / math.sqrt(1 - r * r)
    return t, 2 * stats.t.sf(abs(t), n - 2)


def fisher_z_ci(r, n, level=0.95):
    """The interval tanh(artanh r -/+ z / sqrt(n - 3)) from the comment after Example 11.5.1."""
    z = N01.ppf(1 - (1 - level) / 2)
    c = math.atanh(r)
    return math.tanh(c - z / math.sqrt(n - 3)), math.tanh(c + z / math.sqrt(n - 3))


# =========================================================================== numbers quoted in the notes
def case_study_numbers():
    """Fits and tests of every case study of the chapter, computed from the data of the book."""
    out = {}
    out["cs1121"] = ols(T["cs1121_rod_x"], T["cs1121_rod_y"])
    out["cs1122"] = ols(T["cs1122_ss_x"], T["cs1122_ss_y"])
    out["cs1123"] = ols(T["cs1123_cao_x"], T["cs1123_cao_y"])
    out["cs1124"] = fit_exponential(T["cs1124_moore_x"], T["cs1124_moore_y"])
    out["cs1125"] = fit_power(T["cs1125_ants_x"], T["cs1125_ants_y"])
    out["cs1126"] = fit_logistic(T["cs1126_flock_t"], T["cs1126_flock_p"], 1.0)
    out["cs1131"] = ols(T["cs1131_chd_x"], T["cs1131_chd_y"])
    out["cs1132"] = ols(T["cs1132_camry_x"], T["cs1132_camry_y"])
    out["cs1134A"] = ols(T["cs1134_fly_x"], T["cs1134_fly_A"])
    out["cs1134B"] = ols(T["cs1134_fly_x"], T["cs1134_fly_B"])
    out["cs1141"] = ols(T["cs1141_sat_x"], T["cs1141_sat_y"])
    out["ex1151"] = ols(T["ex1151_butter_x"], T["ex1151_butter_y"])
    return out


# =========================================================================== figures
def _scatter_line(ax, f, xlab, ylab, xs=None, color=BLUE):
    ax.plot(f["x"], f["y"], "o", color=color, ms=4.2, mfc="none", mew=1.2)
    xs = np.linspace(f["x"].min(), f["x"].max(), 2) if xs is None else xs
    ax.plot(xs, f["b0"] + f["b1"] * xs, "-", color=RED, lw=1.6)
    ax.set_xlabel(xlab)
    ax.set_ylabel(ylab)


def _resid_plot(ax, x, e, xlab, ylab="Residual, $y-\\hat y$"):
    ax.axhline(0, color=GREY, lw=0.8)
    ax.plot(x, e, "o", color=BLUE, ms=4.2, mfc="none", mew=1.2)
    ax.set_xlabel(xlab)
    ax.set_ylabel(ylab)


def fig_11_2_1(out=None):
    """Case Study 11.2.1: rough and finished weights of 25 connecting rods, with the least squares line."""
    f = ols(T["cs1121_rod_x"], T["cs1121_rod_y"])
    fig, ax = plt.subplots(figsize=(5.2, 3.5))
    _scatter_line(ax, f, "Rough weight, $x$ (oz)", "Finished weight, $y$ (oz)")
    ax.text(0.04, 0.93, "$y=%.3f+%.3f\\,x$" % (f["b0"], f["b1"]), transform=ax.transAxes, color=RED, va="top")
    savefig(fig, CH, "fig11-2-1", out)


def fig_11_2_2(out=None):
    """Example 11.2.1: the residual plot of the connecting rod fit (no pattern)."""
    f = ols(T["cs1121_rod_x"], T["cs1121_rod_y"])
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    _resid_plot(ax, f["x"], f["resid"], "Rough weight, $x$ (oz)")
    savefig(fig, CH, "fig11-2-2", out)


def fig_11_2_3(out=None):
    """Case Study 11.2.2: Social Security expenditures, 1965-2005, with the least squares line (and the 2010 value)."""
    f = ols(T["cs1122_ss_x"], T["cs1122_ss_y"])
    fig, ax = plt.subplots(figsize=(5.2, 3.5))
    _scatter_line(ax, f, "Years after 1965", "Expenditures ($ billions)", xs=np.array([0, 45.0]))
    ax.plot([45], [713], "s", color=GREEN, ms=5.5)
    ax.annotate("actual 2010: 713", (45, 713), (21, 640), color=GREEN, fontsize=8.5, arrowprops=dict(arrowstyle="-", color=GREEN, lw=0.8))
    ax.plot([45], [f["b0"] + f["b1"] * 45], "x", color=RED, ms=7)
    ax.annotate("line says 543", (45, f["b0"] + f["b1"] * 45), (24, 400), color=RED, fontsize=8.5, arrowprops=dict(arrowstyle="-", color=RED, lw=0.8))
    savefig(fig, CH, "fig11-2-3", out)


def fig_11_2_4(out=None):
    """Case Study 11.2.2: the residual plot, a clear curve."""
    f = ols(T["cs1122_ss_x"], T["cs1122_ss_y"])
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    _resid_plot(ax, f["x"], f["resid"], "Years after 1965")
    savefig(fig, CH, "fig11-2-4", out)


def fig_11_2_5(out=None):
    """Case Study 11.2.3: CaO recovered against CaO present, Chemist B marked."""
    f = ols(T["cs1123_cao_x"], T["cs1123_cao_y"])
    isB = np.array(T["cs1123_cao_chemist"]) == "B"
    fig, ax = plt.subplots(figsize=(5.2, 3.5))
    xs = np.array([0, 42.0])
    ax.plot(xs, f["b0"] + f["b1"] * xs, "-", color=RED, lw=1.6)
    ax.plot(f["x"][~isB], f["y"][~isB], "o", color=BLUE, ms=4.5, mfc="none", mew=1.2, label="Chemist A")
    ax.plot(f["x"][isB], f["y"][isB], "s", color=GREEN, ms=5.5, mfc="none", mew=1.4, label="Chemist B")
    ax.set_xlabel("CaO present (mg), $x$")
    ax.set_ylabel("CaO recovered (mg), $y$")
    ax.legend(frameon=False, loc="lower right")
    ax.text(0.04, 0.93, "$y=%.4f+%.4f\\,x$" % (f["b0"], f["b1"]), transform=ax.transAxes, color=RED, va="top")
    savefig(fig, CH, "fig11-2-5", out)


def fig_11_2_6(out=None):
    """Case Study 11.2.3: the residual plot, Chemist B stands out."""
    f = ols(T["cs1123_cao_x"], T["cs1123_cao_y"])
    isB = np.array(T["cs1123_cao_chemist"]) == "B"
    fig, ax = plt.subplots(figsize=(5.2, 3.0))
    ax.axhline(0, color=GREY, lw=0.8)
    ax.plot(f["x"][~isB], f["resid"][~isB], "o", color=BLUE, ms=4.5, mfc="none", mew=1.2, label="Chemist A")
    ax.plot(f["x"][isB], f["resid"][isB], "s", color=GREEN, ms=5.5, mfc="none", mew=1.4, label="Chemist B")
    ax.set_xlabel("CaO present (mg), $x$")
    ax.set_ylabel("Residual, $y-\\hat y$")
    ax.legend(frameon=False, loc="upper left")
    savefig(fig, CH, "fig11-2-6", out)


def fig_11_2_8(out=None):
    """Case Study 11.2.4: transistors per chip against years after 1975, with the fitted exponential curve."""
    x, y = np.array(T["cs1124_moore_x"], float), np.array(T["cs1124_moore_y"], float)
    a, b = fit_exponential(x, y)
    fig, ax = plt.subplots(figsize=(5.2, 3.5))
    xs = np.linspace(0, 20.5, 200)
    ax.plot(xs, a * np.exp(b * xs) / 1e6, "-", color=RED, lw=1.6)
    ax.plot(x, y / 1e6, "o", color=BLUE, ms=4.8, mfc="none", mew=1.3)
    ax.set_xlabel("Years after 1975, $x$")
    ax.set_ylabel("Transistors per chip (millions)")
    ax.text(0.04, 0.93, "$y=%.0f\\,e^{%.3f\\,x}$" % (a, b), transform=ax.transAxes, color=RED, va="top")
    savefig(fig, CH, "fig11-2-8", out)


def fig_11_2_10(out=None):
    """Case Study 11.2.5: log colony size against log foraging size for 15 red wood ant colonies."""
    lx, ly = np.log10(T["cs1125_ants_x"]), np.log10(T["cs1125_ants_y"])
    f = ols(lx, ly)
    fig, ax = plt.subplots(figsize=(5.2, 3.5))
    _scatter_line(ax, f, "$\\log_{10} x$ (foraging size)", "$\\log_{10} y$ (colony size)")
    ax.text(0.04, 0.93, "$\\log y=%.3f+%.3f\\,\\log x$" % (f["b0"], f["b1"]), transform=ax.transAxes, color=RED, va="top")
    savefig(fig, CH, "fig11-2-10", out)


def fig_11_2_11(out=None):
    """Case Study 11.2.6: the proportion of a red shank flock airborne against time, an S shape."""
    fig, ax = plt.subplots(figsize=(5.2, 3.5))
    ax.plot(T["cs1126_flock_t"], T["cs1126_flock_p"], "o", color=BLUE, ms=4.8, mfc="none", mew=1.3)
    ax.set_xlabel("Time (seconds) of flight, $x$")
    ax.set_ylabel("Proportion airborne, $y$")
    ax.set_ylim(-0.02, 1.05)
    savefig(fig, CH, "fig11-2-11", out)


def fig_11_2_12(out=None):
    """Case Study 11.2.6: the same data with the fitted logistic curve y = 1 / (1 + exp(2.595 - 11.425 x))."""
    a, b = fit_logistic(T["cs1126_flock_t"], T["cs1126_flock_p"], 1.0)
    fig, ax = plt.subplots(figsize=(5.2, 3.5))
    xs = np.linspace(0, 0.62, 200)
    ax.plot(xs, 1 / (1 + np.exp(a + b * xs)), "-", color=RED, lw=1.6)
    ax.plot(T["cs1126_flock_t"], T["cs1126_flock_p"], "o", color=BLUE, ms=4.8, mfc="none", mew=1.3)
    ax.set_xlabel("Time (seconds) of flight, $x$")
    ax.set_ylabel("Proportion airborne, $y$")
    ax.set_ylim(-0.02, 1.05)
    ax.text(0.97, 0.12, "$y=1/(1+e^{%.3f%+.3f\\,x})$" % (a, b), transform=ax.transAxes, color=RED, ha="right")
    savefig(fig, CH, "fig11-2-12", out)


def fig_11_3_1(out=None):
    """Example 11.3.1: the regression curve E(Y|x) = (3x+2)/(6x+3) with the conditional densities at x = 0, 1/2, 1."""
    fig, ax = plt.subplots(figsize=(5.4, 3.6))
    xs = np.linspace(0, 1, 100)
    ax.plot(xs, (3 * xs + 2) / (6 * xs + 3), "-", color=RED, lw=1.8, label="$E(Y\\mid x)=\\frac{3x+2}{6x+3}$")
    ys = np.linspace(0, 1, 100)
    for x0, col in ((0.0, BLUE), (0.5, GREEN), (1.0, MAGENTA)):
        dens = (x0 + ys) / (x0 + 0.5)
        ax.plot(x0 + 0.17 * dens, ys, "-", color=col, lw=1.3)
        ax.plot([x0, x0], [0, 1], ":", color=col, lw=0.8)
        ax.plot([x0], [(3 * x0 + 2) / (6 * x0 + 3)], "o", color=col, ms=4.5)
    ax.text(0.02, 0.04, "$f_{Y|0}(y)=2y$", color=BLUE, fontsize=8)
    ax.text(0.45, 0.04, "$f_{Y|1/2}(y)=y+\\frac{1}{2}$", color=GREEN, fontsize=8)
    ax.text(0.92, 0.04, "$f_{Y|1}(y)=\\frac{2y+2}{3}$", color=MAGENTA, fontsize=8)
    ax.set_xlim(-0.05, 1.45)
    ax.set_ylim(-0.02, 1.05)
    ax.set_xlabel("$x$")
    ax.set_ylabel("$y$")
    ax.legend(frameon=False, loc="lower left", bbox_to_anchor=(0.0, 1.0))
    savefig(fig, CH, "fig11-3-1", out)


def fig_11_3_3(out=None):
    """Case Study 11.3.2: suggested retail price of a four-door Toyota Camry by model year, with the fitted line."""
    f = ols(T["cs1132_camry_x"], T["cs1132_camry_y"])
    fig, ax = plt.subplots(figsize=(5.2, 3.5))
    _scatter_line(ax, f, "Year, $x$ (years after 2005)", "Price ($)")
    ax.text(0.04, 0.93, "$y=%.2f+%.2f\\,x$" % (f["b0"], f["b1"]), transform=ax.transAxes, color=RED, va="top")
    savefig(fig, CH, "fig11-3-3", out)


def fig_11_3_4(out=None):
    """Case Study 11.3.1: cigarette consumption and CHD mortality with the least squares line and the 95% confidence
    band for E(Y|x) (dotted); the 95% prediction band is added as a dashed curve."""
    f = ols(T["cs1131_chd_x"], T["cs1131_chd_y"])
    xs = np.linspace(1000, 4500, 200)
    ci = np.array([ci_mean(f, v)[1] for v in xs])
    pi = np.array([pred_int(f, v)[1] for v in xs])
    yh = f["b0"] + f["b1"] * xs
    fig, ax = plt.subplots(figsize=(5.4, 3.8))
    ax.plot(xs, yh, "-", color=RED, lw=1.5)
    ax.plot(xs, yh + ci, ":", color=RED, lw=1.4)
    ax.plot(xs, yh - ci, ":", color=RED, lw=1.4)
    ax.plot(xs, yh + pi, "--", color=GREY, lw=1.0)
    ax.plot(xs, yh - pi, "--", color=GREY, lw=1.0)
    ax.plot(f["x"], f["y"], "o", color=BLUE, ms=4.5, mfc="none", mew=1.2)
    ax.set_xlabel("Cigarette consumption per adult per year, $x$")
    ax.set_ylabel("CHD mortality per 100,000")
    ax.text(0.04, 0.93, "dotted: 95% band for $E(Y\\mid x)$\ndashed: 95% prediction band", transform=ax.transAxes, va="top", fontsize=8.5)
    savefig(fig, CH, "fig11-3-4", out)


def fig_11_3_5(out=None):
    """Example 11.3.4: Drosophila census counts for the cross-bred Strain A and the in-bred Strain B, two lines."""
    fa, fb = ols(T["cs1134_fly_x"], T["cs1134_fly_A"]), ols(T["cs1134_fly_x"], T["cs1134_fly_B"])
    fig, ax = plt.subplots(figsize=(5.2, 3.5))
    xs = np.array([0, 510.0])
    ax.plot(xs, fa["b0"] + fa["b1"] * xs, "-", color=BLUE, lw=1.5)
    ax.plot(xs, fb["b0"] + fb["b1"] * xs, "-", color=RED, lw=1.5)
    ax.plot(fa["x"], fa["y"], "o", color=BLUE, ms=4.8, mfc="none", mew=1.3)
    ax.plot(fb["x"], fb["y"], "s", color=RED, ms=4.8, mfc="none", mew=1.3)
    ax.text(300, 130, "Strain B: $y^*=%.1f+%.3f\\,x^*$" % (fb["b0"], fb["b1"]), color=RED, fontsize=8.5)
    ax.text(10, 480, "Strain A: $y=%.1f+%.3f\\,x$" % (fa["b0"], fa["b1"]), color=BLUE, fontsize=8.5)
    ax.set_xlabel("Day number, $x$ and $x^*$")
    ax.set_ylabel("Census count")
    savefig(fig, CH, "fig11-3-5", out)


def fig_11_4_1(out=None):
    """Case Study 11.4.1: average SAT score against participation rate for the 50 states and the District of Columbia."""
    f = ols(T["cs1141_sat_x"], T["cs1141_sat_y"])
    fig, ax = plt.subplots(figsize=(5.4, 3.6))
    ax.plot(f["x"], f["y"], "o", color=BLUE, ms=4.2, mfc="none", mew=1.2)
    xs = np.array([0, 100.0])
    ax.plot(xs, f["b0"] + f["b1"] * xs, "-", color=RED, lw=1.4)
    ax.set_xlabel("Participation rate (%)")
    ax.set_ylabel("Average SAT score")
    ax.text(0.97, 0.93, "$r=%.3f$, $r^2=%.3f$" % (f["r"], f["r2"]), transform=ax.transAxes, ha="right", va="top")
    savefig(fig, CH, "fig11-4-1", out)


def fig_x11_1(out=None):
    """Own figure: four ways in which r can mislead (a curve with r near 1, r near 0 for a perfect curve, one outlier,
    a restricted range)."""
    rng = np.random.default_rng(1105)
    fig, axes = plt.subplots(2, 2, figsize=(6.6, 5.2))
    ax = axes[0, 0]                                                    # (a) Social Security
    f = ols(T["cs1122_ss_x"], T["cs1122_ss_y"])
    _scatter_line(ax, f, "Years after 1965", "Expenditures ($ billions)")
    ax.set_title("(a) $r=%.3f$ but curved" % f["r"], fontsize=9.5)
    ax = axes[0, 1]                                                    # (b) y = x^2 on a symmetric range
    x = np.linspace(-1, 1, 21)
    ax.plot(x, x ** 2, "o", color=BLUE, ms=4, mfc="none", mew=1.2)
    ax.set_title("(b) $y=x^2$ exactly, $r=%.3f$" % sample_r(x, x ** 2), fontsize=9.5)
    ax.set_xlabel("$x$")
    ax.set_ylabel("$y$")
    ax = axes[1, 0]                                                    # (c) one outlier
    x = rng.standard_normal(30)
    y = rng.standard_normal(30)
    x[0], y[0] = 9.0, 9.0
    r_with, r_without = sample_r(x, y), sample_r(x[1:], y[1:])
    ax.plot(x[1:], y[1:], "o", color=BLUE, ms=4, mfc="none", mew=1.2)
    ax.plot(x[:1], y[:1], "s", color=RED, ms=6, mfc="none", mew=1.5)
    ax.set_title("(c) one point: $r=%.2f$ with, $%.2f$ without" % (r_with, r_without), fontsize=9.5)
    ax.set_xlabel("$x$")
    ax.set_ylabel("$y$")
    ax = axes[1, 1]                                                    # (d) range restriction
    x = rng.uniform(0, 10, 120)
    y = 1.0 + 0.8 * x + rng.normal(0, 2.0, 120)
    keep = (x > 4) & (x < 6)
    ax.plot(x[~keep], y[~keep], "o", color=GREY, ms=3.2, mfc="none", mew=1.0)
    ax.plot(x[keep], y[keep], "o", color=BLUE, ms=4, mfc="none", mew=1.3)
    ax.axvspan(4, 6, color=BLUE, alpha=0.08)
    ax.set_title("(d) all points $r=%.2f$; only $4<x<6$: $r=%.2f$" % (sample_r(x, y), sample_r(x[keep], y[keep])), fontsize=9.5)
    ax.set_xlabel("$x$")
    ax.set_ylabel("$y$")
    fig.tight_layout()
    savefig(fig, CH, "figx11-1", out)


def fig_x11_2(out=None):
    """Own figure: regression towards the mean. 400 draws from a standard bivariate normal with rho = 0.5, the two
    regression lines E(Y|x) = rho x and E(X|y) = rho y (drawn as x = rho y), the line y = x and the 1-standard
    deviation contour."""
    rng = np.random.default_rng(1106)
    rho = 0.5
    z = rng.standard_normal((400, 2))
    x = z[:, 0]
    y = rho * x + math.sqrt(1 - rho ** 2) * z[:, 1]
    fig, ax = plt.subplots(figsize=(5.0, 5.0))
    ax.plot(x, y, "o", color=BLUE, ms=3.2, mfc="none", mew=0.9, alpha=0.7)
    xs = np.array([-3.5, 3.5])
    ax.plot(xs, xs, ":", color=GREY, lw=1.1, label="$y=x$")
    ax.plot(xs, rho * xs, "-", color=RED, lw=1.6, label="$E(Y\\mid x)=\\rho x$")
    ax.plot(xs, xs / rho, "-", color=GREEN, lw=1.6, label="$E(X\\mid y)=\\rho y$, drawn as $y=x/\\rho$")
    t = np.linspace(0, 2 * math.pi, 200)
    S = np.array([[1, rho], [rho, 1]])
    L = np.linalg.cholesky(S)
    e = L @ np.vstack([np.cos(t), np.sin(t)])
    ax.plot(e[0], e[1], "-", color=PURPLE, lw=1.0)
    ax.axvspan(1.8, 2.2, color=RED, alpha=0.10)
    strip = (x > 1.8) & (x < 2.2)
    ax.plot([2.0], [y[strip].mean()], "D", color=RED, ms=6)
    ax.set_xlim(-3.5, 3.5)
    ax.set_ylim(-3.5, 3.5)
    ax.set_aspect("equal")
    ax.set_xlabel("$x$ (standardised parent)")
    ax.set_ylabel("$y$ (standardised child)")
    ax.legend(frameon=False, loc="lower right", fontsize=8)
    savefig(fig, CH, "figx11-2", out)


def fig_x11_3(out=None):
    """Own figure: the sampling distribution of the slope for three designs with n = 12 and sigma = 1."""
    rng = np.random.default_rng(1107)
    designs = {
        "evenly spread, $x=1,\\dots,12$": np.arange(1, 13, dtype=float),
        "clustered in the middle ($x$ from 4 to 9)": np.linspace(4, 9, 12),
        "half at each end, $x\\in\\{1,12\\}$": np.array([1.0] * 6 + [12.0] * 6),
    }
    fig, axes = plt.subplots(1, 3, figsize=(8.0, 2.7), sharex=True, sharey=True)
    for ax, (name, x) in zip(axes, designs.items()):
        _, b1h, _, _ = simulate_model(rng, x, 2.0, 1.0, 1.0, 20000)
        se = math.sqrt(var_beta1(1.0, x))
        ax.hist(b1h, bins=np.linspace(0.0, 2.0, 61), density=True, color=BLUE, alpha=0.45)
        g = np.linspace(0, 2, 300)
        ax.plot(g, N01.pdf(g, 1.0, se), "-", color=RED, lw=1.5)
        ax.set_title("%s\n$\\mathrm{sd}=%.3f$" % (name, se), fontsize=8.5)
        ax.set_xlabel("$\\hat\\beta_1$")
    axes[0].set_ylabel("density")
    fig.tight_layout()
    savefig(fig, CH, "figx11-3", out)


FIGURES = {
    "11.2.1": fig_11_2_1, "11.2.2": fig_11_2_2, "11.2.3": fig_11_2_3, "11.2.4": fig_11_2_4, "11.2.5": fig_11_2_5,
    "11.2.6": fig_11_2_6, "11.2.8": fig_11_2_8, "11.2.10": fig_11_2_10, "11.2.11": fig_11_2_11, "11.2.12": fig_11_2_12,
    "11.3.1": fig_11_3_1, "11.3.3": fig_11_3_3, "11.3.4": fig_11_3_4, "11.3.5": fig_11_3_5, "11.4.1": fig_11_4_1,
    "x11.1": fig_x11_1, "x11.2": fig_x11_2, "x11.3": fig_x11_3,
}


# =========================================================================== browser demonstrations
def demo_reference():
    """Write ../data/ch11-demos.json: the data sets and the exact numbers that the two demonstrations show."""
    def pack(name, x, y, xlab, ylab, note):
        f = ols(x, y)
        return dict(name=name, x=[float(v) for v in x], y=[float(v) for v in y], xlab=xlab, ylab=ylab, note=note,
                    b0=f["b0"], b1=f["b1"], sse=f["sse"], sst=f["sst"], r=f["r"], r2=f["r2"], s=f["s"],
                    resid=[float(v) for v in f["resid"]])
    sets = {
        "rods": pack("Connecting rods (Case Study 11.2.1)", T["cs1121_rod_x"], T["cs1121_rod_y"], "rough weight x (oz)", "finished weight y (oz)", "25 rods"),
        "socsec": pack("Social Security (Case Study 11.2.2)", T["cs1122_ss_x"], T["cs1122_ss_y"], "years after 1965 x", "expenditures y ($ billions)", "9 points, 1965-2005"),
        "cao": pack("Calcium oxide (Case Study 11.2.3)", T["cs1123_cao_x"], T["cs1123_cao_y"], "CaO present x (mg)", "CaO recovered y (mg)", "10 samples; the 7th (x = 31) is Chemist B"),
        "moore": pack("Transistors per chip (Case Study 11.2.4)", T["cs1124_moore_x"], T["cs1124_moore_y"], "years after 1975 x", "transistors per chip y", "7 Intel chips"),
        "sat": pack("SAT scores (Case Study 11.4.1)", T["cs1141_sat_x"], T["cs1141_sat_y"], "participation rate x (%)", "average SAT score y", "50 states and DC"),
    }
    cao = np.array(T["cs1123_cao_chemist"]) == "A"
    fa = ols(np.array(T["cs1123_cao_x"])[cao], np.array(T["cs1123_cao_y"])[cao])
    lm = ols(T["cs1124_moore_x"], np.log(T["cs1124_moore_y"]))
    ref = dict(cao_without_B=dict(b0=fa["b0"], b1=fa["b1"], s=fa["s"], r2=fa["r2"]),
               moore_log=dict(b0=lm["b0"], b1=lm["b1"], a=math.exp(lm["b0"]), doubling=doubling_time(lm["b1"]), r2=lm["r2"]))
    # regression-estimators demo: exact theory for the designs of the presets
    designs = {
        "even": [float(v) for v in range(1, 13)],
        "middle": [float(v) for v in np.linspace(4, 9, 12)],
        "ends": [1.0] * 6 + [12.0] * 6,
        "shifted": [float(v) for v in range(101, 113)],
    }
    theory = {}
    for k, x in designs.items():
        xx = np.array(x)
        sxx = float(((xx - xx.mean()) ** 2).sum())
        theory[k] = dict(x=x, n=len(x), xbar=float(xx.mean()), sxx=sxx, se_b1=math.sqrt(1 / sxx), sd_b0=math.sqrt(var_beta0(1.0, xx)),
                         corr_b0_b1=float(cov_b0_b1(1.0, xx) / math.sqrt(var_beta0(1.0, xx) * var_beta1(1.0, xx))))
    out = dict(sets=sets, ref=ref, designs=theory)
    os.makedirs(DATA_OUT, exist_ok=True)
    with open(os.path.join(DATA_OUT, "ch11-demos.json"), "w", encoding="utf-8") as fh:
        json.dump(out, fh, ensure_ascii=False, separators=(",", ":"))
    print("wrote data/ch11-demos.json")
    return out


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