#!/usr/bin/env python3
"""Numerical checks for guide chapter 2.2 (the loss function), and its two data plots.
Every formula the chapter states is tested here; the script exits non-zero if any check fails.
Run:  python3 guide-build/tools/check_2_2.py     (writes assets/guide/2-2-bias.svg and 2-2-chi2dist.svg)"""
import pathlib, sys
import numpy as np
from scipy import integrate, optimize, 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(22)

# ---------------------------------------------------------------------------------------------------
# sections 2-3: the chi2, whitening, and the covariance matrix of the measurement model
# ---------------------------------------------------------------------------------------------------
N, K = 12, 3
sig = rng.uniform(0.5, 1.5, N)                      # uncorrelated errors sigma_i
B = rng.normal(0, 0.8, (N, K))                      # correlated shifts beta_ia
U = np.diag(sig**2); Ui = np.diag(1/sig**2)
C = U + B @ B.T                                     # eq. (2.2.6)
r = rng.normal(0, 1.5, N)                           # a residual vector D - T
chi2_cov = r @ np.linalg.solve(C, r)                # eq. (2.2.2)
L = np.linalg.cholesky(C); z = np.linalg.solve(L, r)
check("whitening: chi2 = sum z_i^2 (2.2.4)", z @ z, chi2_cov)
# simulate D - T = sigma*eps + B*lambda and compare the sample covariance with U + B B^T
M = 400000
sim = rng.normal(size=(M, N))*sig + rng.normal(size=(M, K)) @ B.T
Cs = sim.T @ sim / M
check("sample covariance of the model (2.2.5) = U + B B^T, largest deviation", np.abs(Cs - C).max(), 0, 6e-2)
check("correlation of two points, 1% stat and shared 5%: 25/26", 25/np.sqrt(26*26), 25/26)
info(f"correlation coefficient 25/26 = {25/26:.4f}")

# ---------------------------------------------------------------------------------------------------
# section 4, D1, D2: nuisance parameters = covariance matrix
# ---------------------------------------------------------------------------------------------------
A = np.eye(K) + B.T @ Ui @ B
lam_hat = np.linalg.solve(A, B.T @ Ui @ r)          # eq. (2.2.8)
chi2_shift = lambda lam: np.sum((r - B @ lam)**2/sig**2) + lam @ lam        # eq. (2.2.7)
res = optimize.minimize(chi2_shift, np.zeros(K), method="BFGS", options={"gtol": 1e-10})
check("numerical minimum over lambda sits at lambda-hat (2.2.8)", np.abs(res.x - lam_hat).max(), 0, 1e-5)
check("profiled chi2 = covariance-matrix chi2", chi2_shift(lam_hat), chi2_cov, 1e-10)
check("eq. (2.2.9): r U^-1 r - r U^-1 B A^-1 B^T U^-1 r", r @ Ui @ r - (r @ Ui @ B) @ np.linalg.solve(A, B.T @ Ui @ r), chi2_cov, 1e-10)
W = Ui - Ui @ B @ np.linalg.solve(A, B.T @ Ui)
check("Woodbury (2.2.10): (U + B B^T) W = 1, largest deviation", np.abs(C @ W - np.eye(N)).max(), 0, 1e-10)
check("determinant: det C = det U det A (2.2.12)", np.linalg.det(C), np.linalg.det(U)*np.linalg.det(A), 1e-10)
lam = rng.normal(size=K)
check("completing the square (D2)", chi2_shift(lam), chi2_shift(lam_hat) + (lam - lam_hat) @ A @ (lam - lam_hat), 1e-10)
# marginalise one nuisance parameter numerically: N = 3, K = 1, including the normalisation
s3 = np.array([0.5, 0.4, 0.6]); b3 = np.array([0.30, 0.24, 0.36]); r3 = np.array([0.60, -0.20, 0.45])
C3 = np.diag(s3**2) + np.outer(b3, b3)
joint = lambda l: np.exp(-0.5*(np.sum((r3 - b3*l)**2/s3**2) + l*l))/((2*np.pi)**2*np.prod(s3))
marg = integrate.quad(joint, -30, 30, epsabs=1e-14, epsrel=1e-12)[0]
gauss = np.exp(-0.5*r3 @ np.linalg.solve(C3, r3))/np.sqrt((2*np.pi)**3*np.linalg.det(C3))
check("integral over lambda = Gaussian with covariance C, normalisation included (2.2.12)", marg, gauss, 1e-9)
# the worked example of section 4 and Figure 1: five points, 1% independent errors, one shared 5% source
sg, be = np.ones(5), np.full(5, 5.)
def one_source(rr):
    a = 1 + np.sum(be**2/sg**2); t = np.sum(be*rr/sg**2)
    return np.sum(rr**2/sg**2) - t*t/a, t/a          # eq. (2.2.11) and the fitted shift
