#!/usr/bin/env python3
"""Numerical checks for guide chapter 3.1 (the state of the art), and its two data plots.
Every formula the chapter derives is tested here; numbers quoted from the Snowmass whitepaper are only
combined arithmetically, never re-derived. The script exits non-zero if any check fails.
Run:  python3 guide-build/tools/check_3_1.py        (writes assets/guide/3-1-*.svg)"""
import pathlib, sys
import numpy as np
from scipy import integrate, optimize, stats
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

SITE = pathlib.Path(__file__).resolve().parents[2]
FIG = SITE / "assets" / "guide"; FIG.mkdir(parents=True, exist_ok=True)
TEAL, ORANGE, INK, GRID = "#0e7c7b", "#d96c2c", "#16222e", "#ebe6da"
plt.rcParams.update({"font.size": 13, "axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK,
                     "ytick.color": INK, "text.color": INK, "axes.grid": True, "grid.color": GRID,
                     "figure.facecolor": "white", "axes.facecolor": "white", "svg.fonttype": "path",
                     "legend.fontsize": 13, "axes.titlesize": 14})
rng = np.random.default_rng(31)
ok = True
def check(name, got, want, tol=1e-6):
    global ok
    good = abs(got - want) <= tol * max(1.0, abs(want))
    ok &= good
    print(f"{'PASS' if good else 'FAIL'}  {name}: got {got:.10g}, want {want:.10g}")
q = lambda f, a=0, b=1, **k: integrate.quad(f, a, b, limit=400, epsabs=1e-12, epsrel=1e-9, **k)[0]

# ---- section 2: the mismatch uncertainty, eq. (3.1.1), is half a relative difference -------------------------
d_th = lambda s_nnlo, s_nlo: 0.5*abs(s_nnlo - s_nlo)/s_nnlo
check("delta(PDF-TH) for a 4% change between NLO and NNLO sets is 2%", d_th(50.0, 48.0), 0.02)

# ---- section 3 / D1: cross-section as an integral over the luminosity ---------------------------------------
# toy distributions (NOT fits): two species a, b with different shapes
fa = lambda x: 2.0*x**-0.3*(1-x)**4
fb = lambda x: 1.2*x**-0.6*(1-x)**3
s = 1.0                                                  # work in units of s
sig_aa = lambda sh: sh**2*np.exp(-3*sh)                  # arbitrary smooth partonic cross-sections of s-hat
sig_ab = lambda sh: sh*(1+sh)
def lum(fi, fj, m2, same):                               # eq. (3.1.2)
    tau = m2/s
    if tau > 1e-4:                                       # literally eq. (3.1.2)
        return (1/s)*(1/(1+same))*q(lambda x: (fi(x)*fj(tau/x) + fj(x)*fi(tau/x))/x, tau, 1)
    ex = np.exp                                          # same integral in u = ln x, stable for very small tau
    return (1/s)*(1/(1+same))*q(lambda u: fi(ex(u))*fj(tau/ex(u)) + fj(ex(u))*fi(tau/ex(u)), np.log(tau), 0)
def direct(fi, fj, sig):                                 # ordered double integral  int dx1 dx2 fi(x1) fj(x2) sig(x1 x2 s)
    L = np.log(1e-9)                                     # in u = ln x, so that the small-x rise is smooth
    return integrate.dblquad(lambda u2, u1: np.exp(u1+u2)*fi(np.exp(u1))*fj(np.exp(u2))*sig(np.exp(u1+u2)*s),
                             L, 0, L, 0, epsabs=1e-10, epsrel=1e-9)[0]
t0 = 1e-9
lhs = direct(fa, fa, sig_aa) + direct(fa, fb, sig_ab) + direct(fb, fa, sig_ab)       # sum over ORDERED pairs (aa, ab, ba)
rhs = q(lambda lt: np.exp(lt)*(lum(fa, fa, np.exp(lt), 1)*sig_aa(np.exp(lt)) + lum(fa, fb, np.exp(lt), 0)*sig_ab(np.exp(lt))),
        np.log(t0), 0.0)                                 # sum over UNORDERED pairs of  int dm^2 L sigma-hat
check("sigma = sum_{i<=j} int dm^2 L_ij sigma_ij  (D1)", rhs, lhs, 2e-6)
# rapidity form, eq. (3.1.5)
tau = 3e-3; rt = np.sqrt(tau); ymax = -0.5*np.log(tau)
check("x form = rapidity form of L_ab", lum(fa, fb, tau, 0),
      q(lambda y: fa(rt*np.exp(y))*fb(rt*np.exp(-y)) + fb(rt*np.exp(y))*fa(rt*np.exp(-y)), -ymax, ymax), 1e-9)
