#!/usr/bin/env python3
"""Artin formalism audit; exact arithmetic and NON-INTERVAL numerical checks.
PARI's Dedekind evaluation internally factorizes: agreement is NOT independent.
We deliberately never call lfunzeros on zeta_K (its rho zeros are double).
"""
from pathlib import Path
from datetime import datetime
from zoneinfo import ZoneInfo
import json,time,math,cmath
from cypari2 import Pari
R=Path(__file__).resolve().parents[1]
p=Pari();p.allocatemem(800_000_000);p.set_real_precision(50)
P='x^8-3*x^7-63*x^6+90*x^5+1311*x^4-20*x^3-7702*x^2-5524*x-1009'
t0=time.monotonic();out={'status':'[project] exact character/coefficient identities; numerical, non-interval zeros and windings','started_PT':datetime.now(ZoneInfo('America/Los_Angeles')).isoformat(),'polynomial':P,'height':30,'checks':0}
def check(b):
 assert b
 out['checks']+=1
def save():
 out['elapsed_seconds']=time.monotonic()-t0
 (R/'results/q8-transfer.json').write_text(json.dumps(out,indent=2)+'\n')
p(f'P={P};NF=nfinit(P);G=galoisinit(NF);TC=galoischartable(G);T=TC[1];LS=vector(5,j,lfunartin(NF,G,T[,j],TC[2]));')
check([int(x) for x in p('galoisidentify(G)')]==[8,4])
deg=[int(p(f'T[1,{j}]')) for j in range(1,6)];check(deg==[1,1,1,1,2])
out['character_table']=str(p('T'));out['discriminant']=str(p('NF.disc'));out['signature']=[int(x) for x in p('NF.sign')]
# The central quotient Q8/{+1,-1} is C2 x C2; rho x dual(rho) is its regular representation.
check(p('vector(5,k,T[k,5]^2)')==p('vector(5,k,sum(j=1,4,T[k,j]))'))
out['tensor_identity']='rho tensor dual(rho) = 1 + chi_1 + chi_2 + chi_3; hence L(tensor)=zeta of the biquadratic fixed field'
out['quadratic_subfields']=[str(x) for x in p('nfsubfields(NF,2)')]
N=2000
p(f'AK=dirzetak(NF,{N});AP=vector({N},n,1);for(j=2,5,for(k=1,T[1,j],AP=dirmul(AP,lfunan(LS[j],{N}))));')
check(p('AK')==p('AP'))
out['exact_coefficient_convolution_checked_through']=N
print('EXACT PASS',out['discriminant'],deg,out['quadratic_subfields'],flush=True);save()
# Primitive factors (simple zeros are a routine assumption, not a certificate).
p('LI=vector(5,j,lfuninit(LS[j],[1/2,1,31],2));KI=lfuninit(NF,[1/2,1,31],2);')
rows=[]
for j in range(1,6):
 zs=p(f'lfunzeros(LI[{j}],[1e-8,30],32)')
 row={'factor':j,'degree':deg[j-1],'parameters':str(p(f'lfunparams(LS[{j}])')),'multiplicity_in_zeta_K':deg[j-1],'positive_zeros':[str(z) for z in zs],'positive_count':len(zs),'central_order_numeric':int(p(f'lfunorderzero(LI[{j}],2)')),'central_value':str(p(f'lfun(LI[{j}],1/2)'))}
 if j in (2,3,4):row['quadratic_discriminant']=int(p(f'lfunparams(LS[{j}])[1]'))
 row['max_zero_residual']=str(max([abs(p(f'lfun(LI[{j}],1/2+I*({z}))')) for z in zs],default=p(0)))
 rows.append(row);out['factors']=rows;save();print('ZEROS',j,len(zs),'central',row['central_order_numeric'],flush=True)
out['positive_count_with_multiplicity']=sum(r['positive_count']*r['multiplicity_in_zeta_K'] for r in rows)
out['central_order_numeric']=sum(r['central_order_numeric']*r['multiplicity_in_zeta_K'] for r in rows)
out['union'] = sorted([{'height':float(z),'factor':r['factor'],'multiplicity':r['multiplicity_in_zeta_K']} for r in rows for z in r['positive_zeros']],key=lambda x:x['height'])
# Complex values from the Dedekind interface versus explicit factorization.
values=[]
for s in ['2','3/4+I*7/10','1/2+I*141/10','1/3+I*23','1/2']:
 p(f's={s};vk=lfun(KI,s);vp=prod(j=1,5,lfun(LI[j],s)^T[1,j]);')
 err=abs(p('vk-vp'));check(err<p('1e-40'))
 values.append({'s':s,'zeta_K':str(p('vk')),'product':str(p('vp')),'absolute_difference':str(err)})
out['value_comparisons']=values
# Multiplicities by tiny circles, sampled winding, not interval-certified.
local=[]
for r in rows:
 if not r['positive_zeros']:continue
 z=r['positive_zeros'][0]
 vals=p(f'vector(96,k,lfun(KI,1/2+I*({z})+1/10000*exp(2*Pi*I*(k-1)/96)))')
 v=[complex(z) for z in vals]
 w=sum(cmath.phase(b/a) for a,b in zip(v,v[1:]+v[:1]))/(2*math.pi)
 check(abs(w-r['multiplicity_in_zeta_K'])<1e-8)
 local.append({'factor':r['factor'],'height':z,'sampled_circle_radius':0.0001,'vertices':96,'winding':w,'expected_multiplicity':r['multiplicity_in_zeta_K']})
out['local_windings']=local
# Completed Dedekind entire function s(s-1)Lambda_K(s), large rectangle.
contours=[]
for mesh in [8,16]:
 corners=[(-.5,-30),(1.5,-30),(1.5,30),(-.5,30),(-.5,-30)];pts=[]
 for (x,y),(X,Y) in zip(corners,corners[1:]):
  n=math.ceil((abs(X-x)+abs(Y-y))*mesh)
  pts.extend([complex(x+(X-x)*k/n,y+(Y-y)*k/n) for k in range(n)])
 vals=[]
 for z in pts:
  p(f's={z.real}+I*({z.imag});')
  vals.append(complex(p('s*(s-1)*lfunlambda(KI,s)')))
 phases=[cmath.phase(b/a) for a,b in zip(vals,vals[1:]+vals[:1])]
 w=sum(phases)/(2*math.pi);expected=2*out['positive_count_with_multiplicity']+out['central_order_numeric']
 check(abs(w-expected)<1e-7)
 contours.append({'mesh_per_unit':mesh,'vertices':len(vals),'sampled_winding':w,'expected_from_factor_union':expected,'max_phase_step':max(map(abs,phases)),'warning':'Stable sampled winding is not a certified argument-principle contour; internal factorization also means this is not independent.'})
 print('CONTOUR',mesh,w,'expected',expected,flush=True)
out['sampled_global_windings']=contours
save();print('PASS',out['checks'],'checks',out['elapsed_seconds'],'seconds',flush=True)
