#!/usr/bin/env python3
"""Numerical checks for guide chapter 2.3 (three ways to an uncertainty), and its three data plots.
Every formula the chapter states is tested here, and every toy number the chapter quotes is printed here.
The script exits non-zero if any check fails.     Run:  python3 guide-build/tools/check_2_3.py"""
import pathlib, sys
import numpy as np
from scipy import integrate, special, stats
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

ok = True
def check(name, got, want, tol=1e-6):
    global ok
    good = abs(got - want) <= tol * max(1.0, abs(want))
    ok &= bool(good)
    print(f"{'PASS' if good else 'FAIL'}  {name}: got {got:.8g}, want {want:.8g}")
def info(s): print("INFO  " + s)
rng = np.random.default_rng(2023)

# ---------------------------------------------------------------------------------------------------
# sections 1-4 and D1, D2: the quadratic chi2, V = 2 H^-1, Delta chi2 = 1, eigenvector sets, tolerance
# ---------------------------------------------------------------------------------------------------
p = 5
A = rng.standard_normal((p, p)); H = A @ A.T + 0.3 * np.eye(p)          # a positive-definite Hessian of chi2
V = 2 * np.linalg.inv(H)
g = rng.standard_normal(p)                                              # gradient of an observable
dchi2 = lambda d: 0.5 * d @ H @ d                                       # eq. (2.3.4)

# eq. (2.3.6): the Gaussian exp(-chi2/2) has covariance 2 H^-1 (two parameters, direct integration)
H2 = np.array([[3.0, 1.1], [1.1, 0.9]]); V2 = 2 * np.linalg.inv(H2)
w2 = lambda a, b: np.exp(-0.25 * (H2[0, 0]*a*a + 2*H2[0, 1]*a*b + H2[1, 1]*b*b))
norm = integrate.dblquad(lambda b, a: w2(a, b), -30, 30, -30, 30)[0]
for (i, j) in ((0, 0), (0, 1), (1, 1)):
    m = integrate.dblquad(lambda b, a: w2(a, b) * (a, b)[i] * (a, b)[j], -30, 30, -30, 30)[0] / norm
    check(f"covariance of exp(-chi2/2), element {i}{j}, equals (2 H^-1)_{i}{j}", m, V2[i, j], 1e-6)

# D1: the smallest Delta chi2 that moves a linear observable by dO is dO^2 / (g V g)
dO = 0.7
dstar = V @ g * dO / (g @ V @ g)
check("D1: the constrained minimiser moves O by dO", g @ dstar, dO)
check("D1: Delta chi2 at the constrained minimum = dO^2/(g V g)", dchi2(dstar), dO**2 / (g @ V @ g))
worst = min(dchi2(dstar + (np.eye(p) - np.outer(g, g) / (g @ g)) @ rng.standard_normal(p) * 0.3) for _ in range(200))
check("D1: every other point with the same dO has larger Delta chi2", float(worst > dchi2(dstar)), 1.0)
check("Delta chi2 = 1 for one observable is 68.27%", special.erf(1 / np.sqrt(2)), 0.682689, 1e-6)
check("Delta chi2 = 2.71 for one observable is 90%", stats.chi2.cdf(2.706, 1), 0.90, 1e-4)
check("joint 68.27% region of two parameters: Delta chi2 = 2.30", stats.chi2.ppf(0.682689, 2), 2.2957, 1e-4)
info(f"joint 68.27% region of 52 parameters: Delta chi2 = {stats.chi2.ppf(0.682689, 52):.1f}")

# eq. (2.3.7)-(2.3.10): eigen-coordinates, eigenvector sets, master formulas
lam, v = np.linalg.eigh(H)
d = rng.standard_normal(p) * 0.4
z = np.sqrt(lam / 2) * (v.T @ d)
check("eq. (2.3.7): Delta chi2 = sum z_k^2", z @ z, dchi2(d))
for T in (1.0, 3.0, 10.0):
    Sp = [T * np.sqrt(2 / lam[k]) * v[:, k] for k in range(p)]          # displacement of set S_k^+; S_k^- is minus this
    check(f"eq. (2.3.8): each set has Delta chi2 = T^2 (T={T:g})", dchi2(Sp[2]), T * T)
    sym = 0.5 * np.sqrt(sum((g @ s - g @ (-s))**2 for s in Sp))
    check(f"eq. (2.3.9): symmetric master formula = T sqrt(g V g) (T={T:g})", sym, T * np.sqrt(g @ V @ g))
# a curved observable: the asymmetric formula (2.3.10) against the exact maximum and minimum on the Delta chi2 = 1 surface
Q = rng.standard_normal((p, p)); Q = 0.02 * (Q + Q.T)
obs = lambda d: g @ d + d @ Q @ d
Sp = [np.sqrt(2 / lam[k]) * v[:, k] for k in range(p)]
up = np.sqrt(sum(max(obs(s), obs(-s), 0)**2 for s in Sp)); dn = np.sqrt(sum(max(-obs(s), -obs(-s), 0)**2 for s in Sp))
u = rng.standard_normal((400000, p)); u /= np.linalg.norm(u, axis=1)[:, None]
pts = (u * np.sqrt(2 / lam)) @ v.T                                      # points on the surface Delta chi2 = 1
vals = pts @ g + np.einsum("ni,ij,nj->n", pts, Q, pts)
info(f"curved observable: asymmetric master formula +{up:.4f} -{dn:.4f}; exact extremes on Delta chi2 = 1: +{vals.max():.4f} {vals.min():.4f}")
check("eq. (2.3.10): upper error within 3% of the exact extreme for a mildly curved observable", up, vals.max(), 0.03)
check("eq. (2.3.10): lower error within 3% of the exact extreme", dn, -vals.min(), 0.03)

