#!/usr/bin/env python3
"""Numerical checks for guide chapter 2.4 (the global fits: MSHT, CT and NNPDF), and its three data plots.
Every formula and every toy number the chapter states is tested or produced here; exits non-zero on any failure.
Run:  python3 guide-build/tools/check_2_4.py     (writes assets/guide/2-4-*.svg)
All toys are illustrative: none of the numbers below is a measurement or a value from a published fit."""
import pathlib, sys
import numpy as np
from scipy import optimize, stats
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

SITE = pathlib.Path(__file__).resolve().parents[2]
OUT = SITE / "assets" / "guide"; OUT.mkdir(parents=True, exist_ok=True)
TEAL, ORANGE, INK, GRID, MUTED = "#0e7c7b", "#d96c2c", "#16222e", "#ebe6da", "#6b7785"
plt.rcParams.update({"font.size": 14, "axes.labelsize": 14, "xtick.labelsize": 13, "ytick.labelsize": 13,
                     "legend.fontsize": 13, "axes.edgecolor": INK, "axes.labelcolor": INK, "text.color": INK,
                     "xtick.color": INK, "ytick.color": INK, "svg.fonttype": "path", "font.family": "sans-serif"})
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:.10g}, want {want:.10g}")
def note(s): print("      " + s)

# =====================================================================================================
# 1. chi^2 percentiles: hypothesis-testing limits (eqs 2.4.6-2.4.8, derivation D2)
# =====================================================================================================
z68, z90 = stats.norm.ppf(0.68), stats.norm.ppf(0.90)
check("Phi^-1(0.68)", z68, 0.4677, 2e-4); check("Phi^-1(0.90)", z90, 1.2816, 1e-4)
check("two-sided 90% of a Gaussian = 1.645 sigma", stats.norm.ppf(0.95), 1.645, 1e-3)
check("Delta chi^2 = 2.71 at 90% for one parameter", stats.chi2.ppf(0.90, 1), 1.645**2, 2e-3)
for N in (100, 500, 2000):
    x50, x68, x90 = (stats.chi2.ppf(p, N) for p in (0.50, 0.68, 0.90))
    wh = lambda u: N*(1 - 2/(9*N) + u*np.sqrt(2/(9*N)))**3            # Wilson-Hilferty
    check(f"N={N}: median ~ N - 2/3", x50, N - 2/3, 1e-3)
    check(f"N={N}: Wilson-Hilferty xi68", wh(z68), x68, 1e-4)
    check(f"N={N}: xi68 - xi50 ~ 0.468 sqrt(2N)", x68 - x50, z68*np.sqrt(2*N), 0.06)
    check(f"N={N}: xi90 - xi50 ~ 1.282 sqrt(2N)", x90 - x50, z90*np.sqrt(2*N), 0.06)
    note(f"N={N}: xi50={x50:.2f} xi68={x68:.2f} xi90={x90:.2f};  single-set tolerance T68={np.sqrt(x68-x50):.2f}  T90={np.sqrt(x90-x50):.2f}")
x50, x68, x90 = (stats.chi2.ppf(p, 100) for p in (0.50, 0.68, 0.90))
check("N=100: xi50", x50, 99.33, 1e-4); check("N=100: xi68", x68, 106.0, 2e-3); check("N=100: xi90", x90, 118.5, 1e-3)
check("N=100: T68 (single consistent set)", np.sqrt(x68 - x50), 2.6, 0.02)
check("N=100: T90 (single consistent set)", np.sqrt(x90 - x50), 4.4, 0.02)
# error-inflation reading of a tolerance (eq 2.4.11)
# MSTW08 (arXiv:0901.0002, section 6.2) quotes xi_50 = 162.3 for a data set of N = 163 points and calls it "the most
# probable value". The number is the median (50th percentile) of the chi^2 distribution, not its mode N - 2.
check("xi_50 for N=163 is the median, 162.3 (the value MSTW08 quotes)", stats.chi2.ppf(0.50, 163), 162.3, 3e-4)
check("  the mode of that distribution is N - 2 = 161, a different number", 163 - 2, 161, 0)
check("  median of chi^2_N is close to N - 2/3", stats.chi2.ppf(0.50, 163), 163 - 2/3, 1e-4)
check("T=10 at 90% CL = errors x 6.1", 10/stats.norm.ppf(0.95), 6.08, 2e-3)
check("T=sqrt(50) at 90% CL = errors x 4.3", np.sqrt(50)/stats.norm.ppf(0.95), 4.30, 2e-3)