r_same, r_alt = np.full(5, 4.), np.array([4., -4., 4., -4., 4.])
c_same, l_same = one_source(r_same); c_alt, l_alt = one_source(r_alt)
C5 = np.diag(sg**2) + np.outer(be, be)
check("worked example: uncorrelated chi2 = 80", np.sum(r_same**2), 80.0)
check("worked example, coherent offset: chi2 = 80 - 10000/126", c_same, 80 - 10000/126)
check("  the same from the matrix inverse", r_same @ np.linalg.solve(C5, r_same), c_same)
check("  fitted shift 100/126", l_same, 100/126)
check("worked example, alternating residuals: chi2 = 80 - 400/126", c_alt, 80 - 400/126)
check("  the same from the matrix inverse", r_alt @ np.linalg.solve(C5, r_alt), c_alt)
check("  fitted shift 20/126", l_alt, 20/126)
check("  quoted values 0.63, 0.79, 76.8, 0.16", round(c_same, 2) + round(l_same, 2) + round(c_alt, 1) + round(l_alt, 2), 0.63 + 0.79 + 76.8 + 0.16)
info(f"coherent offset: chi2 = {c_same:.3f} with shift {l_same:.3f}; alternating residuals: chi2 = {c_alt:.2f} with shift {l_alt:.3f}")
# variance of a fitted shift is below 1: Var(lambda-hat) = 1 - 1/A for one source when the model is right
a1 = 1 + np.sum(be**2/sg**2)
rs = rng.normal(size=(M, 5))*sg + rng.normal(size=(M, 1))*be
lh = (rs @ (be/sg**2))/a1
check("variance of the fitted shift = 1 - 1/A", lh.var(), 1 - 1/a1, 5e-3)

# ---------------------------------------------------------------------------------------------------
# section 5, D3: the d'Agostini bias
# ---------------------------------------------------------------------------------------------------
def naive_fit(D, sg, s):
    """Minimise (T - D)^T C^-1 (T - D) with C = diag(sg^2) + s^2 D D^T: explicit matrix solution."""
    Cm = np.diag(sg**2) + s*s*np.outer(D, D); one = np.ones(len(D))
    return (one @ np.linalg.solve(Cm, D))/(one @ np.linalg.solve(Cm, one))
def formula(D, sg, s):
    w = np.sum(D/sg**2)/np.sum(1/sg**2); X = np.sum((D - w)**2/sg**2)
    return w/(1 + s*s*X), w, X
D = np.array([8.0, 8.5]); sg2 = np.array([0.16, 0.17]); s = 0.10        # d'Agostini's example: 2% errors, 10% normalisation
That, w, X = formula(D, sg2, s)
check("d'Agostini example: matrix fit = eq. (2.2.14)", naive_fit(D, sg2, s), That, 1e-10)
check("  two-point form (2.2.15)", w/(1 + s*s*(D[0]-D[1])**2/(sg2[0]**2 + sg2[1]**2)), That, 1e-12)
check("  weighted mean 8.235", w, 8.235, 1e-4); check("  result 7.87", That, 7.87, 1e-3)
info(f"d'Agostini example: w = {w:.4f}, X = {X:.3f}, s^2 X = {s*s*X:.4f}, fitted T = {That:.4f}")
Cm = np.diag(sg2**2) + s*s*np.outer(D, D)
num = optimize.minimize_scalar(lambda T: (T - D) @ np.linalg.solve(Cm, T - D)).x
check("  brute-force minimisation of the chi2", num, That, 1e-7)
Dn = rng.normal(5, 0.4, 9); sgn = rng.uniform(0.2, 0.6, 9)
check("n = 9, unequal errors: matrix fit = eq. (2.2.14)", naive_fit(Dn, sgn, 0.07), formula(Dn, sgn, 0.07)[0], 1e-10)
# the rescaling form (2.2.16): minimise over T and lambda numerically
resc = lambda p: np.sum((Dn*(1 - 0.07*p[1]) - p[0])**2/sgn**2) + p[1]**2
pr = optimize.minimize(resc, [5.0, 0.0], method="BFGS", options={"gtol": 1e-10})
Tn, wn, Xn = formula(Dn, sgn, 0.07)
check("rescaling form (2.2.16): minimum in T", pr.x[0], Tn, 1e-6)
check("  rescaling factor f = 1/(1 + s^2 X)", 1 - 0.07*pr.x[1], 1/(1 + 0.07**2*Xn), 1e-6)
check("  chi2 at the minimum = X/(1 + s^2 X)", pr.fun, Xn/(1 + 0.07**2*Xn), 1e-8)

