#!/usr/bin/env python3
"""Numerical checks for guide chapter 3.4 (three methods on one fit), and its three data plots.

Two kinds of check:
  (a) LEDGER ARITHMETIC. Numbers typed here are copied from context/RESULTS_LEDGER.md, context/PHASE_B_LEDGER.md
      and context/PHASE_B_PREREG.md, with the result ID. The script checks the ratios and percentages the chapter
      derives from them. It cannot check the ledger numbers themselves: those come from runs on the project's boxes.
  (b) TOY DEMONSTRATIONS of each diagnostic the chapter derives (D1 to D6). Toys are labelled as toys in the text.
Run:  python3 guide-build/tools/check_3_4.py     (writes assets/guide/3-4-*.svg)"""
import pathlib, sys
import numpy as np
from scipy import special, stats, integrate
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:.10g}, want {want:.10g}")
def truth(name, cond):
    global ok
    ok &= bool(cond)
    print(f"{'PASS' if cond else 'FAIL'}  {name}")
Phi = stats.norm.cdf

# =====================================================================================================
# (a) Ledger numbers and the arithmetic done on them in the chapter
# =====================================================================================================
print("--- ledger arithmetic ---")
N0, N3 = 3089, 4615                                   # PPDF-30: points on R0 and R3
check("PPDF-31 R3: 5707.67/4615", 5707.67 / N3, 1.2368, 1e-4)
check("PPDF-31 R0: 3553.91/3089", 3553.91 / N0, 1.1505, 1e-4)
check("PPDF-35: 5713.228/4615", 5713.228 / N3, 1.2380, 1e-4)
check("PPDF-35: 1.2380/1.17", 1.2380 / 1.17, 1.058, 1e-3)
check("PPDF-35 vs PPDF-31, per cent", 100 * (5713.2278 - 5707.6675) / 5707.6675, 0.097, 5e-3)
check("core-count shift, per cent", 100 * (3090.4757 - 3068.8573) / 3068.8573, 0.7, 1e-2)
check("PPDF-33 Hessian arm: 3068.857/3089", 3068.857 / N0, 0.9935, 1e-4)
check("PPDF-33 clipped truth: 3087.661/3089", 3087.661 / N0, 0.9996, 1e-4)
check("data term + penalty at the clipped truth", 3078.647 + 9.014, 3087.661, 1e-6)
check("penalty/data at the published point", 70729.11 / 3078.65, 22.97, 1e-3)
check("R3 truth: 5680.141/4615", 5680.141 / N3, 1.2308, 1e-4)
check("R3 truth: penalty/data, per cent", 100 * 57.947 / 5680.141, 1.0, 3e-2)
check("PPDF-16a: (3089-17.64)/3089", (N0 - 17.64) / N0, 0.9943, 1e-4)
# the ladder (PPDF-32, corrected entry of 2026-08-06)
sets = np.array([19, 54, 59, 82]); pts = np.array([3089, 3981, 4534, 4615])
fwd = np.array([14, 12, 10, 10]); cen = np.array([12, 9, 8, 8])
check("rung increments in data sets", float(np.all(np.diff(sets) == [35, 5, 23])), 1)
check("exact: DY/W/Z per data set", (cen[0] - cen[1]) / 35, 0.086, 5e-3)
check("exact: jets and photon per data set", (cen[1] - cen[2]) / 5, 0.200, 1e-6)
check("exact ratio jets : DY", ((cen[1] - cen[2]) / 5) / ((cen[0] - cen[1]) / 35), 2.3, 2e-2)
check("forward ratio jets : DY", ((fwd[1] - fwd[2]) / 5) / ((fwd[0] - fwd[1]) / 35), 7.0, 1e-6)
check("constrained directions on R3", 52 - cen[3], 44)
# the step scans at R0 (PHASE_B_LEDGER, finding of 2026-08-06)
h_f = np.array([1e-2, 1e-3, 1e-4, 1e-5, 1e-6])
lam_f = np.array([-7.945e4, -3.704e3, -1.354e2, -1.281e1, -1.210e0]); nneg_f = [13, 10, 7, 5, 2]; flat_f = [17, 15, 14, 13, 12]
h_c = np.array([1e-2, 1e-3, 1e-4, 1e-5]); nneg_c = [4, 0, 0, 0]; flat_c = [12, 11, 12, 12]
r = lam_f[:-1] / lam_f[1:]
print("INFO  forward lambda'_min, ratio per decade of step:", np.round(r, 1))
check("forward ratio, last decade", r[-1], 10.6, 1e-2)
check("forward ratio, 1e-4 to 1e-5", r[-2], 10.6, 1e-2)
# leave-one-out (PPDF-38)
loo = {"neutrino DIS": (4, 9), "jets and dijets": (4, 9), "charged-lepton DIS": (15, 10), "Drell-Yan, W, Z": (33, 10), "top": (23, 8)}
check("leave-one-out classes add up to", sum(v[0] for v in loo.values()), 79)
check("per data set: neutrino DIS", (9 - 8) / 4, 0.250)
check("per data set: charged-lepton DIS", (10 - 8) / 15, 0.133, 3e-3)
check("per data set: DY", (10 - 8) / 33, 0.061, 1e-2)
check("neutrino DIS : DY per data set", 0.250 / 0.061, 4.1, 1e-2)
check("sum of marginal contributions", sum(v[1] - 8 for v in loo.values()), 6)
# Monte Carlo coverage (PPDF-33)
c0 = special.erf(1 / np.sqrt(2)); se52 = np.sqrt(c0 * (1 - c0) / 52)
check("nominal coverage", c0, 0.6827, 1e-4)
check("39/52", 39 / 52, 0.750, 1e-6); check("43/52", 43 / 52, 0.827, 1e-3)
check("binomial error for 52 trials, points", 100 * se52, 6.45, 1e-3)
check("R0 excess in binomial errors", (39 / 52 - c0) / se52, 1.04, 1e-2)
check("R3 excess in binomial errors", (43 / 52 - c0) / se52, 2.24, 1e-2)
# Bayesian arm (PPDF-33)
check("3089/648", N0 / 648, 4.8, 1e-2); check("226/3.2", 226 / 3.2, 70.6, 1e-3)
check("autocorrelation length 1200/3.2", 1200 / 3.2, 375); check("37500/1200", 37500 / 1200, 31.25)
check("sum of the four per-chain minima (retracted run)", 8.1 + 13.2 + 7.1 + 43.5, 71.9, 1e-9)
check("sum of the three per-chain minima (valid run)", 11.2 + 12.0 + 6.3, 29.5, 1e-9)
truth("valid run: min of sums 30.8 >= sum of mins 29.5", 30.8 >= 29.5)
truth("retracted run: min of sums 111.2 >= sum of mins 71.9", 111.2 >= 71.9)
check("Rhat^2 - 1 at 1.1185", 1.1185**2 - 1, 0.251, 2e-3)
check("spread of chain means in within-chain sigmas", np.sqrt(1.1185**2 - 1), 0.50, 5e-3)
check("Rhat^2 - 1 at 1.894", 1.894**2 - 1, 2.59, 2e-3)
check("excess over one, ratio", 0.894 / 0.1185, 7.5, 1e-2)
chi_t = np.array([3047.977, 3038.504, 3086.695, 3072.615])
check("sqrt(2N) for N = 3089", np.sqrt(2 * N0), 78.6, 1e-3)
check("range of the four chi2(truth)", np.ptp(chi_t), 48.2, 1e-3)
check("sample sd of the four chi2(truth)", chi_t.std(ddof=1), 22.2, 5e-3)
check("ten chains at 4.2 h", 10 * 4.2, 42); check("ten boxes of 128 vCPU", 10 * 128, 1280)
check("g_etam: 2*0.256/0.85^2", 2 * 0.256 / 0.85**2, 0.71, 1e-2)