# section 4: N measurements of one quantity whose true errors are s times the quoted ones
N, s, sig = 20, 2.0, 1.0
dat = s * sig * rng.standard_normal((200000, N))
mean = dat.mean(1); c2 = ((dat - mean[:, None])**2).sum(1) / sig**2
check("eq. (2.3.12): spread of the fitted value / Hessian error = s", mean.std() / (sig / np.sqrt(N)), s, 0.01)
check("eq. (2.3.12): <chi2_min>/(N-1) = s^2", c2.mean() / (N - 1), s * s, 0.01)

# ---------------------------------------------------------------------------------------------------
# the toy of section 9:  f(x; theta) = theta1 (1-x)^theta2,  theta2 bounded to [0, 10]
# ---------------------------------------------------------------------------------------------------
TH = np.array([1.0, 3.0]); TMAX = 10.0; NPT = 12; REL = 0.10
grid = np.linspace(0, TMAX, 2001)                                       # theta2 grid for the profile and the posterior
ftrue = lambda x: TH[0] * (1 - x)**TH[1]
def design(xmax):
    xs = np.linspace(xmax / NPT, xmax, NPT); return xs, np.log1p(-xs), REL * ftrue(xs)
def fit(D, L, sig):
    """Global bounded least-squares fit of every row of D. theta1 is linear, so chi2 is profiled over theta2 on the grid
    and the minimum refined by a parabola. Returns theta1, theta2, the profile chi2(theta2) and the sums it is built from."""
    B = np.exp(np.outer(grid, L)) / sig; dd = D / sig
    Sbb = (B * B).sum(1); Sbd = dd @ B.T
    prof = (dd * dd).sum(1)[:, None] - Sbd**2 / Sbb
    k = prof.argmin(1); n = np.arange(len(D)); ki = np.clip(k, 1, len(grid) - 2)
    y0, y1, y2 = prof[n, ki - 1], prof[n, ki], prof[n, ki + 1]; den = y0 - 2 * y1 + y2
    off = np.where((k == ki) & (den > 0), np.clip(0.5 * (y0 - y2) / np.where(den > 0, den, 1), -1, 1), 0.0)
    t2 = np.where(k == ki, grid[ki] + off * (grid[1] - grid[0]), grid[k])
    b = np.exp(np.outer(t2, L)) / sig
    t1 = (b * dd).sum(1) / (b * b).sum(1)
    return t1, t2, prof, Sbb, Sbd
def chi2(th, D, L, sig): return (((D - th[0] * np.exp(th[1] * L)) / sig)**2).sum()
def grad(th, D, L, sig):
    b = np.exp(th[1] * L); r = (D - th[0] * b) / sig**2
    return -2 * np.array([(r * b).sum(), (r * th[0] * b * L).sum()])
def hess(th, D, L, sig):
    """Exact Hessian of chi2: the Gauss-Newton term 2 J^T C^-1 J and the residual term of eq. (2.3.5)."""
    b = np.exp(th[1] * L); r = (D - th[0] * b) / sig**2
    J = np.stack([b, th[0] * b * L], 1)
    GN = 2 * (J.T / sig**2) @ J
    return GN - 2 * np.array([[0, (r * b * L).sum()], [(r * b * L).sum(), (r * th[0] * b * L * L).sum()]]), GN
def bayes(prof, Sbb, Sbd, L0):
    """Exact posterior of f(x0) for a flat prior (theta1 unbounded, theta2 in [0, TMAX]): theta1 is integrated analytically,
    leaving a mixture over the theta2 grid of Gaussians in f with weights w, means mu and widths sd."""
    w = np.exp(-(prof - prof.min()) / 2) / np.sqrt(Sbb); w /= w.sum()
    e = np.exp(np.outer(grid, L0)); return w, (Sbd / Sbb)[:, None] * e, e / np.sqrt(Sbb)[:, None]

# eq. (2.3.5): the exact Hessian against central differences of chi2 itself; the residual term vanishes for exact data
xs, L, sig = design(0.6); D = ftrue(xs) + sig * rng.standard_normal(NPT)
t1, t2, *_ = fit(D[None], L, sig); th = np.array([t1[0], t2[0]])
Hx, GN = hess(th, D, L, sig); h = 1e-4; E = np.eye(2)
Hfd = np.array([[(chi2(th + h*E[i] + h*E[j], D, L, sig) - chi2(th + h*E[i] - h*E[j], D, L, sig) - chi2(th - h*E[i] + h*E[j], D, L, sig)
                  + chi2(th - h*E[i] - h*E[j], D, L, sig)) / (4*h*h) for j in range(2)] for i in range(2)])
