"""Exact geometric reduction and Gaussian inequalities for SRFP311T1 #122.
Run with Python 3.10+ and NumPy/SymPy. The geometric interpretation uses
transitivity of Co0 and the 12-dimensional complex commutant (see manuscript).
The embedded GAP/CTblLib check runs automatically when GAP is on PATH.
Use --require-gap to fail if GAP is absent. The JSON file must be beside this script.
"""
import numpy as np, sympy as s
from itertools import combinations
import time,json
import argparse, shutil, subprocess, tempfile
from pathlib import Path

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--require-gap', action='store_true', help='require the embedded GAP character check to pass')
parser.add_argument('--gap-only', action='store_true')
parser.add_argument('--skip-gap', action='store_true')
args = parser.parse_args()
if args.skip_gap and (args.require_gap or args.gap_only):
 parser.error('Conflicting GAP options')
DATA = Path(__file__).with_suffix('.json')
GAP_SCRIPT = r'''
LeechCheck122 := function(ok,label)
 if not ok then Error(Concatenation("CHECK FAILED: ",label)); fi;
 Print("PASS: ",label,"\n");
end;;
LeechCheck122(LoadPackage("ctbllib")=true,"CTblLib loaded");
Print("GAP: ",GAPInfo.Version,"; CTblLib: ",PackageInfo("ctbllib")[1].Version,"\n");
g:=CharacterTable("2.Co1");; h:=CharacterTable("Co2");; k:=CharacterTable("2xCo2");;
LeechCheck122(g<>fail and h<>fail and k<>fail,"character tables found");
LeechCheck122(Size(k)=2*Size(h) and Size(g)/Size(h)=196560,"group orders and index");
a:=Filtered(Irr(h),c->c[1]=23);; b:=Filtered(Irr(g),c->c[1]=24);; cc:=Filtered(Irr(k),c->c[1]=23);;
LeechCheck122(Length(a)=1 and Length(b)=1 and Length(cc)=2,"natural and tangent character degrees");
zz:=Filtered([1..Length(SizesConjugacyClasses(k))],i->SizesConjugacyClasses(k)[i]=1 and OrdersClassRepresentatives(k)[i]=2);;
LeechCheck122(Length(zz)=1,"unique central involution of product subgroup");
z:=zz[1];;
sg:=Filtered(Irr(k),c->c[1]=1 and c[z]=-1);; odc:=Filtered(cc,c->c[z]=-23);; evc:=Filtered(cc,c->c[z]=23);;
LeechCheck122(Length(sg)=1 and Length(odc)=1 and Length(evc)=1,"central signs of tangent extensions");
LeechCheck122(ValuesOfClassFunction(sg[1]*evc[1])=ValuesOfClassFunction(odc[1]),"extensions differ by sign");
f:=GetFusionMap(k,g);;
LeechCheck122(f<>fail,"stored CTblLib fusion 2xCo2 -> 2.Co1");
ambient:=ValuesOfClassFunction(b[1]);;
LeechCheck122(ambient{f}=ValuesOfClassFunction(sg[1]+odc[1]),"natural module restricts as sign plus odd tangent extension");
# Ind_Co2^(2xCo2)(23) is the sum of its two degree-23 extensions.
# Induction in stages therefore uses the stored maximal-subgroup fusion.
t:=Sum(InducedClassFunctionsByFusionMap(k,g,cc,f));;
LeechCheck122(t[1]=4520880,"induced dimension");
m:=List(Irr(g),c->ScalarProduct(g,t,c));;
Print("Nonzero degree/multiplicity pairs: ",List(Filtered([1..Length(m)],i->m[i]<>0),i->[Irr(g)[i][1],m[i]]),"\n");
LeechCheck122(ForAll(m,a->a=0 or a=1),"multiplicity-free induction");
chosen:=Irr(g){Positions(m,1)};;
expected:=[24,276,299,2576,4576,17250,44275,95680,315744,376740,1821600,1841840];;
LeechCheck122(SortedList(List(chosen,c->c[1]))=expected,"all twelve constituent dimensions");
LeechCheck122(ForAll(chosen,c->ForAll(ValuesOfClassFunction(c),IsRat)),"rational character values");
Print("PASS: induced character multiplicity-free; dimensions and rational values verified.\n");
Print("LEECH122_GAP_OK\n");
QUIT;
'''

def run_gap(required=False):
 gap_exe=shutil.which('gap')
 if gap_exe is None:
  print('NOT RUN: GAP/CTblLib character verification (GAP not found on PATH).',flush=True)
  if required: raise SystemExit(1)
 else:
  with tempfile.TemporaryDirectory(prefix='leech122_gap_') as tmp:
   script=Path(tmp)/'character_check.g'
   script.write_text(GAP_SCRIPT,encoding='utf-8')
   run=subprocess.run([gap_exe,'-q','-T',str(script)],capture_output=True,text=True)
   print(run.stdout,end='',flush=True)
   if run.stderr: print(run.stderr,end='',flush=True)
   marker='LEECH122_GAP_OK'
   if run.returncode!=0 or marker not in run.stdout.splitlines() or 'Error,' in run.stderr or 'Error,' in run.stdout:
    raise SystemExit('FAIL: embedded GAP character verification did not pass.')