check("x form = rapidity form of L_aa", lum(fa, fa, tau, 1),
      q(lambda y: fa(rt*np.exp(y))*fa(rt*np.exp(-y)), -ymax, ymax), 1e-9)

# Higgs kinematics at 14 TeV (m_H = 125 GeV)
mH, rs = 125.0, 14000.0
rtH = mH/rs; yH = np.log(1/rtH)
check("sqrt(tau) for m_H at 14 TeV", rtH, 0.00893, 2e-3)
check("y_max = ln(1/sqrt(tau))", yH, 4.72, 2e-3)
print(f"INFO  |y| < 2.5 at m_H: x from {rtH*np.exp(-2.5):.2e} to {rtH*np.exp(2.5):.3f}")
check("x range lower edge for |y|<2.5", rtH*np.exp(-2.5), 7.3e-4, 1e-2)
check("x range upper edge for |y|<2.5", rtH*np.exp(2.5), 0.109, 1e-2)
for m in (1000.0, 5000.0):
    print(f"INFO  m_X = {m:g} GeV at 14 TeV: sqrt(tau) = {m/rs:.3f}, y_max = {np.log(rs/m):.2f}")
check("sqrt(tau) at 1 TeV", 1000/rs, 0.071, 1e-2); check("sqrt(tau) at 5 TeV", 5000/rs, 0.357, 1e-2)

# the weight w(y) of eq. (3.1.6) for a toy gluon  x g = x^-lam (1-x)^b : the small-x power drops out
lam, bg = 0.3, 5.0
g = lambda x: x**(-1-lam)*(1-x)**bg
def weight(rt):
    ym = np.log(1/rt)
    raw = lambda y: g(rt*np.exp(y))*g(rt*np.exp(-y))
    norm = q(raw, -ym, ym)
    return (lambda y: raw(y)/norm), ym
wH, ymH = weight(rtH)
y0 = 1.3
check("toy weight: small-x power cancels", wH(y0)/wH(0.0),
      ((1-rtH*np.exp(y0))*(1-rtH*np.exp(-y0)))**bg/(1-rtH)**(2*bg), 1e-10)
frac = lambda w, Y: q(w, -Y, Y)
f1, f25 = frac(wH, 1.0), frac(wH, 2.5)
print(f"INFO  toy gluon, m_H at 14 TeV: fraction of L_gg from |y|<1: {f1:.3f}; from |y|<2.5: {f25:.3f}")
check("fraction of toy L_gg inside |y|<1", f1, 0.368, 2e-3)
check("fraction of toy L_gg inside |y|<2.5", f25, 0.827, 2e-3)
Y68 = optimize.brentq(lambda Y: frac(wH, Y) - 0.68, 0.1, ymH)
print(f"INFO  68% of toy L_gg inside |y| < {Y68:.2f}: x from {rtH*np.exp(-Y68):.1e} to {rtH*np.exp(Y68):.3f}")
check("68% of the toy L_gg lies inside |y| <", Y68, 1.94, 3e-3)
check("x at y = -1.94", rtH*np.exp(-Y68), 1.3e-3, 3e-2); check("x at y = +1.94", rtH*np.exp(Y68), 0.062, 1e-2)
w1T, ym1T = weight(1000/rs)
f1T = frac(w1T, 1.0)
print(f"INFO  toy gluon, 1 TeV at 14 TeV: fraction from |y|<1: {f1T:.3f}")
check("fraction of toy L_gg inside |y|<1 at 1 TeV", f1T, 0.740, 2e-3)