for (i, j) in ((0, 0), (0, 1), (1, 1)):
    check(f"eq. (2.3.5): analytic Hessian element {i}{j} = finite difference of chi2", Hx[i, j], Hfd[i, j], 1e-5)
check("the fit is at a stationary point: |gradient| ~ 0", np.linalg.norm(grad(th, D, L, sig)) / np.linalg.norm(Hx), 0, 1e-4)
Hx0, GN0 = hess(TH, ftrue(xs), L, sig)
check("eq. (2.3.5): for noise-free data the Hessian is exactly 2 J^T C^-1 J", np.abs(Hx0 - GN0).max(), 0, 1e-12)

# ---------------------------------------------------------------------------------------------------
# section 5 and D3: finite-difference Hessians. A model with one exactly flat direction, at an exact minimum
#   f = exp(theta1) theta3^2 (1-x)^theta2 : only the product exp(theta1) theta3^2 is determined
# ---------------------------------------------------------------------------------------------------
xs5, L5, sig5 = design(0.6); D5 = ftrue(xs5); th5 = np.array([-2 * np.log(0.8), 3.0, 0.8])     # exp(theta1) theta3^2 = 1: chi2 = 0 exactly
def grad3(t):
    T = np.exp(t[0]) * t[2]**2 * np.exp(t[1] * L5); r = (D5 - T) / sig5**2
    return -2 * np.array([(r * T).sum(), (r * T * L5).sum(), (r * 2 * T / t[2]).sum()])
T5 = ftrue(xs5); J3 = np.stack([T5, T5 * L5, 2 * T5 / th5[2]], 1)
H3 = 2 * (J3.T / sig5**2) @ J3
ev3 = np.linalg.eigvalsh(H3)
check("exactly flat direction: smallest exact eigenvalue / largest = 0", ev3[0] / ev3[-1], 0, 1e-12)
flat = np.array([1.0, 0, -th5[2] / 2]); flat /= np.linalg.norm(flat)
check("the flat direction is (1, 0, -theta3/2): H v = 0", np.linalg.norm(H3 @ flat) / ev3[-1], 0, 1e-12)
def fd(hh, kind):
    M = np.zeros((3, 3))
    for j in range(3):
        e = np.zeros(3); e[j] = hh
        M[:, j] = (grad3(th5 + e) - grad3(th5)) / hh if kind == "forward" else (grad3(th5 + e) - grad3(th5 - e)) / (2 * hh)
    return np.linalg.eigvalsh(0.5 * (M + M.T))
steps = np.logspace(-9, -1, 33)
lf = np.array([fd(hh, "forward")[0] for hh in steps]); lc = np.array([fd(hh, "central")[0] for hh in steps])
i3, i4 = np.argmin(abs(steps - 1e-3)), np.argmin(abs(steps - 1e-4))
info(f"smallest eigenvalue (exact 0, largest {ev3[-1]:.4g}): forward h=1e-3 {lf[i3]:+.4g}, h=1e-4 {lf[i4]:+.4g}; "
     f"central h=1e-3 {lc[i3]:+.4g}, h=1e-4 {lc[i4]:+.4g}")
check("forward differences: a spurious NEGATIVE smallest eigenvalue at every step from 1e-7 to 1e-2", float(np.all(lf[(steps > 0.9e-7) & (steps < 1.1e-2)] < 0)), 1.0)
check("forward differences: the spurious eigenvalue is proportional to h (ratio for a decade = 10)", lf[i3] / lf[i4], 10, 0.02)
i2 = np.argmin(abs(steps - 1e-2))
check("central differences: the error is proportional to h^2 (ratio for a decade = 100)", abs(lc[i2] / lc[i3]), 100, 0.05)
info(f"   central h=1e-2 {lc[i2]:+.4g}; forward h=1e-2 {lf[i2]:+.4g}; forward h=1e-6 {lf[np.argmin(abs(steps - 1e-6))]:+.4g}")
check("central differences at h=1e-4: |error| / forward |error| < 1e-3", float(abs(lc[i4]) < 1e-3 * abs(lf[i4])), 1.0)
# first-order perturbation theory for the forward-difference shift, eq. (2.3.15):  v^T dH v  with dH_ij = (h/2) d_j d_j g_i
def third(j, hh=1e-3):
    e = np.zeros(3); e[j] = hh; return (grad3(th5 + e) - 2 * grad3(th5) + grad3(th5 - e)) / hh**2