# =====================================================================================================
# 2. Dynamic tolerance toy: four data sets along one eigenvector (eqs 2.4.3-2.4.9, derivation D1)
# =====================================================================================================
rng = np.random.default_rng(24)
names = ["A", "B", "C", "D"]; Ns = [60, 150, 400, 900]
share = np.array([0.42, 0.33, 0.20, 0.05])        # share of the curvature each set supplies
pull = np.array([+1.5, -1.9, 0.0, 0.0])           # planted offsets of the preferred parameter, in units of sigma_theta
theta_true = 0.0
a, D = [], []
for N, s, b in zip(Ns, share, pull):
    an = rng.normal(size=N); an *= np.sqrt(s / np.sum(an**2))      # sum_i a_i^2 = share  (so total = 1)
    a.append(an); D.append(an*(theta_true + b) + rng.normal(size=N))
chi2n = lambda n, th: np.sum((D[n] - a[n]*th)**2)
th_hat = sum(a[n] @ D[n] for n in range(4)) / sum(a[n] @ a[n] for n in range(4))
Hglob = 2*sum(a[n] @ a[n] for n in range(4))
# rescaled coordinate t: global chi2 = chi2_0 + t^2
th_of = lambda t: th_hat + t/np.sqrt(Hglob/2)
tot = lambda t: sum(chi2n(n, th_of(t)) for n in range(4))
check("global chi2(t) - chi2(0) = t^2", tot(1.7) - tot(0), 1.7**2, 1e-9)
c0 = np.array([chi2n(n, th_hat) for n in range(4)])
sc = np.sqrt(Hglob/2)
g = np.array([-2*a[n] @ (D[n] - a[n]*th_hat)/sc for n in range(4)])          # d chi2_n / dt at the best fit
h = np.array([2*(a[n] @ a[n])/sc**2 for n in range(4)])                       # d^2 chi2_n / dt^2
check("sum_n g_n = 0", g.sum(), 0, 1e-10); check("sum_n h_n = 2", h.sum(), 2, 1e-12)
tstar = -g/h
check("sum_n h_n t*_n = 0 (best fit is the curvature-weighted mean)", (h*tstar).sum(), 0, 1e-6)
Tp, Tm, rows = [], [], []
for n in range(4):
    xi50, xi68 = stats.chi2.ppf(0.50, Ns[n]), stats.chi2.ppf(0.68, Ns[n])
    Dn = c0[n]*(xi68/xi50 - 1)                                      # allowed rise, eq 2.4.7
    disc = np.sqrt(g[n]**2 + 2*h[n]*Dn)
    tp, tm = (-g[n] + disc)/h[n], (-g[n] - disc)/h[n]               # eq 2.4.8
    # verify on the exact data-set chi2
    f = lambda t: chi2n(n, th_of(t)) - c0[n] - Dn
    check(f"set {names[n]}: crossing t+ solves the exact condition", optimize.brentq(f, 0, 200, xtol=1e-12), tp, 1e-7)
    check(f"set {names[n]}: crossing t- solves the exact condition", optimize.brentq(f, -200, 0, xtol=1e-12), tm, 1e-7)
    Tp.append(tp); Tm.append(tm); rows.append((names[n], Ns[n], c0[n], g[n], h[n], tstar[n], Dn, tm, tp))
    note(f"set {names[n]}: N={Ns[n]:4d} chi2_0={c0[n]:7.1f} g={g[n]:+.2f} h={h[n]:.3f} t*={tstar[n]:+.2f} allowed rise={Dn:5.2f}  t-={tm:+.2f} t+={tp:+.2f}")
