"""Follow-up finite checks: angular characters, noncommuting formulas, compactification.
Offline, mpmath 60 dps. Not interval certification and not an Artin-L computation.
"""
import mpmath as mp, json, random
from pathlib import Path
mp.mp.dps=60
P=Path(__file__).resolve().parent
rng=random.Random(146)
def norm(q):return mp.sqrt(sum(t*t for t in q))
def add(a,b):return [x+y for x,y in zip(a,b)]
def scale(a,t):return [x*t for x in a]
def conj(q):return [q[0]]+[-x for x in q[1:]]
def mul(a,b):
 if len(a)==1:return [a[0]*b[0]]
 h=len(a)//2;x,y=a[:h],a[h:];u,v=b[:h],b[h:]
 return add(mul(x,u),scale(mul(conj(v),y),-1))+add(mul(v,x),mul(y,conj(u)))
def basis(d,k):return [mp.mpf(int(j==k)) for j in range(d)]
def inv(q):return scale(conj(q),1/norm(q)**2)
def expq(q):
 y=norm(q[1:]);return [mp.exp(q[0])*mp.cos(y)]+[mp.exp(q[0])*mp.sin(y)*a/y if y else mp.mpf(0) for a in q[1:]]
def unit(d):
 q=[mp.mpf(0)]+[mp.mpf(rng.uniform(-1,1)) for _ in range(d-1)];return scale(q,1/norm(q))
def cvector(z,d):return [z.real,z.imag]+[mp.mpf(0)]*(d-2)
def serial(a):
 if isinstance(a,dict):return {str(k):serial(v) for k,v in a.items()}
 if isinstance(a,(tuple,list)):return [serial(x) for x in a]
 if isinstance(a,mp.mpc):return {'re':mp.nstr(a.real,35),'im':mp.nstr(a.imag,35)}
 if isinstance(a,mp.mpf):return mp.nstr(a,35)
 return a
out={'dps':60,'status':'finite non-interval checks; known Artin root-number theorem is not numerically evaluated here'}
characters={5:[0,1,1j,-1j,-1]}
w=mp.exp(2j*mp.pi/3);characters[7]=[0,1,w*w,w,w,w*w,1]
profiles=[]
for m,chi in characters.items():
 L=lambda z:mp.dirichlet(z,chi)
 roots=[]
 for h in [4,6,8,10,12,15,18,20]:
  try:r=mp.findroot(L,(mp.mpc('.45',h),mp.mpc('.55',h+.3)),maxsteps=50,tol=mp.mpf('1e-53'))
  except (ValueError,ZeroDivisionError):continue
  if r.imag>1 and abs(r.real-.5)<mp.mpf('1e-45') and all(abs(r-s)>mp.mpf('1e-20') for s in roots):roots.append(r)
  if len(roots)>=2:break
 for r in sorted(roots,key=lambda z:z.imag):
  U=L(r);V=L(mp.conj(r));A=(U+V)/2;B=(U-V)/(2j);rows=[];maxerr=mp.mpf(0)
  for d in [4,8]:
   for _ in range(24):
    I=unit(d);f=add(cvector(A,d),mul(I,cvector(B,d)));pred=(1+I[1])/2*abs(U)**2+(1-I[1])/2*abs(V)**2
    maxerr=max(maxerr,abs(norm(f)**2-pred))
   vals={}
   for label,I in [('i',basis(d,1)),('j',basis(d,2)),('k',basis(d,3)),('-i',scale(basis(d,1),-1))]:
    f=add(cvector(A,d),mul(I,cvector(B,d)));vals[label]={'value':f,'norm':norm(f)}
   rows.append({'dimension':d,'directions':vals})
  assert abs(U)<mp.mpf('1e-48') and maxerr<mp.mpf('1e-48') and abs(V)>mp.mpf('.01')
  profiles.append({'modulus':m,'zero':r,'residual':abs(U),'opposite_norm':abs(V),'perpendicular_norm':abs(V)/mp.sqrt(2),'latitude_law_max_error':maxerr,'samples':rows})
 assert len(roots)>=2
