#!/usr/bin/env python3
"""Paper #123, Revision 2: single-file verifier.
Install: python -m pip install sympy numpy scipy mpmath
Run: python extremal48_vector_harmonics_check.py
No external data files needed. Writes solver results and rational certificate logs
beside the script. Finite checks support, but do not replace, manuscript proofs.
The original finite checks are reconstructed from the manuscript, not copied from
its historical verifier. Floating-point LP/PSD tests are exploratory.
"""
def main():
    import numpy as np
    from scipy.special import eval_gegenbauer, gammaln
    from scipy.optimize import linprog
    import json
    from pathlib import Path
    OUT = Path(__file__).resolve().parent
    T=np.array([.5,1/3,1/6,0,-1/6,-1/3,-.5,-1.]); U=2-2*T
    N=np.array([36848,1678887,12608784,23766960,12608784,1678887,36848,1]); A=np.array([19600,809676,4024080,1011360,-4381776,-1428840,-54096,-4]); B=np.array([1176,84672,869400,2022720,1217160,169344,3528,0]);
    LS=[15,20,25,30,40]; AL=[.001,.01,.1,.5,1,2,5,10,25,50]
    def deriv(l,j,t):
     if l<j:return np.zeros_like(t,dtype=float)
     return np.prod([2*(23+i) for i in range(j)])*eval_gegenbauer(l-j,23+j,t)*np.exp(gammaln(l+1)+gammaln(46)-gammaln(l+46))
    def data(L,vec=False):
     # unit self-point normalization for each kernel
     cols=[]
     for l in range(1,L+1):
      a=deriv(l,1,T); b=deriv(l,2,T); d=l*(l+46)/47
      cols.append(np.r_[a,b[:-1]]/d)
     if vec:
      for l in range(1,L+1):
       # Self-point-normalized divergence-free addition kernel.
       a=deriv(l,1,T); b=deriv(l,2,T)
       # D=47: a_H=(D-1)t p' -(1-t²)p'', b_H=-(D-1)p'-t p''
       cols.append(np.r_[46*T*a-(1-T*T)*b,(-46*a-T*b)[:-1]]/(46*l*(l+46)/47))
     return np.array(cols).T

    def run(vec):
     rows=[]
     for alpha in AL:
      q=np.exp(-alpha*(U-1)); rhs=np.r_[2*q,4*alpha*q[:-1]]
      target=np.dot(q,A-2*N*T+alpha*(4*N*(1-T*T)/47-B))
      for L in LS:
       M=data(L,vec); c=np.ones(M.shape[1]); bounds=[(None,None) if i%L<4 else (0,None) for i in range(len(c))]
       sol=linprog(c,A_eq=M,b_eq=rhs,bounds=bounds,method='highs',options={'primal_feasibility_tolerance':1e-9,'dual_feasibility_tolerance':1e-9})
       row=dict(alpha=alpha,L=L,target=float(target),status=sol.status)
       if sol.success:
        y=sol.eqlin.marginals; row.update(obj=float(sol.fun),margin=float(target-sol.fun),res=float(max(abs(M@sol.x-rhs))),dual_res=float(max(np.max(abs((M.T@y-c)[[i%L<4 for i in range(len(c))]])),np.max(M.T@y-c))),dual=y.tolist(),x=sol.x.tolist())
       rows.append(row)
       print('vec' if vec else 'scalar',alpha,L,sol.status, 'margin %.9g res %.3g'%(row['margin'],row['res']) if sol.success else sol.message,flush=True)
     return rows

    def original_checks():
        """Reconstruct original manuscript finite certificates from the slice moments."""
        import sympy as s
        from math import comb, factorial
        R=s.Rational
        t=s.symbols('t'); w=(1-t*t)/47; w4=(1-t*t)**2/(47*49)
        nodes=list(map(R,['1/2','1/3','1/6','0','-1/6','-1/3','-1/2','-1']))
        ns=[36848,1678887,12608784,23766960,12608784,1678887,36848,1]
        total=52416000
        assert 1+sum(ns)==total
        for j in range(12):
            moment=R(0) if j%2 else s.prod(R(2*i+1,48+2*i) for i in range(j//2))
            assert 1+sum(n*x**j for n,x in zip(ns,nodes))==total*moment
        # Moments of z_3 and z_2^2 z_3^j in the 47-dimensional transverse space.
        def moment(j, extra=0):
            if j%2:return R(0)
            r=j//2; numerator=s.prod(2*i-1 for i in range(1,r+1))
            return numerator*(1-t*t)**(r+extra)/s.prod(47+2*i for i in range(r+extra))
        def hp(r,p=0,extra=0):
            return sum(comb(r,j)*t**(r-j)*s.I**j*moment(j+p,extra) for j in range(r+1))
        polys={}
        for l in range(1,5):
            polys['H'+str(l)]=(s.expand(2*(t-hp(l))),s.expand(4*(w-hp(l-1,extra=1))))
            polys['G'+str(l)]=(s.expand(2*(t-hp(l-1)-s.I*hp(l,1))),s.expand(4*(w+(hp(l-1,1)-t*hp(l,1))/s.I)))
        stated={'H1':(0,0),'G1':(2*(t-1+w),4*w*(1-t)), 'G2':(4*t*w,8*w*(1-t*t)), 'H2':(2*(t-t*t+w),4*w*(1-t)), 'G3':(2*(t-t*t+(1+3*t*t)*w-3*w4),4*(w*(1+2*t-3*t**3)+3*t*w4)), 'H3':(2*(t-t**3+3*t*w),4*(w*(1-t*t)+w4)), 'G4':(2*(t-t**3+(3*t+4*t**3)*w-12*t*w4),4*(w*(1+3*t*t-4*t**4)+3*(4*t*t-1)*w4)), 'H4':(2*(t-t**4+6*t*t*w-3*w4),4*(w*(1-t**3)+3*t*w4))}
        for k in stated:
            assert all(s.expand(a-b)==0 for a,b in zip(polys[k],stated[k]))
        labels=['H1','G1','G2','H2','G3','H3','G4','H4']
        rows={k:[n*polys[k][0].subs(t,x) for n,x in zip(ns,nodes)]+[n*polys[k][1].subs(t,x) for n,x in zip(ns[:-1],nodes[:-1])] for k in labels}
        assert all(v.is_Integer for row in rows.values() for v in row)
        assert rows=={'H1': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'G1': [-35672, -2175012, -20493000, -46522560, -28898856, -4413528, -109368, -4, 1176, 84672, 869400, 2022720, 1217160, 169344, 3528], 'G2': [1176, 42336, 173880, 0, -173880, -42336, -1176, 0, 3528, 225792, 2028600, 4045440, 2028600, 225792, 3528], 'H2': [19600, 809676, 4024080, 1011360, -4381776, -1428840, -54096, -4, 1176, 84672, 869400, 2022720, 1217160, 169344, 3528], 'G3': [20428, 827388, 4036500, 949440, -4369356, -1411128, -53268, -4, 3876, 199872, 1386900, 2022720, 699660, 54144, 828], 'H3': [29400, 1058400, 4347000, 0, -4347000, -1058400, -29400, 0, 1800, 115200, 1035000, 2064000, 1035000, 115200, 1800], 'G4': [29880, 1063200, 4335960, 0, -4335960, -1063200, -29880, 0, 3528, 159232, 1071800, 1898880, 1071800, 159232, 3528], 'H4': [33952, 1116684, 4239360, -61920, -4166496, -1121832, -39744, -4, 2112, 124608, 1048800, 2022720, 1037760, 129408, 2592]}
        assert rows['H1']==[0]*15
        assert rows['H2']==[19600,809676,4024080,1011360,-4381776,-1428840,-54096,-4,1176,84672,869400,2022720,1217160,169344,3528]
        mat=s.Matrix([rows[k] for k in labels[1:]])
        assert mat.rank()==7
        assert abs(mat[:,[0,1,2,3,4,8,9]].det())==2**36*3**13*5**6*7**5*13**2*23**2*43*47**2
        h=lambda l:comb(47+l,l)-(comb(45+l,l-2) if l>=2 else 0)
        dims={k:(h(int(k[1:])) if k[0]=='G' else 48*h(int(k[1:]))-h(int(k[1:])+1)-h(int(k[1:])-1)) for k in labels}
        assert [dims[k] for k in labels]==[1128,48,1175,36800,19552,688597,248724,9339840]
        assert sum(dims.values())==10335864
        assert total*47-sum(dims.values())==2453216136
        assert s.expand(polys['G1'][0]-polys['H2'][0]+2*(1-t*t))==0
        assert s.expand(polys['G1'][1]-polys['H2'][1])==0
        assert s.expand(49*polys['H3'][0]-25*polys['G2'][0]-4800*t*(1-t*t)/47)==0
        assert s.expand(49*polys['H3'][1]-25*polys['G2'][1])==0
        u=[2-2*x for x in nodes]
        orders={'G1':(1,102648000),'G2':(2,8386560),'G3':(3,493920),'G4':(4,R(224000,9)),'H4':(9,R(52,2187)),'H3':(10,R(100,19683)),'H2':(11,R(98,98415))}
        for k,(p,c) in orders.items():
            a=rows[k][:8];b=rows[k][8:]+[0]
            for j in range(1,p+1):
                coef=(-1)**j*(sum(a[i]*u[i]**(j-1) for i in range(8))/factorial(j-1)+(sum(b[i]*u[i]**(j-2) for i in range(8))/factorial(j-2) if j>=2 else 0))
                assert coef==(c if j==p else 0),(k,j,coef)
        for k,expected in [('G1',R(3443620096969,25401600)),('G2',R(68808517723,3810240))]:
            assert sum(-2*a/x**3 for a,x in zip(rows[k][:8],u))/216+sum(6*b/x**4 for b,x in zip(rows[k][8:],u[:-1]))/216==expected
        print('ORIGINAL design, highest-weight contractions, spectral pencil, rank, dimensions, identities, long-range orders, inverse-square normalization PASS')
        # Abel certificate from the original manuscript: all 13 rows/differences.
        q,x,z=s.symbols('q x z');ks=[0,1,2,3,4,5,6,9]
        prefix={1:55272*(q**6+1)+2984688*(q**5+q)+24517080*(q**4+q**2)+47533920*q**3,2:56448*(q**5+1)+2088576*(q**4+q)+10434816*(q**3+q**2),3:40572*(q**4+1)+949032*(q**3+q)+2466072*q**2,4:24000*(q**3+1)+312000*(q**2+q)}
        for k in labels[1:]:
            for diff in ([False] if k=='H2' else [False,True]):
                a=[v-(w if diff else 0) for v,w in zip(rows[k],rows['H2'])]
                P=s.Poly(-sum(a[i]*(1-x)**ks[i] for i in range(8)),x);Q=s.Poly(sum(a[8+i]*(1-x)**ks[i] for i in range(7)),x)
                def C(j):return P.nth(j)+3*sum(Q.nth(i)/R(j-i) for i in range(min(6,j-1)+1))
                F=sum(C(j)*x**j for j in range(7)); expected=x**(int(k[1:])-1)*prefix[int(k[1:])].subs(q,1-x) if k[0]=='G' else 0
                assert s.expand(F-expected)==0
                sn=0; mins=[]
                for j in range(7,100):sn+=C(j);mins.append(sn)
                assert min(mins)>=0
                tail=s.Poly(sum(3*Q.nth(i)*s.prod(z+100-r for r in range(7) if r!=i) for i in range(7)),z)
                assert all(c>=0 for c in tail.all_coeffs()) and (F!=0 or max(mins)>0)
        print('ORIGINAL all 13 Abel certificates PASS')


    original_checks()
    raw_scalar=run(False); raw_vector=run(True)
    assert all(r["status"]==0 for r in raw_scalar+raw_vector)
    json.dump({"scalar":raw_scalar,"vector":raw_vector},open(OUT/"results.json","w"),indent=2)
    import sympy as s, mpmath as mp
    from functools import lru_cache
    import json
    mp.mp.dps=100
    R=s.Rational
    T=list(map(R,['1/2','1/3','1/6','0','-1/6','-1/3','-1/2','-1']))
    N=[36848,1678887,12608784,23766960,12608784,1678887,36848,1]; A=[19600,809676,4024080,1011360,-4381776,-1428840,-54096,-4]; B=[1176,84672,869400,2022720,1217160,169344,3528,0]
    @lru_cache(None)
    def P(l,lam,t):
     if l==0:return R(1)
     if l==1:return t
     return ((2*(l+lam-1)*t*P(l-1,lam,t)-(l-1)*P(l-2,lam,t))/(l+2*lam-1))
    @lru_cache(None)
    def col(l,H=False):
     a=[P(l-1,24,t) for t in T]; b=[R((l-1)*(l+47),49)*P(l-2,25,t) if l>=2 else R(0) for t in T]
     if H:return s.Matrix([t*x-(1-t*t)*y/46 for t,x,y in zip(T,a,b)]+[-x-t*y/46 for t,x,y in zip(T[:-1],a,b)])
     return s.Matrix(a+b[:-1])
    def mf(x):return mp.mpf(int(x.p))/int(x.q)
    def matmp(M):return mp.matrix([[mf(x) for x in row] for row in M.tolist()])
    sets=[[(False,l) for l in range(1,16)],[(False,l) for l in range(1,11)]+[(True,l) for l in [1,2,3,4,14]],[(False,l) for l in [1,2,3,4,5,6,7,8,10]]+[(True,l) for l in [1,2,3,4,8,14]]]
    Ys=[]; Inv=[]
    for bs in sets:
     M=s.Matrix.hstack(*(col(l,h) for h,l in bs)); inv=M.inv(); Inv.append(inv); y=inv.T*s.ones(15,1); Ys.append(y); print('dual',list(y))
     for h in ([False] if bs==sets[0] else [False,True]):
      for l in range(1,101):
       slack=1-(y.T*col(l,h))[0]; assert slack>=0 and (l>4 or slack==0),(h,l,slack)
    print('Exact dual feasibility through 100 PASS')
    D=[A[i]-2*N[i]*T[i] for i in range(8)]; E=[4*N[i]*(1-T[i]**2)/47-B[i] for i in range(8)]

    import sympy as s, math, json, csv, mpmath as mp
    import numpy as np
    from scipy.optimize import linprog
    from functools import lru_cache
    mp.mp.dps=100
    # Rational enclosure of q=exp(-alpha/3). Taylor series for exp(+alpha/3).
    def q_bounds(alpha):
     z=alpha/3; term=R(1); total=term
     for k in range(1,201):term*=z/k;total+=term
     nxt=term*z/201; tail=nxt/(1-z/202)
     lo=1/(total+tail); hi=1/total
     den=10**105
     return R(s.floor(lo*den),den),R(s.ceiling(hi*den),den)
    def lin_interval(coefs,lo,hi):
     return (sum(c*(a if c>=0 else b) for c,a,b in zip(coefs,lo,hi)),sum(c*(b if c>=0 else a) for c,a,b in zip(coefs,lo,hi)))
    ks=[0,1,2,3,4,5,6,9]
    rows=[]
    for a in AL:
     alpha=R(str(a)); qlo,qhi=q_bounds(alpha); lo=[qlo**k for k in ks]; hi=[qhi**k for k in ks]; blo=[2*x for x in lo]+[4*alpha*x for x in lo[:-1]]; bhi=[2*x for x in hi]+[4*alpha*x for x in hi[:-1]]
     for typ,idx in [('scalar',0),('vector',1)]:
      y=Ys[idx]; inv=Inv[idx]; bs=sets[idx]; M=s.Matrix.hstack(*(col(l,h) for h,l in bs)); assert M*inv==s.eye(15)
      mins=[]
      for i,(h,l) in enumerate(bs):
       if l>=5:
        v=lin_interval(list(inv.row(i)),blo,bhi); assert v[0]>0,(a,typ,l); mins.append(v[0])
      assert inv.T*s.ones(15,1)==y
      coefs=[D[i]-2*y[i]+alpha*(E[i]-(4*y[8+i] if i<7 else 0)) for i in range(8)]
      low,high=lin_interval(coefs,lo,hi); assert low*high>0
      assert high-low<R(1,10**97)
      mid=(low+high)/2
      rows.append(dict(alpha=a,kind=typ,margin=mp.nstr(mf(mid),40),lower=str(s.N(low,45)),upper=str(s.N(high,45)),interval_width=mp.nstr(mf(high-low),6),mincoeff_lower=mp.nstr(mf(min(mins)),10),sign=int(s.sign(low)),exact_residual=0))
      print('CERT',a,typ,mp.nstr(mf(mid),16),'mincoeff',mp.nstr(mf(min(mins)),5),'width',mp.nstr(mf(high-low),4))
    # Rational tail bound for all l>=202. Interior |t|<=1/2.
    # E[(t+i sqrt(1-t²) Z)^m] with Z density proportional (1-z²)^(lam-1).
    # <= 2 lam! (8/(3m))^lam + exp(-3m/16).
    # use e^-37.5 < 1/10^16 (certified by Taylor lower bound).
    assert sum(R(75,2)**k/math.factorial(k) for k in range(100))>10**16
    m=200
    Ba=2*math.factorial(24)*R(8,3*m)**24+R(1,10**16)
    Bb=m*m*(2*math.factorial(25)*R(8,3*m)**25+R(1,10**16))
    for typ,idx in [('scalar',0),('vector',1)]:
     y=Ys[idx]; ya=sum(abs(y[i]) for i in range(7)); yb=sum(abs(y[i]) for i in range(8,15));
     # H normalized a <= Ba+Bb/46, b <= Ba+Bb/46
     bound=max(ya*Ba+yb*Bb, (ya+yb)*(Ba+Bb/46)) if typ=='vector' else ya*Ba+yb*Bb
     assert bound<(R(1,70000) if typ=='scalar' else R(1,40000000))
     print('TAIL',typ,'interior bound',s.N(bound,15))
     for h in ([False] if typ=='scalar' else [False,True]):
      for l in range(1,202):
       slack=1-(y.T*col(l,h))[0];assert slack>=0 and (l>4 or slack==0)
     print('EXACT',typ,'dual all degrees PASS')
    # small alpha exact leading Taylor coefficient
    for typ,idx in [('scalar',0),('vector',1)]:
     y=Ys[idx]; dd=[D[i]-2*y[i] for i in range(8)]; ee=[E[i]-(4*y[8+i] if i<7 else 0) for i in range(8)]
     coeff=[]
     for j in range(14):
      val=sum(dd[i]*(-R(ks[i],3))**j/math.factorial(j) for i in range(8))
      if j:val+=sum(ee[i]*(-R(ks[i],3))**(j-1)/math.factorial(j-1) for i in range(8))
      if val: coeff.append((j,val))
     assert coeff[:2]==[(10,-R(98,98415)),(11,R(98,98415) if typ=='scalar' else R(754,688905))]
     assert (dd[0],ee[0])==((R(1234016,5),-17640) if typ=='scalar' else (-11600,488))
     print('ASYMPTOTIC',typ,coeff[:3],'large',dd[0],ee[0])
    # Verify that the selected primal bases remain feasible near both endpoints.
    for typ,idx in [('scalar',0),('vector',1)]:
     for i,(h,l) in enumerate(sets[idx]):
      if l<5:continue
      a=Inv[idx].row(i)
      for j in range(20):
       val=sum(2*a[k]*(-R(ks[k],3))**j/math.factorial(j) for k in range(8))
       if j:val+=sum(4*a[8+k]*(-R(ks[k],3))**(j-1)/math.factorial(j-1) for k in range(7))
       if val:break
      assert val>0 and a[8]>0
     print('ENDPOINT PRIMAL FEASIBILITY',typ,'PASS')
    # Exact polynomial identity checks for both kernels, through degree 40.
    t=s.symbols('t')
    for l in range(1,41):
     p=s.Poly(s.gegenbauer(l,23,t)/s.binomial(l+45,l),t,domain=s.QQ)
     p=p.as_expr(); a=46*t*s.diff(p,t)-(1-t*t)*s.diff(p,t,2); b=-46*s.diff(p,t)-t*s.diff(p,t,2); c=s.diff(p,t,2); lam=l*(l+46)
     assert s.Poly(a+t*b+c,t).is_zero
     assert s.Poly((1-t*t)*s.diff(a,t,2)-47*t*s.diff(a,t)+lam*a+2*c,t).is_zero
     assert s.Poly((1-t*t)*s.diff(b,t,2)-49*t*s.diff(b,t)+(lam-47)*b+2*s.diff(c,t),t).is_zero
     assert s.Poly((1-t*t)*s.diff(c,t,2)-51*t*s.diff(c,t)+(lam-96)*c,t).is_zero
     assert a.subs(t,1)==46*R(l*(l+46),47)
    print('EXACT CURL POLYNOMIAL IDENTITIES degrees 1..40 PASS')
    # Uniform certificate for alpha >= 25, using q < 1/4000.
    qlo,qhi=q_bounds(R(25)); assert qhi<R(1,4000)
    qmax=R(1,4000); alpha0=R(25)
    for i,(h,l) in enumerate(sets[1]):
     if l<5:continue
     v=Inv[1].row(i)
     lower=4*v[8]+min(0,2*v[0]/alpha0)-sum((2*abs(v[k])/alpha0+(4*abs(v[8+k]) if k<7 else 0))*qmax**ks[k] for k in range(1,8))
     assert lower>0
     print('SHORT RANGE coefficient/alpha lower',('H' if h else 'G')+str(l),s.N(lower,12))
    y=Ys[1]; dd=[D[i]-2*y[i] for i in range(8)]; ee=[E[i]-(4*y[8+i] if i<7 else 0) for i in range(8)]
    lower=ee[0]+dd[0]/alpha0-sum((abs(dd[k])/alpha0+abs(ee[k]))*qmax**ks[k] for k in range(1,8))
    assert lower>10
    print('UNIFORM SHORT RANGE alpha>=25: margin > 10*alpha PASS; lower/alpha =',s.N(lower,15))
    # PSD tests on random tangent fields, full Gram via tangent bases in 48D.
    rng=np.random.default_rng(123); X=rng.normal(size=(7,48)); X/=np.linalg.norm(X,axis=1)[:,None]; Q=[np.linalg.qr(x.reshape(-1,1),mode='complete')[0][:,1:] for x in X]
    min_eig={'G':1.,'H':1.}
    for l in range(1,41):
     for h in [False,True]:
      t=X@X.T; d=l*(l+46)/47; a=deriv(l,1,t)/d; b=deriv(l,2,t)/d
      if h:a,b=t*a-(1-t*t)*b/46,-a-t*b/46
      K=np.block([[a[i,j]*(Q[i].T@Q[j])+b[i,j]*np.outer(Q[i].T@X[j],Q[j].T@X[i]) for j in range(len(X))] for i in range(len(X))]); assert np.max(abs(K-K.T))<1e-11; assert np.max(abs(np.trace(K.reshape(7,47,7,47),axis1=1,axis2=3).diagonal()-47))<1e-10
      eig=np.linalg.eigvalsh(K)[0]; min_eig['H' if h else 'G']=min(min_eig['H' if h else 'G'],eig);assert eig>-1e-10
    print('PSD sampled min eigenvalues',min_eig)
    # Export every grid point including raw solver residuals vs exact reconstructed optimum.
    raw=json.load(open(OUT/'results.json')); certified={(r['alpha'],r['kind']):r for r in rows}
    with open(OUT/'grid.csv','w',newline='') as f:
     fields=['kind','alpha','L','raw_status','raw_margin','raw_primal_residual','raw_dual_residual','certified_margin','certified_margin_interval_width','certified_primal_residual','certified_sign']; w=csv.DictWriter(f,fieldnames=fields);w.writeheader()
     for typ,rr in raw.items():
      for r in rr:
       z=certified[r['alpha'],typ];w.writerow(dict(kind=typ,alpha=r['alpha'],L=r['L'],raw_status=r['status'],raw_margin=r.get('margin'),raw_primal_residual=r.get('res'),raw_dual_residual=r.get('dual_res'),certified_margin=z['margin'],certified_margin_interval_width=z['interval_width'],certified_primal_residual=0,certified_sign=z['sign']))
    json.dump(rows,open(OUT/'rigorous_results.json','w'),indent=2)
    print('ALL CHECKS PASSED')

if __name__ == "__main__":
    main()