dH = np.stack([0.5 * third(j) for j in range(3)], 1); dH = 0.5 * (dH + dH.T)
check("eq. (2.3.15): forward-difference shift of the zero eigenvalue = h v^T dH v", lf[i4] / steps[i4], flat @ dH @ flat, 0.01)
# one-dimensional truncation coefficients, eq. (2.3.14)
fn, f2, f3 = np.sin, lambda t: -np.sin(t), lambda t: -np.cos(t); t0, hh = 0.7, 1e-3
check("eq. (2.3.14): forward-difference error = (h/2) g''", (fn(t0 + hh) - fn(t0)) / hh - np.cos(t0), hh / 2 * f2(t0), 1e-3)
check("eq. (2.3.14): central-difference error = (h^2/6) g'''", ((fn(t0 + hh) - fn(t0 - hh)) / (2 * hh) - np.cos(t0)) * 1e6, hh**2 / 6 * f3(t0) * 1e6, 1e-3)
# conditioning, eq. (2.3.13): relative error of the inverse <= kappa x relative error of H (to first order)
kap = 1e6; Hk = np.diag([1.0, 1 / kap]); P = rng.standard_normal((2, 2)); P = 0.5 * (P + P.T); eps = 1e-9
dV = np.linalg.inv(Hk + eps * P) - np.linalg.inv(Hk)
amp = (np.linalg.norm(dV, 2) / np.linalg.norm(np.linalg.inv(Hk), 2)) / (eps * np.linalg.norm(P, 2) / np.linalg.norm(Hk, 2))
info(f"condition number {kap:g}: a relative error {eps:g} in H became a relative error {amp * eps:.3g} in the inverse (amplification {amp:.3g})")
check("eq. (2.3.13): amplification of the relative error is at most the condition number", float(amp <= kap * 1.001), 1.0)
check("eq. (2.3.13): and reaches a fair fraction of it for a generic perturbation", float(amp > 0.01 * kap), 1.0)

# ---------------------------------------------------------------------------------------------------
# section 6 and D4: the linear-Gaussian theorem
# ---------------------------------------------------------------------------------------------------
Nl, pl = 30, 4
X = rng.standard_normal((Nl, pl)); Bm = rng.standard_normal((Nl, Nl)); C = Bm @ Bm.T / Nl + 0.5 * np.eye(Nl); Ci = np.linalg.inv(C)
F = X.T @ Ci @ X; Fi = np.linalg.inv(F); Am = Fi @ X.T @ Ci
check("D4: A C A^T = F^-1 (replica covariance, exact matrix identity)", np.abs(Am @ C @ Am.T - Fi).max(), 0, 1e-12)
check("D4: Hessian of the linear chi2 is 2F, so 2 H^-1 = F^-1", np.abs(2 * np.linalg.inv(2 * F) - Fi).max(), 0, 1e-12)
thtrue = rng.standard_normal(pl); Lc = np.linalg.cholesky(C)
D0 = X @ thtrue + Lc @ rng.standard_normal(Nl); that = Am @ D0
reps = (D0 + (Lc @ rng.standard_normal((Nl, 200000))).T) @ Am.T
check("D4: replica mean = fit to the central data", np.abs(reps.mean(0) - that).max(), 0, 0.01)
check("D4: replica sample covariance = F^-1 (200,000 replicas)", np.abs(np.cov(reps.T) - Fi).max() / np.abs(Fi).max(), 0, 0.02)
# eq. (2.3.17): the N_rep - 1 divisor is unbiased; relative error of sigma is 1/sqrt(2(N_rep - 1)).
# (separate generator, so the random stream of the rest of the script is unchanged)
_r17 = np.random.default_rng(31).standard_normal((40000, 100)) * 1.7
check("eq. (2.3.17): variance with divisor N_rep - 1 is unbiased (100 replicas)", _r17.var(1, ddof=1).mean() / 1.7**2, 1.0, 2e-3)
check("eq. (2.3.17): divisor N_rep is low by (N_rep - 1)/N_rep", _r17.var(1).mean() / 1.7**2, 0.99, 2e-3)
check("relative error of sigma from 100 replicas = 1/sqrt(2*99) = 7.1%", _r17.std(1, ddof=1).std() / 1.7, 1 / np.sqrt(198), 0.02)
# the posterior with a flat prior: exponent identity  chi2(theta) = chi2_min + (theta - that)^T F (theta - that)
tt = rng.standard_normal(pl); c2 = lambda t: (D0 - X @ t) @ Ci @ (D0 - X @ t)
check("D4: chi2(theta) - chi2_min = (theta - theta_hat)^T F (theta - theta_hat)", c2(tt) - c2(that), (tt - that) @ F @ (tt - that), 1e-9)
# two layers of noise: replicas scatter about the TRUTH with covariance 2 F^-1
data = X @ thtrue + (Lc @ rng.standard_normal((Nl, 200000))).T
rep1 = (data + (Lc @ rng.standard_normal((Nl, 200000))).T) @ Am.T
check("eq. (2.3.19): one replica per independent data set scatters about the truth with covariance 2 F^-1",
      np.abs(np.cov(rep1.T) - 2 * Fi).max() / np.abs(Fi).max(), 0, 0.03)
