independent_check.py

back to table · edit · history · where entries came from · files · download

7910 bytes, as of the version from 2026-11-27 13:33 (current). Recorded here, not run.

"""Independent full-polynomial checks for the two-variable Riley table.

Usage: sage -python independent_check.py document.json [check-results.json]
Requires SageMath and numberdb; no credentials and no generator imports.
Constructs the literal Schubert word over a Laurent ring, the tridiagonal
continuant determinant on the diagonal, Fox derivatives of wa(bw)^-1 for the
Alexander specialization, and the explicit Chebyshev binomial sum on q=1.
It independently enumerates presentations and checks known answers and
corrupted coefficients, coordinate signs and missing entries. Exact comparison
is of complete polynomials, not evaluations at numerical sample points.
"""
import json
import math
import sys
from pathlib import Path
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.polynomial.laurent_polynomial_ring import LaurentPolynomialRing
from sage.matrix.constructor import matrix
from sage.matrix.special import identity_matrix

P = PolynomialRing(ZZ, names=('x', 'y'))
L = LaurentPolynomialRing(ZZ, names=('M', 'X'))
M, X = L.gens()
V = PolynomialRing(ZZ, 'v'); v = V.gen()
T = LaurentPolynomialRing(ZZ, 't'); t = T.gen()
QY = PolynomialRing(QQ, 'Y'); Y = QY.gen()


def expected_selection():
    # Deliberately independent of the generator's helper and iteration scheme.
    return [(p, q) for p in range(3, 50) for q in range(1, p)
            if p % 2 and q % 2 and ZZ(p).gcd(ZZ(q)) == 1]


def signs(p, q):
    # floor(jq/p) is computed with exact quotient/remainder.
    return [ZZ(1) if divmod(j*q, p)[0] % 2 == 0 else ZZ(-1)
            for j in range(1, p)]


def word_polynomial(p, q, reverse_signs=False):
    eps = signs(p, q)
    if reverse_signs:
        eps = [-s for s in eps]
    assert eps == eps[::-1]
    A = matrix(L, [[M, 1], [0, M**(-1)]])
    Ai = matrix(L, [[M**(-1), -1], [0, M]])
    B = matrix(L, [[M, 0], [X, M**(-1)]])
    Bi = matrix(L, [[M**(-1), 0], [-X, M]])
    W = identity_matrix(L, 2)
    for j, s in enumerate(eps):
        W = W * ((A if s == 1 else Ai) if j % 2 == 0 else (B if s == 1 else Bi))
    assert W.det() == 1 and W[1, 0] == X*W[0, 1]
    return W[0, 0]-(M-M**(-1))*W[0, 1]


def agrees_word(f, p, q):
    return f(X, X+(M-M**(-1))**2) == word_polynomial(p, q)


def normalise_alexander(f):
    f = T(f)
    minimum = min(f.exponents())
    g = f*t**(-minimum)
    return g if g[0] > 0 else -g


def fox_alexander(p, q):
    eps = signs(p, q)
    word = [('a' if j % 2 == 0 else 'b', int(s)) for j, s in enumerate(eps)]
    # r=wa(w^-1)b^-1, so delete the b-column of the abelianized Fox matrix.
    relator = word + [('a', 1)] + [(g, -s) for g, s in reversed(word)] + [('b', -1)]
    exponent = 0; derivative = T.zero()
    for generator, s in relator:
        if generator == 'a':
            derivative += t**exponent if s == 1 else -t**(exponent-1)
        exponent += s
    assert exponent == 0
    return normalise_alexander(derivative)


