#!/usr/bin/env python3
"""Numerical checks for guide chapter 2.5 (Bayesian fits and Colibri), and its two data plots.
A small Metropolis sampler, a small Hamiltonian Monte Carlo sampler and a small nested sampler are implemented
here and verified against analytic answers on toy posteriors. Every formula the chapter states is tested;
the script exits non-zero if any check fails.
Run:  python3 guide-build/tools/check_2_5.py     (writes assets/guide/2-5-paths.svg, 2-5-nested.svg)"""
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:.10g}, want {want:.10g}")

def info(s): print("INFO  " + s)

rng = np.random.default_rng(25)

# ===================================================================================================
# tools: autocorrelation time, effective sample size, R-hat
def tau_int(x):
    """Integrated autocorrelation time 1 + 2 sum rho_t, eq. (2.5.20), with Geyer's initial-positive-sequence cut."""
    x = np.asarray(x, float) - np.mean(x); n = len(x)
    f = np.fft.rfft(x, 2 * n); acov = np.fft.irfft(f * np.conj(f))[:n] / (n - np.arange(n))
    rho = acov / acov[0]
    s = 0.0
    for k in range(0, n - 1, 2):
        pair = rho[k] + rho[k + 1]
        if pair < 0: break
        s += pair
    return max(2 * s - 1, 1e-12)

def ess(chains):
    """Effective sample size of an (m, n) array of m chains: the sum over chains of n / tau."""
    return sum(len(c) / tau_int(c) for c in np.atleast_2d(chains))

def rhat(chains):
    """Gelman-Rubin R-hat of an (m, n) array, eq. (2.5.22)."""
    c = np.atleast_2d(chains); n = c.shape[1]
    W = c.var(axis=1, ddof=1).mean(); Bn = c.mean(axis=1).var(ddof=1)
    return np.sqrt(((n - 1) / n * W + Bn) / W)

# ===================================================================================================
# section 2: priors and bounds
W, sig = 3.0, 0.4
check("variance of a uniform prior of width W = W^2/12, eq. (2.5.4)",
      integrate.quad(lambda t: t * t / W, -W / 2, W / 2)[0], W * W / 12)
# a Gaussian likelihood of width sig, centred in a box of width W: variance of the truncated Gaussian
def trunc_var(a):                    # variance of a unit Gaussian truncated to [-a, a]
    return 1 - 2 * a * stats.norm.pdf(a) / (2 * stats.norm.cdf(a) - 1)
a = 5.0
num = integrate.quad(lambda t: t * t * np.exp(-t * t / 2), -a, a)[0] / integrate.quad(lambda t: np.exp(-t * t / 2), -a, a)[0]
check("truncated-Gaussian variance formula, eq. (2.5.4)", trunc_var(a), num, 1e-10)
check("box 10 sigma wide changes the variance by 2a phi(a)/(2Phi(a)-1), a=5", 1 - trunc_var(5.0), 1.4867e-5, 1e-8)
check("flat-direction limit: truncated variance -> a^2/3 = W^2/(12 sigma^2)", trunc_var(0.05) / (0.05 ** 2 / 3), 1.0, 1e-3)
# the bounded parameter theta = lo + (hi-lo) sigmoid(z): Jacobian and the induced prior on z
sigm = lambda z: 1 / (1 + np.exp(-z))
z0, h = 0.7, 1e-6
check("d sigmoid/dz = u(1-u), eq. (2.5.5)", (sigm(z0 + h) - sigm(z0 - h)) / (2 * h), sigm(z0) * (1 - sigm(z0)), 1e-8)
check("logistic density u(1-u) is normalised", integrate.quad(lambda z: sigm(z) * (1 - sigm(z)), -60, 60)[0], 1.0, 1e-10)
check("its variance is pi^2/3", integrate.quad(lambda z: z * z * sigm(z) * (1 - sigm(z)), -60, 60)[0], np.pi ** 2 / 3, 1e-9)
check("so its precision is 3/pi^2 = 0.304 (ledger)", 3 / np.pi ** 2, 0.304, 1e-3)
# 'flat' is a coordinate statement: flat in theta on [0.01, 1] puts 0.9/0.99 of the mass in the top decade of ln theta
check("flat on [0.01,1]: mass in [0.1,1]", (1 - 0.1) / (1 - 0.01), 0.9090909, 1e-6)

# ===================================================================================================
# section 3: Metropolis
def metropolis(logp, q0, n, step, rng, keep=None):
    q = np.array(q0, float); lp = logp(q); out = np.empty((n, len(q) if keep is None else len(keep))); acc = 0
    for i in range(n):
        qn = q + step * rng.standard_normal(len(q)); lpn = logp(qn)
        if np.log(rng.random()) < lpn - lp: q, lp = qn, lpn; acc += 1
        out[i] = q if keep is None else q[keep]
    return out, acc / n