# closure expectations (section 10): chi2_min of a level-1 fit, and of a replica fit
P_ = X @ Am; res = data - data @ P_.T
c2l1 = np.einsum("ni,ij,nj->n", res, Ci, res)
check("eq. (2.3.29): <chi2_min> of a level-1 fit = N - p", c2l1.mean(), Nl - pl, 0.01)
check("eq. (2.3.29): its variance = 2(N - p)", c2l1.var(), 2 * (Nl - pl), 0.03)
check("trace of the projector X F^-1 X^T C^-1 = p", np.trace(P_), pl, 1e-9)
# coverage of a linear observable by the one-sigma band, and its binomial error
gl = rng.standard_normal(pl); sO = np.sqrt(gl @ Fi @ gl)
covd = np.mean(np.abs((data @ Am.T - thtrue) @ gl) < sO)
check("coverage of the one-sigma band in the linear-Gaussian case = 68.27%", covd, 0.682689, 0.005)
check("eq. (2.3.30): binomial error on a coverage measured on 52 independent trials", np.sqrt(0.682689 * 0.317311 / 52), 0.0645, 2e-3)
info(f"75.0% on 52 trials sits {(0.750 - 0.6827) / np.sqrt(0.682689 * 0.317311 / 52):.2f} binomial standard deviations above 68.27%")

# ---------------------------------------------------------------------------------------------------
# D5: beyond the linear case. An invertible model: the replica density is likelihood x |dT/dtheta|
#     T(theta) = exp(theta), one datum D = 1 with error s
# ---------------------------------------------------------------------------------------------------
s1 = 0.15
like = lambda t: np.exp(-(np.exp(t) - 1)**2 / (2 * s1 * s1))
qd = lambda f: integrate.quad(f, -3, 2, epsabs=1e-13, epsrel=1e-12, limit=400, points=[0])[0]
m_rep = qd(lambda t: t * like(t) * np.exp(t)) / qd(lambda t: like(t) * np.exp(t))
m_post = qd(lambda t: t * like(t)) / qd(like)
samp = np.log(1 + s1 * rng.standard_normal(4000000))
check("eq. (2.3.20): mean of ln(D_k) = mean of the density L(theta) |dT/dtheta|", samp.mean(), m_rep, 2e-4)
check("eq. (2.3.20): its variance too", samp.var(), qd(lambda t: t * t * like(t) * np.exp(t)) / qd(lambda t: like(t) * np.exp(t)) - m_rep**2, 2e-3)
check("replica mean shift = -s^2/2 to leading order", m_rep, -s1**2 / 2, 2e-3)
check("flat-prior posterior mean shift = -3 s^2/2 to leading order", m_post, -1.5 * s1**2, 4e-3)
info(f"T = exp(theta), s = {s1}: replica mean {m_rep:+.5f}, flat-prior posterior mean {m_post:+.5f}, Hessian centre 0, common width ~ {s1}")
info(f"   difference of the two means in units of the width: {(m_rep - m_post) / s1:.3f}")

# eq. (2.3.21): gradient descent stopped after time t, linear model in the eigenbasis of H
lamk = np.array([40.0, 0.05]); eta, nstep, s0, nrep = 1e-3, 2000, 0.7, 400000
astar = np.sqrt(2 / lamk) * rng.standard_normal((nrep, 2))             # each replica's own minimum, about the central fit
a = s0 * rng.standard_normal((nrep, 2))                                # initial values, independent of the data
for _ in range(nstep): a -= eta * lamk * (a - astar)                   # d(chi2)/da_k = lam_k (a_k - a*_k)
tt_ = eta * nstep
for k in range(2):
    want = (1 - np.exp(-lamk[k] * tt_))**2 * 2 / lamk[k] + np.exp(-2 * lamk[k] * tt_) * s0**2
    check(f"eq. (2.3.21): variance of stopped replicas, eigenvalue {lamk[k]:g} (Hessian value {2 / lamk[k]:g})", a[:, k].var(), want, 0.01)
info(f"   flat direction: stopped-replica variance {a[:, 1].var():.3f}, initial variance {s0**2:.3f}, Hessian variance {2 / lamk[1]:.0f}")

# section 8: on a direction the data cannot see, the posterior is the prior. T depends on u = theta1 + theta2 only
Lw = 2.0
post = lambda w_, u_: np.exp(-0.5 * ((1.3 - u_) / 0.2)**2)             # likelihood: independent of w
nrm = integrate.dblquad(post, 0, 3, -Lw, Lw)[0]
check("eq. (2.3.26): posterior variance along a null direction = prior variance L^2/3",
      integrate.dblquad(lambda w_, u_: post(w_, u_) * w_ * w_, 0, 3, -Lw, Lw)[0] / nrm, Lw**2 / 3, 1e-8)

# ---------------------------------------------------------------------------------------------------
# section 7: effective sample size and R-hat
# ---------------------------------------------------------------------------------------------------
rho, n = 0.9, 400000
from scipy.signal import lfilter
n = 4000000; xch = lfilter([1.0], [1.0, -rho], rng.standard_normal(n) * np.sqrt(1 - rho**2))
xc = xch - xch.mean(); ac = [1.0] + [float((xc[:-t] * xc[t:]).mean() / xc.var()) for t in range(1, 120)]
tau = 1 + 2 * sum(ac[1:])
check("eq. (2.3.23): integrated autocorrelation time of an AR(1) chain = (1+rho)/(1-rho)", tau, (1 + rho) / (1 - rho), 0.04)
bm = xch[: n - n % 2000].reshape(-1, 2000).mean(1)
check("eq. (2.3.23): variance of the mean of n correlated draws = sigma^2 tau / n", bm.var() * 2000, (1 + rho) / (1 - rho), 0.12)
info(f"   AR(1) with rho = {rho}: tau = {tau:.1f}, so {n} draws are worth {n / tau:.0f} independent ones")
def rhat(ch):
    m, nn = ch.shape; W = ch.var(1, ddof=1).mean(); Bn = ch.mean(1).var(ddof=1)
    return np.sqrt(((nn - 1) / nn * W + Bn) / W)
