#!/usr/bin/env python3
"""First-pass certification: one HEPData differential cross-section on the Z5^3 character basis,
projected onto constant ⊗ E47, compared with the predicted gap.  Uses /workspace/shared/z5cube."""
import os
for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"): os.environ.setdefault(_v, "1")
import json, hashlib, sys
import numpy as np, yaml
sys.path.insert(0, "/workspace/shared/z5cube")
import z5cube as z
import z5cube.projectors

RNG = np.random.default_rng(470125)
SRC = "table4a.yaml"
RECORD = "https://www.hepdata.net/record/ins1768911"
TABLE_URL = "https://www.hepdata.net/download/table/ins1768911/Table%204a/1/yaml"

# ---------------- data ----------------
d = yaml.safe_load(open(SRC))
xb = d["independent_variables"][0]["values"]
lo = np.array([v["low"] for v in xb], float); hi = np.array([v["high"] for v in xb], float)
dep = d["dependent_variables"][0]["values"]
y = np.array([v["value"] for v in dep], float)
pc = lambda s: float(str(s).strip().rstrip("%")) / 100
ecor = np.array([pc(v["errors"][0]["symerror"]) for v in dep]) * y
eunc = np.array([pc(v["errors"][1]["symerror"]) for v in dep]) * y
nb = len(y)
# ASSUMPTION: 'correlated' component treated as 100% correlated across bins (no covariance table used).
Cy = np.diag(eunc**2) + np.outer(ecor, ecor)

# ---------------- embedding (ASSUMPTION: no repo convention exists) ----------------
# site i (lexicographic, i = 25x1+5x2+x3) <- bin-index coordinate u = i*(nb-1)/124, linear interpolation.
u = np.arange(125) * (nb - 1) / 124
W = np.zeros((125, nb))
for i, ui in enumerate(u):
    j = min(int(np.floor(ui)), nb - 2); t = ui - j
    W[i, j] += 1 - t; W[i, j + 1] += t
f = W @ y
Cf = W @ Cy @ W.T

# ---------------- character decomposition ----------------
c = z.to_characters(f)
pw = np.abs(c)**2 / np.sum(np.abs(c)**2)
s = z.sites()
top = np.argsort(-pw)[:8]

P = z.P47(); Q = np.eye(125) - P
K2 = z.projectors._K2()
X = z.character_table()
P_hat = X.conj() @ P @ X.T                       # E47 projector in character basis
e47_weight_per_char = np.real(np.diag(P_hat))   # <chi_k|P47|chi_k>

def stats(fv):
    rint = z.residual_internal(fv)
    r = Q @ fv
    ray_K2 = float(r @ K2 @ r / (r @ r))
    gam = np.eye(125) - K2 / 99144.0
    contr = float(np.linalg.norm(gam @ r) / np.linalg.norm(r))
    F = np.outer(fv, fv)                          # ASSUMPTION: coupled lift F = f(space) ⊗ f(internal)
    rcpl = z.residual_const_E47(F)
    R = F - z.project_const_E47(F)
    ray_D = z.rayleigh_D(R)
    return dict(r_internal=rint, r_coupled=rcpl, rayleigh_K2_residual=ray_K2,
                gamma_one_step_contraction=contr, rayleigh_D_residual=ray_D,
                const_fraction=float(abs(c0(fv))**2 / (fv @ fv)))
def c0(fv): return fv.sum() / np.sqrt(125)

base = stats(f)

# heat-flow test of the predicted gap: ||exp(-tD)F - P0 F|| <= exp(-gamma t) ||F - P0 F||
F0 = np.outer(f, f)
ts = np.linspace(0, 4, 81); dt = ts[1] - ts[0]
h = z.heat_residual_curve(F0, ts)
step = h[1:] / h[:-1]
tail_rate = float(-np.log(h[-1] / h[-2]) / dt)
heat = dict(t_max=float(ts[-1]), dt=float(dt), h0=float(h[0]), max_step_ratio=float(step.max()),
            bound_exp_minus_gamma_dt=float(np.exp(-z.GAP_D * dt)),
            rel_excess=float(step.max() / np.exp(-z.GAP_D * dt) - 1), tail_rate=tail_rate,
            tail_rate_minus_gamma=float(tail_rate - z.GAP_D),
            pass_=bool(np.all(h <= np.exp(-z.GAP_D * ts) * h[0] * (1 + 1e-10))))

# cross-check against CERN Spectral's independent module
xcheck = None
try:
    sys.path.insert(0, "/workspace/cern-spectral"); import z5lattice as zl
    ops = zl.internal_operators()
    xcheck = dict(P47_maxdiff=float(np.abs(ops["P47"] - z.P47()).max()),
                  gamma_diff=float(abs(zl.GAMMA_EXACT - z.GAP_D)),
                  fcc_L_maxdiff=float(np.abs(zl.fcc_laplacian() - z.fcc_laplacian()).max()),
                  char_coeff_maxdiff=float(np.abs(zl.character_transform(f) - c).max()),
                  z5lattice_sha256=hashlib.sha256(open("/workspace/cern-spectral/z5lattice.py", "rb").read()).hexdigest())
except Exception as e:
    xcheck = dict(error=repr(e))

