checks.py

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

10326 bytes, as of the version from 2026-12-01 18:07 (current). Recorded here, not run.

"""Executable build checks for T894, separate from the AA root generator.

Run with generate.py, transition-data.json and the repository's check.py in
the same directory: sage -python checks.py. Results are printed as JSON after
RESULT_JSON so a read-only builder mount can preserve them on its host.
An optional stored-values.json reruns every numerical check on API readback.
This is builder evidence, not an independent critic's verdict.
"""
import json, math, sys, hashlib, platform
from pathlib import Path
import numberdb.sage as numberdb
from numberdb._write import to_text
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.matrix.constructor import matrix
from sage.modules.free_module_element import vector
from sage.rings.real_mpfi import RealIntervalField
from sage.env import SAGE_VERSION
import generate
import check as deterministic

HERE=Path(__file__).resolve().parent
data=json.loads((HERE/'transition-data.json').read_text())
R=PolynomialRing(ZZ,'x');x=R.gen()
def say(word,base):
    out=[];i=0
    while i<len(word):
        j=i+1
        while j<len(word) and word[j]==word[i]:j+=1
        r=j-i;digits=[]
        while r:digits.append(str(r%base));r//=base
        out.extend(reversed(digits));out.append(word[i]);i=j
    return ''.join(out)

def components(adjacency):
    seen=set();order=[]
    def visit(u):
        if u in seen:return
        seen.add(u)
        for v in adjacency[u]:visit(v)
        order.append(u)
    for u in adjacency:visit(u)
    reverse={u:[] for u in adjacency}
    for u in adjacency:
        for v in adjacency[u]:reverse[v].append(u)
    result=[];seen=set()
    def collect(u,comp):
        if u in seen:return
        seen.add(u);comp.append(u)
        for v in reverse[u]:collect(v,comp)
    for u in reversed(order):
        if u not in seen:
            comp=[];collect(u,comp);result.append(comp)
    return result

def period(adjacency,comp):
    members=set(comp);depth={comp[0]:0};todo=[comp[0]]
    for u in todo:
        for v in adjacency[u]:
            if v in members and v not in depth:
                depth[v]=depth[u]+1;todo.append(v)
    assert len(depth)==len(comp)
    g=0
    for u in comp:
        for v in adjacency[u]:
            if v in members:g=math.gcd(g,depth[u]+1-depth[v])
    return abs(g)

def count_roots(p,a,b):
    # PARI's exact rational Sturm count, independent of AA root refinement.
    return int(p.__pari__().polsturm([a,b]))

def bracket(p,lo,hi,places=115):
    assert p(lo)<0<p(hi)
    assert count_roots(p,lo,hi)==1
    steps=0
    while hi-lo>QQ(1)/10**places:
        middle=(lo+hi)/2
        if p(middle)<0:lo=middle
        else:hi=middle
        steps+=1
    assert p(lo)<0<p(hi)
    return lo,hi,steps

def literal_checks(atoms,decays,base):
    for a in atoms:
        assert say(a,base)==''.join(decays[a]),a

def boundary_closure(pairs,decays):
    pairs=set(pairs);todo=list(pairs)
    for left,right in todo:
        assert left[-1]!=right[0],(left,right)
        children=decays[left]+decays[right]
        for pair in zip(children,children[1:]):
            if pair not in pairs:pairs.add(pair);todo.append(pair)
    return len(pairs)

atoms=data['atoms'];decays=data['decays'];literal_checks(atoms,decays,10)
assert all(say(a,4)==say(a,10) for a in atoms)
# Every listed decimal atom has runs of length at most three. No count digit
# depends on the chosen radix b>=4, and boundary closure prevents new mergers.
from itertools import groupby
assert max(len(list(g)) for a in atoms for _,g in groupby(a))==3
pairs=[pair for a in atoms for pair in zip(decays[a],decays[a][1:])]
stable_pairs=boundary_closure(pairs,decays)
print('92 literal decimal decays and stable descendant boundaries checked',stable_pairs,flush=True)
M=matrix(ZZ,[[decays[a].count(b) for b in atoms] for a in atoms])
char=M.charpoly('x')
q=char//(x**18*(x-1)**2*(x+1))
assert char==x**18*(x-1)**2*(x+1)*q
assert q.degree()==71 and q==generate.POLYNOMIALS['conway']
print('Exact 92-by-92 characteristic polynomial matches published factorization',flush=True)
adj={a:set(decays[a]) for a in atoms};comps=components(adj)
assert sorted(map(len,comps))==[1,91]
big=next(c for c in comps if len(c)==91)
assert next(c for c in comps if len(c)==1)==['22']
assert period(adj,big)==1 and decays['22']==['22']
B=matrix(ZZ,[[decays[a].count(b) for b in big] for a in big])
v=vector(ZZ,[1]*len(big))
for _ in range(250):v=B*v
ratios=[QQ(a)/b for a,b in zip(B*v,v)]
assert QQ(130)/100<min(ratios)<=max(ratios)<QQ(131)/100
assert count_roots(q,QQ(130)/100,QQ(131)/100)==1
# All internal/seed decomposition boundaries are closed under decay, proving
# exact independent evolution of these finite atom counts at every step.
def decompositions(word):
    def rec(i,parts):
        if i==len(word):yield parts;return
        for a in atoms:
            if word.startswith(a,i) and (not parts or parts[-1][-1]!=a[0]):
                yield from rec(i+len(a),parts+[a])
    return rec(0,[])
word='1';seed_decomposition=None
for n in range(18):
    for parts in decompositions(word):
        try:closure=boundary_closure(list(zip(parts,parts[1:]))+pairs,decays)
        except AssertionError:continue
        if any(a in big for a in parts):seed_decomposition=(n,parts,closure);break
    if seed_decomposition:break
    word=say(word,10)