ch = rng.standard_normal((4, 5000))
check("eq. (2.3.24): R-hat = 1 for chains that sample the same distribution", rhat(ch), 1.0, 2e-3)
off = np.array([-0.6, -0.2, 0.2, 0.6])
check("eq. (2.3.24): R-hat for chains stuck at different means = sqrt(1 + var(means)/W)", rhat(ch + off[:, None]), np.sqrt(1 + off.var(ddof=1)), 0.01)
info(f"   R-hat = 1.1185 means the chain means scatter by {np.sqrt(1.1185**2 - 1):.2f} within-chain standard deviations; 1.05 allows {np.sqrt(1.05**2 - 1):.2f}")

# ---------------------------------------------------------------------------------------------------
# section 9: the ladder from a constrained to a nearly flat exponent, three methods, with closure coverage (section 10)
# ---------------------------------------------------------------------------------------------------
X0 = 0.5; L0 = np.array([np.log1p(-X0)]); F0 = ftrue(X0)
NTRIAL, NREP = 3000, 200
LADDER = (0.6, 0.12, 0.03, 0.015)
rows = []
for xmax in LADDER:
    xs, L, sig = design(xmax); T0 = ftrue(xs)
    Jt = np.stack([np.exp(TH[1] * L), TH[0] * np.exp(TH[1] * L) * L], 1); Ft = (Jt.T / sig**2) @ Jt; evF = np.linalg.eigvalsh(Ft)
    s2 = np.sqrt(np.linalg.inv(Ft)[1, 1])
    cov = np.zeros(3); W = [[], [], []]; nob = 0; atb = 0.0; cb = 0
    for t in range(NTRIAL):
        D = T0 + sig * rng.standard_normal(NPT)
        t1, t2, prof, Sbb, Sbd = fit(D[None], L, sig); th = np.array([t1[0], t2[0]]); cb += (th[1] <= 0) or (th[1] >= TMAX)
        Hx, _ = hess(th, D, L, sig); b0 = np.exp(th[1] * L0[0]); gg = np.array([b0, th[0] * b0 * L0[0]])
        if np.linalg.eigvalsh(Hx)[0] <= 0: nob += 1; sH = np.inf                 # no band: counted as covering, excluded from the width
        else: sH = np.sqrt(gg @ (2 * np.linalg.inv(Hx)) @ gg); W[0].append(sH)
        cov[0] += abs(th[0] * b0 - F0) < sH
        k1, k2, *_ = fit(D + sig * rng.standard_normal((NREP, NPT)), L, sig); fk = k1 * np.exp(k2 * L0[0])
        atb += np.mean((k2 <= 0) | (k2 >= TMAX)); sM = fk.std(ddof=1); W[1].append(sM)
        cov[1] += abs(fk.mean() - F0) < sM
        w, mu, sd = bayes(prof[0], Sbb, Sbd[0], L0)
        Pt = (w * special.ndtr((F0 - mu[:, 0]) / sd[:, 0])).sum(); cov[2] += 0.158655 < Pt < 0.841345
        m = (w * mu[:, 0]).sum(); W[2].append(np.sqrt((w * (sd[:, 0]**2 + mu[:, 0]**2)).sum() - m * m))
    med = [float(np.median(w_)) / F0 for w_ in W]
    rng_ = [np.percentile(w_, [10, 90]) / F0 for w_ in W]
    rows.append((xmax, s2, evF[-1] / evF[0], med, cov / NTRIAL, nob / NTRIAL, cb / NTRIAL, atb / NTRIAL))
    info(f"x_max={xmax:<5g} sigma(theta2)={s2:6.3f} condition={evF[-1]/evF[0]:9.3g} | median width/f at x=0.5: Hessian {med[0]:7.3f} MC {med[1]:6.3f} "
         f"Bayes {med[2]:6.3f} | coverage H {cov[0]/NTRIAL:.3f} MC {cov[1]/NTRIAL:.3f} B {cov[2]/NTRIAL:.3f} | "
         f"Hessian not positive {nob/NTRIAL:.3f}, best fit at a bound {cb/NTRIAL:.3f}, replicas at a bound {atb/NTRIAL:.3f}")
    info("      10%-90% range of the width over data sets: " + "; ".join(f"{nm} {a:.3g} to {b:.3g}" for nm, (a, b) in zip(("Hessian", "MC", "Bayes"), rng_)))
se = np.sqrt(0.6827 * 0.3173 / NTRIAL)
r0 = rows[0]
check("constrained rung: Hessian and Monte Carlo widths agree", r0[3][1] / r0[3][0], 1, 0.03)
check("constrained rung: Hessian and Bayesian widths agree", r0[3][2] / r0[3][0], 1, 0.03)
for nm, c in zip(("Hessian", "Monte Carlo", "Bayesian"), r0[4]):
    check(f"constrained rung: {nm} coverage = 68.3% within 3.5 binomial errors", c, 0.6827, 3.5 * se)