# simulation: truth T = 1, n points, independent 5% errors, one common 3% normalisation
def simulate(n, s, sg, trials):
    n0 = 1 + s*rng.normal(size=(trials, 1))
    Dm = n0*(1 + sg*rng.normal(size=(trials, n)))            # every point shares the factor n0
    w = Dm.mean(axis=1); X = ((Dm - w[:, None])**2).sum(axis=1)/sg**2
    return (w/(1 + s*s*X)), w                                # naive fit by (2.2.14); t0 fit (T0 = 1) is the mean w
s_sim, sg_sim = 0.03, 0.05
ns = np.array([2, 5, 10, 20, 50, 100, 200, 300])
naive_mean, t0_mean, naive_err = [], [], []
for n in ns:
    a, b = simulate(int(n), s_sim, sg_sim, 40000)
    naive_mean.append(a.mean()); t0_mean.append(b.mean()); naive_err.append(a.std()/np.sqrt(len(a)))
naive_mean, t0_mean = np.array(naive_mean), np.array(t0_mean)
pred = 1/(1 + (ns - 1)*s_sim**2)                             # eq. (2.2.17)
for n, a, b, p in zip(ns, naive_mean, t0_mean, pred):
    check(f"simulated mean of the naive fit, n = {n}: eq. (2.2.17)", a, p, 2e-3)
    check(f"simulated mean of the t0 fit, n = {n}: unbiased", b, 1.0, 1e-3)
# the simulation uses (2.2.14); confirm against the explicit matrix fit on a few pseudo-experiments
for n in (5, 50):
    n0 = 1 + s_sim*rng.normal(); Dm = n0*(1 + sg_sim*rng.normal(size=n))
    check(f"matrix fit = (2.2.14) on a pseudo-experiment, n = {n}", naive_fit(Dm, np.full(n, sg_sim), s_sim),
          formula(Dm, np.full(n, sg_sim), s_sim)[0], 1e-9)
check("bias for 100 points, 2% normalisation: 1/(1 + 99*0.0004)", 1/(1 + 99*0.02**2), 0.9619, 1e-4)
check("bias for 300 points, 3% normalisation", 1/(1 + 299*0.03**2), 0.7880, 1e-4)
info(f"bias factors: n=100, s=2%: {1/(1+99*0.0004):.4f};  n=300, s=3%: {1/(1+299*0.0009):.4f}")

