#!/usr/bin/env python3
"""Arithmetic Capacity and Equivariant Spectral--Slope Geometry (V6.1).

One self-contained verification script: exact LP certificates for d=2, 4, 6,
CM curve invariants and point count, height-two formal inverse through degree
73, exact Velu identities, CM coefficients in TWO coordinate systems, finite
(A.2)/(A.3) tests, the [-5] Frobenius test, a degree-49 IP(G) residual test,
and the rank-two B2 glued-lattice isotropy model.

All coefficient computations use exact fractions; no third-party packages.
Finite-degree checks are NOT all-orders proofs and do not establish any
global theta, mass, density, or RH-transfer contract.

Run: python3 arithmetic_capacity.py
"""
from fractions import Fraction as F
from math import comb, factorial
import time

A, B, P = -35, -98, 5


def vp(x, p=P):
    x = F(x)
    if not x: return float('inf')
    a, b = abs(x.numerator), x.denominator
    k = 0
    while a % p == 0: a //= p; k += 1
    while b % p == 0: b //= p; k -= 1
    return k


class K:
    """Q(sqrt(-7)): a+b*S, S^2=-7; CM coefficients in the (1,S) basis."""
    __slots__ = ('a','b')
    def __init__(self, a=0, b=0):
        if isinstance(a, K): self.a,self.b=a.a,a.b
        else: self.a,self.b=F(a),F(b)
    def __add__(self, other):
        other = K(other); return K(self.a+other.a,self.b+other.b)
    __radd__ = __add__
    def __neg__(self): return K(-self.a,-self.b)
    def __sub__(self, other): return self + (-K(other))
    def __rsub__(self, other): return K(other)-self
    def __mul__(self,other):
        other=K(other)
        return K(self.a*other.a-7*self.b*other.b,self.a*other.b+self.b*other.a)
    __rmul__ = __mul__
    def __truediv__(self,other):
        other=K(other); n=other.a**2+7*other.b**2
        return K((self.a*other.a+7*self.b*other.b)/n,(self.b*other.a-self.a*other.b)/n)
    def __pow__(self,n):
        assert n>=0
        z=K(1); x=self
        while n:
            if n&1: z*=x
            x*=x; n//=2
        return z
    def __eq__(self,o):
        o=K(o); return self.a==o.a and self.b==o.b
    def __bool__(self): return bool(self.a or self.b)
    def __repr__(self): return f'({self.a})+({self.b})*sqrt(-7)'


def umul(f,g,N):
    out=[F(0)]*(N+1)
    for i,a in enumerate(f[:N+1]):
        if a:
            for j,b in enumerate(g[:N+1-i]):
                if b: out[i+j]+=a*b
    return out


def upow(f,k,N):
    ans=[F(1)]+[F(0)]*N
    while k:
        if k&1: ans=umul(ans,f,N)
        f=umul(f,f,N); k//=2
    return ans


def ucompose(f,g,N):
    out=[F(0)]*(N+1)
    for c in reversed(f[:N+1]):
        out=umul(out,g,N)
        out[0]+=c
    return out


def uinv(f,N):
    assert f[0]!=0
    out=[F(1,1)/f[0]]
    for n in range(1,N+1):
        out.append(-sum((f[i]*out[n-i] for i in range(1,min(n,len(f)-1)+1)),F(0))/f[0])
    return out


