independent_check.py

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

6097 bytes, as of the version from 2026-11-27 09:56 (current). Recorded here, not run.

"""Exact build checks for T813; this is not an independent critique verdict.

SageMath 10.9 and numberdb 0.1.10 were used. No generator code is imported.
    sage -python independent_check.py stored-records.json > check-results.json
The input is {"records":[{"params":{"p":3,"q":1},"number":"x + 1"},...]}.
With no filename, use stored-records.json, else offline.json, beside this file.
Every selected row is checked, with a separately enumerated joint domain and
exact rational-floor signs. Method 1 literally multiplies the defining 2x2
word matrices. Method 2 forms and computes the full tridiagonal determinant
of Corollary 5.3 in Jo–Kim arXiv:2201.03922v2. The q=1 slice is checked by an
explicit binomial formula for ordinary second-kind Chebyshev polynomials,
not by the generator's recurrence. Native polynomial coefficient types,
monicity, constant coefficient, degree, squarefreeness and sign reversal are
checked. Known controls and deliberately corrupted inputs test the checker.
"""
import argparse
import hashlib
import json
import platform
import time
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
# Initialize this named module before generic matrix construction on modular Sage.
from sage.rings.polynomial.laurent_polynomial_ring import LaurentPolynomialRing
from sage.matrix.constructor import matrix
from sage.symbolic.ring import SR
from sage.arith.misc import binomial
from sage.version import version

P = PolynomialRing(ZZ, 'x')
x = P.gen()
V = PolynomialRing(ZZ, 'v')
v = V.gen()


def signs(p, q):
    return [ZZ(-1)**(QQ(j*q)/QQ(p)).floor() for j in range(1,p)]


def literal_word(p, q, negate=False):
    a=matrix(P,[[1,1],[0,1]])
    b=matrix(P,[[1,0],[x,1]])
    w=matrix(P,[[1,0],[0,1]])
    for j,sgn in enumerate(signs(p,q)):
        if negate: sgn=-sgn
        w=w*((a if j%2==0 else b)**sgn)
    assert w.det()==1
    assert w[1,0]==x*w[0,1]
    return P(w[0,0])


def determinant(p, q):
    eps=signs(p,q)
    assert eps==list(reversed(eps))
    d=matrix(V,p-1,p-1)
    for j,e in enumerate(eps):
        d[j,j]=e*v
        if j: d[j,j-1]=1; d[j-1,j]=1
    return (-1)**((p-1)//2)*d.det()


def chebyshev(n, t):
    if n<0: return t.parent().zero()
    return sum(((-1)**j*binomial(n-j,j)*(2*t)**(n-2*j)
                for j in range(n//2+1)), t.parent().zero())


def expected_keys():
    # Separate domain enumeration: include all integers, then test the constraints.
    return [(p,q) for p in range(3,52) for q in range(1,p)
            if ZZ(p) % 2 == 1 and ZZ(q) % 2 == 1 and ZZ(p).gcd(q)==1]


def valid_keys(rows):
    return [(int(r['params']['p']),int(r['params']['q'])) for r in rows]==expected_keys()


def main():
    ap=argparse.ArgumentParser(description=__doc__)
    ap.add_argument('input',nargs='?')
    opts=ap.parse_args()
    base=Path(__file__).parent
    source=Path(opts.input) if opts.input else next(p for p in [base/'stored-records.json',base/'offline.json'] if p.exists())
    packet=json.loads(source.read_text())
    rows=packet['records']
    start=time.monotonic(); failures=[]; comparisons=[]
    assert valid_keys(rows), 'parameter order, completeness or identities differ'
    known=literal_word(3,1)==x+1 and literal_word(5,1)==x*x+3*x+1 and literal_word(5,3)==x*x-x+1
    assert known
    negative={
        'changed_coefficient_rejected':literal_word(5,3)!=x*x-x+2,
        'wrong_lower_left_sign_rejected':literal_word(5,3)!=P((x*x-x+1)(-x)),
        'missing_presentation_rejected':not valid_keys(rows[:-1]),
        'reordered_parameters_rejected':not valid_keys(list(reversed(rows))),
    }
    # Wrong sign controls must fail both independently implemented full checks.
    negative['determinant_wrong_coefficient_rejected']=(x*x-x+2)(-v*v)!=determinant(5,3)
    negative['determinant_wrong_coordinate_rejected']=(x*x-x+1)(v*v)!=determinant(5,3)
    assert all(negative.values())
    largest=0; q1=0
    for record in rows:
        p,q=int(record['params']['p']),int(record['params']['q'])
        f=P(record['number']); n=(p-1)//2
        checks={
            'native_exact_coefficients':type(f).__name__=='Polynomial_integer_dense_flint' and all(type(c).__name__=='Integer' for c in f.list()),
            'degree':f.degree()==n,
            'monic':f.leading_coefficient()==1,
            'constant':f[0]==1,
            'squarefree':f.gcd(f.derivative())==1,
            'literal_word':f==literal_word(p,q),
            'determinant':f(-v*v)==determinant(p,q),
            'mirror':f==literal_word(p,q,negate=True),
        }
        if q==1:
            Q=PolynomialRing(QQ,'x'); t=(Q.gen()+2)/2
            checks['chebyshev_slice']=Q(f)==chebyshev(n,t)-chebyshev(n-1,t)
            q1+=1
        if not all(checks.values()): failures.append({'p':p,'q':q,'checks':checks})
        comparisons.append({'p':p,'q':q,'degree':n,'checks':checks})
        largest=max(largest,len(record['number']))
    result={'checked_entries':len(comparisons),'total_entries':len(rows),'failures':failures,
        'known_answer_control':bool(known),'negative_control_rejected':all(negative.values()),
        'controls':negative,'q1_chebyshev_rows':q1,'largest_polynomial_characters':largest,
        'comparisons':comparisons,'seconds':time.monotonic()-start,
        'versions':{'sage':version,'python':platform.python_version(),'numberdb':numberdb.__version__},
        'input_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),
        'checker_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        'skill_manifest':'../20261126T081302Z-build-skills/manifest.json',
        'skill_bundle_sha256':'b5c3c7985b7c9e178b4899d083a9e3bc4284989dff76f05e5b0e52835d47eed2',
        'limitations':'Exact implementation checks performed by the builder; a fresh independent critic and argument-selection review are still required.'}
    print(json.dumps(result))
    return bool(failures)

if __name__=='__main__':
    raise SystemExit(main())