#!/usr/bin/env python3
"""500 low zeta zeros: finite illustration, not a test of RH or full GUE.
All positive pair differences (not just adjacent gaps); no diagonal pairs.
Unfold by smooth Riemann-von Mangoldt Nbar; translation edge correction.
"""
import json,time,math
from pathlib import Path
import mpmath as mp
import numpy as np
R=Path(__file__).resolve().parents[1];mp.mp.dps=25;t0=time.monotonic();N=500
cache=R/'results/zeros-mpmath-500.json'
if cache.exists():zeros=json.loads(cache.read_text())['zeros']
else:
 zeros=[]
 for n in range(1,N+1):
  zeros.append(str(mp.im(mp.zetazero(n))))
  if n%25==0:
   print('ZERO',n,zeros[-1],'elapsed',time.monotonic()-t0,flush=True)
   (R/'results/zeros-progress.json').write_text(json.dumps({'zeros':zeros,'dps':mp.mp.dps}))
 cache.write_text(json.dumps({'zeros':zeros,'dps':mp.mp.dps,'method':'mpmath.zetazero n=1..500 (non-interval)'},indent=2)+'\n')
t=np.array([float(z) for z in zeros]);x=t/(2*np.pi)*np.log(t/(2*np.pi))-t/(2*np.pi)+7/8
L=x[-1]-x[0];gaps=np.diff(x);du=x[None,:]-x[:,None];du=du[np.triu_indices(N,1)];du=du[du<4]
bins=np.arange(0,4.0001,0.2);weights=L/(L-du);hist,_=np.histogram(du,bins,weights=weights);density=hist/(N*np.diff(bins));centres=(bins[1:]+bins[:-1])/2
pred=[]
for a,b in zip(bins[:-1],bins[1:]):pred.append(float(mp.quad(lambda u:1-mp.sinc(mp.pi*u)**2,[a,b])/(b-a)))
out={'status':'[project] small, low-height, deterministic sample; descriptive only','N':N,'first_height':float(t[0]),'last_height':float(t[-1]),'unfolding':'Nbar(t)=t/(2pi)log(t/(2pi))-t/(2pi)+7/8; not fitted to the observed zeros','estimator':'Sum_{i<j} 1_[a,b)(x_j-x_i) L/(L-(x_j-x_i)) / (N*(b-a)), L=x_N-x_1','self_pairs_removed':True,'range':[0,4],'bins':bins.tolist(),'centres':centres.tolist(),'observed_pair_density':density.tolist(),'GUE_bin_mean':pred,'unfolded_mean_adjacent_gap':float(np.mean(gaps)),'unfolded_min_gap':float(np.min(gaps)),'unfolded_max_gap':float(np.max(gaps)),'rms_difference_from_GUE':float(np.sqrt(np.mean((density-np.array(pred))**2))),'positive_pairs_with_difference_below_4':len(du),'elapsed_seconds':time.monotonic()-t0,'warning':'The first 500 zeros are not asymptotic; no p-value, RH proof, or universal GUE theorem follows. A finite or density-zero off-line exceptional set would be invisible to limiting bulk statistics.'}
(R/'results/pair-correlation.json').write_text(json.dumps(out,indent=2)+'\n');print('PASS',out,flush=True)
