#!/usr/bin/env python3
"""Reproducible independent *tests*, not a formal proof of Bost's conjecture.

Python 3 standard library only; exact Fraction arithmetic in suites 1-4,
complex floating-point in suite 5. Deterministic random seed.

Tests source algebraic identities in the candidate rank-2 tensor-product proof.
Does NOT establish its arithmetic Harder--Narasimhan induction, functorial
integral constructions, or novelty. Does NOT run Lean.
"""
from fractions import Fraction as Q
from itertools import permutations
from math import factorial, exp
import random

rng = random.Random(20261123)

def mat_det(A):
    """Exact determinant for Fraction matrices; complex float also works."""
    n = len(A)
    if n == 0:
        return 1
    M = [list(row) for row in A]
    out = 1
    for j in range(n):
        i = next((k for k in range(j, n) if abs(M[k][j]) > 1e-13), None)
        if i is None:
            return 0
        if i != j:
            M[j], M[i] = M[i], M[j]
            out = -out
        a = M[j][j]
        out *= a
        for k in range(j+1, n):
            t = M[k][j] / a
            for l in range(j+1, n):
                M[k][l] -= t * M[j][l]
            M[k][j] = 0
    return out

def mm(A, B):
    if not A:
        return []
    return [[sum((A[i][k] * B[k][j] for k in range(len(B))), Q(0))
             for j in range(len(B[0]))] for i in range(len(A))]

def poly_mul(p, q):
    """Homogeneous binary forms: index is the power of Y."""
    r = [Q(0)] * (len(p) + len(q) - 1)
    for i, x in enumerate(p):
        for j, y in enumerate(q):
            r[i+j] += x*y
    return r

def poly_pow(p, e):
    r = [Q(1)]
    for _ in range(e):
        r = poly_mul(r, p)
    return r

def sym_matrix(g, degree):
    a, b, c, d = g[0][0], g[0][1], g[1][0], g[1][1]
    return [[poly_mul(poly_pow([a,c], degree-j),poly_pow([b,d],j))[i]
             for j in range(degree+1)] for i in range(degree+1)]

def random_gl2():
    while True:
        g = [[Q(rng.randint(-3,3)) for _ in range(2)] for _ in range(2)]
        if mat_det(g):
            return g