# ---------------------------------------------------------------------------------------------------
# section 6, D4: the t0 prescription
# ---------------------------------------------------------------------------------------------------
T0 = 5.3; one = np.ones(9)
Ct0 = np.diag(sgn**2) + (0.07*T0)**2*np.outer(one, one)                # eq. (2.2.18)
Tt0 = (one @ np.linalg.solve(Ct0, Dn))/(one @ np.linalg.solve(Ct0, one))
Sig2 = 1/np.sum(1/sgn**2)
check("t0 fit returns the weighted mean for any T0 (2.2.19)", Tt0, wn, 1e-10)
check("t0 variance = Sigma^2 + s^2 T0^2 (2.2.19)", 1/(one @ np.linalg.solve(Ct0, one)), Sig2 + (0.07*T0)**2, 1e-10)
chi_t0 = lambda T: (T - Dn) @ np.linalg.solve(Ct0, T - Dn)
check("t0 chi2 profile: X + (T - w)^2/(Sigma^2 + s^2 T0^2)", chi_t0(wn + 0.4), Xn + 0.16/(Sig2 + (0.07*T0)**2), 1e-10)
check("d'Agostini example with t0: returns the weighted mean", formula(D, sg2, 0)[1], 8.235, 1e-4)
# sampling variance of the t0 estimator in the simulation: sigma^2/n + s^2 (to first order in s)
a, b = simulate(20, s_sim, sg_sim, 400000)
check("simulated variance of the t0 fit, n = 20: sigma^2/n + s^2", b.var(), sg_sim**2/20 + s_sim**2, 2e-2*1e-3)
# several experiments with their own normalisations: iterate eq. (2.2.20)
De = np.array([1.10, 0.95, 1.02]); se = np.array([0.02, 0.05, 0.03]); ne = np.array([0.10, 0.02, 0.05])
def step(T0): wgt = 1/(se**2 + ne**2*T0**2); return np.sum(wgt*De)/np.sum(wgt)
it = [0.0]
for _ in range(6): it.append(step(it[-1]))
info("t0 iteration from T0 = 0: " + ", ".join(f"{v:.5f}" for v in it[1:]))
fixed = optimize.brentq(lambda T: step(T) - T, 0.5, 1.5)
check("iteration converges to the fixed point", it[-1], fixed, 1e-8)
check("the third iterate is within 1e-4 of the fixed point", abs(it[3] - fixed), 0, 1e-4)
check("first iterate (T0 = 0) is the statistics-only weighted mean", it[1], np.sum(De/se**2)/np.sum(1/se**2), 1e-12)

# ---------------------------------------------------------------------------------------------------
# section 7, D5: statistics of the chi2
# ---------------------------------------------------------------------------------------------------
Nd, npar, trials = 60, 7, 200000
Bc = rng.normal(0, 0.5, (Nd, 2)); Cd = np.diag(rng.uniform(0.5, 1.5, Nd)) + Bc @ Bc.T
Ld = np.linalg.cholesky(Cd)
noise = rng.normal(size=(trials, Nd)) @ Ld.T                     # correlated noise with covariance Cd
zs = np.linalg.solve(Ld, noise.T).T
c2 = (zs**2).sum(axis=1)
check("mean of chi2 at the truth = N (2.2.22)", c2.mean(), Nd, 3e-3)
check("variance of chi2 at the truth = 2N (2.2.22)", c2.var(), 2*Nd, 2e-2)
J = rng.normal(size=(Nd, npar)); Jw = np.linalg.solve(Ld, J)     # linear model T = T* + J theta, whitened
P = Jw @ np.linalg.solve(Jw.T @ Jw, Jw.T)
check("P is a projector of trace p", np.trace(P), npar, 1e-10); check("  P^2 = P", np.abs(P @ P - P).max(), 0, 1e-10)
c2min = (zs*(zs @ (np.eye(Nd) - P))).sum(axis=1)
check("mean of chi2 at the minimum = N - p (2.2.24)", c2min.mean(), Nd - npar, 3e-3)
check("variance of chi2 at the minimum = 2(N - p)", c2min.var(), 2*(Nd - npar), 2e-2)
check("E z^4 = 3 for a unit normal", stats.norm.moment(4), 3.0)
# the numbers quoted in section 7 (inputs from context/PHASE_B_LEDGER.md)
N3, chi3 = 4615, 5713.228
check("ledger: R3 chi2/N = 1.2380", chi3/N3, 1.2380, 5e-5)
check("ledger: PPDF-31 R3 chi2/N = 1.2368", 5707.67/N3, 1.2368, 5e-5)
check("ledger: R0 chi2/N = 1.1505", 3553.91/3089, 1.1505, 5e-5)
check("ledger: R3 penalties off chi2/N = 16.35", 75434.44/N3, 16.35, 5e-4)
check("ledger: closure chi2(truth)/N = 0.9996", 3087.661/3089, 0.9996, 5e-5)
check("ledger: penalty / data at the R0 best fit = 0.0025", 8.927/3530.643, 0.0025, 5e-5)
sd3, sd0 = np.sqrt(2/N3), np.sqrt(2/3089)
check("sqrt(2/4615) = 0.0208", sd3, 0.0208, 1e-4); check("sqrt(2/3089) = 0.0254", sd0, 0.0254, 1e-4)
check("(1.2380 - 1)/0.0208 = 11.4", (chi3/N3 - 1)/sd3, 11.4, 5e-3)
check("closure: (0.9996 - 1)/0.0254 = -0.02", (3087.661/3089 - 1)/sd0, -0.02, 5e-3)
check("expected chi2/N at the minimum of a linear 52-parameter fit: (4615 - 52)/4615 = 0.9887", (N3 - 52)/N3, 0.9887, 5e-5)
check("uniform error rescaling sqrt(1.2380) = 1.113", np.sqrt(chi3/N3), 1.113, 5e-4)
info(f"chi2 = {chi3} for {N3} points: log10 of the tail probability = {stats.chi2.logsf(chi3, N3)/np.log(10):.1f}")
info(f"sqrt(2/N): N=50 {np.sqrt(2/50):.3f}, N=300 {np.sqrt(2/300):.3f}, N=4615 {sd3:.4f}")
check("50 points at 1.3: 1.5 standard deviations", 0.3/np.sqrt(2/50), 1.5, 1e-9)
check("500 points at 1.3: 4.7 standard deviations", 0.3/np.sqrt(2/500), 4.7, 1e-2)
check("fitted shift moves the predictions by 3.97%", 5*100/126, 3.97, 1e-3)
check("ledger: 70729.11/3078.65 = 23", 70729.11/3078.65, 22.97, 1e-3)
check("sqrt(2/50) = 0.20", np.sqrt(2/50), 0.20, 1e-9); check("sqrt(2/300) = 0.082", np.sqrt(2/300), 0.082, 1e-3)