d = 100
_, acc = metropolis(lambda q: -0.5 * q @ q, rng.standard_normal(d), 40000, 2.38 / np.sqrt(d), rng, keep=[0])
check("Metropolis, isotropic Gaussian d=100, step 2.38/sqrt(d): acceptance near 0.234", acc, 0.234, 0.03)
# expected acceptance for a d-dim unit Gaussian in the large-d limit: 2 Phi(-l/2), l = step sqrt(d)
check("2 Phi(-s/2) at s = 2.38, eq. (2.5.8)", 2 * stats.norm.cdf(-2.38 / 2), 0.234, 2e-3)
# D1: Delta ~ N(-s^2/2, s^2) gives E[min(1, e^Delta)] = 2 Phi(-s/2); and s^2 Phi(-s/2) is largest at s = 2.38
s_ = 1.7; dl = -s_ ** 2 / 2 + s_ * np.random.default_rng(3).standard_normal(2000000)   # own stream
check("D1: E[min(1,exp(Delta))] = 2 Phi(-s/2) at s = 1.7", np.mean(np.minimum(1, np.exp(dl))), 2 * stats.norm.cdf(-s_ / 2), 2e-3)
sg = np.linspace(1, 4, 30001)
check("D1: s^2 Phi(-s/2) is largest at s = 2.38", sg[np.argmax(sg ** 2 * stats.norm.cdf(-sg / 2))], 2.38, 2e-3)
check("section 7: (1.3)^-52 is about 1e-6", 1.3 ** -52, 1.2e-6, 1e-7)

# the cost comparison of section 4: a d=20 Gaussian with standard deviations log-spaced from 0.1 to 1
d = 20
sds = np.logspace(-1, 0, d); kappa = (sds.max() / sds.min()) ** 2
logp = lambda q: -0.5 * np.sum((q / sds) ** 2)
grad = lambda q: q / sds ** 2                                   # gradient of U = -log p
step = 2.38 / np.sqrt(np.sum(1 / sds ** 2))
xs, acc = metropolis(logp, sds * rng.standard_normal(d), 300000, step, rng, keep=[d - 1])
tau_M = tau_int(xs[:, 0])
info(f"Metropolis d=20, kappa={kappa:.0f}: step {step:.3f}, acceptance {acc:.3f}, tau(slowest) = {tau_M:.0f} likelihood calls")
check("Metropolis acceptance on the anisotropic target stays near 0.234", acc, 0.234, 0.05)
# diffusion estimate: each step moves a coordinate by variance acc*step^2, so tau = 4 sigma^2/(acc step^2);
# with step^2 = 2.38^2/sum(1/sigma_i^2) and acc = 0.234 this is tau = 3.0 sum_i (sigma_max/sigma_i)^2, eq. (2.5.9)
check("4/(0.234 * 2.38^2) = 3.0", 4 / (0.234 * 2.38 ** 2), 3.0, 0.01)
check("Metropolis tau(slowest) = 3 sum_i (sigma_max/sigma_i)^2, eq. (2.5.9)", tau_M, 3.0 * np.sum(sds.max() ** 2 / sds ** 2), 0.3)
info(f"sum_i (sigma_max/sigma_i)^2 = {np.sum(sds.max() ** 2 / sds ** 2):.0f}; d*kappa = {d * kappa:.0f}")

# ===================================================================================================
# section 4 and D2, D3: leapfrog
def leapfrog(q, p, gradU, eps, L, Minv=None):
    q = np.array(q, float); p = np.array(p, float)
    vel = (lambda p: p) if Minv is None else (lambda p: Minv @ p)
    p = p - 0.5 * eps * gradU(q)
    for i in range(L):
        q = q + eps * vel(p)
        p = p - (eps if i < L - 1 else 0.5 * eps) * gradU(q)
    return q, p

# D3: one leapfrog step on U = w^2 q^2/2 is the linear map of eq. (2.5.36)
w, eps = 1.7, 0.31
A = np.array([[1 - eps ** 2 * w ** 2 / 2, eps], [-eps * w ** 2 * (1 - eps ** 2 * w ** 2 / 4), 1 - eps ** 2 * w ** 2 / 2]])
q1, p1 = leapfrog([0.8], [-0.3], lambda q: w * w * q, eps, 1)
check("leapfrog step matrix, q component", q1[0], (A @ [0.8, -0.3])[0], 1e-12)
check("leapfrog step matrix, p component", p1[0], (A @ [0.8, -0.3])[1], 1e-12)
check("det of the step matrix = 1 (volume preserved)", np.linalg.det(A), 1.0, 1e-12)
check("trace of the step matrix = 2 - eps^2 w^2", np.trace(A), 2 - eps ** 2 * w ** 2, 1e-12)
# stability: bounded for eps w < 2, exponentially growing for eps w > 2
for ew, stable in [(1.99, True), (2.01, False)]:
    e = ew / w; q, p = leapfrog([1.0], [0.0], lambda q: w * w * q, e, 2000)
    check(f"leapfrog at eps*w = {ew} is {'stable' if stable else 'unstable'}", float(abs(q[0]) < 1e3), float(stable))
# the shadow Hamiltonian p^2/2 + w^2 q^2 (1 - eps^2 w^2/4)/2 is conserved exactly
Hs = lambda q, p: 0.5 * p ** 2 + 0.5 * w ** 2 * q ** 2 * (1 - eps ** 2 * w ** 2 / 4)
q, p = leapfrog([0.8], [-0.3], lambda q: w * w * q, eps, 137)
check("shadow Hamiltonian conserved after 137 steps, eq. (2.5.37)", Hs(q[0], p[0]), Hs(0.8, -0.3), 1e-12)
Htrue = lambda q, p: 0.5 * p ** 2 + 0.5 * w ** 2 * q ** 2
check("energy error = eps^2 w^4 (q'^2 - q^2)/8, eq. (2.5.38)", Htrue(q[0], p[0]) - Htrue(0.8, -0.3),
      eps ** 2 * w ** 4 * (q[0] ** 2 - 0.8 ** 2) / 8, 1e-12)