# chi^2 of the internal residual vs uncertainties (H0: f ∈ E47 exactly)
r = Q @ f; Cr = Q @ Cf @ Q
wv, Vv = np.linalg.eigh(Cr); keep = wv > wv.max() * 1e-12
proj = Vv[:, keep].T @ r
chi2 = float(np.sum(proj**2 / wv[keep])); dof = int(keep.sum())
# component of residual outside the covariance support (cannot be explained by any fluctuation)
out_support = float(np.linalg.norm(r - Vv[:, keep] @ proj) / np.linalg.norm(r))

# MC within errors
L = np.linalg.cholesky(Cy + 1e-30 * np.eye(nb))
mc = [stats(W @ (y + L @ RNG.normal(size=nb))) for _ in range(2000)]
mcs = {k: (float(np.mean([m[k] for m in mc])), float(np.std([m[k] for m in mc]))) for k in base}

# null: random relabelling of the 125 sites (same values, structure destroyed)
perm = [z.residual_internal(f[RNG.permutation(125)]) for _ in range(5000)]
haar = [z.residual_internal(RNG.normal(size=125)) for _ in range(5000)]

res = dict(
    record=RECORD, table="Table 4a (combined normalized 1/σ dσ/dpT^ll, Born, 13 TeV)", table_url=TABLE_URL,
    doi="10.17182/hepdata.92377.v3/t4", n_bins=nb, pt_range_GeV=[float(lo[0]), float(hi[-1])],
    embedding="linear interpolation in bin index onto 125 sites, lexicographic Z5^3 order; site digits x_i <-> m_i=2-x_i of V2⊗V2⊗V2",
    character_top=[dict(k=s[i].tolist(), power_fraction=float(pw[i])) for i in top],
    E47_weight_on_characters=dict(min=float(e47_weight_per_char.min()), max=float(e47_weight_per_char.max()),
                                  mean=float(e47_weight_per_char.mean()), P47_translation_invariant=bool(z.is_translation_invariant(P))),
    central=base, mc_mean_std=mcs,
    chi2_residual=dict(chi2=chi2, dof=dof, residual_fraction_outside_cov_support=out_support),
    null_site_permutation_r_internal=dict(mean=float(np.mean(perm)), std=float(np.std(perm)),
                                          p_value_le_data=float(np.mean(np.array(perm) <= base["r_internal"]))),
    null_haar_r_internal=dict(mean=float(np.mean(haar)), std=float(np.std(haar)), expected_sqrt_78_over_125=float(np.sqrt(78/125))),
    heat_flow_gap_test=heat, crosscheck_cern_spectral_z5lattice=xcheck,
    predicted=dict(GAP_K2=z.GAP_K2, LAMBDA_MAX_K2=z.LAMBDA_MAX_K2, RHO_STAR=z.RHO_STAR, GAP_FCC=z.GAP_FCC, GAP_D=z.GAP_D),
    gap_checks=dict(
        K2_rayleigh_in_band=bool(z.GAP_K2 - 1e-6 <= base["rayleigh_K2_residual"] <= z.LAMBDA_MAX_K2 + 1e-6),
        gamma_contraction_le_rho=bool(base["gamma_one_step_contraction"] <= z.RHO_STAR + 1e-12),
        heat_flow_bound=heat["pass_"],
        D_rayleigh_ge_gap=bool(base["rayleigh_D_residual"] >= z.GAP_D - 1e-9)),
    sha256=dict(data=hashlib.sha256(open(SRC, "rb").read()).hexdigest(),
                script=hashlib.sha256(open(__file__, "rb").read()).hexdigest(),
                z5cube_projectors=hashlib.sha256(open("/workspace/shared/z5cube/z5cube/projectors.py", "rb").read()).hexdigest()),
)
json.dump(res, open("results.json", "w"), indent=2)
print(json.dumps(res, indent=2))

# ---------------- plot ----------------
import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2, figsize=(12, 8))
ctr = 0.5 * (lo + hi)
ax[0, 0].errorbar(ctr, y, yerr=np.sqrt(np.diag(Cy)), fmt=".", ms=3); ax[0, 0].set(xscale="log", yscale="log",
    xlabel="pT^ll [GeV]", ylabel="1/σ dσ/dpT [1/GeV]", title="ATLAS 13 TeV Z pT (HEPData ins1768911, Table 4a)")
ax[0, 1].plot(f, label="f (embedded)"); ax[0, 1].plot(P @ f, label="P47 f"); ax[0, 1].plot(Q @ f, label="Q78 f")
ax[0, 1].set(xlabel="site index 25x1+5x2+x3", title=f"internal residual r={base['r_internal']:.3f}"); ax[0, 1].legend()
ax[1, 0].bar(range(125), pw); ax[1, 0].set(yscale="log", xlabel="character k (lexicographic)", ylabel="|c_k|²/||f||²",
    title="Z5^3 character power")
ax[1, 1].hist(perm, 60, alpha=.6, label="site-permutation null"); ax[1, 1].hist(haar, 60, alpha=.4, label="Haar random")
ax[1, 1].axvline(base["r_internal"], c="k", label="data"); ax[1, 1].axvline(np.sqrt(78/125), c="r", ls="--", label="√(78/125)")
ax[1, 1].set(xlabel="||Q78 f||/||f||", title="internal residual vs nulls"); ax[1, 1].legend()
fig.tight_layout(); fig.savefig("residual_plot.png", dpi=130)