def test_sym_and_equivariance():
    count=0; negative=0
    for m in range(2,7):
        for _ in range(25):
            g=random_gl2(); detg=mat_det(g)
            if detg < 0: negative+=1
            S=sym_matrix(g,m-1)
            assert mat_det(S)==detg**(m*(m-1)//2)
            a,b,c,d=g[0][0],g[0][1],g[1][0],g[1][1]
            h=[[d/detg, -c/detg],[-b/detg, a/detg]]
            Sd=sym_matrix(g,m-2)
            for j in range(m-1):
                # iota(w_j)=(X w_j,Y w_j): binary forms degree m-1
                PX=[S[i][j] for i in range(m)]
                PY=[S[i][j+1] for i in range(m)]
                lhs0=[h[0][0]*PX[i]+h[0][1]*PY[i] for i in range(m)]
                lhs1=[h[1][0]*PX[i]+h[1][1]*PY[i] for i in range(m)]
                rhs0=[Q(0)]*m; rhs1=[Q(0)]*m
                for i in range(m-1):
                    rhs0[i]+=Sd[i][j]
                    rhs1[i+1]+=Sd[i][j]
                assert lhs0==rhs0 and lhs1==rhs1
            count+=1
    assert negative>0
    return count

def disc_roots(a0, roots):
    r=a0**(2*len(roots)-2)
    for i in range(len(roots)):
        for j in range(i+1,len(roots)):
            r*= (roots[i]-roots[j])**2
    return r

def test_disc_covariance():
    count=0
    for m in range(2,6):
        for _ in range(35):
            roots=[Q(i+1, m+1) for i in range(m)]
            rng.shuffle(roots)
            a0=Q(rng.randint(1,9),rng.randint(1,9))
            while True:
                g=random_gl2()
                a,b,c,d=g[0][0],g[0][1],g[1][0],g[1][1]
                if all(a-b*z != 0 for z in roots): break
            roots2=[(d*z-c)/(a-b*z) for z in roots]
            a02=a0
            for z in roots: a02*=a-b*z
            assert disc_roots(a02, roots2)==mat_det(g)**(m*(m-1))*disc_roots(a0,roots)
            count+=1
    return count

def poly_det(M):
    """Determinant of matrix with homogeneous linear-form entries [a,b]."""
    n=len(M)
    result=[Q(0)]*(n+1)
    for perm in permutations(range(n)):
        inversions=sum(perm[i]>perm[j] for i in range(n) for j in range(i+1,n))
        sign=-1 if inversions%2 else 1
        term=[Q(1)]
        for i in range(n): term=poly_mul(term,M[i][perm[i]])
        for j in range(n+1): result[j]+=sign*term[j]
    return result

def phi_of_pencil(X,Y):
    m=len(X); r=m-1
    phi=[[Q(0)]*m for _ in range(m)]
    for row_deleted in range(m):
        M=[[[X[i][j],Y[i][j]] for j in range(r)]
           for i in range(m) if i != row_deleted]
        p=poly_det(M)
        for k in range(m):
            phi[row_deleted][k]=(-1 if row_deleted%2 else 1)*p[m-1-k]
    return phi

def test_minor_covariance():
    count=0
    for m in range(2,6):
        r=m-1
        X0=[[Q(int(i==j)) for j in range(r)] for i in range(m)]
        Y0=[[Q(int(i==j+1)) for j in range(r)] for i in range(m)]
        assert abs(mat_det(phi_of_pencil(X0,Y0)))==1
        for _ in range(15):
            # Invertible triangular matrices with varying non-unit determinants:
            # this tests the actual covariance *exponents*, not only det=1.
            dp=[rng.choice([-3,-2,-1,1,2,3]) for _ in range(m)]
            dr=[rng.choice([-3,-2,-1,1,2,3]) for _ in range(r)]
            P=[[Q(dp[i] if i==j else (rng.randint(-2,2) if i<j else 0))
                for j in range(m)] for i in range(m)]
            R=[[Q(dr[i] if i==j else (rng.randint(-2,2) if i<j else 0))
                for j in range(r)] for i in range(r)]
            X=mm(mm(P,X0),R)
            Y=mm(mm(P,Y0),R)
            assert mat_det(phi_of_pencil(X,Y)) == mat_det(phi_of_pencil(X0,Y0))*mat_det(P)**r*mat_det(R)**m
            count+=1
    return count

def test_summation_by_parts():
    count=0
    for _ in range(2000):
        length=rng.randint(1,12)
        n=[Q(rng.randint(1,10)) for _ in range(length)]
        s=n[:]
        for k in range(length-1):
            moved=Q(rng.randint(0, int(s[k])))
            s[k]-=moved; s[k+1]+=moved
        beta=[Q(rng.randint(-10,10))]
        for k in range(length-1):
            beta.append(beta[-1]-Q(rng.randint(0,5)))
        assert sum(s)==sum(n)
        assert all(sum(s[:k])<=sum(n[:k]) for k in range(1,length))
        assert sum(s[k]*beta[k] for k in range(length))<=sum(n[k]*beta[k] for k in range(length))
        d=[Q(rng.randint(1,6)) for _ in range(length)]
        nu=[Q(rng.randint(0,8))]
        for k in range(length-1):nu.append(nu[-1]-Q(rng.randint(0,3)))
        mu=Q(rng.randint(-9,9),rng.randint(1,4))
        U=[sum(d[:k+1])*mu-Q(rng.randint(0,6)) for k in range(length-1)]
        U.append(sum(d)*mu)
        lhs=nu[-1]*U[-1]+sum((nu[k]-nu[k+1])*U[k] for k in range(length-1))
        rhs=sum(d[k]*nu[k] for k in range(length))*mu
        assert lhs<=rhs
        count+=1
    return count

def complex_det(A):
    return mat_det(A)

def test_cholesky_cb():
    count=0
    for m in range(2,9):
        for _ in range(120):
            dia=[exp(rng.uniform(-0.35,0.35)) for i in range(m)]
            scale=exp(-sum(__import__('math').log(t) for t in dia)/m)
            dia=[t*scale for t in dia]
            U=[[complex(dia[i]) if i==j else
                (complex(rng.uniform(-0.1,0.1),rng.uniform(-0.1,0.1)) if i<j else 0j)
                for j in range(m)] for i in range(m)]
            G=[[sum(U[k][i].conjugate()*U[k][j] for k in range(m)) for j in range(m)]
                for i in range(m)]
            H=[[G[i][j]+G[i+1][j+1] for j in range(m-1)] for i in range(m-1)]
            dh=complex_det(H)
            target=sum(1/t**2 for t in dia)
            assert abs(complex_det(G).real-1)<1e-6
            assert abs(dh.imag)<1e-6
            assert dh.real+1e-7>=target, (m,dh,target)
            assert target+1e-10>=m
            count+=1
    return count

def main():
    tests=[('symmetric powers and GL2 equivariance',test_sym_and_equivariance),
           ('binary discriminant covariance',test_disc_covariance),
           ('adjugate-minor determinant covariance',test_minor_covariance),
           ('inner and outer summation by parts (exact rational)',test_summation_by_parts),
           ('complex Cholesky-Cauchy-Binet',test_cholesky_cb)]
    for name,fn in tests:
        n=fn()
        print(f'PASS {name}: {n} trials')
    print('All five computational test suites passed. NOT a proof of the global theorem.')

if __name__=='__main__':main()