def univariate_data(N):
    """wp(z)=z^-2 + sum c[n] z^(2n), t=-2wp/wp' and z(t)=t(z)^-1."""
    c={1:F(-A,5),2:F(-B,7)}
    for n in range(3,(N-3)//2+2):
        denom=2*n*(2*n-1)-12
        c[n]=6*sum((c[i]*c[n-1-i] for i in range(1,n-1)),F(0))/denom
    top=[F(0)]*(N+1); bot=[F(0)]*(N+1)
    top[0]=bot[0]=F(1)
    for n,x in c.items():
        if 2*n+2<=N:
            top[2*n+2]+=x
            bot[2*n+2]-=n*x
    ratio=umul(top,uinv(bot,N),N)
    tz=[F(0)]+ratio[:N]  # multiply by z
    zt=[F(0)]*(N+1); zt[1]=F(1)
    for k in range(2,N+1):
        zt[k]=-ucompose(tz,zt,k)[k]
    assert ucompose(tz,zt,N)==[F(0),F(1)]+[F(0)]*(N-1)
    return c,tz,zt


def padd(f,g):
    out=dict(f)
    for mon,x in g.items():
        out[mon]=out.get(mon,0)+x
        if not out[mon]: del out[mon]
    return out


def pscale(f,s):
    return {mon:x*s for mon,x in f.items() if x*s}


def pmul(f,g,N):
    out={}
    for m,a in f.items():
        for n,b in g.items():
            mon=tuple(i+j for i,j in zip(m,n))
            if sum(mon)>N: continue
            out[mon]=out.get(mon,0)+a*b
    return {mon:x for mon,x in out.items() if x}


def pexp(f,N,nvars=None,one=None):
    """Truncated exp of a zero-constant multivariate series.

    Specify nvars (and one for non-rational coefficients) for the empty
    series: exp(0) is the multiplicative identity in the intended arity.
    """
    if not f:
        if nvars is None:
            raise ValueError('nvars is required to exponentiate an empty series')
        return {(0,)*nvars: F(1) if one is None else one}
    assert all(any(m) for m in f)
    zero=(0,)*len(next(iter(f)))
    if nvars is not None:
        assert len(zero)==nvars
    out={zero: (K(1) if isinstance(next(iter(f.values())),K) else F(1)) if one is None else one}
    power=dict(out)
    for k in range(1,N+1):
        power=pmul(power,f,N)
        if not power: break
        out=padd(out,pscale(power,F(1,factorial(k))))
    return out


def plog1p(f,N):
    zero=(0,)*len(next(iter(f)))
    out={}; power={zero:F(1)}
    for k in range(1,N+1):
        power=pmul(power,f,N)
        if not power: break
        out=padd(out,pscale(power,F((-1)**(k+1),k)))
    return out


def hlog(c,tz,N,alpha=F(1)):
    """H(z,w)=log B(t(z),t(w)), no spurious poles, sigma via wp."""
    # Divided difference needs t(z) through z^(N+1), not just z^N.
    assert len(tz)>N+1, 'hlog requires t(z) coefficients through degree N+1'
    if N>=4:
        assert max((2*n+2 for n in c),default=0)>=N-(N%2), \
            'hlog requires wp coefficients through the last even degree <= N' 
    # t(z)/z and the divided difference (t(z)-t(w))/(z-w).
    az={(i-1,0):t for i,t in enumerate(tz) if t and i>1 and i-1<=N}
    aw={(0,i-1):t for i,t in enumerate(tz) if t and i>1 and i-1<=N}
    dd={}
    for i,t in enumerate(tz):
        if t and i>1:
            for k in range(i):
                mon=(i-1-k,k)
                if sum(mon)<=N: dd[mon]=dd.get(mon,F(0))+t
    # s(z)=log(sigma_E(z)/z); s''=-(wp(z)-z^-2).
    sigma_terms={}
    for n,cn in c.items():
        d=2*n+2
        if d<=N: sigma_terms[d]=-cn/F(d*(d-1))
    sdiff={}
    for deg,val in sigma_terms.items():
        for j in range(1,deg):
            mon=(deg-j,j)
            sdiff[mon]=sdiff.get(mon,F(0))+val*comb(deg,j)*(-1)**j
    return padd(padd(padd({(1,1):alpha},plog1p(az,N)),plog1p(aw,N)),padd(pscale(plog1p(dd,N),-1),sdiff))


def substitute_sep(h,z,weight,N):
    """Evaluate h(z(t),z(u)) times per-(a,b) weight, in 2 variables."""
    powers=[upow(z,n,N) for n in range(N+1)]
    out={}
    for (a,b),coeff in h.items():
        if a+b>N: continue
        wt=coeff*weight(a,b)
        if not wt: continue
        for i,ci in enumerate(powers[a]):
            if ci:
                for j,cj in enumerate(powers[b][:N+1-i]):
                    if cj:
                        mon=(i,j)
                        out[mon]=out.get(mon,0)+wt*ci*cj
    return {mon:x for mon,x in out.items() if x}


def a2_check(h,zt,N):
    """log B(t1+t2 in formal law,u) minus separate, in t coordinates."""
    zpow=[upow(zt,k,N) for k in range(N+1)]
    out={}
    for (a,b),coeff in h.items():
        if a+b>N or a<2 or b<1: continue
        for j in range(1,a):
            scalar=coeff*comb(a,j)
            for k,x in enumerate(zpow[j]):
                if not x:continue
                for l,y in enumerate(zpow[a-j][:N+1-k]):
                    if not y:continue
                    for m,v in enumerate(zpow[b][:N+1-k-l]):
                        if v:
                            mon=(k,l,m)
                            out[mon]=out.get(mon,F(0))+scalar*x*y*v
    ratio=pexp({m:v for m,v in out.items() if v},N,nvars=3)
    return ratio


def denominators(poly,qu=False):
    if qu:
        return [(mon,val) for mon,val in poly.items() if min(vp(val.a),vp(val.b))<0]
    return [(mon,val) for mon,val in poly.items() if val.denominator!=1]


def check_curve():
    """Exact CM curve invariants, inertness, and point count mod 5."""
    print('[Curve and supersingularity]')
    D=-16*(4*A**3+27*B**2)
    j=F(1728*4*A**3,4*A**3+27*B**2)
    assert D == -(2**12)*(7**3) and j == -3375
    assert pow((-7)%P,(P-1)//2,P) == P-1
    n=1+sum((y*y-x**3-A*x-B)%P==0 for x in range(P) for y in range(P))
    assert n == P+1
    print(f'  discriminant={D}, j={j}, #E(F_5)={n}, a_5={P+1-n}')


def lp_d2(nu0,nu1,p=P):
    return min(F(nu0),F(nu1),F(nu0+nu1,p+1))


def gain_d2(nu0,nu1,p=P):
    return F(p*(nu0+nu1),p*p-1)-lp_d2(nu0,nu1,p)


def check_lp_pair(p,d,nu,delta,dual):
    """Verify both sides of an exact primal-dual optimum certificate."""
    odd_h=tuple(range(1,d,2))
    assert len(nu)==len(delta)==d and all(x>=0 for x in delta)
    assert all(dual[(s,h)]>=0 for s in range(d) for h in odd_h)
    for s in range(d):
        for h in odd_h:
            assert p**h*delta[s]+delta[(s+h)%d]>=1
    for t in range(d):
        assert sum(p**h*dual[(t,h)]+dual[((t-h)%d,h)] for h in odd_h)<=nu[t]
    primal=sum(F(nu[s])*delta[s] for s in range(d))
    dual_objective=sum(dual.values())
    assert primal==dual_objective
    return primal


def check_lp():
    print('\n[Frobenius-orbit LP certificates]')
    for m in (2,10,50,100):
        single=gain_d2(m,0)
        balanced=gain_d2(m//2,m//2)
        assert single == P*balanced
        print(f'  d=2, |nu|={m}: single={single}, balanced={balanced}, ratio={single/balanced}')
    dual_zero={(s,h):F(0) for s in range(4) for h in (1,3)}
    one=check_lp_pair(P,4,(80,0,20,0),[F(0),F(1),F(0),F(1)],dual_zero)
    dual_bal={(s,h):(F(25,6) if h==1 else F(0)) for s in range(4) for h in (1,3)}
    bal=check_lp_pair(P,4,(25,25,25,25),[F(1,6)]*4,dual_bal)
    dual_asym=dict(dual_zero)
    dual_asym.update({(0,1):F(5), (2,1):F(2), (3,1):F(20,39), (0,3):F(17,39)})
    asym=check_lp_pair(P,4,(80,5,10,5),[F(1,156),F(151,156),F(25,156),F(31,156)],dual_asym)
    assert (one,bal,asym)==(F(0),F(50,3),F(310,39))
    print(f'  d=4 exact primal=dual optima: single={one}, balanced={bal}, asymmetric={asym}')
    # d=6: balanced and asymmetric exact rational primal/dual certificates.
    d=6; zero={(s,h):F(0) for s in range(d) for h in (1,3,5)}
    dual_bal6={(s,h):(F(25,6) if h==1 else F(0))
               for s in range(d) for h in (1,3,5)}
    bal6=check_lp_pair(P,d,(25,)*d,[F(1,6)]*d,dual_bal6)
    dual_asym6=dict(zero)
    dual_asym6.update({(0,1):F(5), (2,1):F(2),
                      (0,3):F(1733,1736), (3,1):F(695,1736),
                      (4,1):F(6805,1736), (5,1):F(375,1736)})
    asym6=check_lp_pair(P,d,(150,5,10,5,20,5),
                        [F(x,1953) for x in (13,1888,325,328,313,388)],
                        dual_asym6)
    assert (bal6,asym6)==(F(25),F(2720,217))
    print(f'  d=6 exact primal=dual optima: balanced={bal6}, asymmetric={asym6}')


def sparse_mul(A,B,N):
    out={}
    for i,a in A.items():
        for j,b in B.items():
            if i+j<=N: out[i+j]=out.get(i+j,F(0))+a*b
    return {i:a for i,a in out.items() if a}


def sparse_add(A,B,scale=1):
    out=dict(A)
    for k,v in B.items(): out[k]=out.get(k,F(0))+scale*v
    return {k:v for k,v in out.items() if v}


def sparse_comp(A,G,N):
    out={}; power={0:F(1)}
    for k in range(N+1):
        if k in A:
            out=sparse_add(out,{i:A[k]*v for i,v in power.items()})
        if k<N: power=sparse_mul(power,G,N)
    return out


def check_formal_inverse():
    print('\n[Height-two formal inverse]')
    # L(X)=X+X^25/5 (mod X^76), as the next logarithm term has degree 625.
    L={1:F(1),25:F(1,5)}
    g={1:F(1)}
    for _ in range(5):
        g=sparse_add(g,sparse_add(sparse_comp(L,g,75),{1:F(1)},-1),-1)
    assert g == {1:F(1),25:-F(1,5),49:F(1),73:-F(37,5)}
    jets={n:factorial(n)*g[n] for n in (25,49,73)}
    assert all(j.denominator==1 for j in jets.values())
    assert tuple(vp(j) for j in jets.values())==(5,10,15)
    print('  g(X) = X - X^25/5 + X^49 - 37*X^73/5 + O(X^76)')
    print('  vp(g^(25)(0)),vp(g^(49)(0)),vp(g^(73)(0)) = (5, 10, 15)')
    return jets


def check_glued_lattice(jets):
    """B2 orbit Gram isotropy and exact p-index/slope-exponent averages."""
    print('\n[B2 glued lattice: finite-dimensional model]')
    matrices=[((s,0),(0,t)) for s in (1,-1) for t in (1,-1)]
    matrices += [((0,s),(t,0)) for s in (1,-1) for t in (1,-1)]
    assert len(matrices)==8
    for J in jets:
        # Orbit of J*e1: Q=sum_g (g J e1)(g J e1)^T = 4 J^2 I_2.
        V=[(J*m[0][0],J*m[1][0]) for m in matrices]
        Q00=sum(x*x for x,y in V)
        Q01=sum(x*y for x,y in V)
        Q11=sum(y*y for x,y in V)
        assert (Q00,Q01,Q11)==(4*J*J,0,4*J*J)
        for b in (1,2,4):
            a=vp(J)
            assert vp(J*P**b)==a+b
            # Exact average of degree exponents; multiply by log(p) for degree.
            assert F((a+b)+a,2)-a==F(b,2)
    print('  Orbit Gram Q = 4 J^2 I_2 (all checked nonzero jet values)')
    print('  Mean saturated image degree = (b/2)*log(5), for b=1,2,4')
    print('  These abstract lattice checks do not construct a global theta frame.')


def ip_residual(zt,N):
    """Coefficients of G - (1/5) G^(sigma^2)(s^25), lambda^24=-1.

    For lambda^24=-1, sigma^2(lambda)=-lambda; the index m
    contributes at degree 25*m and must not be truncated at m=1.
    Coefficients are stored by (degree, reduced lambda exponent).
    """
    assert len(zt)>N
    residual={}
    for n,zcoeff in enumerate(zt[:N+1]):
        if not zcoeff: continue
        exponent=n-1
        key=(n,exponent%24)
        residual[key]=residual.get(key,F(0))+(-1)**(exponent//24)*zcoeff
    for m in range(1,N//25+1):
        if not zt[m]: continue
        exponent=m-1
        key=(25*m,exponent%24)
        sub=F(1,5)*(-1)**(exponent//24)*(-1)**exponent*zt[m]
        residual[key]=residual.get(key,F(0))-sub
    return {key:coeff for key,coeff in residual.items() if coeff}


def check_cm_biextension():
    """Coordinate-correct CM series and truncated integrality checks."""
    print("\n[CM biextension, exact rational arithmetic]")
    c=(K(F(1,2),F(1,2))); cb=K(F(1,2),F(-1,2))
    root=K(F(-7,2),F(1,2))
    # Exact degree-two Velu map, and pullback of x*omega.
    # Write r for the kernel point, gx=3r^2+A, omega=dx/(2y).
    gx=3*root**2+A
    assert root**2+7*root+14==0
    assert root**3+A*root+B==0                 # (r,0) lies on E
    assert A-5*gx==c**4*A and B-7*root*gx==c**6*B
    assert c*cb==2 and c*(c-cb)==root
    # (d/dx)(y/(x-r)) / (omega/dx) = x-r-gx/(x-r).
    # Multiply through by (x-r)^2 and compare cubic polynomials.
    left=(-A*root-2*B, -A, -3*root, K(1))
    right=(-root**3+gx*root, 3*root**2-gx, -3*root, K(1))
    assert left==right
    # Also check the rational coefficient identity in the pullback:
    # [c]^*(x omega) - (cbar*x-r/c)*omega = -(1/c)*d(y/(x-r)).
    assert K(1)-c*cb == -K(1)  # coefficient of x*(x-r)
    alpha=root/(c*(c-cb))
    assert alpha==1
    print('  Velu quotient and cubic differential identities: PASS')
    print('CM eigenvector splitting alpha =',alpha)
    C,tz,zt=univariate_data(49)
    assert zt[5]==-14 and zt[7]==-42
    h=hlog(C,tz,16)
    print('logarithm-coordinate coefficient [z^5 w] log B =',h[(5,1)])
    ht=substitute_sep(h,zt,lambda a,b:F(1),6)
    print('Weierstrass-coordinate coefficient [t^5 u] log B =',ht[(5,1)])
    assert h[(5,1)]==F(-196,5) and ht[(5,1)]==F(-266,5)
    print('mixed partials:',factorial(5)*h[(5,1)],factorial(5)*ht[(5,1)])
    # (A2) via exp of the additivity defect; integral over Z at this curve.
    ratio2=a2_check(h,zt,7)
    bad2=denominators(ratio2)
    print('A.2 through total degree 7:',len(ratio2),'nonzero coefficients;',len(bad2),'non-Z coefficients')
    if bad2: print('A2 FIRST failures',bad2[:10])
    assert not bad2
    # (A3) check the CM generator, conjugate, and two extra integral CM maps.
    for tag, endo, adjoint in [('c',c,cb), ('cbar',cb,c),
                               ('2',K(2),K(2)), ('1+c',1+c,1+cb)]:
        a3log=substitute_sep(h,zt,lambda a,b: endo**a-adjoint**b,16)
        ratio3=pexp(a3log,16,nvars=2,one=K(1))
        bad3=denominators(ratio3,qu=True)
        bad_ok=[(mon,v) for mon,v in ratio3.items()
                if (v.a-v.b).denominator!=1 or (2*v.b).denominator!=1]
        print(f'A.3 for {tag} through degree 16: {len(ratio3)} terms; {len(bad_ok)} outside O_K; {len(bad3)} non-5-integral')
        if bad_ok: print('A3 FIRST failures',bad_ok[:10])
        assert not bad3 and not bad_ok
    # Formal endomorphism [-5]t=t(-5*z(t)).
    neg5z=[-5*t for t in zt]
    mult=ucompose(tz,neg5z,25)
    lowbad=[(i,v) for i,v in enumerate(mult[:25]) if vp(v)<1]
    print('[-5](t) mod 5, degrees <25:',lowbad)
    print('[-5] degree 25 coefficient mod 5:',
          (mult[25].numerator*pow(mult[25].denominator,-1,5))%5 if vp(mult[25])>=0 else 'not integral')
    assert not lowbad and vp(mult[25])==0
    assert (mult[25].numerator*pow(mult[25].denominator,-1,5))%5==1
    # Since [-5] mod 5 is Frobenius^2, choose lambda^24=-1 and
    # sigma^2(lambda)=-lambda. G(s)=lambda^-1*z(lambda*s), and all
    # nonzero z coefficients have odd degree, so sigma^2(G)=G.
    # In Q_5(lambda) use lambda^24=-1 to reduce each coefficient.
    residual=ip_residual(zt,49)
    bad_ip=[(n,j,coeff) for (n,j),coeff in residual.items() if vp(coeff)<0]
    # Synthetic regression: a nonzero z(t) coefficient at index 5 must
    # also contribute at degree 125, not just the m=1 degree-25 term.
    synthetic=[F(0)]*126
    synthetic[1]=F(1); synthetic[5]=F(-14)
    assert ip_residual(synthetic,125)[(125,4)]==F(14,5)
    print('IP(G) through degree 49: ',len(bad_ip),'non-5-integral residual coefficients')
    print('IP(G) degree-25 residual coefficient:',residual[(25,0)])
    assert not bad_ip and residual[(25,0)]==60680624743
    assert factorial(5)*h[(5,1)] == -4704
    assert factorial(5)*ht[(5,1)] == -6384
    assert vp(h[(5,1)]) == vp(ht[(5,1)]) == -1
    assert vp(factorial(5)*h[(5,1)]) == 0
    assert vp(factorial(5)*ht[(5,1)]) == 0
    print('Exceptional coefficient valuations: v5 = -1 in both systems; mixed derivatives are 5-integral')
    return factorial(5)*h[(5,1)], factorial(5)*ht[(5,1)]



def main():
    started=time.perf_counter()
    check_curve()
    check_lp()
    jets=check_formal_inverse()
    zjet,tjet=check_cm_biextension()
    check_glued_lattice([jets[25], jets[49], jets[73],zjet,tjet])
    print(f"\nPASS: all stated exact identities and finite-order checks ({time.perf_counter()-started:.3f} sec).")
    print("BOUNDARY: finite truncations do not imply all-orders or global realizations.")


if __name__ == '__main__':
    main()