# first-order variation, eq. (3.1.6): L[g(1+r)] against the weighted average of r
r_of = lambda x: 0.01*(1 + 0.5*np.log10(x/rtH))          # an x-dependent relative shift of the gluon, 1% at x = sqrt(tau)
L0 = q(lambda y: g(rtH*np.exp(y))*g(rtH*np.exp(-y)), -ymH, ymH)
L1 = q(lambda y: g(rtH*np.exp(y))*(1+r_of(rtH*np.exp(y)))*g(rtH*np.exp(-y))*(1+r_of(rtH*np.exp(-y))), -ymH, ymH)
lin = q(lambda y: wH(y)*(r_of(rtH*np.exp(y)) + r_of(rtH*np.exp(-y))), -ymH, ymH)
check("first-order variation of L_gg (3.1.6)", L1/L0 - 1, lin, 2e-4)
check("uniform 1% shift of g moves L_gg by 2% (to first order)", 1.01**2 - 1, 0.02, 2e-4)
# the two-point formula, eq. (3.1.8): relative uncertainty r sqrt(2(1+rho))
for rho in (1.0, 0.0, -0.5, -1.0):
    cov = 0.01**2*np.array([[1, rho], [rho, 1]])
    d = rng.multivariate_normal([0, 0], cov, size=400000)
    got = np.std((1+d[:, 0])*(1+d[:, 1]) - 1)
    check(f"delta L/L for 1% gluon, rho = {rho:+.1f}", got, 0.01*np.sqrt(2*(1+rho)), 2e-4)   # second-order term is r^2 sqrt2
check("rho = 0 value", 0.01*np.sqrt(2), 0.0141, 1e-4)
# alpha_S: the explicit alpha_S^2 of the lowest-order gg -> H cross-section, with the FLAG value quoted in the whitepaper
check("2 x 0.0008/0.1184", 2*0.0008/0.1184, 0.0135, 1e-4)

# ---- section 4 / D2: Hessian and replica propagation, correlation, ellipses ---------------------------------
n = 6
A = rng.normal(size=(n, n)); Cth = A @ A.T/n + 0.2*np.eye(n)          # covariance of the fit parameters
ga, gb = rng.normal(size=n), rng.normal(size=n)                        # gradients of two observables
evals, U = np.linalg.eigh(Cth)
plus = [np.sqrt(evals[k])*U[:, k] for k in range(n)]                   # eigenvector sets: one standard deviation each way
dA = np.array([ga @ p - ga @ (-p) for p in plus]); dB = np.array([gb @ p - gb @ (-p) for p in plus])
sA, sB = 0.5*np.sqrt(np.sum(dA**2)), 0.5*np.sqrt(np.sum(dB**2))
check("Hessian master formula (3.1.9) = sqrt(g C g)", sA, np.sqrt(ga @ Cth @ ga))
check("Hessian correlation (3.1.11)", np.sum(dA*dB)/(4*sA*sB), (ga @ Cth @ gb)/np.sqrt((ga @ Cth @ ga)*(gb @ Cth @ gb)))
reps = rng.multivariate_normal(np.zeros(n), Cth, size=400000)
ra, rb = reps @ ga, reps @ gb
check("replica standard deviation (3.1.10), 1/(N_rep - 1)", ra.std(ddof=1), sA, 5e-3)
check("replica correlation (3.1.11), same normalisation", np.cov(ra, rb, ddof=1)[0, 1]/(ra.std(ddof=1)*rb.std(ddof=1)), np.sum(dA*dB)/(4*sA*sB), 5e-3)
# the 1/(N_rep - 1) estimator is unbiased for small ensembles; 1/N_rep is low by (N_rep - 1)/N_rep
small = (reps[:200000] @ ga).reshape(-1, 5)
check("mean of the 1/(N_rep-1) variance over ensembles of 5 replicas = true variance", small.var(axis=1, ddof=1).mean()/sA**2, 1.0, 1e-2)
check("mean of the 1/N_rep variance over ensembles of 5 replicas = 4/5 of it", small.var(axis=1, ddof=0).mean()/sA**2, 0.8, 1e-2)
# ellipses, eq. (3.1.12)
check("content of the ellipse with projections +-1 sigma", 1 - np.exp(-0.5), 0.3935, 1e-4)
check("content of the ellipse with projections +-2 sigma", 1 - np.exp(-2.0), 0.8647, 1e-4)
check("Delta chi2 for 68.27% in two dimensions", -2*np.log(1 - 0.6827), 2.30, 2e-3)
check("Delta chi2 for 95.45% in two dimensions", -2*np.log(1 - 0.9545), 6.18, 2e-3)
check("same from the chi2 distribution", stats.chi2.ppf(0.9545, 2), -2*np.log(1 - 0.9545))
Cab = np.array([[ga @ Cth @ ga, ga @ Cth @ gb], [ga @ Cth @ gb, gb @ Cth @ gb]])
v = np.stack([ra, rb], 1); m2 = np.einsum("ni,ij,nj->n", v, np.linalg.inv(Cab), v)
check("Monte Carlo content of the Delta chi2 = 4 ellipse", np.mean(m2 < 4.0), 1 - np.exp(-2.0), 3e-3)
check("projection of the Delta chi2 = n^2 ellipse is n sigma", np.sqrt(4.0*Cab[0, 0]), 2*sA)