# =====================================================================================================
# (b) Toys
# =====================================================================================================
rng = np.random.default_rng(34)

# --- D1: the scaled curvature, the flat criterion, the width of a bounded flat direction -------------
print("--- D1 ---")
p = 6
Jm = rng.normal(size=(30, p)) * np.logspace(1, -2, p); Hm = 2 * Jm.T @ Jm          # chi2 = |J d|^2 -> Hessian 2 J^T J
wid = np.logspace(-1, 1, p)                                                       # prior half-widths
Hs = Hm * np.outer(wid, wid); lam, V = np.linalg.eigh(Hs)
t = 0.37; dth = wid * V[:, 0] * t                                                 # a step of t along the softest scaled direction
check("Delta chi2 = lambda' t^2 / 2", 0.5 * dth @ Hm @ dth, 0.5 * lam[0] * t * t, 1e-9)
check("variance 2/lambda' from the covariance 2 H^-1", V[:, 2] @ (2 * np.linalg.inv(Hs)) @ V[:, 2], 2 / lam[2], 1e-8)
check("lambda' = 2  <=>  one-sigma width = one half-width", np.sqrt(2 / 2.0), 1.0)
check("sd of a uniform density on [-1, 1]", np.sqrt(integrate.quad(lambda u: u * u / 2, -1, 1)[0]), 1 / np.sqrt(3))
# a direction of scaled curvature lam, flat prior on [-1,1]: posterior sd, exact
def post_sd(lam):
    s = np.sqrt(2 / lam); a = 1 / s
    return s * np.sqrt(1 - 2 * a * stats.norm.pdf(a) / (2 * Phi(a) - 1))
