#!/usr/bin/env python3
"""Export PARI zeros / a_n of A5/2I Artin L-functions of the galpol degree-120 field (ramified 2,11,23).
usage: zeros_export.py NAME H NMAX_BUILD a2 ; conductor 2^a2 * 11^e * 23^e, Vga = [0]*dim (totally real field: complex conj trivial).
All PARI numbers are uncertified floats.  zeta: lfuncreate(1)."""
import sys, json, time
from pathlib import Path
from an_build import *
from cypari2 import Pari
import os
PRECD = int(os.environ.get("PRECD", 288))
name = sys.argv[1]; H = float(sys.argv[2]); NM = int(sys.argv[3]); a2 = int(sys.argv[4]) if len(sys.argv) > 4 else 0
EO = {'three': [-1,1]*11, 'threep': [-1,1]*11, 'four': [0,1]*11, 'five': [1]*22, 'rho': []}
dim = {'zeta':1,'rho':2,'three':3,'threep':3,'four':4,'five':5}[name]
e = {'rho':2,'three':2,'threep':2,'four':2,'five':4}.get(name, 0)
pari = Pari(); pari.allocatemem(3*10**9); pari.set_real_precision_bits(PRECD)
t0 = time.time()
out = dict(name=name, dim=dim, H=H)
if name == 'zeta':
    L = pari('lfuncreate(1)'); N = 1; av, lim = None, 20000
    an = [1.0]*20000
    out['rootno'] = 1; eps = 1
else:
    ram = {2: [], 11: EO[name], 23: EO[name]}
    OPT2 = json.loads(sys.argv[5]) if len(sys.argv) > 5 else []
    ram[2] = OPT2
    import an_exact
    pairs = an_exact.build_pairs(name, ram, NM); lim = NM
    N = 2**a2 * 11**e * 23**e
    pari('phi=(1+sqrt(5))/2;')
    pari.set_real_precision_bits(PRECD)
    XX = pari([p[0] for p in pairs]); YY = pari([p[1] for p in pairs])
    pari('AVx=0'); AVv = XX + YY*pari('phi'); AV = AVv
    av = [float(p[0]) + float(p[1])*1.618033988749895 for p in pairs[:20000]]
    best = None
    for eps in (1, -1):
        try:
            Lc = pari.lfuncreate([AV, 0, [0]*dim, 1, N, eps]); c = int(pari.lfuncheckfeq(Lc))
        except Exception as ex: c = 0
        print('checkfeq eps', eps, c, flush=True)
        if best is None or c < best[0]: best = (c, eps, Lc)
    c, eps, L = best; out['checkfeq'] = c; out['rootno'] = eps
    an = [float(x) for x in av[:20000]]
    out['lim'] = lim
out['conductor'] = N; out['Vga'] = [0]*dim; out['an'] = an
out['order0'] = int(pari.lfunorderzero(L)) if name != 'zeta' else 0
t1 = time.time()
zs = pari.lfunzeros(L, H); out['zeros_pos'] = [float(z) for z in zs]
out['secs_zeros'] = round(time.time()-t1, 1)
Path(f'zeros-{name}.json').write_text(json.dumps(out))
print(name, 'N', N, 'eps', eps, 'ord0', out['order0'], 'nz', len(out['zeros_pos']), 'secs', out['secs_zeros'], flush=True)