if args.gap_only:
 run_gap(required=True)
 raise SystemExit(0)

start=time.time(); v=[1,0,1,0,0,0,1,1,1,0,1]
B=np.zeros((12,12),dtype=np.int64); B[0,1:]=1; B[1:,0]=1
for i in range(11):
 for j in range(11): B[i+1,j+1]=v[(j-i)%11]
c0=(np.arange(4096)[:,None]>>np.arange(12))&1; cw=np.hstack((c0,(c0@B)%2)); octads=cw[cw.sum(1)==8]; assert len(octads)==759
X=[]
for i,j in combinations(range(24),2):
 for a in (4,-4):
  for b in (4,-4):
   w=np.zeros(24,dtype=np.int64);w[i]=a;w[j]=b;X.append(w)
X=[np.array(X)]; signs=np.array([[(-1)**((k>>i)&1)*2 for i in range(8)] for k in range(256) if k.bit_count()%2==0],dtype=np.int64)
Y=np.zeros((759,128,24),dtype=np.int64)
for j,c in enumerate(octads): Y[j][:,c.astype(bool)]=signs
X.append(Y.reshape(-1,24)); signs=1-2*cw
for i in range(24):
 w=signs.copy();w[:,i]*=-3;X.append(w)
X=np.concatenate(X); assert X.shape==(196560,24); assert np.all((X*X).sum(1)==32)
u=X[0]; shells=[32,16,8,0,-8,-16,-32]; us=X@u; Ys={k:X[us==k] for k in shells}; ns=[4600,47104,93150,47104,4600,1];assert [len(Ys[k]) for k in shells]==[1]+ns
assert len(np.unique(X,axis=0))==196560
for k,nk in zip(shells[1:],ns):
 Y=Ys[k]; assert np.array_equal(32*Y.sum(0),nk*k*u)
 # Q = sum (P_u y)(P_u y)^T, in integer coordinates.
 ZY=32*Y-k*u[None,:]
 assert np.array_equal(23*(ZY.T@ZY),nk*(1024-k*k)*(32*np.eye(24,dtype=np.int64)-np.outer(u,u)))
reps={k:Ys[k][0] for k in shells}; specs=[(k,a) for k in shells for a in ([0] if abs(k)==32 else [0,1])]; Z=32*np.eye(24,dtype=np.int64)-np.outer(u,u)
sites=[]; E=s.zeros(12,12); irow=0
for k in shells:
 x=reps[k]; inds=[i for i,(kk,a) in enumerate(specs) if kk==k]; picked=[];rank=0
 for z in Z:
  w1=32*z-(z@x)*x;w2=(z@x)*(32*u-k*x); mat=np.stack([w1,w2],axis=1)[:,:len(inds)]
  for q in range(24):
   r=mat[q].tolist(); rnk=s.Matrix(picked+[r]).rank()
   if rnk>rank:
    picked.append(r); sites.append((k,z.copy(),q)); rank=rnk
    for ind,val in zip(inds,r): E[irow,ind]=s.Rational(val,32)
    irow+=1
   if rank==len(inds):break
  if rank==len(inds):break
 assert rank==len(inds)
assert irow==12; Ei=E.inv(); print('generation',time.time()-start,flush=True)
levels=shells[1:]; R=[s.zeros(12,12) for _ in range(11)]
for i,(k,z,q) in enumerate(sites):
 x=reps[k];p=32*np.eye(24,dtype=np.int64)[q]-x[q]*x
 for b,(ks,kind) in enumerate(specs):
  y=Ys[ks]; zy=y@z; W=32*z[None,:]-zy[:,None]*y if kind==0 else zy[:,None]*(32*u[None,:]-ks*y)
  xy=y@x; wp=W@p; wx=W@x; yp=y@p; wc=0
  if k==ks: wc=int((32*z-(z@x)*x if kind==0 else (z@x)*(32*u-k*x))[q])
  for j,(lev,n) in enumerate(zip(levels,ns)):
   mask=xy==lev;t=s.Rational(lev,32)
   R[j][i,b]=s.Rational(int(wp[mask].sum()),1024)-n*t*s.Rational(wc,32)
   if j<5:R[6+j][i,b]=s.Rational(int((wx[mask]*yp[mask]).sum()),32768)+n*(1-t*t)/23*s.Rational(wc,32)
 print('row',i,round(time.time()-start,2),flush=True)
A=[Ei*r*(-2 if j<6 else 4) for j,r in enumerate(R)];H=s.zeros(12)
for j,lev in enumerate(levels):
 dist=2-2*s.Rational(lev,32);H+=A[j]*(-2/dist**3)
 if j<5:H+=A[6+j]*(6/dist**4)
ev=H.eigenvects();print('roots',[(a,b) for a,b,c in ev],flush=True)
M=[]
for val,mult,vecs in ev:
 assert mult==1
 vec=vecs[0]; ix=next(i for i in range(12) if vec[i]);row=[]
 for a in A:
  out=a*vec;lam=out[ix]/vec[ix];assert out==lam*vec;row.append(lam)
 M.append((val,row))