check("posterior sd at lambda' = 2, in half-widths", post_sd(2.0), 0.5396, 1e-3)
check("posterior sd as lambda' -> 0", post_sd(1e-6), 1 / np.sqrt(3), 1e-4)
check("posterior sd at lambda' = 200 is the data width", post_sd(200.0), 0.1, 1e-6)
check("truncated-Gaussian sd against quadrature (lambda'=2)",
      np.sqrt(integrate.quad(lambda u: u * u * np.exp(-0.5 * 2 * u * u / 2), -1, 1)[0] / integrate.quad(lambda u: np.exp(-0.5 * 2 * u * u / 2), -1, 1)[0]),
      post_sd(2.0), 1e-8)
# invariance of the count under reparametrisation that rescales parameters and bounds together
s = rng.uniform(0.1, 10, p); Hm2 = Hm / np.outer(s, s)
check("lambda' is unchanged when parameters and bounds are rescaled together",
      np.abs(np.linalg.eigvalsh(Hm2 * np.outer(wid * s, wid * s)) - lam).max() / lam.max(), 0, 1e-10)

# --- D2: forward and central differences at an exact minimum with nearly flat directions -------------
print("--- D2 ---")
def fd_toy(seed=1, m=10, N=60):
    r_ = np.random.default_rng(seed); p = 2 * m
    A = r_.normal(size=(N, m)) * np.logspace(3, 0.5, m)
    B = r_.normal(size=(p, p)) * np.logspace(0, -3, p)[:, None]
    ths = np.concatenate([r_.uniform(-.5, .5, m), r_.uniform(.8, 1.5, m)])
    g = lambda th: np.exp(th[:m]) * th[m:]**2
    def Jg(th):
        J = np.zeros((m, p)); i = np.arange(m)
        J[i, i] = np.exp(th[:m]) * th[m:]**2; J[i, m + i] = 2 * np.exp(th[:m]) * th[m:]; return J
    d = A @ g(ths)                                           # noise-free data: an exact minimum at ths, chi2 = 0
    grad = lambda th: 2 * Jg(th).T @ A.T @ (A @ g(th) - d) + 2 * B.T @ B @ (th - ths)
    Hex = 2 * Jg(ths).T @ A.T @ A @ Jg(ths) + 2 * B.T @ B
    def fd(h, scheme):
        H = np.zeros((p, p))
        for i in range(p):
            e = np.zeros(p); e[i] = h
            H[:, i] = (grad(ths + e) - grad(ths)) / h if scheme == "forward" else (grad(ths + e) - grad(ths - e)) / (2 * h)
        return np.linalg.eigvalsh(0.5 * (H + H.T))
    return Hex, fd, grad, ths
