# [project] Hardy–Littlewood / Selberg window experiment.
# Tile [t0, T] by consecutive windows [t, t+H(t)], H(t) = c/log t, and record the fraction containing a sign
# change of Hardy's Z (program B: own numpy Riemann–Siegel, rs_numpy.Z). Compare with the expected number of
# zeros per window lam = H * (1/2pi) log(t/2pi) (density of zeros), and with 1-exp(-lam) (what independent,
# Poisson-like zeros would give) and min(1,lam) (perfectly evenly spaced zeros).
# Spot-check: classification of random windows recomputed with mpmath.siegelz at a finer endpoint/interior grid.
import numpy as np, json, mpmath as mp
from rs_numpy import Z
rng=np.random.default_rng(20261112)
def windows(c,t0,T):
    ws=[];t=t0
    while True:
        H=c/np.log(t)
        if t+H>T: break
        ws.append((t,H)); t+=H
    return ws
def has_sc(t,H,npts=None):
    n=npts or max(12,int(H/0.004))
    z=Z(np.linspace(t,t+H,n))
    return bool(np.any(np.sign(z[1:])!=np.sign(z[:-1]))), float(np.min(np.abs(z)))
res={"program":"hl_windows.py (Z from rs_numpy = program B)","H":"c/log t","ranges":[[10,100],[100,500],[500,1000],[1000,2000]],"rows":[]}
allw={}
for c in [0.5,1,2,4,8,16]:
    for (a,b) in res["ranges"]:
        ws=windows(c,a,b); sc=[has_sc(t,H) for t,H in ws]
        f=np.mean([s for s,_ in sc])
        lam=np.mean([H*np.log(t/(2*np.pi))/(2*np.pi) for t,H in ws])
        row={"c":c,"range":[a,b],"windows":len(ws),"frac_with_sign_change":round(float(f),4),
             "mean_expected_zeros_per_window":round(float(lam),4),"poisson_1-exp(-lam)":round(float(1-np.exp(-lam)),4),
             "even_spacing_min(1,lam)":round(float(min(1,lam)),4)}
        res["rows"].append(row); print(row,flush=True)
        allw[(c,a)]=(ws,sc)
# mpmath spot check: 40 random windows from c=2 and c=8, ranges 100-500 and 1000-2000
mp.mp.dps=15; mism=0; checked=0
for key in [(2,100),(2,1000),(8,100),(8,1000)]:
    ws,sc=allw[key]
    for i in rng.choice(len(ws),10,replace=False):
        t,H=ws[i]; pts=[mp.siegelz(t+H*k/40) for k in range(41)]
        s=any(mp.sign(pts[k])!=mp.sign(pts[k+1]) for k in range(40))
        checked+=1; mism+= (s!=sc[i][0])
res["mpmath_spotcheck"]={"windows_checked":checked,"classification_mismatches":int(mism),"grid":"41 pts per window, mpmath.siegelz"}
print(res["mpmath_spotcheck"])
json.dump(res,open("hl_windows.json","w"),indent=1)