# ---------------------------------------------------------------------------------------------------
# section 8: tension between two data sets
# ---------------------------------------------------------------------------------------------------
a1_, a2_, e1, e2 = 1.30, 0.70, 0.10, 0.20
chi = lambda th: (th - a1_)**2/e1**2 + (th - a2_)**2/e2**2
th_hat = optimize.minimize_scalar(chi).x
check("tension: best fit is the weighted mean", th_hat, (a1_/e1**2 + a2_/e2**2)/(1/e1**2 + 1/e2**2), 1e-7)
check("tension: chi2_min = (a1 - a2)^2/(e1^2 + e2^2) (2.2.25)", chi(th_hat), (a1_ - a2_)**2/(e1**2 + e2**2), 1e-9)
tot = (a1_ - a2_)**2/(e1**2 + e2**2)
check("  share paid by set 1: e1^2/(e1^2 + e2^2)", (th_hat - a1_)**2/e1**2/tot, e1**2/(e1**2 + e2**2), 1e-7)
check("  share paid by set 2: e2^2/(e1^2 + e2^2)", (th_hat - a2_)**2/e2**2/tot, e2**2/(e1**2 + e2**2), 1e-7)
check("a 3 sigma tension adds 9; over 300 points that is 0.03 per point", 9/300, 0.03)
# an N-point version: two 150-point sets that disagree by 3 sigma in one shared parameter
n1 = 150
d1 = 1.0 + rng.normal(0, 1, n1); d2 = 1.0 + 3*np.sqrt(2/n1) + rng.normal(0, 1, n1)      # unit errors; the means differ by 3 sigma
m1, m2 = d1.mean(), d2.mean(); mm = (m1 + m2)/2
extra = np.sum((d1 - mm)**2) + np.sum((d2 - mm)**2) - np.sum((d1 - m1)**2) - np.sum((d2 - m2)**2)
check("N-point sets: cost of a common fit = (m1 - m2)^2/(2/n)", extra, (m1 - m2)**2/(2/n1), 1e-9)

# ---------------------------------------------------------------------------------------------------
# section 9: a Gaussian theory shift adds its covariance to the experimental one
# ---------------------------------------------------------------------------------------------------
Bth = rng.normal(0, 0.6, (N, 2)); Cth = Bth @ Bth.T
sim2 = rng.normal(size=(M, N)) @ L.T + rng.normal(size=(M, 2)) @ Bth.T
check("covariance of data about a shifted theory = C + C_th (2.2.26), largest deviation",
      np.abs(sim2.T @ sim2/M - (C + Cth)).max(), 0, 8e-2)
A2 = np.eye(2) + Bth.T @ np.linalg.solve(C, Bth)
check("profiling the theory shifts = using C + C_th", r @ np.linalg.solve(C, r) - (r @ np.linalg.solve(C, Bth)) @ np.linalg.solve(A2, Bth.T @ np.linalg.solve(C, r)),
      r @ np.linalg.solve(C + Cth, r), 1e-10)