check("flattest rung: the three widths are ordered Hessian > Monte Carlo > Bayesian", float(rows[-1][3][0] > rows[-1][3][1] > rows[-1][3][2]), 1.0)
check("flattest rung: Hessian width / Bayesian width > 2", float(rows[-1][3][0] / rows[-1][3][2] > 2), 1.0)
check("flattest rung: the Bayesian width is the prior-only width within 5%", rows[-1][3][2], ((1 - X0)**np.linspace(0, TMAX, 200001)).std() / F0, 0.05)
# the prior-only band at x = 0.5: theta1 fixed by the data to ~1, theta2 uniform on [0, 10]
u = np.linspace(0, TMAX, 200001); fpr = (1 - X0)**u
info(f"prior-only spread of (1-x)^theta2 at x=0.5 for theta2 uniform on [0,10], in units of the true f: {fpr.std() / F0:.3f}")

# ---------------------------------------------------------------------------------------------------
# plots
# ---------------------------------------------------------------------------------------------------
TEAL, ORANGE, INK, GRID, MUTED = "#0e7c7b", "#d96c2c", "#16222e", "#ebe6da", "#6b7280"
plt.rcParams.update({"font.size": 14, "axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK,
                     "text.color": INK, "axes.grid": True, "grid.color": GRID, "figure.facecolor": "white", "axes.facecolor": "white",
                     "savefig.facecolor": "white", "svg.fonttype": "none", "font.family": "sans-serif", "legend.frameon": False})
out = pathlib.Path(__file__).resolve().parents[2] / "assets" / "guide"; out.mkdir(parents=True, exist_ok=True)

# figure: error of the smallest eigenvalue against the step
fig, ax = plt.subplots(figsize=(8, 4.6))
ax.loglog(steps, np.abs(lf) / ev3[-1], "o-", color=ORANGE, ms=4, label="forward differences (eigenvalue negative)")
ax.loglog(steps, np.maximum(np.abs(lc) / ev3[-1], 1e-18), "s-", color=TEAL, ms=4, label="central differences")
ax.loglog(steps[18:], 2e-1 * steps[18:], ":", color=INK, lw=1.2); ax.text(2e-5, 1.5e-4, "slope 1", fontsize=13)
ax.loglog(steps[18:], 3e-2 * steps[18:]**2, ":", color=INK, lw=1.2); ax.text(1.5e-2, 1.2e-6, "slope 2", fontsize=13)
ax.set_xlabel("finite-difference step h"); ax.set_ylabel("|smallest eigenvalue| / largest")
ax.set_ylim(1e-17, 1); ax.legend(loc="upper left", fontsize=13)
ax.text(0.98, 0.05, "exact value: 0", transform=ax.transAxes, ha="right", fontsize=13, color=MUTED)
fig.tight_layout(); fig.savefig(out / "2-3-findiff.svg"); plt.close(fig)

# one data set on the flat rung x_max = 0.03, chosen (by seed) to have its best fit inside the bounds
def one(xmax, seed):
    r = np.random.default_rng(seed); xs, L, sig = design(xmax); D = ftrue(xs) + sig * r.standard_normal(NPT)
    t1, t2, prof, Sbb, Sbd = fit(D[None], L, sig); th = np.array([t1[0], t2[0]])
    Hx, _ = hess(th, D, L, sig); k1, k2, *_ = fit(D + sig * r.standard_normal((400, NPT)), L, sig)
    return dict(xs=xs, L=L, sig=sig, D=D, th=th, H=Hx, k1=k1, k2=k2, prof=prof[0], Sbb=Sbb, Sbd=Sbd[0])
seed = next(sd_ for sd_ in range(7, 200) if 2.0 < one(0.03, sd_)["th"][1] < 5.0 and np.linalg.eigvalsh(one(0.03, sd_)["H"])[0] > 0)
flatd, cons = one(0.03, seed), one(0.6, seed)
info(f"figure data set (seed {seed}), x_max=0.03: best fit theta = ({flatd['th'][0]:.3f}, {flatd['th'][1]:.2f}); Hessian sigma(theta2) = "
     f"{np.sqrt(2 * np.linalg.inv(flatd['H'])[1, 1]):.2f}; replicas at a bound {np.mean((flatd['k2'] <= 0) | (flatd['k2'] >= TMAX)):.2f}; "
     f"replica std of theta2 {flatd['k2'].std():.2f}")
wpost = np.exp(-(flatd["prof"] - flatd["prof"].min()) / 2) / np.sqrt(flatd["Sbb"]); wpost /= wpost.sum()
mpost = (wpost * grid).sum(); spost = np.sqrt((wpost * grid**2).sum() - mpost**2)
info(f"   posterior of theta2: mean {mpost:.2f}, std {spost:.2f}; prior std {TMAX / np.sqrt(12):.2f}")

