# [project] Block 4: Littlewood's lemma for f = zeta^a with a COMPLEX exponent (the shape of the Q8 aligned
# half-product F = L(rho)^{1/2} [..]^{i/4} [..]^{1/4} G, see hyper-critical/q8-half-hecke-20261111.md).
# Branch of log zeta continued horizontally from sigma1 = 3 (the usual convention behind S(t)).
# Littlewood expression  E(a) = ∫_left log|f| dt − ∫_right log|f| dt − ∫_bottom arg f dσ + ∫_top arg f dσ
# should equal 2π·Re(a)·Σ_{zeros in box}(β − σ0): the imaginary part of the exponent carries weight 0.
# Box: σ0 = 0.3 ≤ σ ≤ 3, 10 ≤ t ≤ 40 (6 zeta zeros, each β − σ0 = 0.2 ⇒ Σ = 1.2, 2πΣ = 7.5398).
# Double-computed: C = em_numpy (σ step 0.005, t step 0.005); A = mpmath.zeta (σ step 0.02, t step 0.04).
import json, numpy as np, mpmath as mp
import em_numpy as E
S0, S1, T0, T1 = 0.3, 3.0, 10.0, 40.0
def grid_logzeta(sig, t, zfun):
    """log zeta on grid (rows = t, cols = sigma descending from S1), arg unwrapped along sigma from S1."""
    Zg = np.array([zfun(s, t) for s in sig]).T               # shape (nt, nsig)
    lz = np.log(np.abs(Zg)); ph = np.unwrap(np.angle(Zg), axis=1)
    return lz, ph
def trap(y, x): return float(np.sum(0.5*(y[1:] + y[:-1])*np.diff(x)))
def expr(a, sig, t, lz, ph):
    lf = a.real*lz - a.imag*ph                                # log|f|
    af = a.real*ph + a.imag*lz                                # arg f
    left, right = trap(lf[:, -1], t), trap(lf[:, 0], t)
    sa = sig[::-1]                                            # ascending sigma for horizontal integrals
    bottom, top = trap(af[0, ::-1], sa), trap(af[-1, ::-1], sa)
    return left - right - bottom + top
res = {"box": [S0, S1, T0, T1], "zeros_in_box": [float(mp.zetazero(k).imag) for k in range(1, 7)],
       "two_pi_sum_dist_expected_a1": 2*np.pi*6*(0.5 - S0)}
EXPS = {"1": 1+0j, "1/2": 0.5+0j, "1/2+i/4": 0.5+0.25j, "i/4": 0.25j, "-i/4": -0.25j, "1/4": 0.25+0j}
# C: numpy Euler–Maclaurin
sig = np.round(np.arange(S1, S0 - 1e-9, -0.005), 6); t = np.round(np.arange(T0, T1 + 1e-9, 0.005), 6)
lz, ph = grid_logzeta(sig, t, lambda s, tt: E.zeta(s, tt))
res["C_numpy"] = {k: expr(a, sig, t, lz, ph) for k, a in EXPS.items()}
# A: mpmath on a coarser grid
sigA = np.round(np.arange(S1, S0 - 1e-9, -0.02), 6); tA = np.round(np.arange(T0, T1 + 1e-9, 0.04), 6)
lzA, phA = grid_logzeta(sigA, tA, lambda s, tt: np.array([complex(mp.zeta(mp.mpc(s, x))) for x in tt]))
res["A_mpmath"] = {k: expr(a, sigA, tA, lzA, phA) for k, a in EXPS.items()}
res["predicted_2pi_Re(a)_Sum"] = {k: 2*np.pi*a.real*1.2 for k, a in EXPS.items()}
json.dump(res, open("littlewood_complex_exponent.json", "w"), indent=1)
for k in EXPS: print(f"a={k:8s} C={res['C_numpy'][k]: .5f}  A={res['A_mpmath'][k]: .5f}  predicted={res['predicted_2pi_Re(a)_Sum'][k]: .5f}")