Tplus, Tminus = min(Tp), min(abs(t) for t in Tm)
note(f"dynamic tolerance: T+ = {Tplus:.2f} (set {names[int(np.argmin(Tp))]}),  T- = {Tminus:.2f} (set {names[int(np.argmin(np.abs(Tm)))]})")
check("toy: T+ quoted in the chapter", Tplus, 3.18, 2e-3); check("toy: T- quoted in the chapter", Tminus, 2.41, 2e-3)
check("toy: set A chi2_0", c0[0], 63.9, 1e-3); check("toy: set B chi2_0", c0[1], 156.7, 1e-3)
check("toy: set A slope", g[0], -1.33, 5e-3); check("toy: set B slope", g[1], 1.66, 5e-3)
check("toy: set A allowed rise", rows[0][6], 5.64, 2e-3); check("toy: set B allowed rise", rows[1][6], 8.63, 2e-3)
check("toy: set B preferred point", tstar[1], -2.52, 5e-3); check("toy: set A preferred point", tstar[0], 1.58, 5e-3)

fig, ax = plt.subplots(figsize=(8, 4.6), facecolor="white")
tt = np.linspace(-5, 5, 401); cols = [TEAL, ORANGE, INK, MUTED]; sty = ["-", "-", "--", ":"]
for n in range(4):
    Dn = rows[n][6]
    ax.plot(tt, [(chi2n(n, th_of(t)) - c0[n])/Dn for t in tt], color=cols[n], ls=sty[n], lw=2.4, label=f"{names[n]}: {Ns[n]} points")
ax.axhline(1, color=INK, lw=1); ax.text(0.4, 1.08, "68% limit of each set", fontsize=13, color=INK, ha="center")
ax.axvspan(-Tminus, Tplus, color=TEAL, alpha=0.10)
ax.axvline(Tplus, color=TEAL, lw=1.2); ax.axvline(-Tminus, color=ORANGE, lw=1.2)
ax.annotate(f"$T^+$ = {Tplus:.2f}", (Tplus, -0.42), xytext=(Tplus + 0.15, -0.42), fontsize=14, color="#0a5c5b", va="center")
ax.annotate(f"$T^-$ = {Tminus:.2f}", (-Tminus, -0.42), xytext=(-Tminus - 0.15, -0.42), fontsize=14, color="#a84f1c", va="center", ha="right")
ax.set_xlim(-5, 5); ax.set_ylim(-0.6, 2.2); ax.grid(color=GRID); ax.set_axisbelow(True)
ax.set_xlabel("distance along the eigenvector, in units where global $\\Delta\\chi^2 = t^2$")
ax.set_ylabel("rise in the set's $\\chi^2$ / allowed rise")
ax.legend(loc="lower center", ncol=4, frameon=False, bbox_to_anchor=(0.5, 1.0), columnspacing=1.0, handlelength=1.5, handletextpad=0.5, fontsize=13)
fig.tight_layout(); fig.savefig(OUT / "2-4-tolerance.svg", facecolor="white"); plt.close(fig)

# =====================================================================================================
# 3. Lagrange-multiplier scan (eqs 2.4.12-2.4.15, derivation D3)
# =====================================================================================================
# (a) quadratic chi2, linear observable: profile is the Hessian parabola
r2 = np.random.default_rng(5); n = 6
M = r2.normal(size=(n, n)); Hm = M @ M.T + n*np.eye(n); c = r2.normal(size=n)       # chi2 = chi2_0 + (1/2) d^T H d ; X = X0 + c.d
lam_, V = np.linalg.eigh(Hm)
Xk = (V.T @ c)/np.sqrt(lam_/2)                                                       # dX/dz_k with z_k = sqrt(lam_k/2) v_k.d
for lam in (-3.0, 0.7, 4.0):
    dmin = optimize.minimize(lambda d: 0.5*d @ Hm @ d + lam*(c @ d), np.zeros(n), jac=lambda d: Hm @ d + lam*c, method="BFGS", options={"gtol": 1e-11}).x
    dX, dchi = c @ dmin, 0.5*dmin @ Hm @ dmin
    check(f"LM (lambda={lam}): Delta X = -lambda |grad X|^2 / 2", dX, -lam*np.sum(Xk**2)/2, 1e-6)
    check(f"LM (lambda={lam}): Delta chi2 = (Delta X)^2 / |grad X|^2", dchi, dX**2/np.sum(Xk**2), 1e-6)
T = 3.0
members = [(c @ (V[:, k]*T/np.sqrt(lam_[k]/2)), c @ (-V[:, k]*T/np.sqrt(lam_[k]/2))) for k in range(n)]
check("Hessian master formula = T |grad X| = LM range", 0.5*np.sqrt(sum((p - m)**2 for p, m in members)), T*np.sqrt(np.sum(Xk**2)), 1e-10)
check("|grad_z X|^2 = 2 c^T H^-1 c (covariance 2 H^-1)", np.sum(Xk**2), 2*c @ np.linalg.solve(Hm, c), 1e-10)