# figure: the parameter plane
fig, ax = plt.subplots(figsize=(8, 4.8))
a1 = np.linspace(0.8, 1.35, 331); A1, A2 = np.meshgrid(a1, grid[::5])
c2g = (((flatd["D"][None, None] - A1[..., None] * np.exp(A2[..., None] * flatd["L"])) / flatd["sig"])**2).sum(-1)
pg = np.exp(-(c2g - c2g.min()) / 2); srt = np.sort(pg.ravel())[::-1]; cum = np.cumsum(srt) / srt.sum()
lev = [srt[np.searchsorted(cum, q)] for q in (0.9545, 0.6827)]
ax.contourf(A1, A2, pg, levels=lev + [pg.max() * 1.01], colors=["#cfe6e5", "#8fc4c2"])
ax.plot(flatd["k1"], flatd["k2"], ".", color=ORANGE, ms=4.5, alpha=0.75, zorder=3)
ang = np.linspace(0, 2 * np.pi, 400); lamH, vH = np.linalg.eigh(flatd["H"])
ell = flatd["th"][:, None] + (vH * np.sqrt(2 / lamH)) @ np.array([np.cos(ang), np.sin(ang)])
ax.plot(ell[0], ell[1], "--", color=INK, lw=1.8, zorder=4)
ax.plot(*flatd["th"], "+", color=INK, ms=13, mew=2, zorder=5); ax.plot(*TH, "*", color="white", mec=INK, ms=15, zorder=5)
for yb in (0, TMAX): ax.axhline(yb, color=MUTED, lw=1.3)
ax.set_xlim(0.8, 1.35); ax.set_ylim(-4.5, 15.5); ax.set_xlabel("normalisation θ₁"); ax.set_ylabel("exponent θ₂")
ax.text(1.345, 10.5, "prior bound", ha="right", color=MUTED, fontsize=13); ax.text(1.345, -1.5, "prior bound", ha="right", color=MUTED, fontsize=13)
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
ax.legend(handles=[Patch(color="#8fc4c2", label="posterior, 68% and 95%"), Line2D([], [], ls="", marker=".", color=ORANGE, label="replica fits"),
                   Line2D([], [], ls="--", color=INK, label="Hessian, Δχ² = 1"), Line2D([], [], ls="", marker="*", mfc="white", mec=INK, ms=13, label="truth")],
          loc="upper left", fontsize=13, ncol=2, columnspacing=1.2, handletextpad=0.5)
fig.tight_layout(); fig.savefig(out / "2-3-plane.svg"); plt.close(fig)

# figure: the three bands on f(x)/f_true(x), constrained and flat
xx = np.linspace(0.0, 0.8, 81); Lx = np.log1p(-xx); ft = ftrue(xx)
fig, axs = plt.subplots(1, 2, figsize=(8, 4.4))
for ax, d_, ttl, yl in ((axs[0], cons, "data up to x = 0.6", (0.78, 1.36)), (axs[1], flatd, "data up to x = 0.03", (-1.5, 5.5))):
    w, mu, sd = bayes(d_["prof"], d_["Sbb"], d_["Sbd"], Lx)
    lo, hi = [], []
    for j in range(len(xx)):                                             # 16% and 84% points of the mixture, by bisection on its CDF
        fs = np.linspace((mu[:, j] - 6 * sd[:, j]).min(), (mu[:, j] + 6 * sd[:, j]).max(), 4000)
        cdf = (w[:, None] * special.ndtr((fs[None] - mu[:, j:j+1]) / sd[:, j:j+1])).sum(0)
        lo.append(np.interp(0.158655, cdf, fs)); hi.append(np.interp(0.841345, cdf, fs))
    ax.fill_between(xx, np.array(lo) / ft, np.array(hi) / ft, color="#8fc4c2", label="Bayesian, 68%")
    fk = d_["k1"][:, None] * np.exp(np.outer(d_["k2"], Lx)); mM, sM = fk.mean(0), fk.std(0, ddof=1)
    for sgn, lab in ((1, "Monte Carlo, mean ± σ"), (-1, None)): ax.plot(xx, (mM + sgn * sM) / ft, color=ORANGE, lw=2.2, label=lab)
    b0 = np.exp(d_["th"][1] * Lx); G = np.stack([b0, d_["th"][0] * b0 * Lx]); sH = np.sqrt(np.einsum("ax,ab,bx->x", G, 2 * np.linalg.inv(d_["H"]), G))
    for sgn, lab in ((1, "Hessian, Δχ² = 1"), (-1, None)): ax.plot(xx, (d_["th"][0] * b0 + sgn * sH) / ft, "--", color=INK, lw=1.8, label=lab)
    ax.axhline(1, color=MUTED, lw=1); ax.axvspan(d_["xs"][0], d_["xs"][-1], color="#f3efe4", zorder=0)
    ax.set_ylim(*yl); ax.set_xlim(0, 0.8); ax.set_xlabel("x"); ax.set_title(ttl, fontsize=14)
axs[0].set_ylabel("fitted f / true f"); axs[0].legend(loc="upper center", fontsize=13)
fig.tight_layout(); fig.savefig(out / "2-3-bands.svg"); plt.close(fig)

print("wrote 2-3-findiff.svg, 2-3-plane.svg, 2-3-bands.svg;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