assert seed_decomposition
print('Decimal seed enters primitive growing component at iterate',seed_decomposition[0],flush=True)

ta=data['ternary_atoms'];td=data['ternary_decays'];names=list(ta)
tdwords={ta[a]:[ta[b] for b in td[a]] for a in names}
literal_checks(list(tdwords),tdwords,3)
ternary_boundary_count=boundary_closure([p for a in tdwords for p in zip(tdwords[a],tdwords[a][1:])],tdwords)
N=matrix(ZZ,[[td[a].count(b) for b in names] for a in names])
assert N.transpose()==matrix(ZZ,data['ternary_matrix_columns_are_parents'])
assert N.charpoly('x')==(x**3-x-1)*(x**5-x**3+1)
assert len(components({a:set(td[a]) for a in names}))==1
assert period({a:set(td[a]) for a in names},names)==1
vv=vector(ZZ,[1]*8)
for _ in range(250):vv=N*vv
rr=[QQ(a)/b for a,b in zip(N*vv,vv)]
assert QQ(132)/100<min(rr)<=max(rr)<QQ(133)/100
print('Eight-fermion ternary matrix, all images, primitive component and cubic factor checked',flush=True)

assert say('1',2)=='11' and say('11',2)=='101'
assert say('111',2)=='111'
assert all(say(s,3)==s for s in ['22','11110','11112'])
assert all(say('22',b)=='22' for b in [4,5,10,16])
assert say('1111',3)=='111' and say('1111',4)=='101'
lengths={}
for base in [2,3,4,5,10]:
    word='1';ls=[]
    for n in range(26):
        ls.append(len(word));word=say(word,base)
    lengths[str(base)]=ls
assert lengths['4']==lengths['5']==lengths['10']

control_lo,control_hi,_=bracket(x*x-2,QQ(14)/10,QQ(15)/10)
assert control_lo**2<2<control_hi**2
negative=False
try:literal_checks(['11'],{'11':['11']},2)
except AssertionError:negative=True
assert negative
negative_bracket=False
try:bracket(x**3-x**2-1,QQ(132)/100,QQ(133)/100)
except AssertionError:negative_bracket=True
assert negative_bracket
assert deterministic.exactness({'float':1.0})
assert deterministic.exactness({'nan':RealIntervalField(64)('nan')})

g=generate.LookAndSayGrowth();values={p['regime']:g.value(p,100) for p in g.enumerate()}
assert not deterministic.exactness(values)
assert not deterministic.exact_in_disguise(values)
assert not deterministic.prose(values)
assert not deterministic.names_its_rings(str(HERE/'generate.py'))
serialized={k:to_text(v,digits=100) for k,v in values.items()}
stored_path=HERE/'stored-values.json'
if stored_path.exists():
    stored=json.loads(stored_path.read_text());assert set(stored)==set(serialized)
    assert stored==serialized
else:stored=serialized
independent={'binary':x**3-x**2-1,'ternary':x**3-x-1,'conway':q}
evidence={}
for regime,text in stored.items():
    assert isinstance(text,str) and text.count('.')==1
    d=len(text.split('.')[1]);centre=QQ(text.replace('.',''))/10**d
    ulp=QQ(1)/10**d;lower=centre-ulp;upper=centre+ulp
    p=independent[regime];lo,hi=generate.BRACKETS[regime]
    left,right,steps=bracket(p,lo,hi)
    native_lo=values[regime].lower().exact_rational();native_hi=values[regime].upper().exact_rational()
    assert lower<=native_lo<native_hi<=upper
    assert lower<left<right<upper
    assert count_roots(p,lower,upper)==1
    assert d==99 and right-left<QQ(1)/10**115
    evidence[regime]={'stored':text,'return_type':type(values[regime]).__name__,
        'working_bits':int(values[regime].parent().precision()),
        'native_lower':str(native_lo),'native_upper':str(native_hi),'native_width':str(native_hi-native_lo),
        'stored_lower':str(lower),'stored_upper':str(upper),'independent_lower':str(left),
        'independent_upper':str(right),'independent_width':str(right-left),
        'bisection_steps':steps,'stored_interval_sturm_count':1,'contained':True}
    print(regime,text,flush=True)
result={'checked_entries':3,'total_entries':3,'failures':[],
    'known_answer_control':True,'negative_control_rejected':negative and negative_bracket,
    'controls':{'sqrt2':True,'corrupt_binary_decay_rejected':negative,'wrong_growth_bracket_rejected':negative_bracket,'float_and_nan_refused':True,'fixed_words':True},
    'source_data_sha256':hashlib.sha256((HERE/'transition-data.json').read_bytes()).hexdigest(),
    'skill_manifest':'agents/runs/20261201T152955Z-build-skills/manifest.json',
    'versions':{'sage':SAGE_VERSION,'python':platform.python_version(),'numberdb':numberdb.__version__},
    'decimal':{'atoms':92,'ordered_literal_decays':92,'stable_pair_count':stable_pairs,
        'characteristic_polynomial':str(char),'p71':str(q),'scc_sizes':sorted(map(len,comps)),
        'growing_period':1,'collatz_lower':str(min(ratios)),'collatz_upper':str(max(ratios)),
        'seed_iterate':seed_decomposition[0],'seed_atoms':seed_decomposition[1]},
    'ternary':{'ordered_fermions':names,'charpoly':str(N.charpoly('x')),'stable_pair_count':ternary_boundary_count,'primitive':True},
    'direct_lengths':lengths,'entries':evidence,'serialized_values':serialized,
    'size':deterministic.measure(values),'stored_readback':stored_path.exists()}
print('RESULT_JSON '+json.dumps(result,sort_keys=True),flush=True)