#!/usr/bin/env python3
"""Exact finite-field counts and cohomological factor checks for E and E x E."""
from pathlib import Path
import json,cmath,math
from cypari2 import Pari
R=Path(__file__).resolve().parents[1];p=Pari();q=5;a=-3
counts=[]
for n in range(1,9):
 p(f'F=ffgen(ffinit(5,{n}),a);E=ellinit([1,1],F);')
 actual=int(p('ellcard(E)'))
 if n==1:power=a
 else:
  prevprev,prev=a, a*a-2*q
  if n==2:power=prev
  else:
   for k in range(3,n+1):prevprev,prev=prev,a*prev-q*prevprev
   power=prev
 expected=q**n+1-power
 assert actual==expected
 counts.append({'extension_degree':n,'field_size':q**n,'E_point_count':actual,'trace_Frobenius_n':power,'E_times_E_point_count':actual**2})
alpha=complex(-3,math.sqrt(11))/2;beta=alpha.conjugate()
roots=[1/alpha,1/beta]
surface_zeros=[{'weight':1,'multiplicity':2,'T_real':r.real,'T_imag':r.imag,'radius':abs(r)} for r in roots]+[{'weight':3,'multiplicity':2,'T_real':(r/q).real,'T_imag':(r/q).imag,'radius':abs(r/q)} for r in roots]
out={'status':'[project] Exact point counts checked with PARI ellcard; analytic roots from exact polynomial, displayed as floating-point','curve':'y^2 = x^3 + x + 1 over F_5','q':q,'a':a,'genus':1,'counts':counts,'P1':'1 + 3 T + 5 T^2','Z_curve':'(1 + 3 T + 5 T^2)/((1-T)(1-5T))','zeros':[{'T_real':r.real,'T_imag':r.imag,'abs_T':abs(r),'s_real':-math.log(abs(r))/math.log(q),'s_imag_principal':-cmath.phase(r)/math.log(q)} for r in roots],'surface':'E x E (smooth projective, dimension 2)','Z_surface':'(1+3T+5T^2)^2 (1+15T+125T^2)^2 / ((1-T)(1+T+25T^2)(1-5T)^4(1-25T))','surface_zeros':surface_zeros,'warning':'The finite-field local zeta is NOT an entire global Hasse-Weil L-function, and does not contain ordinary Riemann zeta as a factor in the same complex variable.'}
# Logarithmic derivative coefficients of the rational formula equal exact surface point counts.
p('T=x+O(x^9);ZS=(1+3*T+5*T^2)^2*(1+15*T+125*T^2)^2/((1-T)*(1+T+25*T^2)*(1-5*T)^4*(1-25*T));DV=T*deriv(log(ZS));')
for c in counts:assert int(p(f'polcoef(DV,{c["extension_degree"]})'))==c['E_times_E_point_count']
(R/'results/finite-geometry.json').write_text(json.dumps(out,indent=2)+'\n')
print('PASS',len(counts),'extension-field counts, E and E x E. roots',roots,'radius',1/math.sqrt(5))