def chebyshev(n):
    # U_n(z)=sum (-1)^k binom(n-k,k) (2z)^(n-2k), evaluated at z=(Y+2)/2.
    if n < 0:
        return QY.zero()
    return sum((ZZ(-1)**k)*ZZ(math.comb(n-k, k))*(Y+2)**(n-2*k)
               for k in range(n//2+1))


def entries(document):
    result = {}
    for p, row in document['Numbers'].items():
        for q, record in row.items():
            text = record['number'] if isinstance(record, dict) else record
            key = (int(p), int(q))
            assert key not in result
            result[key] = P(str(text))
    return result


def check(document, parabolic=None, chebyshev_document=None, alexander_document=None):
    data = entries(document)
    expected = expected_selection()
    failures = []
    controls = [((3,1), P('y+1')), ((5,1), P('y^2+3*y+1')), ((5,3), P('x*y-y+1'))]
    known = all(agrees_word(f, *pq) for pq, f in controls)
    negative = all(not agrees_word(f+1, *pq) and not agrees_word(f(-P.gen(0),-P.gen(1)), *pq)
                   for pq, f in controls)
    missing = dict(data); missing.pop((3,1), None)
    enumeration_rejected = set(missing) != set(expected)
    if list(data) != expected:
        failures.append('Stored ordered selection differs from the 255 admissible presentations through p=49')
    checked=[]; determinant_count=fox_count=cheb_count=0; sibling_count=0
    for pq, f in data.items():
        p,q = pq; n=(p-1)//2
        if not agrees_word(f,p,q): failures.append(f'{pq}: word identity failed')
        if f(X,X+(M-M**(-1))**2) != word_polynomial(p,q,True):
            failures.append(f'{pq}: sign reversal failed')
        phi = V(f(v,v))
        eps = signs(p,q)
        H = matrix(V,p-1,p-1)
        for j,s in enumerate(eps):
            H[j,j]=s*v
            if j+1<p-1: H[j,j+1]=H[j+1,j]=1
        determinant = (ZZ(-1)**n)*H.det()
        if phi(-v*v) != determinant: failures.append(f'{pq}: determinant failed')
        determinant_count += 1
        if phi.degree()!=n or not phi.is_monic() or phi[0]!=1 or phi.gcd(phi.derivative())!=1:
            failures.append(f'{pq}: diagonal degree/normalization/squarefreeness failed')
        if normalise_alexander(f(T.zero(),t+t**(-1)-2)) != fox_alexander(p,q):
            failures.append(f'{pq}: Fox Alexander failed')
        fox_count += 1
        if parabolic:
            other=parabolic['Numbers'][str(p)][str(q)]
            if isinstance(other,dict):other=other['number']
            if phi != V(str(other).replace('x','v')):failures.append(f'{pq}: T813 mismatch')
            sibling_count += 1
        if q==1:
            if QY(f(Y,Y)) != chebyshev(n)-chebyshev(n-1):failures.append(f'{pq}: Chebyshev failed')
            if chebyshev_document:
                ua=QY(chebyshev_document['Numbers'][str(n)].replace('x','Y'))
                ub=QY(chebyshev_document['Numbers'][str(n-1)].replace('x','Y'))
                if QY(f(Y,Y)) != ua((Y+2)/2)-ub((Y+2)/2):
                    failures.append(f'{pq}: stored T99 mismatch')
            cheb_count += 1
        checked.append({'p':p,'q':q,'degree':int(f.total_degree()),'terms':len(f.dict()),'diagonal_degree':int(phi.degree()),'coefficient_types':sorted(set(type(c).__name__ for c in f.coefficients()))})
    alexander_controls=[]
    if alexander_document:
        # S(3,1) is the trefoil; S(5,3) is the figure-eight knot (up to mirror).
        for pq,n,k in [((3,1),3,1),((5,3),4,1)]:
            record=alexander_document['Numbers'][str(n)][str(k)]
            text=record['number'] if isinstance(record,dict) else record
            actual=normalise_alexander(data[pq](T.zero(),t+t**(-1)-2))
            if actual!=T(text):failures.append(f'{pq}: T138 low-knot mismatch')
            alexander_controls.append({'p':pq[0],'q':pq[1],'T138_identity':f'{n},{k}','polynomial':str(actual)})
    if not known:failures.append('Known-answer control failed')
    if not negative or not enumeration_rejected:failures.append('Negative control failed')
    return {'checked_entries':len(checked),'total_entries':len(data),'failures':failures,'known_answer_control':bool(known),'negative_control_rejected':bool(negative and enumeration_rejected),'word_checks':len(checked),'sign_reversal_checks':len(checked),'determinant_checks':determinant_count,'fox_alexander_checks':fox_count,'chebyshev_checks':cheb_count,'T813_comparisons':sibling_count,'T138_controls':alexander_controls,'entries':checked,'method':'Exact Laurent word matrices, tridiagonal determinants, Fox derivative and explicit Chebyshev sums; no generator imports.'}


if __name__=='__main__':
    document=json.loads(Path(sys.argv[1]).read_text())
    result=check(document)
    target=Path(sys.argv[2]) if len(sys.argv)>2 else Path('check-results.json')
    target.write_text(json.dumps(result,indent=2)+'\n')
    print(json.dumps(result))
    raise SystemExit(bool(result['failures']))