# reversibility: flip the momentum, integrate again, flip again -> back at the start
U3 = lambda q: 0.5 * q @ q + 0.1 * np.sum(q ** 4); g3 = lambda q: q + 0.4 * q ** 3     # an anharmonic test potential
qa, pa = rng.standard_normal(3), rng.standard_normal(3)
qb, pb = leapfrog(qa, pa, g3, 0.1, 25); qc, pc = leapfrog(qb, -pb, g3, 0.1, 25)
check("leapfrog is reversible (anharmonic potential)", np.max(np.abs(np.r_[qc - qa, -pc - pa])), 0.0, 1e-12)
# volume preservation for the anharmonic potential: Jacobian determinant of the 6-dim map by finite differences
def flow(y): return np.concatenate(leapfrog(y[:3], y[3:], g3, 0.1, 25))
y0 = np.r_[qa, pa]; J = np.empty((6, 6))
for j in range(6):
    e = np.zeros(6); e[j] = 1e-6; J[:, j] = (flow(y0 + e) - flow(y0 - e)) / 2e-6
check("leapfrog Jacobian determinant = 1 (anharmonic potential)", np.linalg.det(J), 1.0, 1e-7)
# energy error scales as eps^2 at fixed trajectory length
dH = lambda e, L: (lambda r: U3(r[0]) + 0.5 * r[1] @ r[1])(leapfrog(qa, pa, g3, e, L)) - U3(qa) - 0.5 * pa @ pa
check("energy error ratio for eps -> eps/2 is 4", dH(0.1, 20) / dH(0.05, 40), 4.0, 0.03)
# D3: spread of the energy error over a quarter-period trajectory in d dimensions = eps^2 sqrt(d)/4
for d_ in (10, 160):
    e = 0.2; L = int(round(np.pi / 2 / e)); errs = []
    for _ in range(4000):
        q = rng.standard_normal(d_); p = rng.standard_normal(d_)
        q2, p2 = leapfrog(q, p, lambda q: q, e, L)
        errs.append(0.5 * (q2 @ q2 + p2 @ p2 - q @ q - p @ p))
    check(f"std of energy error, d={d_}: eps^2 sqrt(d)/4, eq. (2.5.15)", np.std(errs), e ** 2 * np.sqrt(d_) / 4, 0.06)