Hex, fd, grad, ths = fd_toy()
wex = np.linalg.eigvalsh(Hex)
truth("toy: exact Hessian at the minimum is positive definite", wex.min() > 0)
print(f"INFO  toy: exact flat count (lambda<2) = {(wex < 2).sum()} of {len(wex)}, condition {wex.max() / wex.min():.2e}")
hs = np.array([1e-2, 1e-3, 1e-4, 1e-5, 1e-6])
toy = {s_: [(int((w < 0).sum()), int((w < 2).sum()), w.min()) for w in (fd(h, s_) for h in hs)] for s_ in ("forward", "central")}
for s_ in toy: print(f"INFO  toy {s_}: (negative, flat<2) at h=1e-2..1e-6:", [(a, b) for a, b, _ in toy[s_]])
n_exact = int((wex < 2).sum())
truth("toy: forward differences give negative eigenvalues at every step", all(a > 0 for a, _, _ in toy["forward"]))
truth("toy: forward flat count exceeds the exact one at every step", all(b > n_exact for _, b, _ in toy["forward"]))
truth("toy: central differences converge to the exact counts", toy["central"][-1][:2] == (0, n_exact) and toy["central"][-2][:2] == (0, n_exact))
lf = np.array([c for _, _, c in toy["forward"]]); lc = np.array([c for _, _, c in toy["central"]])
check("toy: forward lambda_min scales as h (ratio per decade)", lf[2] / lf[3], 10, 2e-2)
check("toy: central lambda_min scales as h^2 where negative (ratio per decade)", lc[0] / lc[1], 100, 0.15)
# the shift formula for a cluster of soft eigenvalues: the estimated soft eigenvalues are those of
#   S = Lambda_soft + V_soft^T E V_soft,   E = symmetrised (h/2) d^2 G_a / d theta_b^2   (degenerate perturbation theory)
h = 1e-6; pdim = len(ths)
E = np.zeros((pdim, pdim))
for b in range(pdim):
    e = np.zeros(pdim); e[b] = 1e-4
    E[:, b] = 0.5 * h * (grad(ths + e) - 2 * grad(ths) + grad(ths - e)) / 1e-8          # (h/2) d^2 G_a / d theta_b^2
E = 0.5 * (E + E.T)
wv, Vv = np.linalg.eigh(Hex); q = 10                                                   # ten soft eigenvalues, then a gap
print(f"INFO  toy: soft eigenvalues up to {wv[q-1]:.3g}, next stiff eigenvalue {wv[q]:.3g}")
S = np.diag(wv[:q]) + Vv[:, :q].T @ E @ Vv[:, :q]; wS = np.linalg.eigvalsh(S); wF = fd(h, "forward")
check("toy: lowest forward eigenvalue = lowest eigenvalue of the soft block", wF[0], wS[0], 1e-4)
check("toy: second lowest likewise", wF[1], wS[1], 1e-4)
check("toy: number of negative forward eigenvalues = number of negative eigenvalues of the soft block", int((wF < 0).sum()), int((wS < 0).sum()))
single = wv[0] + Vv[:, 0] @ E @ Vv[:, 0]
print(f"INFO  toy: one-vector formula gives {single:.3g}, soft-block formula {wS[0]:.4g}, forward differences {wF[0]:.4g}")
truth("toy: the one-vector formula is not enough when soft eigenvalues cluster", abs(single - wF[0]) > 0.5 * abs(wF[0]))
tr = np.trace(Vv[:, :q].T @ E @ Vv[:, :q])
print(f"INFO  toy: trace of the soft block of E = {tr:.3g}; eigenvalues of that block: {np.round(np.linalg.eigvalsh(Vv[:, :q].T @ E @ Vv[:, :q]), 2)}")

# --- D3: incremental and marginal counts -------------------------------------------------------------
print("--- D3 ---")
def Fcls(dirs, p=8, n=12, seed=0):
    r_ = np.random.default_rng(seed); J = np.zeros((n, p)); J[:, dirs] = r_.normal(size=(n, len(dirs))); return J.T @ J