out['character_profiles']=profiles
# Noncommuting ordered Euler factors, even at a real s=2.
i,j,k=[basis(4,n) for n in (1,2,3)];one=basis(4,0)
A=inv(add(one,scale(i,-mp.mpf(1)/4)));B=inv(add(one,scale(j,-mp.mpf(1)/9)))
out['ordered_euler']={'factor_2_then_3':mul(A,B),'factor_3_then_2':mul(B,A),'difference_norm':norm(add(mul(A,B),scale(mul(B,A),-1))),'a6_order_23':mul(i,j),'a6_order_32':mul(j,i)}
assert out['ordered_euler']['difference_norm']>0
# exp(a+b) != exp(a)exp(b), and principal log(product) need not add.
left=expq(add(i,j));right=mul(expq(i),expq(j));out['exponential_addition']={'exp_i_plus_j':left,'exp_i_times_exp_j':right,'difference_norm':norm(add(left,scale(right,-1)))}
# Negative-real log branch produces different (-1)^j.
pi_i=scale(i,mp.pi);pi_j=scale(j,mp.pi)
out['negative_base_powers']={'exp_j_log_i_minus1':expq(mul(j,pi_i)),'exp_j_log_j_minus1':expq(mul(j,pi_j)),'difference_norm':norm(add(expq(mul(j,pi_i)),scale(expq(mul(j,pi_j)),-1)))}
# Octonionic associator and Artin's 2-generator limit.
a,b,c=[basis(8,n) for n in (1,2,4)];ab_c=mul(mul(a,b),c);a_bc=mul(a,mul(b,c))
out['octonion_associator']={'left':ab_c,'right':a_bc,'difference_norm':norm(add(ab_c,scale(a_bc,-1)))}
assert out['octonion_associator']['difference_norm']==2
# Q8 faithful representation: FS indicator -1 and an invariant skew form.
I=mp.matrix([[1,0],[0,1]]);Mi=mp.matrix([[1j,0],[0,-1j]]);Mj=mp.matrix([[0,1],[-1,0]]);Mk=Mi*Mj;J=Mj
G=[I,-I,Mi,-Mi,Mj,-Mj,Mk,-Mk]
tr=lambda M:M[0,0]+M[1,1]
fs=sum(tr(g*g) for g in G)/8
assert fs==-1
out['Q8_representation']={'frobenius_schur_indicator':fs,'skew_form_preservation_max_error':max(mp.norm(g.T*J*g-J) for g in G),'local_factor_for_i_t_quarter':mp.det(I-Mi/4),'local_factor_for_j_t_quarter':mp.det(I-Mj/4),'zeta_half':mp.zeta(mp.mpf('.5')),'central_zero_conclusion':'For a holomorphic self-dual completed Artin L-function with root number -1, Lambda(1/2)=0 exactly. Root numbers for explicit fields not calculated by this script.'}
# Inversion q -> q/|q|^2: escaping sphere centre/radius and tiny linked meridians.
ends=[]
for n in [1,10,100,1000]:
 t=mp.im(mp.zetazero(n));a=mp.mpf('.5');D=a*a+t*t
 ends.append({'zero_index':n,'height':t,'inverted_sphere_centre':a/D,'inverted_sphere_radius':t/D,'inverse_norm_of_sphere':1/mp.sqrt(D)})
out['compactification']=ends
# Plus/minus mirror: exact cosh/sinh models of real-type even/odd symmetry.
models=[]
for d in (4,8):
 q=scale(unit(d),mp.mpf('.7'));E=expq(q);Em=expq(scale(q,-1));even=scale(add(E,Em),mp.mpf('.5'));odd=scale(add(E,scale(Em,-1)),mp.mpf('.5'))
 assert abs(even[0]-mp.cos(mp.mpf('.7')))<mp.mpf('1e-55') and norm(even[1:])<mp.mpf('1e-55')
 assert abs(odd[0])<mp.mpf('1e-55') and abs(norm(odd)-mp.sin(mp.mpf('.7')))<mp.mpf('1e-55')
 det=mp.cos(mp.mpf('.7'))**2*(mp.sin(mp.mpf('.7'))/mp.mpf('.7'))**(d-2)
 models.append({'dimension':d,'even_value':even,'odd_value':odd,'odd_norm':norm(odd),'odd_jacobian_determinant_at_critical_radius_point7':det,'odd_centre_local_degree':1,'note':'cosh/sinh toy symmetry models, not computed Artin L-values'})
out['mirror_sign_models']=models
(P/'angles-results.json').write_text(json.dumps(serial(out),indent=2)+'\n')
print(json.dumps(serial(out),indent=2))
