#!/usr/bin/env python3
"""CERN Open Data -> Z5^3 lattice -> E47 spectral filter, with a numeric contraction check.

Usage: python3 run_filter.py --recid 545 --file data/545/Dimuon_DoubleMu.csv [--tag main]

Embedding (modeling choice, NOT from Nick's repos -- the repos define the lattice and operators,
not a map from collider events to sites): for each event, sum the lepton four-momenta
P = sum_i (E_i, px_i, py_i, pz_i) and bin
  x = 5 equal bins of log10 M(P) over [0.3, 300] GeV  (edges ~0.3, 1.19, 4.75, 18.9, 75.4, 300)
  y = 5 equal bins of rapidity Y(P) over [-2.4, 2.4]
  z = 5 equal bins of azimuth phi(P) over [-pi, pi)    (cyclic -> natural Z5 axis)
values outside the range are clipped into the edge bins. Site index pi = 25x + 5y + z.
The occupancy histogram n_x gives f = n / ||n||.

Initial state on H = l2(Z5^3) (x) V2^{(x)3} (C^15625), both factors indexed by the same pi:
  product  : psi = f (x) f
  diagonal : psi(x, k) = f_x delta_{x k}  (event at site x carries internal basis state |k=x>)
Residual R(t) = exp(-tD) psi - P0 psi with D = L (x) I + I (x) B, P0 = |u0><u0| (x) P47.
Bound (repo theorem): ||R(t+dt)|| <= exp(-gamma dt) ||R(t)||, gamma = (15-3 sqrt5)/2.
"""
import argparse, hashlib, json, os, zlib, datetime, platform
import numpy as np, pandas as pd, scipy
from scipy.linalg import expm
import z5lattice as z

HERE = os.path.dirname(os.path.abspath(__file__))
M_RANGE = (0.3, 300.0); Y_RANGE = (-2.4, 2.4); PHI_RANGE = (-np.pi, np.pi)
DT = 0.05; N_STEPS = 200; FLOOR = 1e-11
CHECK_FLOOR = 1e-8   # judge the bound only while ||R|| > CHECK_FLOOR*||R0|| (above round-off)
REL_TOL = 1e-7      # allowed relative excess over exp(-gamma dt), >> observed iterate-vs-spectral error


def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""): h.update(chunk)
    return h.hexdigest()


def adler32(path):
    a = 1
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""): a = zlib.adler32(chunk, a)
    return f"adler32:{a & 0xffffffff:08x}"


def bin5(v, lo, hi):
    return np.clip(np.floor((v - lo) / (hi - lo) * 5).astype(int), 0, 4)


def embed(df):
    n_lep = max(int(c[1:]) for c in df.columns if c.startswith("E") and c[1:].isdigit())
    E = sum(df[f"E{i}"] for i in range(1, n_lep+1)).to_numpy()
    px = sum(df[f"px{i}"] for i in range(1, n_lep+1)).to_numpy()
    py = sum(df[f"py{i}"] for i in range(1, n_lep+1)).to_numpy()
    pz = sum(df[f"pz{i}"] for i in range(1, n_lep+1)).to_numpy()
    M = np.sqrt(np.clip(E**2 - px**2 - py**2 - pz**2, 0, None))
    Y = 0.5*np.log((E + pz)/(E - pz))
    phi = np.arctan2(py, px)
    x = bin5(np.log10(np.clip(M, 1e-9, None)), *np.log10(M_RANGE))
    y = bin5(Y, *Y_RANGE); zz = bin5(phi, *PHI_RANGE)
    idx = z.site_index(x, y, zz)
    counts = np.bincount(idx, minlength=125)
    m_check = float(np.max(np.abs(M - df["M"].to_numpy()))) if "M" in df else None
    return counts, dict(n_leptons=n_lep, n_events=int(len(df)), max_abs_M_vs_csv_GeV=m_check,
                        max_rel_M_vs_csv=(float(np.max(np.abs(M - df["M"].to_numpy())/df["M"].to_numpy())) if "M" in df else None),
                        clipped_M=int(np.sum((M < M_RANGE[0]) | (M >= M_RANGE[1]))),
                        clipped_Y=int(np.sum((Y < Y_RANGE[0]) | (Y >= Y_RANGE[1]))))