cls = {"A": Fcls([0, 1, 2, 3], seed=1), "B": Fcls([2, 3, 4, 5], seed=2), "C": Fcls([5, 6], seed=3), "D": Fcls([0, 1], seed=4)}
nflat = lambda names: 8 - np.linalg.matrix_rank(sum((cls[k] for k in names), np.zeros((8, 8))), tol=1e-8)
order = "ABCD"
inc = [nflat(order[:i]) - nflat(order[:i + 1]) for i in range(4)]
mar = [nflat(order.replace(k, "")) - nflat(order) for k in order]
print("INFO  toy classes A,B,C,D: incremental", inc, " marginal", mar, " flat with all:", nflat(order))
truth("toy: incremental (4,2,1,0), marginal (0,1,1,0)", inc == [4, 2, 1, 0] and mar == [0, 1, 1, 0])
truth("toy: marginal <= incremental for every class (submodularity of rank)", all(m_ <= i_ for m_, i_ in zip(mar, inc)))
truth("toy: for the last class added the two numbers are the same number", inc[-1] == mar[-1])
truth("ledger: marginal <= incremental for DY (2 <= 3), jets (1 <= 1), top (0 <= 0)", 2 <= 3 and 1 <= 1 and 0 <= 0)
# random test of submodularity
bad = 0
for trial in range(300):
    r_ = np.random.default_rng(trial); P = [r_.normal(size=(r_.integers(1, 4), 9)) * (r_.random(9) < 0.5) for _ in range(5)]
    rk = lambda idx: np.linalg.matrix_rank(np.vstack([P[i] for i in idx])) if idx else 0
    c = 4; S = [0, 1]; full = [0, 1, 2, 3]
    bad += (rk(full + [c]) - rk(full)) > (rk(S + [c]) - rk(S))
check("rank gain never grows when more data are already present (300 random cases)", bad, 0)

# --- D4: coverage with a displaced centre, and the size of the largest pull --------------------------
print("--- D4 ---")
cov = lambda b, r=1.0: Phi(r - b) - Phi(-r - b)
check("coverage with no offset", cov(0), c0, 1e-12)
z = rng.normal(size=400000)
for b in (0.5, 1.0, 2.0):
    check(f"coverage with centre offset {b} sigma, formula vs simulation", np.mean(np.abs(z + b) < 1), cov(b), 4e-3)
check("coverage at offset 1 sigma", cov(1.0), 0.477, 2e-3); check("coverage at offset 2 sigma", cov(2.0), 0.157, 3e-3)
check("coverage when the centre is the truth", float(np.mean(np.abs(np.zeros(10)) < 1)), 1.0)
pmax = lambda a, n=52: 1 - (2 * Phi(a) - 1)**n
med = stats.norm.ppf((0.5**(1 / 52) + 1) / 2)
check("median of the largest |z| among 52 unit Gaussians", med, 2.48, 2e-3)
check("same by simulation", np.median(np.abs(rng.normal(size=(40000, 52))).max(axis=1)), med, 1e-2)
print(f"INFO  P(max|z| >= 5 among 52) = {pmax(5):.2e};  P(max|z| >= 3.5) = {pmax(3.5):.3f}")
truth("P(max|z| >= 5 among 52) is below 1e-4", pmax(5) < 1e-4)
# coverage in parameter space of a level-1 fit, linear model, exact minimum: 68.27%
Jl = rng.normal(size=(120, 8)); Cth = np.linalg.inv(Jl.T @ Jl); sd = np.sqrt(np.diag(Cth))
eta = rng.normal(size=(20000, 120)); est = eta @ Jl @ Cth                         # best fit minus truth for each noise draw
check("level-1 linear fit: parameter coverage", np.mean(np.abs(est) < sd), c0, 6e-3)
# the same with an optimiser that stops short along the stiffest direction by 5 sigma of that direction
lam8, V8 = np.linalg.eigh(np.linalg.inv(Cth)); zs = (est @ V8) * np.sqrt(lam8)     # pulls along eigen-directions
check("pulls along eigen-directions have unit variance", zs.var(), 1.0, 2e-2)
zs_bad = zs.copy(); zs_bad[:, -1] += 5.0
check("coverage along a direction whose centre is 5 sigma off", np.mean(np.abs(zs_bad[:, -1]) < 1), cov(5.0), 1e-3)