# (b) a non-linear toy: f(x) = A (1-x)^eta fitted at x <= 0.65, observable X = f(0.9)
r3 = np.random.default_rng(11)
xs = np.linspace(0.10, 0.60, 10); A0, eta0 = 1.0, 3.0
model = lambda p, x: p[0]*(1 - x)**p[1]
sig = 0.10*model([A0, eta0], xs); dat = model([A0, eta0], xs) + sig*r3.normal(size=xs.size)
chi2 = lambda p: np.sum(((dat - model(p, xs))/sig)**2)
obs = lambda p: model(p, 0.9)
best = optimize.minimize(chi2, [1.0, 3.0], method="Nelder-Mead", options={"xatol": 1e-11, "fatol": 1e-13, "maxiter": 20000}).x
c2min, X0 = chi2(best), obs(best)
def hess(fn, p, e=1e-4):
    k = len(p); Hh = np.zeros((k, k))
    for i in range(k):
        for j in range(k):
            ei, ej = np.eye(k)[i]*e, np.eye(k)[j]*e
            Hh[i, j] = (fn(p+ei+ej) - fn(p+ei-ej) - fn(p-ei+ej) + fn(p-ei-ej))/(4*e*e)
    return Hh
H2 = hess(chi2, best); l2, V2 = np.linalg.eigh(H2)
Tt = 1.0                                                                             # one consistent data set: Delta chi2 = 1
mem = [(obs(best + s*Tt*V2[:, k]/np.sqrt(l2[k]/2))) for k in range(2) for s in (+1, -1)]
sym = 0.5*np.sqrt(sum((mem[2*k] - mem[2*k+1])**2 for k in range(2)))
up = np.sqrt(sum(max(mem[2*k] - X0, mem[2*k+1] - X0, 0)**2 for k in range(2)))
dn = np.sqrt(sum(max(X0 - mem[2*k], X0 - mem[2*k+1], 0)**2 for k in range(2)))
# the scan: minimise chi2 + lambda X for a ladder of lambda
scan = []
for lam in np.concatenate([np.linspace(-20500, 0, 120), np.linspace(0, 60000, 60)[1:]]):
    p = optimize.minimize(lambda q: chi2(q) + lam*obs(q), best, method="Nelder-Mead", options={"xatol": 1e-10, "fatol": 1e-12, "maxiter": 20000}).x
    scan.append((obs(p), chi2(p) - c2min))
scan = np.array(sorted(scan)); Xs, dchis = scan[:, 0], scan[:, 1]
# cross-check the scan against the constrained minimum at fixed X (eliminate A)
def prof(Xv):
    r = optimize.minimize_scalar(lambda e: chi2([Xv/0.1**e, e]), bounds=(0.5, 8), method="bounded", options={"xatol": 1e-12})
    return r.fun - c2min
check("LM point lies on the constrained profile (low side)", dchis[5], prof(Xs[5]), 1e-4)
check("LM point lies on the constrained profile (high side)", dchis[-5], prof(Xs[-5]), 1e-4)
lo = optimize.brentq(lambda v: prof(v) - Tt**2, 0.2*X0, X0); hi = optimize.brentq(lambda v: prof(v) - Tt**2, X0, 4*X0)
note(f"non-linear toy: best fit A={best[0]:.4f} eta={best[1]:.4f} chi2_min={c2min:.2f} ({xs.size} points);  X0 = f(0.9) = {X0*1e3:.3f}e-3")
note(f"  Hessian symmetric: +-{sym*1e3:.3f}e-3   Hessian asymmetric: +{up*1e3:.3f}e-3 -{dn*1e3:.3f}e-3   LM scan: +{(hi-X0)*1e3:.3f}e-3 -{(X0-lo)*1e3:.3f}e-3")
check("toy X0 (x 1e3) quoted", X0*1e3, 0.734, 1e-3); check("toy symmetric Hessian error (x 1e3)", sym*1e3, 0.171, 3e-3)
check("toy LM upper error (x 1e3)", (hi - X0)*1e3, 0.189, 3e-3); check("toy LM lower error (x 1e3)", (X0 - lo)*1e3, 0.154, 3e-3)
check("toy asymmetric Hessian upper (x 1e3)", up*1e3, 0.188, 3e-3); check("toy asymmetric Hessian lower (x 1e3)", dn*1e3, 0.154, 3e-3)
# the same scan at Delta chi2 = 9 shows the asymmetry growing with the tolerance
lo9 = optimize.brentq(lambda v: prof(v) - 9, 0.2*X0, X0); hi9 = optimize.brentq(lambda v: prof(v) - 9, X0, 4*X0)
note(f"  at Delta chi2 = 9: LM +{(hi9-X0)*1e3:.3f}e-3 -{(X0-lo9)*1e3:.3f}e-3,  3 x symmetric Hessian = {3*sym*1e3:.3f}e-3")
check("toy LM upper error at Delta chi2=9 (x 1e3)", (hi9 - X0)*1e3, 0.705, 2e-3); check("toy LM lower error at Delta chi2=9 (x 1e3)", (X0 - lo9)*1e3, 0.379, 2e-3)