# ---- section 6: systematic floor, correlation model, profiling ----------------------------------------------
N, sst, ssy = 50, 0.05, 0.01
means = (1 + rng.normal(0, sst, size=(200000, N)) + rng.normal(0, ssy, size=(200000, 1))).mean(1)
check("variance of the mean with a common systematic (3.1.13)", means.var(), sst**2/N + ssy**2, 1e-2)
check("stat 5%/point, 50 points, sys 1%", np.sqrt(sst**2/N + ssy**2), 0.0122, 3e-3)
check("floor: 100x more data, sys 1%, stat 5%/point", np.sqrt(sst**2/(100*N) + ssy**2), 0.0100, 3e-3)
# forcing one nuisance parameter on two spectra, eq. (3.1.14)
w1, w2, l1, l2, c1, c2 = 7.0, 19.0, -1.32, 0.39, 4.1, 7.2
joint = optimize.minimize_scalar(lambda l: c1 + w1*(l-l1)**2 + c2 + w2*(l-l2)**2).fun
check("cost of a common nuisance parameter (3.1.14)", joint - (c1 + c2), w1*w2/(w1+w2)*(l1-l2)**2)
# whitepaper tables IV and V: shifts and chi2 values (quoted numbers, arithmetic only)
dl = {"hard": 0.74 + 0.43, "shower": 1.32 + 0.39, "isr": 0.47 + 0.33}
check("parton-shower shifts differ by", dl["shower"], 1.71)
excess_all, excess_ps = 45 - 11.3, 45 - 14.1
check("excess chi2 of the fully correlated joint fit", excess_all, 33.7)
check("excess removed by decorrelating the shower model", excess_ps, 30.9)
w_ps = 2*excess_ps/dl["shower"]**2
print(f"INFO  equal-weight estimate: w = {w_ps:.1f}, i.e. each spectrum fixes the shower parameter to +-{1/np.sqrt(w_ps):.2f} sigma")
check("equal-weight w for the shower nuisance", w_ps, 21.1, 3e-3)
check("1/sqrt(w)", 1/np.sqrt(w_ps), 0.22, 2e-2)
check("profiling at S^2 = 3 with T^2 = 10 lowers the uncertainty by 12%", 1 - 1/np.sqrt(1.3), 0.12, 5e-3)
check("1% luminosity at rho = 1 needs r = 0.5%", 0.005*np.sqrt(2*(1+1)), 0.01)
check("x > tau at 5 TeV", (5000/14000)**2, 0.13, 3e-2)
check("jet chi2 per point, fully correlated (289/171)", 289/171, 1.69, 3e-3)
check("jet chi2 per point, decorrelation scenario 2 (248/171)", 248/171, 1.45, 3e-3)
# profiling one eigenvector, eqs. (3.1.15)-(3.1.16)
def profiled_width(beta, sig, T2):
    chi2 = lambda b: np.sum((beta*b)**2/sig**2) + T2*b*b            # pseudo-data at the central prediction: D - T = 0
    return optimize.brentq(lambda b: chi2(b) - T2, 0, 2)
beta = rng.normal(0.02, 0.01, size=30); sig = np.full(30, 0.015)
S2 = np.sum(beta**2/sig**2)
for T2 in (1.0, 10.0):
    check(f"profiled width, T^2 = {T2:g} (3.1.16)", profiled_width(beta, sig, T2), 1/np.sqrt(1 + S2/T2))
check("S^2/T^2 needed to halve an uncertainty", 1/np.sqrt(1 + 3.0), 0.5)
check("S^2/T^2 needed for a factor 5", 1/np.sqrt(1 + 24.0), 0.2)
check("same data, T^2 = 10 instead of 1, S^2 = 3", 1/np.sqrt(1 + 0.3), 0.877, 1e-3)
check("LHeC alpha_S: 6 x 0.00018", 6*0.00018, 0.0011, 2e-2)