# --- D5: the replicate test; combining ESS; R-hat ----------------------------------------------------
print("--- D5 ---")
Nd = 300; Lc = rng.normal(size=(Nd, Nd)) / np.sqrt(Nd) + np.eye(Nd); C = Lc @ Lc.T; Ci = np.linalg.inv(C); Lch = np.linalg.cholesky(C)
Tm = lambda th: np.sin(np.arange(Nd)[:, None] * th[None, :] / 40).sum(axis=1) + (th**2).sum()   # any non-linear model
def chi2_truth(th_true, data_seed):
    eta = Lch @ np.random.default_rng(data_seed).normal(size=Nd); D = Tm(th_true) + eta
    res = D - Tm(th_true); return res @ Ci @ res
a1, a2 = chi2_truth(np.array([0.3, 1.2, 2.0]), 123456), chi2_truth(np.array([5.0, -1.0, 0.1]), 123456)
check("chi2 at the truth is the same for two different truths, same noise seed", a1, a2, 1e-9)
vals = np.array([chi2_truth(np.array([0.3, 1.2, 2.0]), sd_) for sd_ in range(4000)])
check("chi2 at the truth: mean over noise seeds = N", vals.mean(), Nd, 6e-3)
check("chi2 at the truth: variance over noise seeds = 2N", vals.var(), 2 * Nd, 8e-2)
truth("chi2 at the truth differs between noise seeds", len(set(np.round(vals[:4], 6))) == 4)
ess = rng.uniform(1, 300, size=(4, 52))                                           # per-chain, per-parameter ESS (random)
truth("min over parameters of summed ESS >= sum of per-chain minima", ess.sum(axis=0).min() >= ess.min(axis=1).sum())
# R-hat for chains on one data set and on different data sets (independent draws; linear Gaussian)
def rhat(ch):
    n = ch.shape[1]; W = ch.var(axis=1, ddof=1).mean(); Bn = ch.mean(axis=1).var(ddof=1); return np.sqrt(((n - 1) / n * W + Bn) / W)
same = np.mean([rhat(rng.normal(size=(4, 2000))) for _ in range(300)])
diff = np.mean([rhat(rng.normal(size=(4, 2000)) + rng.normal(size=(4, 1)))**2 for _ in range(4000)])
check("R-hat, four chains on one data set", same, 1.0, 2e-3)
check("mean R-hat^2, four chains each on its own noise draw", diff, 2.0, 3e-2)

# --- D6: the three open experiments --------------------------------------------------------------------
print("--- D6 ---")
p = 10; Q = np.linalg.qr(rng.normal(size=(p, p)))[0]; lam10 = np.logspace(-3, 6, p); H10 = Q @ np.diag(lam10) @ Q.T
gvec = rng.normal(size=p)
check("variance of f: g^T 2H^-1 g = sum 2 (g.v)^2/lambda", gvec @ (2 * np.linalg.inv(H10)) @ gvec, np.sum(2 * (gvec @ Q)**2 / lam10), 1e-6)
worst = True; lo_ok = True
for trial in range(400):
    r_ = np.random.default_rng(trial); Q_ = np.linalg.qr(r_.normal(size=(12, 12)))[0]
    l_ = np.sort(10**r_.uniform(-3, 5, 12)); H_ = Q_ @ np.diag(l_) @ Q_.T
    kf = int(r_.integers(1, 6)); keep = np.sort(r_.permutation(12)[kf:]); mu = np.linalg.eigvalsh(H_[np.ix_(keep, keep)])
    worst &= bool(np.all(mu >= l_[:12 - kf] * (1 - 1e-9)) and np.all(mu <= l_[kf:] * (1 + 1e-9)))
    n_full, n_sub = int((l_ < 2).sum()), int((mu < 2).sum())
    lo_ok &= (max(n_full - kf, 0) <= n_sub <= n_full)