def occupancy_summary(counts):
    nz = counts[counts > 0]; p = nz/nz.sum()
    g = counts.reshape(5, 5, 5)
    top = np.argsort(counts)[::-1][:5]
    return dict(populated_sites=int((counts > 0).sum()), empty_sites=int((counts == 0).sum()),
                min=int(counts.min()), max=int(counts.max()), median=float(np.median(counts)),
                mean=float(counts.mean()), shannon_entropy_bits=float(-(p*np.log2(p)).sum()),
                max_entropy_bits=float(np.log2(125)),
                marginal_x_logM=g.sum((1, 2)).tolist(), marginal_y_rapidity=g.sum((0, 2)).tolist(),
                marginal_z_phi=g.sum((0, 1)).tolist(),
                top5=[dict(site=list(map(int, z.SITES[i])), index=int(i), count=int(counts[i])) for i in top],
                histogram_of_counts=dict(zip(*[a.tolist() for a in np.unique(
                    np.digitize(counts, [1, 10, 100, 1000, 10000]), return_counts=True)])),
                histogram_bins_note="keys: 0 -> 0 events, 1 -> 1-9, 2 -> 10-99, 3 -> 100-999, 4 -> 1000-9999, 5 -> >=10000")


def contraction_check(psi, ops, L):
    gamma = z.GAMMA_EXACT
    lam_s, Us = np.linalg.eigh(L)
    beta_i, Ui = np.linalg.eigh(ops["B"])
    u0 = np.ones(125)/np.sqrt(125)
    P0psi = np.outer(u0, u0) @ psi @ ops["P47"].T
    R = psi - P0psi
    r0 = np.linalg.norm(R)
    Es = expm(-DT*L); Ei = (Ui*np.exp(-DT*beta_i)) @ Ui.T   # exp(-dt B) via eigh (B is diagonalizable, huge norm)
    norms = [r0]
    for _ in range(N_STEPS):
        R = Es @ R @ Ei.T
        nr = np.linalg.norm(R); norms.append(nr)
        if nr < FLOOR * r0: break
    norms = np.array(norms)
    ratios = norms[1:]/norms[:-1]
    ts = DT*np.arange(len(norms))
    spec = z.residual_curve(psi, lam_s, Us, beta_i, Ui, ts)
    # first step contains the instantaneous kill of internal (B>=11664) and high-L components
    rates = -np.log(ratios)/DT
    tail = slice(len(rates)//2, None)
    fit = np.polyfit(ts[len(ts)//2:], np.log(norms[len(norms)//2:]), 1)
    bound = np.exp(-gamma*DT)
    return dict(
        P0_weight=float(np.linalg.norm(P0psi)**2/np.linalg.norm(psi)**2),
        initial_residual_norm=float(r0), steps=int(len(ratios)), dt=DT, t_final=float(ts[-1]),
        final_residual_norm=float(norms[-1]),
        max_step_ratio=float(ratios.max()), bound_step_ratio_exp_minus_gamma_dt=float(bound),
        min_rate_per_unit_t=float(rates.min()), first_step_rate=float(rates[0]),
        tail_median_rate=float(np.median(rates[tail])), loglinear_fit_rate_second_half=float(-fit[0]),
        gamma=float(gamma),
        rate_minus_gamma_min=float(rates.min() - gamma),
        iterate_vs_spectral_max_rel_err=float(np.max(np.abs(norms - spec)/np.maximum(spec, 1e-300))),
        steps_checked=int(np.sum(norms[:-1] > CHECK_FLOOR*r0)),
        max_rel_excess_over_bound_checked=float(np.max(ratios[norms[:-1] > CHECK_FLOOR*r0]/bound - 1)),
        max_rel_excess_over_bound_all_steps=float(np.max(ratios/bound - 1)),
        check_floor=CHECK_FLOOR, rel_tol=REL_TOL,
        bound_holds=bool(np.all(ratios[norms[:-1] > CHECK_FLOOR*r0] <= bound*(1 + REL_TOL))),
    )


def discrete_internal_check(v, ops):
    P = ops["P47"]; G = ops["Gamma"]
    r = v - P @ v; ns = [np.linalg.norm(r)]
    for _ in range(400):
        r = G @ r; ns.append(np.linalg.norm(r))
        if ns[-1] < FLOOR*ns[0]: break
    ratios = np.array(ns[1:])/np.array(ns[:-1])
    return dict(E47_weight_of_f=float(np.linalg.norm(P @ v)**2), Omega_c_reference=47/125,
                steps=len(ratios), max_step_ratio=float(ratios.max()), bound_rho=z.RHO_DISCRETE,
                max_rel_excess_over_bound=float(np.max(ratios/z.RHO_DISCRETE - 1)),
        bound_holds=bool(np.all(ratios[np.array(ns[:-1]) > CHECK_FLOOR*ns[0]] <= z.RHO_DISCRETE*(1+REL_TOL))))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--recid", required=True); ap.add_argument("--file", required=True)
    ap.add_argument("--tag", default="main"); a = ap.parse_args()
    path = os.path.abspath(a.file)
    meta = json.load(open(os.path.join(HERE, "data", f"api_{a.recid}.json")))["metadata"]
    fmeta = next(f for f in meta["_files"] if f["key"] == os.path.basename(path))
    ck = adler32(path)
    assert ck == fmeta["checksum"], (ck, fmeta["checksum"])
    df = pd.read_csv(path)
    counts, emb = embed(df)
    f = counts/np.linalg.norm(counts)
    L = z.fcc_laplacian(); ops = z.internal_operators()
    assert abs(np.sort(np.linalg.eigvalsh(L))[1] - z.GAMMA_EXACT) < 1e-12
    fh = z.character_transform(f); lam = z.fcc_eigenvalues()
    gap_modes = np.isclose(lam, z.GAMMA_EXACT)
    res = dict(
        schema="cern-spectral-cert/1", tag=a.tag,
        timestamp=datetime.datetime.now().astimezone().isoformat(timespec="seconds"),
        record=dict(recid=int(a.recid), title=meta.get("title"), doi=meta.get("doi"),
                    file=fmeta["key"], url="https://opendata.cern.ch" + fmeta["uri"].split("eospublic.cern.ch/")[1],
                    size=fmeta["size"], checksum_catalog=fmeta["checksum"], checksum_local=ck,
                    sha256=sha256(path), license=meta.get("license")),
        embedding=dict(rule="x=log10 M bin [0.3,300] GeV, y=rapidity bin [-2.4,2.4], z=phi bin [-pi,pi); pi=25x+5y+z",
                       **emb),
        occupancy=occupancy_summary(counts),
        spectral=dict(constant_mode_weight=float(abs(fh[0])**2),
                      gap_mode_weight_spatial=float(np.sum(np.abs(fh[gap_modes])**2)),
                      E47_weight_internal=float(np.linalg.norm(ops["P47"] @ f)**2)),
        continuous_D=dict(product_state=contraction_check(np.outer(f, f), ops, L),
                          diagonal_state=contraction_check(np.diag(f), ops, L)),
        discrete_Gamma_internal=discrete_internal_check(f, ops),
        code=dict(script=os.path.abspath(__file__), script_sha256=sha256(__file__),
                  module=os.path.join(HERE, "z5lattice.py"), module_sha256=sha256(os.path.join(HERE, "z5lattice.py")),
                  python=platform.python_version(), numpy=np.__version__, scipy=scipy.__version__),
        sources=dict(repo="nicholaskouns-create/E47-Kartekeya", commit="e9be2deefb3e188b2a552be235ab73af173433bf",
                     gamma_def="website/interfaces/fcc-e47-spatial-lift/index.html (+ fcc_e47_validation.py)",
                     gamma_citizen="website/citizens/citizens.json civic_id 12 (machine_validated=false)",
                     Gamma_discrete="E47-Foundry-Lifetime-Intersection research/e47-invariant-transport-gradient-2026-11-20.md @ 0c6062a2"),
    )
    Lc = z.cubic_laplacian()
    res["gap_conventions"] = dict(
        headline_gamma_fcc=float(z.GAMMA_EXACT), headline_gamma_formula="(15-3*sqrt5)/2 = min nonzero eig of FCC (12-nbr) Laplacian on Z5^3",
        fcc_gap_numeric=float(np.sort(np.linalg.eigvalsh(L))[1]),
        cubic_gap_numeric=float(np.sort(np.linalg.eigvalsh(Lc))[1]), cubic_gap_formula="(5-sqrt5)/2 = 2(1-cos(2pi/5))",
        ratio_fcc_over_cubic=float(z.GAMMA_EXACT/((5-np.sqrt(5))/2)),
        compressed_cubic_QtLQ_min=z.compressed_gap(Lc, ops["Q"]),
        compressed_fcc_QtLQ_min=z.compressed_gap(L, ops["Q"]),
        note=("gamma_fcc = 3*(5-sqrt5)/2 exactly because the FCC gap modes w have a=3 directions s in S with w.s = +-1 mod 5, "
              "each contributing 2(1-cos 2pi/5); it is a different graph (12 neighbours), not a rescaling of the cubic L. "
              "Q^T L Q (approx 1.7572 for cubic L) is the E47-compressed Laplacian in the site==internal-basis identification; "
              "it is NOT the gap of D = L(x)I + I(x)B, whose gap is the bare spatial gap. Headline bound uses gamma_fcc."))
    res["verdict"] = dict(
        pass_=bool(all(v["bound_holds"] for v in res["continuous_D"].values()) and res["discrete_Gamma_internal"]["bound_holds"]),
        meaning="Numeric floating-point check that the observed per-step residual ratios never exceed exp(-gamma*dt) "
                "(and 15/17 for the discrete internal map). It instantiates a theorem already proved in the repo; it is "
                "not a proof, and passing it says nothing physical about the CMS data, which only sets the initial state.")
    out = os.path.join(HERE, "certs", f"cert_{a.recid}_{a.tag}.json")
    json.dump(res, open(out, "w"), indent=2)
    print(json.dumps(res, indent=2))


if __name__ == "__main__":
    main()
