# [project] Block 4: Hardy's Z-function idea for the classical Q8 Artin L-function L(rho,s) (rho = 2-dim faithful rep).
# The character of rho is real and Lambda(s) = W·Lambda(1-s) with W = ±1, so W^{-1/2}·Lambda(1/2+it) is real.
# A = sign changes of PARI lfunhardy on a grid; B = sign changes of the real part of W^{-1/2}·lfunlambda(1/2+it)
# (our own normalisation; imaginary part must vanish); Z0 = PARI lfunzeros count (incl. a central zero at t=0 if any).
# Fields as in hyper-critical/q8-half-hecke-20261111.md. Run with /workspace/tools/pari-venv/bin/python.
import json, numpy as np
from cypari2 import Pari
pari = Pari(); pari.allocatemem(800*10**6); pari.set_real_precision(20)
FIELDS = [("2.2304.8t5.b.a", "x^8+12*x^6+36*x^4+36*x^2+9"), ("2.2304.8t5.a.a", "x^8-12*x^6+36*x^4-36*x^2+9")]
TMAX, STEP = 30.0, 0.02
out = {"T": TMAX, "step": STEP, "fields": {}}
for lab, pol in FIELDS:
    pari(f"P=({pol}); N=nfinit(P); G=galoisinit(N); TC=galoischartable(G); T=TC[1]; dg=vector(5,j,T[1,j]); "
         f"j2=select(x->x==2,dg,1)[1]; L=lfunartin(N,G,T[,j2],TC[2]); Li=lfuninit(L,[1/2,{TMAX+2}]);")
    W = complex(pari("lfunrootres(Li)[3]"))
    t = np.arange(STEP/2, TMAX, STEP)                    # offset grid avoids t = 0 exactly
    zA = np.array([float(pari(f"lfunhardy(Li,{x:.10f})")) for x in t])
    lam = np.array([complex(pari(f"lfunlambda(Li,1/2+I*{x:.10f})")) for x in t])
    zB = lam / np.sqrt(W + 0j)
    sc = lambda v: int(np.sum(np.sign(v[1:]) != np.sign(v[:-1])))
    zeros = [float(z) for z in pari(f"lfunzeros(Li,{TMAX})")]
    out["fields"][lab] = {"root_number": [W.real, W.imag], "sign_changes_lfunhardy": sc(zA),
        "sign_changes_W^-1/2_Lambda": sc(zB.real), "max_imag_over_abs_W^-1/2_Lambda": float(np.max(np.abs(zB.imag)/np.maximum(np.abs(zB), 1e-300))),
        "lfunzeros_count_0_to_T": len(zeros), "lfunzeros": zeros,
        "central_zero_order": int(pari("lfunorderzero(Li)")),
        "max_rel_abs_diff_|A|_vs_|B|": None}
    # |Z| from lfunhardy is |L(1/2+it)| ; |Lambda| includes the gamma factor, so compare signs only
    agree = np.mean(np.sign(zA) == np.sign(zB.real)) if True else None
    out["fields"][lab]["sign_agreement_A_B"] = float(agree)
    print(lab, {k: v for k, v in out["fields"][lab].items() if k != "lfunzeros"})
json.dump(out, open("q8_hardy_z.json", "w"), indent=1)