truth("interlacing: lambda_i <= mu_i <= lambda_(i+k) after freezing k parameters (400 random cases)", worst)
truth("flat count after freezing k parameters lies between n-k and n (400 random cases)", lo_ok)
# freezing the parameters that carry the flat directions removes them; freezing others does not
Hb = np.diag([1e-3, 1e-2, 50., 400., 3e3, 2e4]) + 1e-4
check("freeze the two flat axes: flat count", int((np.linalg.eigvalsh(Hb[2:, 2:]) < 2).sum()), 0)
check("freeze two stiff axes instead: flat count", int((np.linalg.eigvalsh(Hb[:4, :4]) < 2).sum()), 2)
Tneed = lambda c1: 1 / (np.sqrt(2) * special.erfinv(c1))
check("tolerance needed when coverage is already nominal", Tneed(c0), 1.0, 1e-9)
sfac = 3.0; zz = rng.normal(size=400000) * sfac; c1 = np.mean(np.abs(zz) < 1)
check("toy: true scatter 3 sigma -> coverage at T=1", c1, special.erf(1 / (sfac * np.sqrt(2))), 5e-3)
check("toy: T recovered from that coverage", Tneed(special.erf(1 / (sfac * np.sqrt(2)))), sfac, 1e-9)
check("toy: T^2 for a measured coverage of 26.1%", Tneed(0.2611)**2, 9.0, 2e-3)