def hmc(U, gradU, q0, n, eps, L, rng, M=None, jitter=0.2):
    """Hamiltonian Monte Carlo with mass matrix M: momenta ~ N(0, M), leapfrog, Metropolis accept on exp(-dH)."""
    q = np.array(q0, float); dim = len(q)
    if M is None: Lm, Minv = np.eye(dim), None
    else: Lm, Minv = np.linalg.cholesky(M), np.linalg.inv(M)
    K = (lambda p: 0.5 * p @ p) if Minv is None else (lambda p: 0.5 * p @ Minv @ p)
    out = np.empty((n, dim)); acc = 0; ngrad = 0
    for i in range(n):
        p = Lm @ rng.standard_normal(dim)
        e = eps * (1 + jitter * (2 * rng.random() - 1)); Li = rng.integers(max(1, L // 2), L + L // 2 + 1)
        qn, pn = leapfrog(q, p, gradU, e, Li, Minv); ngrad += Li + 1
        if np.log(rng.random()) < U(q) + K(p) - U(qn) - K(pn): q = qn; acc += 1
        out[i] = q
    return out, acc / n, ngrad / n

# cost comparison on the same d=20 target: unit mass, then mass = inverse covariance
d = 20
Uq = lambda q: 0.5 * np.sum((q / sds) ** 2)
x1, a1, g1 = hmc(Uq, grad, sds * rng.standard_normal(d), 6000, 1.0 * sds.min(), 16, rng)
t1 = tau_int(x1[:, -1]) * g1
x2, a2, g2 = hmc(Uq, grad, sds * rng.standard_normal(d), 6000, 0.9, 2, rng, M=np.diag(1 / sds ** 2))
t2 = max(tau_int(x2[:, k]) for k in range(d)) * g2
info(f"HMC unit mass: acceptance {a1:.2f}, {g1:.1f} gradients per step, cost per independent draw = {t1:.0f} gradients")
info(f"HMC mass = inverse covariance: acceptance {a2:.2f}, {g2:.1f} gradients per step, cost = {t2:.1f} gradients")
check("HMC variance of the slowest coordinate (unit mass)", x1[:, -1].var(), 1.0, 0.12)
check("HMC variance of the stiffest coordinate (unit mass)", x1[:, 0].var() / sds[0] ** 2, 1.0, 0.12)
check("HMC (unit mass) is cheaper than Metropolis by more than 10x", float(tau_M / t1 > 10), 1.0)
check("preconditioning removes the remaining factor (cost below 10 gradients)", float(t2 < 10), 1.0)
COST = (tau_M, t1, t2)

# ===================================================================================================
# the toy posterior used for the rest of the chapter: a linear model with Gaussian errors
Ndat, d = 30, 4
Amat = rng.standard_normal((Ndat, d)) * np.array([1.0, 2.0, 4.0, 0.7]); Amat[:, 1] += 1.5 * Amat[:, 0]
truth = np.array([0.5, -1.0, 0.3, 2.0])
D = Amat @ truth + rng.standard_normal(Ndat)                    # unit covariance
F = Amat.T @ Amat; Sig = np.linalg.inv(F)                       # Fisher matrix and posterior covariance
best = Sig @ Amat.T @ D; chi2min = np.sum((D - Amat @ best) ** 2)
chi2 = lambda th: np.sum((D - Amat @ th) ** 2)
ev = np.linalg.eigvalsh(F)
info(f"toy linear model: N_dat={Ndat}, d={d}, chi2_min={chi2min:.2f}, Fisher condition number {ev[-1]/ev[0]:.0f}")
check("chi2 is exactly quadratic about the best fit", chi2(best + [0.1, -0.2, 0.05, 0.3]) - chi2min,
      np.array([0.1, -0.2, 0.05, 0.3]) @ F @ [0.1, -0.2, 0.05, 0.3], 1e-10)

# HMC on the toy posterior, four chains, mass matrix = Fisher matrix
Up = lambda th: 0.5 * chi2(th); gp = lambda th: -Amat.T @ (D - Amat @ th)
chains = np.array([hmc(Up, gp, best + 3 * np.sqrt(np.diag(Sig)) * rng.standard_normal(d), 3000, 0.9, 2, rng, M=F)[0][200:]
                   for _ in range(4)])
pooled = chains.reshape(-1, d)
for k in range(d):
    e_k = ess(chains[:, :, k]); se = np.sqrt(Sig[k, k] / e_k)
    check(f"HMC posterior mean, parameter {k} (in units of its standard error)", (pooled[:, k].mean() - best[k]) / se, 0.0, 4.0)
check("HMC posterior covariance (largest relative error of a variance)",
      np.max(np.abs(np.diag(np.cov(pooled.T)) / np.diag(Sig) - 1)), 0.0, 0.1)
check("HMC posterior correlation theta_0-theta_1", np.corrcoef(pooled.T)[0, 1], Sig[0, 1] / np.sqrt(Sig[0, 0] * Sig[1, 1]), 0.03)
rh = max(rhat(chains[:, :, k]) for k in range(d)); es = min(ess(chains[:, :, k]) for k in range(d))
info(f"HMC toy: 4 chains x 2800 draws, max R-hat {rh:.4f}, min ESS {es:.0f}")
check("HMC toy: R-hat below 1.01", float(rh < 1.01), 1.0)
c2 = np.array([chi2(t) for t in pooled[::4]])
check("Bayesian complexity <chi2> - chi2_min = d for a Gaussian posterior, eq. (2.5.33)", c2.mean() - chi2min, d, 0.05)

# a bounded parameter with no data: HMC in z = logit(u) returns the prior, variance W^2/12 (section 2)
Uz = lambda z: -np.sum(np.log(sigm(z)) + np.log(1 - sigm(z)))  # -log of the logistic density
gz = lambda z: -(1 - 2 * sigm(z))
zz, _, _ = hmc(Uz, gz, [0.0], 40000, 1.2, 3, rng)
u = sigm(zz[:, 0])
check("flat direction: posterior mean of u is 1/2", u.mean(), 0.5, 0.01)
check("flat direction: posterior variance of u is 1/12 (the prior)", u.var(), 1 / 12, 0.02)

# ===================================================================================================
# section 6 and D4: effective sample size and R-hat
phi = 0.9; n = 200000
x = np.empty(n); x[0] = rng.standard_normal() / np.sqrt(1 - phi ** 2); eta = rng.standard_normal(n)
for i in range(1, n): x[i] = phi * x[i - 1] + eta[i]
check("AR(1): tau = (1+phi)/(1-phi) = 19, eq. (2.5.21)", tau_int(x), (1 + phi) / (1 - phi), 0.08)
# variance of the mean of a correlated chain = sigma^2 tau / n, eq. (2.5.20)
reps, n = 4000, 2000
y = np.empty((reps, n)); y[:, 0] = rng.standard_normal(reps) / np.sqrt(1 - phi ** 2); eta = rng.standard_normal((reps, n))
for i in range(1, n): y[:, i] = phi * y[:, i - 1] + eta[:, i]
s2 = 1 / (1 - phi ** 2)
exact = s2 / n * (1 + 2 * sum((1 - t / n) * phi ** t for t in range(1, n)))
check("var of the chain mean, exact finite-n sum of eq. (2.5.19)", y.mean(axis=1).var(), exact, 0.06)
check("large-n form sigma^2 tau/n agrees with it", s2 * 19 / n, exact, 0.01)
check("R-hat of independent well-mixed chains is 1", rhat(rng.standard_normal((4, 5000))), 1.0, 0.002)
# chains stuck at different places: R-hat^2 - 1 is the between-chain variance in units of W
stuck = rng.standard_normal((4, 5000)) + np.array([[0.0], [1.0], [2.0], [3.0]])
check("R-hat for four unit-variance chains with means 0,1,2,3", rhat(stuck) ** 2, 1 + np.var([0, 1, 2, 3], ddof=1), 0.03)
# the retraction of section 10 in miniature: m perfectly sampled chains, each on its OWN noise draw of the data.
# The best fit scatters between draws with the posterior covariance itself, so E[B/n] = 2W/n + W and R-hat^2 -> 2.
r2 = []
for _ in range(3000):
    centres = rng.standard_normal(4)                            # best-fit scatter, in units of the posterior width
    r2.append(rhat(centres[:, None] + rng.standard_normal((4, 400))) ** 2)
check("perfect chains on four different datasets: mean R-hat^2 = 2, eq. (2.5.23)", np.mean(r2), 2.0, 0.03)
r1 = [rhat(rng.standard_normal((4, 400))) for _ in range(3000)]
check("the same chains on one dataset: mean R-hat = 1", np.mean(r1), 1.0, 0.003)
info(f"different datasets: median R-hat {np.median(np.sqrt(r2)):.3f}; sqrt(2) = {np.sqrt(2):.3f}")

# ===================================================================================================
# section 7 and D5: nested sampling on the toy posterior with a flat prior in a box
halfw = 10.0; lo, hi = best - halfw, best + halfw; Vbox = (2 * halfw) ** d
Lc = np.linalg.cholesky(F)                                      # F = Lc Lc^T
lnL = lambda th: -0.5 * (chi2(th) - chi2min)                    # likelihood normalised to L_max = 1
Vd = np.pi ** (d / 2) / special.gamma(d / 2 + 1)                # volume of the unit d-ball
lnZ_exact = 0.5 * d * np.log(2 * np.pi) - 0.5 * np.linalg.slogdet(F)[1] - np.log(Vbox)
I_exact = np.log(Vbox) - 0.5 * d * np.log(2 * np.pi * np.e) + 0.5 * np.linalg.slogdet(F)[1]
info(f"toy evidence: ln Z = {lnZ_exact:.4f}, information I = {I_exact:.3f} nats")
# the evidence integral done directly as a check of the Laplace formula (exact for a Gaussian, eq. 2.5.31)
z1 = [integrate.quad(lambda t: np.exp(-0.5 * t * t * lam), -40 / np.sqrt(lam), 40 / np.sqrt(lam))[0] for lam in ev]
check("Gaussian integral: prod sqrt(2 pi/lambda_i) / V_prior", np.log(np.prod(z1) / Vbox), lnZ_exact, 1e-10)
ellvol = lambda c: Vd * c ** (d / 2) / np.sqrt(np.linalg.det(F))    # volume of the ellipsoid chi2 - chi2_min < c

def draw_exact(c, rng):
    """One point uniform in the prior box subject to chi2 - chi2_min < c (possible because the toy is Gaussian)."""
    while True:
        if ellvol(c) < Vbox:
            v = rng.standard_normal((64, d)); v /= np.linalg.norm(v, axis=1)[:, None]
            v *= (np.sqrt(c) * rng.random(64) ** (1 / d))[:, None]
            th = best + np.linalg.solve(Lc.T, v.T).T
            good = np.all((th > lo) & (th < hi), axis=1)
        else:
            th = lo + (hi - lo) * rng.random((64, d)); dl = th - best
            good = np.einsum("ij,jk,ik->i", dl, F, dl) < c
        if good.any(): return th[np.argmax(good)]

def draw_walk(live, lstar, rng, nsteps=30):
    """The general method: start from a random live point and random-walk inside the constraint L > L*."""
    th = live[rng.integers(len(live))].copy()
    Lcov = np.linalg.cholesky(np.cov(live.T) + 1e-12 * np.eye(d)) * 2.38 / np.sqrt(d) * 0.6
    for _ in range(nsteps):
        tn = th + Lcov @ rng.standard_normal(d)
        if np.all((tn > lo) & (tn < hi)) and lnL(tn) > lstar: th = tn
    return th

def nested(N, rng, mode="exact", frac=1e-4):
    live = lo + (hi - lo) * rng.random((N, d)); ll = np.array([lnL(t) for t in live])
    dead, dl, lw = [], [], []; lnZ = -np.inf; k = 0
    while True:
        k += 1; i = np.argmin(ll)
        lnw = ll[i] + np.log(np.exp(-(k - 1) / N) - np.exp(-k / N))       # L_k (X_{k-1} - X_k), eq. (2.5.27)
        dead.append(live[i].copy()); dl.append(ll[i]); lw.append(lnw); lnZ = np.logaddexp(lnZ, lnw)
        new = draw_exact(-2 * ll[i], rng) if mode == "exact" else draw_walk(live, ll[i], rng)
        live[i] = new; ll[i] = lnL(new)
        if ll.max() - k / N < lnZ + np.log(frac): break                    # what is left cannot change Z
    for t, l in zip(live, ll):                                             # the final live points share X_k
        dead.append(t.copy()); dl.append(l); lw.append(l - k / N - np.log(N)); lnZ = np.logaddexp(lnZ, lw[-1])
    dead, dl, lw = np.array(dead), np.array(dl), np.array(lw); wgt = np.exp(lw - lnZ)
    return dict(lnZ=lnZ, th=dead, lnL=dl, w=wgt, k=k, I=np.sum(wgt * dl) - lnZ)

N = 200
run = nested(N, rng)
sdZ = np.sqrt(I_exact / N)
info(f"nested sampling, {N} live points, exact constrained draws: {run['k']} iterations, ln Z = {run['lnZ']:.3f} "
     f"(exact {lnZ_exact:.3f}), information {run['I']:.2f} (exact {I_exact:.2f}), predicted error {sdZ:.3f}")
check("nested sampling ln Z against the exact value, in units of sqrt(I/N)", (run["lnZ"] - lnZ_exact) / sdZ, 0.0, 3.0)
check("nested sampling information I, eq. (2.5.28)", run["I"], I_exact, 0.06)
mean_ns = run["w"] @ run["th"]; var_ns = run["w"] @ (run["th"] - mean_ns) ** 2
kish = 1 / np.sum(run["w"] ** 2)
info(f"posterior by-product: {len(run['w'])} weighted points, Kish effective number {kish:.0f}")
for k in range(d):
    check(f"nested-sampling posterior mean, parameter {k} (standard errors)", (mean_ns[k] - best[k]) / np.sqrt(Sig[k, k] / kish), 0.0, 4.0)
check("nested-sampling posterior variances (largest relative error)", np.max(np.abs(var_ns / np.diag(Sig) - 1)), 0.0, 0.15)
check("complexity from nested-sampling weights = d", -2 * (run["w"] @ run["lnL"]) + 2 * run["lnL"].max(), d, 0.1)
# shrinkage: the true prior volume of each dead point is known for the toy once its ellipsoid is inside the box
cs = -2 * run["lnL"][:run["k"]]
rmax = np.sqrt(cs[:, None] * np.diag(Sig)[None, :])            # half-extent of the ellipsoid along each axis
inside = np.all(rmax < halfw, axis=1)
lnX_true = np.log(np.array([ellvol(c) for c in cs]) / Vbox)
kk = np.arange(1, run["k"] + 1)[inside]; lnX_true = lnX_true[inside]
lt = np.diff(lnX_true)                                          # ln t for successive shrinkages
check("mean of ln t = -1/N, eq. (2.5.26)", lt.mean() * N, -1.0, 0.06)
check("variance of ln t = 1/N^2", lt.var() * N * N, 1.0, 0.12)
check("ln X_k follows -k/N within its random walk (end of run, in units of sqrt(k)/N)",
      (lnX_true[-1] + kk[-1] / N) / (np.sqrt(kk[-1]) / N), 0.0, 3.0)
check("analytic E[ln t] = -1/N for the largest of N uniforms",
      integrate.quad(lambda t: np.log(t) * N * t ** (N - 1), 0, 1)[0], -1 / N, 1e-8)
check("analytic E[(ln t)^2] = 2/N^2", integrate.quad(lambda t: np.log(t) ** 2 * N * t ** (N - 1), 0, 1)[0], 2 / N ** 2, 1e-8)
# where the posterior mass sits: the weight per unit ln X peaks at -ln X = I + ln[(2 pi e)^(d/2) / (V_d d^(d/2))]
shift = 0.5 * d * np.log(2 * np.pi * np.e) - np.log(Vd * d ** (d / 2))
check("peak offset ln[(2 pi e)^(d/2)/(V_d d^(d/2))] is close to ln(pi d)/2", shift, 0.5 * np.log(np.pi * d), 0.04)
# the statistical error on ln Z over repeated runs = sqrt(I/N), eq. (2.5.29)
Nr = 100
zs = np.array([nested(Nr, rng)["lnZ"] for _ in range(60)])
info(f"60 runs with {Nr} live points: mean ln Z {zs.mean():.3f} (exact {lnZ_exact:.3f}), scatter {zs.std(ddof=1):.3f}, "
     f"sqrt(I/N) = {np.sqrt(I_exact / Nr):.3f}")
check("scatter of ln Z over 60 runs = sqrt(I/N)", zs.std(ddof=1), np.sqrt(I_exact / Nr), 0.25)
check("mean ln Z over 60 runs is unbiased (in standard errors)", (zs.mean() - lnZ_exact) / (zs.std(ddof=1) / np.sqrt(60)), 0.0, 3.5)
# the general version: random-walk replacement, using likelihood calls only
runw = nested(N, rng, mode="walk")
info(f"nested sampling with random-walk replacement: ln Z = {runw['lnZ']:.3f}, {runw['k']} iterations")
check("random-walk nested sampler ln Z, in units of sqrt(I/N)", (runw["lnZ"] - lnZ_exact) / sdZ, 0.0, 3.5)

# ===================================================================================================
# section 8 and D6, D7: evidence, Occam factor, complexity
# widening one prior width by 10 lowers ln Z by ln 10 and leaves the posterior alone
check("ln Z shift for a 10x wider prior in one direction", (lnZ_exact - np.log(10)) - lnZ_exact, -np.log(10), 1e-12)
# one-dimensional evidence with the prior cutting the likelihood: Z = sqrt(2 pi) sigma [2 Phi(a) - 1]/W, a = W/(2 sigma)
s, Wd = 0.5, 1.2
check("1-D evidence with truncation, eq. (2.5.32)", integrate.quad(lambda t: np.exp(-t * t / (2 * s * s)) / Wd, -Wd / 2, Wd / 2)[0],
      np.sqrt(2 * np.pi) * s * (2 * stats.norm.cdf(Wd / (2 * s)) - 1) / Wd, 1e-10)
check("flat-direction limit of the Occam factor is 1", np.sqrt(2 * np.pi) * 50 * (2 * stats.norm.cdf(1 / 100) - 1), 1.0, 1e-4)
# complexity of one direction = variance of the truncated unit Gaussian, eq. (2.5.34)
for a in (0.1, 1.0, 4.0):
    t = rng.standard_normal(4000000); t = t[np.abs(t) < a]
    check(f"complexity per direction, a = W/2sigma = {a}", np.mean(t ** 2), trunc_var(a), 0.01)
# level-1 closure: chi2_min ~ chi2 with N_dat - d degrees of freedom; posterior-mean chi2 has expectation N_dat
P = Amat @ Sig @ Amat.T
e = rng.standard_normal((20000, Ndat)); cm = np.einsum("ij,ij->i", e, e) - np.einsum("ij,jk,ik->i", e, P, e)
check("L1 closure: E[chi2_min] = N_dat - d, eq. (2.5.35)", cm.mean(), Ndat - d, 0.01)
check("L1 closure: var[chi2_min] = 2 (N_dat - d)", cm.var(), 2 * (Ndat - d), 0.05)
check("L1 closure: E[<chi2>_posterior] = N_dat", cm.mean() + d, Ndat, 0.01)

# ===================================================================================================
# arithmetic on numbers quoted from the project ledgers (context/RESULTS_LEDGER.md, context/PHASE_B_LEDGER.md)
check("PPDF-1: 4.248 - 0.1269 = complexity 4.121", 4.248 - 0.1269, 4.121, 1e-3)
check("PPDF-11 L0: 4.80 + 10.39 = 15.19", 4.80 + 10.39, 15.19, 1e-9)
check("PPDF-11 L1: 622.9 + 11.6 = 634.5", 622.9 + 11.6, 634.5, 1e-9)
check("PPDF-12: 649.5 + 13.73 = 663.3 to the rounding shown", 649.5 + 13.73, 663.3, 2e-4)
check("PPDF-12: 649.5/648 = 1.002", 649.5 / 648, 1.002, 5e-4)
check("PPDF-12 vs PPDF-7: -381.9 - (-1835.1) = +1453", -381.9 + 1835.1, 1453.2, 1e-9)
check("PPDF-12 vs PPDF-7: half the chi2 gap (3626.5 - 649.5)/2 = 1488", (3626.5 - 649.5) / 2, 1488.5, 1e-9)
check("so the Occam part of the gap is -35.3", 1453.2 - 1488.5, -35.3, 1e-9)
check("PPDF-9: -1943.9 - (-1835.1) = -108.8", -1943.9 + 1835.1, -108.8, 1e-9)
check("sqrt(2/648) = 0.056", np.sqrt(2 / 648), 0.056, 1e-2)
check("PPDF-16a: (3089 - 17.64)/3089 = 0.9943", (3089 - 17.64) / 3089, 0.9943, 1e-4)
check("PPDF-16a: 3068.7/3089 = 0.9934", 3068.7 / 3089, 0.9934, 1e-4)
check("PPDF-16a: 3086.3/3089 = 0.9991", 3086.3 / 3089, 0.9991, 1e-4)
check("PPDF-33: ESS 3.2 from 1200 draws = autocorrelation length 375", 1200 / 3.2, 375, 1e-9)
check("PPDF-33: divergences 3/1200 = 0.25%", 3 / 1200, 0.0025, 1e-9)
check("PPDF-33: 3089/648 = 4.8", 3089 / 648, 4.8, 0.01)
check("PPDF-33: 226/3.2 = about 70", 226 / 3.2, 70, 0.01)
check("retracted run: invalid sum of per-chain minima 8.1+13.2+7.1+43.5 = 71.9", 8.1 + 13.2 + 7.1 + 43.5, 71.9, 1e-9)
check("v11: sum of per-chain minima 11.2+12.0+6.3 = 29.5 is a lower bound on 30.8", float(11.2 + 12.0 + 6.3 <= 30.8), 1.0)
check("v11: excess of R-hat over 1 fell by (1.8941-1)/(1.1185-1) = about 8", (1.8941 - 1) / (1.1185 - 1), 7.54, 0.01)
check("v11: ten chains at 4.2 h = 42 h", 10 * 4.2, 42, 1e-9)
check("tree depth 8 = at most 2^8 - 1 = 255 leapfrog steps", 2 ** 8 - 1, 255, 0)

# ===================================================================================================
# plots
TEAL, ORANGE, INK, GRID = "#0e7c7b", "#d96c2c", "#16222e", "#ebe6da"
plt.rcParams.update({"font.size": 14, "axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK,
                     "text.color": INK, "font.family": ["Helvetica Neue", "Arial", "DejaVu Sans"], "svg.fonttype": "none"})
OUT = pathlib.Path(__file__).resolve().parents[2] / "assets" / "guide"; OUT.mkdir(parents=True, exist_ok=True)

# Figure 1: the same number of likelihood or gradient calls spent by Metropolis and by HMC on a narrow 2-D Gaussian
prng = np.random.default_rng(7)
s1, s2, ang = 1.0, 0.08, np.pi / 5
R = np.array([[np.cos(ang), -np.sin(ang)], [np.sin(ang), np.cos(ang)]])
C2 = R @ np.diag([s1 ** 2, s2 ** 2]) @ R.T; P2 = np.linalg.inv(C2)
lp2 = lambda q: -0.5 * q @ P2 @ q; g2f = lambda q: P2 @ q
start = R @ np.array([-1.3, 0.0]); ncall = 240
pm, am = metropolis(lp2, start, ncall, 2.38 / np.sqrt(2) * s2 * 1.4, prng)
pts = [start.copy()]; ends = [start.copy()]; q = start.copy(); eps2, L2 = 1.2 * s2, 20
for _ in range(ncall // L2):
    p = prng.standard_normal(2); qq, pp = q.copy(), p.copy(); seg = [qq.copy()]
    pp = pp - 0.5 * eps2 * g2f(qq)
    for i in range(L2):
        qq = qq + eps2 * pp; pp = pp - (eps2 if i < L2 - 1 else 0.5 * eps2) * g2f(qq); seg.append(qq.copy())
    if np.log(prng.random()) < -lp2(q) + 0.5 * p @ p + lp2(qq) - 0.5 * pp @ pp:
        pts += seg[1:]; q = qq
    ends.append(q.copy())
pts, ends = np.array(pts), np.array(ends)
fig, axs = plt.subplots(1, 2, figsize=(8, 4.6), sharex=True, sharey=True); fig.patch.set_facecolor("white")
tt = np.linspace(0, 2 * np.pi, 200); circ = np.array([np.cos(tt), np.sin(tt)])
for ax, title in zip(axs, ("Metropolis: 240 likelihood calls", "Hamiltonian: 240 gradient calls")):
    for ns in (1, 2):
        el = R @ (np.array([[s1], [s2]]) * ns * circ)
        ax.plot(el[0], el[1], color=INK, lw=1.1, alpha=0.55)
    ax.set_title(title, fontsize=14); ax.set_xlabel("parameter 1"); ax.grid(True, color=GRID, lw=1); ax.set_axisbelow(True)
    ax.set_aspect("equal"); ax.set_xlim(-2.4, 2.4); ax.set_ylim(-2.4, 2.4); ax.set_xticks([-2, -1, 0, 1, 2]); ax.set_yticks([-2, -1, 0, 1, 2])
    ax.plot(*start, "o", color=INK, ms=7, zorder=5)
axs[0].set_ylabel("parameter 2")
axs[0].plot(np.r_[start[0], pm[:, 0]], np.r_[start[1], pm[:, 1]], color=ORANGE, lw=1.6)
axs[1].plot(pts[:, 0], pts[:, 1], color=TEAL, lw=1.1, alpha=0.8)
axs[1].plot(ends[1:, 0], ends[1:, 1], "o", color=TEAL, ms=6, mec="white", mew=1)
for ax in axs: ax.annotate("start", start, xytext=(start[0] - 0.75, start[1] + 1.0), fontsize=14,
                            arrowprops=dict(arrowstyle="-", color=INK, lw=1, shrinkB=5))
fig.tight_layout(); fig.savefig(OUT / "2-5-paths.svg", facecolor="white"); plt.close(fig)
info(f"figure 1: Metropolis acceptance {am:.2f}; HMC {ncall // L2} trajectories of {L2} steps")

# Figure 2: where the posterior mass sits in a nested-sampling run on the toy
fig, ax = plt.subplots(figsize=(8, 4.6)); fig.patch.set_facecolor("white")
kall = np.arange(1, run["k"] + 1); mlnX = kall / N
dens = run["w"][:run["k"]] * N                                    # weight per unit ln X (each step is 1/N of an e-fold)
sm = np.convolve(dens, np.ones(25) / 25, mode="same")
ax.fill_between(mlnX, sm, color=TEAL, alpha=0.25, lw=0); ax.plot(mlnX, sm, color=TEAL, lw=2, label="one run, 200 live points")
# analytic: with r^2 = chi2 - chi2_min, X = V_d r^d /(sqrt(det F) V_box) and L = exp(-r^2/2)
rr = np.linspace(1e-3, 9, 3000); lx = -np.log(Vd * rr ** d / np.sqrt(np.linalg.det(F)) / Vbox)
an = np.exp(-rr ** 2 / 2) * np.exp(-lx) / np.exp(lnZ_exact)
ax.plot(lx, an, color=INK, lw=1.6, ls="--", label="exact")
check("analytic posterior weight per unit ln X integrates to 1", -np.sum(0.5 * (an[1:] + an[:-1]) * np.diff(lx)), 1.0, 2e-3)
ax.axvline(I_exact, color=ORANGE, lw=2); ax.text(I_exact - 0.15, 0.36, "information", color=ORANGE, ha="right", fontsize=14)
ax.set_xlim(I_exact - 9, I_exact + 7); ax.set_ylim(0, 0.42)
ax.set_xlabel("prior volume removed, in e-folds (minus ln X)"); ax.set_ylabel("posterior mass per e-fold")
ax.grid(True, color=GRID, lw=1); ax.set_axisbelow(True); ax.legend(frameon=False, loc="upper left", fontsize=13)
fig.tight_layout(); fig.savefig(OUT / "2-5-nested.svg", facecolor="white"); plt.close(fig)
info(f"figure 2: exact peak of the posterior mass at minus ln X = {lx[np.argmax(an)]:.2f} = I + {lx[np.argmax(an)] - I_exact:.2f}")
check("peak of the posterior mass sits at I + ln[(2 pi e)^(d/2)/(V_d d^(d/2))]", lx[np.argmax(an)] - I_exact, shift, 0.02)

# ---- reviewer's addition: the F of section 5 (half the Hessian of chi2) against chapter 2.3's conventions.
# The script's variable d is the number of parameters, written p in the chapter. Separate generator: stream above unchanged.
_g = np.random.default_rng(77); _N, _p = 25, 3
_X = _g.normal(size=(_N, _p)); _A = _g.normal(size=(_N, _N)); _C = _A @ _A.T + _N * np.eye(_N); _Ci = np.linalg.inv(_C)
_D = _g.normal(size=_N); _chi2 = lambda t: (_D - _X @ t) @ _Ci @ (_D - _X @ t)
_t0 = _g.normal(size=_p); _h = 1e-3; _H = np.zeros((_p, _p)); _E = np.eye(_p) * _h
for _a in range(_p):
    for _b in range(_p):
        _H[_a, _b] = (_chi2(_t0 + _E[_a] + _E[_b]) - _chi2(_t0 + _E[_a] - _E[_b]) - _chi2(_t0 - _E[_a] + _E[_b]) + _chi2(_t0 - _E[_a] - _E[_b])) / (4 * _h * _h)
_F = _X.T @ _Ci @ _X
check("linear model: F = (1/2) d^2 chi2 = J^T C^-1 J (the F of section 5 is H/2 of chapter 2.3)", np.abs(_H / 2 - _F).max() / np.abs(_F).max(), 0, 1e-6)
check("  and Sigma = F^-1 equals V = 2 H^-1", np.abs(np.linalg.inv(_F) - 2 * np.linalg.inv(_H)).max() / np.abs(np.linalg.inv(_F)).max(), 0, 1e-6)
print("wrote assets/guide/2-5-paths.svg, 2-5-nested.svg;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
