#!/usr/bin/env python3
"""Second, independent check of the key residuals: truncate the PARI zeros at lower heights (40, 60, 80, 110) and compare the
residual with the density-based estimate of the omitted zeros (code B, doubles).  python3 cutoff_check.py b.a"""
import sys, json, math
KEY = sys.argv[1] if len(sys.argv) > 1 else 'b.a'
sys.argv = ['run.py', KEY]
import run as R
import numpy as np
out = []
full = {c: (R.ZP[c].copy(), R.ZD[c].copy()) for c in range(7)}
def dens(c, t): return (math.log(R.chars[c]['conductor']) + R.dims[c]*math.log(t/(2*math.pi)))/(2*math.pi)
for T in (8.0, 12.0, 16.0, 20.0):
    fam = R.Fam('E', T, 0.0); famG = R.Fam('G', T) if T <= 8 else None
    for H in (40, 60, 80, 110):
        for c in range(7): R.ZP[c] = full[c][0][full[c][0] <= H]; R.ZD[c] = full[c][1][full[c][1] <= H]
        ulin_z = 0; est = 0; estabs = 0
        for c, s in ((R.TRIV, 1), (R.OM, 1), (R.OMB, 1), (R.PSI3, -1)):
            Z = R.zero_f(fam, c); A = R.arch_f(fam, c) + R.pole_f(fam, c); P = R.prime_lam_f(fam, c)
            ulin_z += s*(Z-A-P)/4
            # estimated omitted zero sum (both families of positive zeros): 2 * int_H^inf h(t) dens(t) dt
            from scipy import integrate
            estabs += 2*integrate.quad(lambda t: math.exp(-(t/T)**2)*dens(c, t), H, np.inf)[0]/4
            est += s*2*integrate.quad(lambda t: math.exp(-(t/T)**2)*dens(c, t), H, np.inf)[0]/4
        row = dict(T=T, H=H, u_resid_B=ulin_z, u_smooth_estimate_signed=-est, u_unsigned_density_estimate=estabs)  # resid = zero - (A+P) = -(omitted)
        if famG:
            Z = R.zero_f(famG, R.RW); P = R.prime_lam_f(famG, R.RW)
            row['n_resid_B'] = Z - P
        # rho real part with central zero
        Z = R.zero_f(fam, R.RHO); A = R.arch_f(fam, R.RHO); P = R.prime_lam_f(fam, R.RHO)
        row['rho_resid_B'] = Z-A-P
        row['rho_est_omitted'] = -2*integrate.quad(lambda t: math.exp(-(t/T)**2)*dens(R.RHO, t), H, np.inf)[0]
        out.append(row)
        print(KEY, row, flush=True)
json.dump(out, open(f'cutoff-check-{KEY}.json', 'w'), indent=1)