# ---------------------------------------------------------------------------------------------------
# section 10: the penalty function
# ---------------------------------------------------------------------------------------------------
elu = lambda t, al: np.where(t >= 0, t, al*(np.exp(np.minimum(t, 0)) - 1))             # eq. (2.2.27)
al = 1e-7
check("ELU is continuous at 0", float(elu(-1e-12, al)), float(elu(1e-12, al)), 1e-9)
check("ELU(-f) for a negative distribution f = -0.02 is 0.02", float(elu(0.02, al)), 0.02)
check("ELU(-f) for a positive distribution f = 3 is -alpha(1 - e^-3)", float(elu(-3.0, al)), -al*(1 - np.exp(-3)), 1e-12)
check("ELU(-f) for large positive f tends to -alpha", float(elu(-50.0, al)), -al, 1e-12)

# ---------------------------------------------------------------------------------------------------
# the two data plots
# ---------------------------------------------------------------------------------------------------
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,
                     "text.color": INK, "font.family": "sans-serif", "svg.fonttype": "none",
                     "figure.facecolor": "white", "axes.facecolor": "white", "savefig.facecolor": "white"})
OUT = pathlib.Path(__file__).resolve().parents[2] / "assets" / "guide"; OUT.mkdir(parents=True, exist_ok=True)
def style(ax):
    ax.grid(True, color=GRID, lw=1); ax.set_axisbelow(True)
    for sp in ("top", "right"): ax.spines[sp].set_visible(False)

fig, ax = plt.subplots(figsize=(8, 4.6)); style(ax)
nn = np.linspace(2, 300, 300)
ax.plot(nn, 1/(1 + (nn - 1)*s_sim**2), color=ORANGE, lw=2.2, label="prediction, Eq. (2.2.17)")
ax.plot(ns, naive_mean, "o", color=ORANGE, ms=8, mec="white", mew=1.2, label="simulation: covariance built from the data")
ax.plot(ns, t0_mean, "s", color=TEAL, ms=8, mec="white", mew=1.2, label="simulation: covariance built from a fixed reference")
ax.axhline(1, color=INK, lw=1, ls=(0, (4, 3)))
ax.set_xlabel("number of data points sharing the normalisation"); ax.set_ylabel("mean fitted value / true value")
ax.set_ylim(0.76, 1.03); ax.set_xlim(0, 310)
ax.legend(frameon=False, fontsize=13, loc="lower left")
ax.text(304, 1.006, "truth", ha="right", va="bottom", fontsize=13, color=INK)
fig.savefig(OUT / "2-2-bias.svg", bbox_inches="tight"); plt.close(fig)

fig, ax = plt.subplots(figsize=(8, 4.6)); style(ax)
xx = np.linspace(0.55, 1.65, 2000)
for Nn, col, ls in ((50, MUTED, (0, (2, 2))), (300, INK, (0, (5, 2))), (4615, TEAL, "-")):
    pdf = stats.chi2.pdf(xx*Nn, Nn)*Nn
    ax.plot(xx, pdf/pdf.max(), color=col, lw=2.2, ls=ls, label=f"{Nn:,} data points")
    if Nn == 4615: ax.fill_between(xx, pdf/pdf.max(), color=TEAL, alpha=0.15, lw=0)
ax.axvline(1.2380, color=ORANGE, lw=2.2); ax.axvline(1.17, color=ORANGE, lw=1.6, ls=(0, (4, 3)))
ax.text(1.25, 1.44, "solid line: this project,\nglobal fit, 1.238", color=ORANGE, fontsize=13, va="top", ha="left")
ax.text(1.25, 1.22, "dashed line: NNPDF4.0,\npublished, 1.17", color=ORANGE, fontsize=13, va="top", ha="left")
ax.set_xlabel("χ² per data point"); ax.set_ylabel("probability density (peak scaled to 1)")
ax.set_xlim(0.55, 1.65); ax.set_ylim(0, 1.5); ax.set_yticks([0, 0.25, 0.5, 0.75, 1.0])
ax.legend(frameon=False, fontsize=13, loc="upper left")
fig.savefig(OUT / "2-2-chi2dist.svg", bbox_inches="tight"); plt.close(fig)

print("wrote 2-2-bias.svg and 2-2-chi2dist.svg;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