# =====================================================================================================
# Plots (ledger numbers; the toy panel is labelled as a toy)
# =====================================================================================================
TEAL, ORANGE, INK, GRID, MUTED = "#0e7c7b", "#d96c2c", "#16222e", "#ebe6da", "#6b7480"
plt.rcParams.update({"font.size": 14, "axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK,
                     "axes.grid": True, "grid.color": GRID, "axes.axisbelow": True, "figure.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 (ladder)
from matplotlib.lines import Line2D
fig, ax = plt.subplots(figsize=(7.8, 4.7))
ax.axhspan(12, 15.5, color=ORANGE, alpha=0.08, lw=0); ax.axhspan(5.5, 8, color=TEAL, alpha=0.08, lw=0)
ax.plot(sets, fwd, "o--", color=ORANGE, lw=2, ms=8, label="forward differences (superseded)")
ax.plot(sets, cen, "o-", color=TEAL, lw=2.6, ms=9, label="central differences (converged)")
for x_, f_, c_ in zip(sets, fwd, cen):
    ax.annotate(str(f_), (x_, f_), textcoords="offset points", xytext=(9, 7), ha="left", color=ORANGE, fontsize=14)
    ax.annotate(str(c_), (x_, c_), textcoords="offset points", xytext=(-9, -17), ha="right", color=TEAL, fontsize=14)
ax.text(87.5, 14.9, "12 or more: registered as structural", fontsize=13, color=ORANGE, va="top", ha="right")
ax.text(13.5, 6.0, "8 or fewer: registered as cured", fontsize=13, color=TEAL, va="bottom", ha="left")
ax.set_xlabel("data sets in the fit"); ax.set_ylabel("flat directions, of 52"); ax.set_xlim(12, 89); ax.set_ylim(5.5, 15.5)
ax.set_yticks(range(6, 16, 2)); ax.set_xticks([19, 54, 59, 82]); ax.set_xticklabels(["19\nR0", "54\nR1", "59\nR2", "82\nR3"])
ax.get_xticklabels()[1].set_ha("right"); ax.get_xticklabels()[2].set_ha("left")
fig.legend(loc="lower center", ncol=2, fontsize=13, bbox_to_anchor=(0.54, 0.0), columnspacing=1.5)
fig.tight_layout(rect=(0, 0.08, 1, 1)); fig.savefig(out / "3-4-ladder.svg"); plt.close(fig)

# Figure (step scan): counts against the differencing step, ledger (left) and toy (right)
fig, axs = plt.subplots(1, 2, figsize=(7.8, 4.9), sharex=True)
ax = axs[0]
ax.plot(h_f, flat_f, "o--", color=ORANGE, lw=2, ms=7); ax.plot(h_c, flat_c, "o-", color=TEAL, lw=2.4, ms=8)
ax.plot(h_f, nneg_f, "s--", color=ORANGE, lw=1.6, ms=6, mfc="white"); ax.plot(h_c, nneg_c, "s-", color=TEAL, lw=1.6, ms=6, mfc="white")
ax.set_xscale("log"); ax.set_ylim(-1, 19); ax.set_yticks(range(0, 19, 4)); ax.set_title("This project, R0\n52 parameters", fontsize=13, color=INK)
ax.set_xlabel("step / prior half-width"); ax.set_ylabel("number of eigenvalues")
ax = axs[1]
ax.plot(hs, [b for _, b, _ in toy["forward"]], "o--", color=ORANGE, lw=2, ms=7); ax.plot(hs, [b for _, b, _ in toy["central"]], "o-", color=TEAL, lw=2.4, ms=8)
ax.plot(hs, [a for a, _, _ in toy["forward"]], "s--", color=ORANGE, lw=1.6, ms=6, mfc="white"); ax.plot(hs, [a for a, _, _ in toy["central"]], "s-", color=TEAL, lw=1.6, ms=6, mfc="white")
ax.axhline(n_exact, color=INK, lw=1, ls=":"); ax.text(8e-7, 11.2, f"dotted: exact flat count, {n_exact}", fontsize=13, color=INK, va="center")
ax.set_xscale("log"); ax.set_ylim(-1, 12.5); ax.set_yticks(range(0, 13, 2)); ax.set_title("Toy with a known answer\n20 parameters", fontsize=13, color=INK); ax.set_xlabel("step")
for a_ in axs: a_.set_xticks([1e-6, 1e-4, 1e-2])
hd = [Line2D([], [], color=ORANGE, ls="--", marker="o", lw=2, ms=7, label="flat, forward"), Line2D([], [], color=TEAL, ls="-", marker="o", lw=2.4, ms=8, label="flat, central"),
      Line2D([], [], color=ORANGE, ls="--", marker="s", mfc="white", lw=1.6, ms=6, label="negative, forward"), Line2D([], [], color=TEAL, ls="-", marker="s", mfc="white", lw=1.6, ms=6, label="negative, central")]
fig.legend(handles=hd, loc="lower center", ncol=2, fontsize=13, columnspacing=1.5)
fig.tight_layout(rect=(0, 0.13, 1, 1)); fig.savefig(out / "3-4-stepscan.svg"); plt.close(fig)

# Figure (coverage)
fig, ax = plt.subplots(figsize=(7.8, 4.7))
labs = ["singlet", "gluon", "valence", "$T_8$", "mean", "R0", "R3"]; vals_ = [62, 56, 76, 38, 57.9, 75.0, 82.7]
xs = [0, 1, 2, 3, 4, 7, 8]; cols = [TEAL] * 5 + [ORANGE] * 2
ax.bar(xs, vals_, color=cols, width=0.7)
for x_, v_ in zip(xs, vals_): ax.text(x_, v_ + 1.5, f"{v_:g}", ha="center", fontsize=13, color=INK)
ax.plot([-0.6, 8.6], [68.27, 68.27], color=INK, lw=1.4); ax.text(5.5, 70.0, "nominal 68.3", ha="center", fontsize=13, color=INK)
ax.plot([-0.6, 8.6], [55, 55], color=MUTED, lw=1.2, ls="--"); ax.text(5.5, 49.5, "gate 55", ha="center", fontsize=13, color=MUTED)
ax.set_xticks(xs); ax.set_xticklabels(labs); ax.set_xlim(-0.6, 8.6); ax.set_ylim(0, 118); ax.set_yticks(range(0, 101, 20))
ax.set_ylabel("coverage of the truth (%)"); ax.grid(axis="x", visible=False)
ax.text(2, 106, "Bayesian, Phase A\nby flavour, five noise draws", ha="center", va="center", fontsize=13, color=TEAL)
ax.text(6.9, 106, "Monte Carlo, Phase B\n52 parameters", ha="center", va="center", fontsize=13, color=ORANGE)
fig.tight_layout(); fig.savefig(out / "3-4-coverage.svg"); plt.close(fig)

print("wrote 3-4-ladder.svg, 3-4-stepscan.svg, 3-4-coverage.svg;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
