#!/usr/bin/env python3
"""Export PARI zeros (|Im|<=H, both signs) for the 7 Artin L-functions of each 2T field.
Run: /workspace/tools/pari-venv/bin/python3 zeros_export.py b.a  [H]
Non-self-dual L(rho⊗w): positive zeros of L and of its dual (= conj of negative zeros of L)."""
import json, sys, time
from cypari2 import Pari
pari = Pari(); pari.allocatemem(6*10**9); pari.set_real_precision(38)
FIELDS = {'b.a': dict(label='2.26569.24t7.b.a', pol='x^8-x^7+x^6-4*x^5+5*x^4-8*x^3+4*x^2-8*x+16'),
          'a.a': dict(label='2.26569.24t7.a.a', pol='x^8-x^7-44*x^6+43*x^5+442*x^4-32*x^3-1311*x^2-1156*x-241')}
key = sys.argv[1]; H = int(sys.argv[2]) if len(sys.argv) > 2 else 110
fd = FIELDS[key]; D = json.load(open('../tetra1112/pari-data.json'))[fd['label']]
pari(f"P={fd['pol']}; S=polredbest(nfsplitting(P)); NF=nfinit(S); G=galoisinit(NF); TC=galoischartable(G);")
ordr = int(pari('TC[2]')); out = dict(label=fd['label'], H=H, chars={})
for c in range(1, 8):
    t0 = time.time()
    pari(f"L=lfunartin(NF,G,TC[1][,{c}],{ordr});")
    dim = int(pari(f'TC[1][1,{c}]')); par = pari('lfunparams(L)')
    N = int(par[0]); fe = float(pari('lfuncheckfeq(L)'))
    dual_selfdual = bool(int(pari('lfunisdual(L)'))) if False else None
    rec = dict(col=c, dim=dim, conductor=N, Vga=[int(x) for x in par[2]], feq_digits=fe)
    if dim == 1 and c == 1: pass
    zs = pari(f"lfunzeros(L,{H})")
    rec['zeros_pos'] = [float(z) for z in zs]
    # dual
    pari("Ld=lfuncreate(L); ")  # same
    try:
        pari("Ld=lfundual(L);")
        zd = pari(f"lfunzeros(Ld,{H})"); rec['zeros_dual_pos'] = [float(z) for z in zd]
        rec['rootno'] = str(pari('lfunrootres(L)[3]'))
        rec['order0'] = int(pari('lfunorderzero(L)'))
    except Exception as e:
        rec['dual_err'] = str(e)
    out['chars'][str(c)] = rec
    print(c, dim, N, rec['Vga'], 'feq', fe, len(rec['zeros_pos']), len(rec.get('zeros_dual_pos', [])), rec.get('rootno'), rec.get('order0'), round(time.time()-t0,1), flush=True)
    json.dump(out, open(f'zeros-{key}.json', 'w'))