# ---- section 7: conventions of the perturbative expansion; the photon ---------------------------------------
CF = 4/3
aS = 0.118
plus = lambda f: q(lambda x: (f(x) - f(1.0))/(1-x))
g2_guide = CF*(plus(lambda x: x*(1+x*x)) + 1.5)                        # gamma_qq(2) in the alpha_S/2pi convention of chapter 1.4
check("gamma_qq(2), chapter 1.4 convention", g2_guide, -4*CF/3)
for k in range(4):                                                     # a_s^(k+1) P_wp^(k) = (alpha_S/2pi)^(k+1) P_guide^(k)
    check(f"P_wp^({k}) = 2^{k+1} P_guide^({k})", (aS/(4*np.pi))**(k+1)*2**(k+1), (aS/(2*np.pi))**(k+1), 1e-12)
check("(2 pi_b)(2 pi_c) = 121 parton pairs for 5 flavours and the gluon", (2*5 + 1)**2, 121)
# P_photon,q: the abelian copy of P_gq
check("int x P_gamma,q = 4/3", q(lambda x: 1 + (1-x)**2), 4/3)
alpha, MZ, Q0 = 1/137.036, 91.1876, 1.65
rate = alpha/(2*np.pi)*(4/3)*(4/9)
Lq = np.log(MZ**2/Q0**2)
print(f"INFO  photon momentum: rate bound {rate:.2e} per unit ln mu^2; ln(MZ^2/Q0^2) = {Lq:.3f}; bound {rate*Lq:.4f}")
check("rate bound", rate, 6.9e-4, 1e-2); check("ln(MZ^2/Q0^2)", Lq, 8.02, 1e-3)
check("bound on the inelastic photon momentum generated from Q0 to MZ", rate*Lq, 0.0055, 1e-2)

# ---- section 8 / D4, D5: theory covariance ------------------------------------------------------------------
sg, sth, Dl = 1.0, 2.0, 1.5            # experimental error, assumed theory error, the actual shift of theory 2
w2n = (1/(sg**2 + sth**2))/(1/sg**2 + 1/(sg**2 + sth**2))
check("weight of the data set with a theory error (3.1.21)", w2n, sg**2/(2*sg**2 + sth**2))
th = 3.0
D1 = th + rng.normal(0, sg, 400000); D2 = th + Dl + rng.normal(0, sg, 400000)
est_no = 0.5*(D1 + D2); est_th = (1-w2n)*D1 + w2n*D2
check("bias without theory covariance = Delta/2", est_no.mean() - th, Dl/2, 5e-3)
check("bias with theory covariance", est_th.mean() - th, Dl*sg**2/(2*sg**2 + sth**2), 5e-3)
# the quoted uncertainty with the theory covariance treats Delta as random with variance s^2
D2r = th + rng.normal(0, sth, 400000) + rng.normal(0, sg, 400000)
check("variance of the estimate with theory covariance", ((1-w2n)*D1 + w2n*D2r).var(), sg**2*(sg**2 + sth**2)/(2*sg**2 + sth**2), 1e-2)
check("it lies between sigma^2/2 and sigma^2", float(sg**2/2 < sg**2*(sg**2 + sth**2)/(2*sg**2 + sth**2) < sg**2), 1.0)
print(f"INFO  sigma=1, s=2: weight {w2n:.3f}, bias {Dl*w2n:.3f} (was {Dl/2:.3f}), uncertainty {np.sqrt(sg**2*(sg**2+sth**2)/(2*sg**2+sth**2)):.3f} (was {np.sqrt(0.5):.3f})")
check("weight for sigma=1, s=2", w2n, 1/6); check("uncertainty for sigma=1, s=2", np.sqrt(5/6), 0.913, 1e-3)
check("uncertainty without theory error", np.sqrt(0.5), 0.707, 1e-3)
# correlated prediction, eq. (3.1.22)
for rho in (0.0, 0.5, 1.0):
    cov = sth**2*np.array([[1, rho], [rho, 1]])
    dd = rng.multivariate_normal([0, 0], cov, size=400000); eps = rng.normal(0, sg, 400000)
    err = eps + dd[:, 0] - dd[:, 1]                                    # (theta-hat + 0) - (theta + Delta')
    check(f"variance of the prediction error, rho = {rho}", err.var(), sg**2 + 2*sth**2*(1-rho), 1e-2)
check("jet scale variation shrinks from NLO to NNLO by a factor", 11/1.6, 6.9, 1e-2)