known=[(0,1,276),(73073,58982400,4576),(219791,92160000,44275),(558817,163840000,315744),(24731,5760000,1821600),(1479317,294912000,1841840),(199381,18432000,376740),(40598593,1474560000,95680),(872241,10240000,17250),(432845153,1474560000,2576),(797071,737280,299),(24913889,6553600,24)]
D={s.Rational(a,b)*32**3:d for a,b,d in known}; assert set(D)==set(val for val,row in M)
# compute dimensions directly from trace of each coefficient operator
MM=s.Matrix([row for val,row in M if val!=0]); assert MM.rank()==11
T=[s.Rational(lev,32) for lev in levels]; Tr=s.Matrix([196560*23*2*n*t for n,t in zip(ns,T)]+[196560*4*n*(1-t*t) for n,t in zip(ns,T)])[:11,0]
# above last list includes sixth zero, truncated
mults=MM.T.inv()*Tr; dims=iter(mults); result=[]
for val,row in M:
 dim=276 if val==0 else int(next(dims)); result.append({'riesz':str(val),'dimension':dim,'coefficients':[str(c) for c in row]})
assert all(D[s.Rational(r['riesz'])]==r['dimension'] for r in result)
assert all(v.is_Integer for v in MM)
print('M',result,'det',MM.det(),flush=True)
with DATA.open(encoding='utf-8') as f:
 published=json.load(f)
assert sorted(result,key=lambda r:r['dimension'])==sorted(published,key=lambda r:r['dimension']), 'Published JSON differs from reconstructed spectrum'
print('Published JSON matches the exact reconstructed spectrum.')
# Independent full-space Gram check and power-series positivity certificate.
from math import prod
N=196560; D0=24
w=s.Matrix([-nn*t for t,nn in zip(T,ns)]+[nn*(1-t*t)/23 for t,nn in zip(T[:5],ns[:5])]); G=23*w*w.T
for i,(t,nn) in enumerate(zip(T,ns)):
 G[i,i]+=nn*(22+t*t)
 if i<5:
  G[6+i,6+i]+=nn*(1-t*t)**2
  G[i,6+i]-=nn*t*(1-t*t);G[6+i,i]-=nn*t*(1-t*t)
S=s.diag(*([-2]*6+[4]*5));G=N*S*G*S
assert MM.T*s.diag(*mults)*MM==G
assert abs(MM.det())==2**41*3**22*5**9*7**4*13**3*23
assert set(mults)==set(D.values())-{276}
assert all(v.is_Integer and v>0 for v in mults)
assert sum(mults)+276==N*23
q,x,z,n=s.symbols('q x z n')
base_row=next(r for r in result if r['dimension']==4576)
base=list(map(s.Integer,base_row['coefficients']))
# The contact tie identity holds for every smooth central potential.
row24=next(r for r in result if r['dimension']==24)
diff24=[s.Integer(a)-b for a,b in zip(row24['coefficients'],base)]
assert diff24==[-2*nn*(1-t*t) for nn,t in zip(ns[:5],T[:5])]+[0]*6
print('Exact 24-versus-4576 identity verified.')
for it in result:
 if it['dimension']==276: continue
 c=list(map(s.Integer,it['coefficients']));c=[a-b for a,b in zip(c,base)] if it['dimension']!=4576 else c
 P=s.Poly(sum(-c[i]*q**k for i,k in enumerate([0,1,2,3,4,6])).subs(q,1-x),x);Q=s.Poly(sum(c[6+i]*q**i for i in range(5)).subs(q,1-x),x)
 d=-1 if Q.is_zero else Q.degree(); coeff=lambda k:P.nth(k)+2*sum(Q.nth(j)/s.Integer(k-j) for j in range(min(k,d+1))) if k else P.nth(0)
 prefix=sum(coeff(k)*x**k for k in range(7));
 # certify finite prefix by converting it to nonnegative Bernstein coefficients on [0,1]
 deg=max(0,s.Poly(prefix,x).degree()) if prefix else 0
 bcoeff=[sum(s.Poly(prefix,x).nth(j)*s.binomial(k,j)/s.binomial(deg,j) for j in range(k+1)) for k in range(deg+1)]
 assert all(v>=0 for v in bcoeff)
 tail_positive=False
 if d>=0:
  num,den=s.fraction(s.factor(2*sum(Q.nth(j)/(n-j) for j in range(d+1))))
  assert all(num.subs(n,k)>=0 for k in range(7,10))
  assert all(v>=0 for v in s.Poly(num.subs(n,z+10),z).all_coeffs())
  assert all(v>0 for v in s.Poly(den.subs(n,z+7),z).all_coeffs())
  tail_positive=num.subs(n,10)>0
 assert tail_positive or any(v>0 for v in bcoeff)
 print('Gaussian inequality certified:',it['dimension'])
print('All trace Gram and Gaussian checks passed.')


if args.skip_gap:
 print("NOT RUN: GAP explicitly skipped in this invocation.")
else:
 run_gap(required=args.require_gap)
