#!/usr/bin/env python3
"""Ball-arithmetic sign certificate using exact Euler coefficients and a proved tail.
Requires cypari2==2.2.4 and python-flint==0.9.0. See q8.md for the proof.
Unlike a central-value evaluation, the theta sums do not impose a root number.
"""
from pathlib import Path
import json
from cypari2 import Pari
from flint import arb,ctx
ROOT=Path(__file__).resolve().parent
p=Pari()
ctx.prec=256
M=1000
reference=json.loads((ROOT/'q8-results.json').read_text())
cert=dict(method='Exact modular factorizations + Arb K0 sums + explicit positive geometric tail',
          flint_version='0.9.0', precision_bits=ctx.prec, cutoff=M, fields=[], checks=0)
def check(ok):
    assert ok
    cert['checks']+=1

def coefficients(poly):
    # Independently derive every coefficient through M, rather than importing lfunan.
    P=p(poly)
    check(p.poldisc(P) == 2**24*3**14) # no extra index primes outside 2 and 3
    spf=list(range(M+1))
    for ell in range(2,M+1):
        if spf[ell]==ell:
            for n in range(ell*ell,M+1,ell):
                if spf[n]==n:spf[n]=ell
    local={}
    factor_audit=[]
    for ell in range(2,M+1):
        if spf[ell]!=ell:continue
        if ell in (2,3):
            powers=[1]+[0]*(M.bit_length())
            factor_audit.append(dict(prime=ell, factor='1 (nontrivial inertia has no fixed vector)'))
        else:
            F=p.factormod(P,ell)
            ds=[int(F[j,0].poldegree()) for j in range(F.nrows())]
            check(len(set(ds))==1 and ds[0] in (1,2,4))
            ap={1:2,2:-2,4:0}[ds[0]]
            powers=[1,ap]
            power=ell*ell
            while power<=M:
                powers.append(ap*powers[-1]-powers[-2]);power*=ell
            factor_audit.append(dict(prime=ell,degrees=ds,trace=ap))
        local[ell]=powers
    a=[0]*(M+1);a[1]=1
    for n in range(2,M+1):
        ell=spf[n];q=n;e=0
        while q%ell==0:q//=ell;e+=1
        a[n]=local[ell][e]*a[q]
    return a,factor_audit

for f in reference['fields']:
    a,audit=coefficients(f['polynomial'])
    check(a[1:]==f['coefficients_first_2000'][:M])
    nu=f['gamma'][0]
    points=[]
    for ts in ['3/4','4/3']:
        t=arb(ts)
        c=arb.pi()*t/24
        r=(-c).exp()
        finite=arb(0)
        for n in range(1,M+1):
            if a[n]: finite+=a[n]*(n if nu else 1)*(c*n).bessel_k(0)
        finite*=t/12 if nu else 4
        # K0(x) <= exp(-x)*sqrt(pi/(2*x)), |a(n)| <= d(n) <= n.
        # Replace n^(3/2) or n^(1/2) by n^2 to obtain a simple geometric bound.
        m=M+1
        square_sum=r**m*(m*m/(1-r)+2*m*r/(1-r)**2+r*(1+r)/(1-r)**3)
        bound=((t/12).sqrt() if nu else 4*(12/t).sqrt())*square_sum
        enclosure=finite+arb(0,bound.upper())
        sign=1 if enclosure>0 else -1 if enclosure<0 else 0
        check(sign!=0)
        coarse={(-1,'3/4'):('-0.177599','-0.177597'),
                (-1,'4/3'):('0.133198','0.133199'),
                (1,'3/4'):('10.120627','10.120630'),
                (1,'4/3'):('7.590470','7.590473')}[(f['sign'],ts)]
        check(enclosure>arb(coarse[0]) and enclosure<arb(coarse[1]))
        # Cross-check normalization against PARI's independently implemented theta.
        p.set_real_precision(60)
        p(f'P={f["polynomial"]};N=nfinit(P);G=galoisinit(N);TC=galoischartable(G);L=lfunartin(N,G,TC[1][,5],TC[2]);')
        # str returns decimal digits; request the value entirely within GP precision.
        theta=p(f'lfuntheta(L,{ts})')
        difference=abs(float(enclosure.mid())-float(theta))
        check(difference<1e-12)
        points.append(dict(t=ts,finite_sum=str(finite),tail_bound=str(bound),
                           certified_enclosure=str(enclosure),certified_sign=sign,
                           pari_theta_cross_check=str(theta)))
        print(f['label'],ts,'theta in',enclosure,'tail <=',bound,flush=True)
    W=points[0]['certified_sign']*points[1]['certified_sign']
    check(W==f['sign'])
    cert['fields'].append(dict(label=f['label'],polynomial=f['polynomial'],
           gamma_shift=nu,points=points,certified_root_number=W,
           exact_prime_factor_audit=audit))
(ROOT/'q8-certificate.json').write_text(json.dumps(cert,indent=2)+'\n')
print('CERTIFIED',[(f['label'],f['certified_root_number']) for f in cert['fields']],cert['checks'],'assertions')