# ---- section 9 / D6: combining replica sets -----------------------------------------------------------------
mu, sd = np.array([1.00, 1.03, 0.98]), np.array([0.020, 0.035, 0.015])
pool = np.concatenate([rng.normal(m, s_, 300) for m, s_ in zip(mu, sd)])
check("900 replicas in the combination", len(pool), 900)
big = np.concatenate([rng.normal(m, s_, 300000) for m, s_ in zip(mu, sd)])
check("mean of the mixture (3.1.23)", big.mean(), mu.mean(), 2e-4)
var_mix = np.mean(sd**2) + np.mean((mu - mu.mean())**2)
check("variance of the mixture (3.1.24)", big.var(), var_mix, 5e-3)
print(f"INFO  toy combination: within {np.sqrt(np.mean(sd**2)):.4f}, between {np.sqrt(np.mean((mu-mu.mean())**2)):.4f}, total {np.sqrt(var_mix):.4f}")
check("toy: rms of the individual uncertainties", np.sqrt(np.mean(sd**2)), 0.0248, 3e-3)
check("toy: spread of the central values", np.sqrt(np.mean((mu - mu.mean())**2)), 0.0205, 3e-3)
check("toy: combined uncertainty", np.sqrt(var_mix), 0.0322, 3e-3)
for rho in (0.0, 0.5, 1.0):                                            # average of two determinations with correlation rho
    cov = 0.02**2*np.array([[1, rho], [rho, 1]])
    dd = rng.multivariate_normal([0, 0], cov, size=400000)
    check(f"variance of the average of two, rho = {rho} (3.1.25)", dd.mean(1).var(), 0.02**2*(1+rho)/2, 1e-2)

# ---- section 11: this project (ledger numbers, arithmetic only) ---------------------------------------------
check("chi2/N = 5713.23/4615", 5713.23/4615, 1.2380, 1e-4)
check("ratio to NNPDF4.0's 1.17", 1.2380/1.17, 1.058, 1e-3)

# ---- figures ------------------------------------------------------------------------------------------------
fig, ax = plt.subplots(figsize=(8, 4.6))
for rt, col, lab in ((rtH, TEAL, "mass 125 GeV"), (1000/rs, ORANGE, "mass 1 TeV")):
    w, ym = weight(rt); ys = np.linspace(-ym, ym, 601)
    ax.plot(ys, [w(y) for y in ys], color=col, lw=2.6, label=lab)
ys = np.linspace(-Y68, Y68, 200)
ax.fill_between(ys, 0, [wH(y) for y in ys], color=TEAL, alpha=0.16, lw=0)
ax.annotate("68% of the\nluminosity", (0, 0.045), ha="center", color=TEAL, fontsize=13)
ax.set_xlabel("rapidity of the produced state"); ax.set_ylabel("share of the gluon–gluon luminosity\nper unit rapidity")
ax.set_xlim(-5, 5); ax.set_ylim(0, 0.5)
sec = ax.secondary_xaxis("top", functions=(lambda y: y, lambda y: y))
tk = [-4, -2, 0, 2, 4]; sec.set_xticks(tk); sec.set_xticklabels([f"{rtH*np.exp(t):.1g}" for t in tk])
sec.set_xlabel("momentum fraction of one gluon, for mass 125 GeV")
ax.legend(loc="upper left", frameon=False, title="toy gluon, 14 TeV")
fig.tight_layout(); fig.savefig(FIG / "3-1-rapidity.svg"); plt.close(fig)

fig, ax = plt.subplots(figsize=(8, 4.6))
S = np.linspace(0, 8, 400)
ax.plot(S, 1/np.sqrt(1 + S**2), color=TEAL, lw=2.6, label="tolerance $T^2=1$")
ax.plot(S, 1/np.sqrt(1 + S**2/10), color=ORANGE, lw=2.6, label="tolerance $T^2=10$")
for lvl, txt in ((0.5, "halved"), (0.2, "one fifth")):
    ax.axhline(lvl, color=INK, lw=1, ls=(0, (4, 3))); ax.text(7.95, lvl + 0.02, txt, ha="right", fontsize=13)
ax.set_xlabel("sensitivity of the new data, $S$ (standard deviations spanned by one error set)")
ax.set_ylabel("uncertainty after profiling\n÷ uncertainty before"); ax.set_xlim(0, 8); ax.set_ylim(0, 1.05)
ax.legend(loc="upper right", frameon=False)
fig.tight_layout(); fig.savefig(FIG / "3-1-profiling.svg"); plt.close(fig)

print("wrote 3-1-rapidity.svg, 3-1-profiling.svg;", "ALL CHECKS PASS" if ok else "SOME CHECKS FAILED")
sys.exit(0 if ok else 1)