fig, ax = plt.subplots(figsize=(8, 4.6), facecolor="white")
m = (dchis < 14)
ax.plot(Xs[m]*1e3, dchis[m], "o", ms=4.5, color=TEAL, label="Lagrange-multiplier scan")
xx = np.linspace(0.55, 1.6, 300)*1e-3
ax.plot(xx*1e3, ((xx - X0)/sym)**2, color=ORANGE, lw=2.2, ls="--", label="Hessian parabola")
for lev, lab in ((1, "$\\Delta\\chi^2 = 1$"), (9, "$\\Delta\\chi^2 = 9$")):
    ax.axhline(lev, color=INK, lw=1); ax.text(0.565, lev + 0.3, lab, fontsize=13)
ax.set_xlim(0.55, 1.6); ax.set_ylim(0, 13); ax.grid(color=GRID); ax.set_axisbelow(True)
ax.set_xlabel("observable $X = f(0.9)$, in units of $10^{-3}$"); ax.set_ylabel("rise in $\\chi^2$ above the minimum")
ax.legend(loc="upper center", frameon=False)
fig.tight_layout(); fig.savefig(OUT / "2-4-lagrange.svg", facecolor="white"); plt.close(fig)

# =====================================================================================================
# 4. Early stopping by cross-validation (eqs 2.4.16-2.4.18, derivation D4)
# =====================================================================================================
r4 = np.random.default_rng(7)
Npt, P, s4 = 80, 16, 0.3
xg = np.sort(r4.uniform(-1, 1, Npt)); truth = lambda x: np.sin(3*x) + 0.5*x**2
yg = truth(xg) + s4*r4.normal(size=Npt)
basis = lambda x: np.polynomial.legendre.legvander(x, P - 1)
idx = r4.permutation(Npt); tr, va = np.sort(idx[:Npt//2]), np.sort(idx[Npt//2:])
Jt, bt = basis(xg[tr])/s4, yg[tr]/s4; Jv, bv = basis(xg[va])/s4, yg[va]/s4
lam4, U4 = np.linalg.eigh(Jt.T @ Jt); lam4 = np.clip(lam4, 0, None)
rate = 1.0/lam4.max()                                # theta <- theta - (rate/2) grad chi2 ;  factor (1 - rate*lam_i) per step
proj = U4.T @ (Jt.T @ bt)                            # theta_hat_i = proj_i / lam_i
def theta_at(t):
    filt = np.where(lam4 > 1e-12*lam4.max(), (1 - (1 - rate*lam4)**t)/np.where(lam4 > 0, lam4, 1), rate*t)
    return U4 @ (filt*proj)
# verify the closed form against explicit gradient descent
th = np.zeros(P)
for _ in range(300): th = th - rate*(Jt.T @ (Jt @ th - bt))
check("gradient descent after 300 steps = closed form (eq 2.4.17)", np.linalg.norm(th - theta_at(300)), 0, 1e-9)
xf = np.linspace(-1, 1, 400); Bf = basis(xf)
ts = np.unique(np.round(np.logspace(0, 7, 141)).astype(int))
ctr = np.array([np.sum((Jt @ theta_at(t) - bt)**2)/len(tr) for t in ts])
cva = np.array([np.sum((Jv @ theta_at(t) - bv)**2)/len(va) for t in ts])
dtrue = np.array([np.mean(((Bf @ theta_at(t)) - truth(xf))**2)/s4**2 for t in ts])
neff = np.array([np.sum(1 - (1 - rate*lam4)**t) for t in ts])
check("training chi2 never increases", float(np.all(np.diff(ctr) <= 1e-12)), 1)
i_s = int(np.argmin(cva)); i_t = int(np.argmin(dtrue))
note(f"cross-validation toy: {P} parameters, {len(tr)} training + {len(va)} validation points")
note(f"  validation minimum at step {ts[i_s]}: chi2_tr/N={ctr[i_s]:.2f} chi2_val/N={cva[i_s]:.2f} distance to truth={dtrue[i_s]:.3f} effective parameters={neff[i_s]:.1f}")
note(f"  at the last step {ts[-1]}:        chi2_tr/N={ctr[-1]:.2f} chi2_val/N={cva[-1]:.2f} distance to truth={dtrue[-1]:.3f} effective parameters={neff[-1]:.1f}")
note(f"  best possible stopping point (unknowable in a real fit): step {ts[i_t]}, distance to truth={dtrue[i_t]:.3f}")
check("toy: stopping step quoted", ts[i_s], 22, 1e-9); check("toy: chi2_tr/N at stop", ctr[i_s], 0.84, 0.01)
check("toy: chi2_val/N at stop", cva[i_s], 0.83, 0.01); check("toy: effective parameters at stop", neff[i_s], 10.7, 0.01)
check("toy: chi2_tr/N at the end", ctr[-1], 0.74, 0.01); check("toy: chi2_val/N at the end", cva[-1], 12.2, 0.01)
check("toy: distance to truth at stop", dtrue[i_s], 0.136, 0.01); check("toy: distance to truth at the end", dtrue[-1], 6.5, 0.01)
check("stopped fit is closer to the truth than the converged fit", float(dtrue[i_s] < dtrue[-1]), 1)
check("number of weights of a 2-5-3-1 network", 5*(2+1) + 3*(5+1) + 1*(3+1), 37); check("seven such networks", 7*37, 259)

fig, ax = plt.subplots(figsize=(8, 4.6), facecolor="white")
ax.plot(ts, ctr, color=TEAL, lw=2.4, label="training half"); ax.plot(ts, cva, color=ORANGE, lw=2.4, label="validation half")
ax.plot(ts, dtrue, color=INK, lw=1.8, ls="--", label="distance to the truth")
ax.axvline(ts[i_s], color=INK, lw=1); ax.text(ts[i_s]*1.3, 19, "stop: validation minimum", fontsize=13, va="center")
ax.set_xscale("log"); ax.set_yscale("log"); ax.set_xlim(1, 1e7); ax.set_ylim(0.08, 30); ax.grid(color=GRID, which="major"); ax.set_axisbelow(True)
ax.set_xlabel("gradient-descent steps"); ax.set_ylabel("$\\chi^2$ per point")
ax.legend(loc="lower center", frameon=False, ncol=3, columnspacing=1.4, handlelength=1.8, bbox_to_anchor=(0.5, 1.0))
fig.tight_layout(); fig.savefig(OUT / "2-4-stopping.svg", facecolor="white"); plt.close(fig)

# =====================================================================================================
# 5. Combination: Hessian -> replicas, pooling, replicas -> Hessian (eqs 2.4.19-2.4.24, derivations D5, D6)
# =====================================================================================================
r5 = np.random.default_rng(3)
# (a) Hessian set -> Monte Carlo replicas reproduces the Hessian covariance
npts, neig = 5, 4
f0 = r5.normal(size=npts); dplus = 0.1*r5.normal(size=(neig, npts)); fplus, fminus = f0 + dplus, f0 - dplus + 0.0
covH = sum(np.outer((fplus[j] - fminus[j])/2, (fplus[j] - fminus[j])/2) for j in range(neig))
R = r5.normal(size=(400000, neig)); reps = f0 + R @ ((fplus - fminus)/2)
covMC = np.cov(reps.T)
check("replicas from a Hessian set: covariance reproduced (max element error)", np.abs(covMC - covH).max(), 0, 1e-3)
check("replicas from a Hessian set: mean = central member", np.abs(reps.mean(0) - f0).max(), 0, 1e-3)
# (b) pooling three groups: law of total variance (eq 2.4.21)
mu = np.array([1.000, 1.030, 0.985]); sg = np.array([0.020, 0.015, 0.025])
mu_c = mu.mean(); var_c = np.mean(sg**2) + np.mean((mu - mu_c)**2)
pool = np.concatenate([r5.normal(m, s, 2_000_000) for m, s in zip(mu, sg)])
check("pooled mean", pool.mean(), mu_c, 1e-4); check("pooled standard deviation = total-variance formula", pool.std(), np.sqrt(var_c), 1e-3)
check("pooled mean quoted", mu_c, 1.0050, 1e-4); check("pooled sigma quoted", np.sqrt(var_c), 0.0277, 3e-3)
check("spread of the three central values", np.sqrt(np.mean((mu - mu_c)**2)), 0.0187, 3e-3)
check("rms of the three uncertainties", np.sqrt(np.mean(sg**2)), 0.0204, 3e-3)
inside = np.mean(np.abs(pool - mu_c) < np.sqrt(var_c))
note(f"pooled toy: mean {mu_c:.4f}, sigma {np.sqrt(var_c):.4f}; fraction of replicas within one sigma = {inside:.3f} (a Gaussian has 0.683)")
check("pooled distribution is not Gaussian: one-sigma content", inside, 0.661, 3e-3)
# (c) replicas -> Hessian by singular value decomposition (eq 2.4.22-2.4.24)
xgrid = np.linspace(0.01, 0.9, 40); nrep_g = 300
groups = []
for gi in range(3):
    mean_g = xgrid**-0.2*(1 - xgrid)**3*(1 + 0.03*(gi - 1)*np.cos(3*xgrid))
    modes = np.array([0.02*(m + 1)**-0.7*mean_g*np.cos((m + 1)*np.pi*xgrid + gi) for m in range(8)])
    groups.append(mean_g + r5.normal(size=(nrep_g, 8)) @ modes)
ens = np.vstack(groups); Nrep = ens.shape[0]
check("pooled ensemble has 900 replicas", Nrep, 900)
fbar = ens.mean(0); Dm = (ens - fbar).T/np.sqrt(Nrep - 1)                     # columns = replicas
U, S, Vt = np.linalg.svd(Dm, full_matrices=False)
cov = np.cov(ens.T)
check("covariance = D D^T", np.abs(Dm @ Dm.T - cov).max(), 0, 1e-12)
full = fbar + (U*S).T                                                          # members f_j = fbar + s_j u_j
check("all members kept: symmetric formula reproduces the variance", np.abs(np.sum((full - fbar)**2, 0) - np.diag(cov)).max(), 0, 1e-12)
check("member j is a linear combination of replicas: s_j u_j = D v_j", np.abs(Dm @ Vt[3] - S[3]*U[:, 3]).max(), 0, 1e-12)
frac = np.cumsum(S**2)/np.sum(S**2)
worst = {}
for ne in (5, 10, 20):
    kept = fbar + (U[:, :ne]*S[:ne]).T
    err = np.sqrt(np.sum((kept - fbar)**2, 0))/np.sqrt(np.diag(cov))
    check(f"N_eig={ne}: missing variance = discarded s_j^2", np.trace(cov) - np.sum((kept - fbar)**2), np.sum(S[ne:]**2), 1e-10)
    worst[ne] = err.min()
    note(f"N_eig={ne}: fraction of total variance kept {frac[ne-1]:.4f}; uncertainty at worst grid point {err.min():.3f} of the full one")
check("toy: 5 members keep 99.8% of the total variance", frac[4], 0.998, 1e-3)
check("toy: 5 members, worst point", worst[5], 0.51, 0.01); check("toy: 10 members, worst point", worst[10], 0.91, 0.01); check("toy: 20 members, worst point", worst[20], 1.00, 0.005)
# (d) finite number of replicas (eq 2.4.25, derivation D6)
sims = r5.normal(size=(40000, 100))
check("N_rep=100: error on the mean = sigma/10", sims.mean(1).std(), 0.1, 0.02)
check("N_rep=100: relative error on the uncertainty = 1/sqrt(2 N_rep) = 7.1%", sims.std(1, ddof=1).std(), 1/np.sqrt(200), 0.03)
check("N_rep=900: relative error on the uncertainty = 2.4%", 1/np.sqrt(1800), 0.0236, 3e-3)
check("N_rep=40 members of a 4th-moment check: var(s^2) = 2 sigma^4/(N-1)", sims.var(1, ddof=1).var(), 2/99, 0.03)

# =====================================================================================================
# 6. Reading a set: worked examples (eqs 2.4.26-2.4.30)
# =====================================================================================================
X0h = 50.0; Xp = np.array([50.9, 49.6, 50.3, 50.05]); Xm = np.array([49.2, 50.5, 50.1, 49.90])
symh = 0.5*np.sqrt(np.sum((Xp - Xm)**2))
uph = np.sqrt(np.sum(np.maximum.reduce([Xp - X0h, Xm - X0h, np.zeros(4)])**2))
dnh = np.sqrt(np.sum(np.maximum.reduce([X0h - Xp, X0h - Xm, np.zeros(4)])**2))
note(f"Hessian example: X = {X0h} +-{symh:.3f} (symmetric), +{uph:.3f} -{dnh:.3f} (asymmetric); at 68% from a 90% set: +-{symh/1.645:.3f}")
check("Hessian example: symmetric", symh, 0.970, 1e-3); check("Hessian example: up", uph, 1.074, 1e-3); check("Hessian example: down", dnh, 0.900, 1e-3)
check("Hessian example: 90% -> 68%", symh/1.645, 0.590, 2e-3)
Yp = np.array([20.5, 19.9, 20.1, 20.0]); Ym = np.array([19.6, 20.2, 19.95, 20.02]); symY = 0.5*np.sqrt(np.sum((Yp - Ym)**2))
corr = np.sum((Xp - Xm)*(Yp - Ym))/(4*symh*symY)
note(f"Hessian example: second observable Y = 20.0 +-{symY:.3f}, correlation cos(phi) = {corr:.3f}")
check("Hessian example: Y error", symY, 0.480, 2e-3); check("Hessian example: correlation", corr, 0.980, 2e-3)
check("ratio X/Y error with the correlation", (X0h/20.0)*np.sqrt((symh/X0h)**2 + (symY/20.0)**2 - 2*corr*(symh/X0h)*(symY/20.0)),
      0.5*np.sqrt(np.sum((Xp/Yp - Xm/Ym)**2)), 0.02)
note(f"  error on X/Y from the members: {0.5*np.sqrt(np.sum((Xp/Yp - Xm/Ym)**2)):.4f}; ignoring the correlation: {(X0h/20.0)*np.sqrt((symh/X0h)**2 + (symY/20.0)**2):.4f}")
check("ratio error from members", 0.5*np.sqrt(np.sum((Xp/Yp - Xm/Ym)**2)), 0.0156, 0.01)
check("ratio error ignoring correlation", (X0h/20.0)*np.sqrt((symh/X0h)**2 + (symY/20.0)**2), 0.0772, 2e-3)
Xr = np.array([50.4, 49.1, 50.9, 49.8, 50.2, 51.3, 49.5, 50.0, 48.9, 50.6])
note(f"MC example: mean {Xr.mean():.3f}, std (N-1) {Xr.std(ddof=1):.3f}, std (N) {Xr.std():.3f}, error on the mean {Xr.std(ddof=1)/np.sqrt(10):.3f}, relative error on sigma {1/np.sqrt(20):.3f}")
check("MC example: mean", Xr.mean(), 50.07, 1e-4); check("MC example: std (N-1)", Xr.std(ddof=1), 0.769, 1e-3); check("MC example: std (N)", Xr.std(), 0.729, 1e-3)
# non-linear observable: mean of the observable versus observable of the mean
big = r5.normal(1.0, 0.1, 2_000_000)
check("<X^2> - <X>^2 = sigma^2 for X^2 of a replica set", np.mean(big**2) - np.mean(big)**2, 0.01, 0.02)
# symmetric (one member per eigenvector) sets, as produced by eq 2.4.24
dsym = np.array([0.5, -0.3, 0.2, 0.1])
check("one-member-per-eigenvector formula", np.sqrt(np.sum(dsym**2)), 0.5*np.sqrt(np.sum((2*dsym)**2)), 1e-12)

print("\nALL CHECKS PASS" if ok else "\nSOME CHECKS FAILED")
sys.exit(0 if ok else 1)
