independent_check.py

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

5338 bytes, as of the version from 2026-11-27 21:40 (current). Recorded here, not run.

"""Independent exhaustive digit-tree check. No imports from generate.py.

Run: python independent_check.py INPUT.json [RESULTS.json]. INPUT is a
checkpoint with entries or a full NumberDB document with flat Numbers.
Sage is not required: every operation here is exact Python integer arithmetic.
The campaign executes this file through its isolated builder as well.
"""
import sys,json,re,copy,pathlib,math

def is_prime(p):
    return p>=2 and all(p%d for d in range(2,math.isqrt(p)+1))

def polynomial(t):
    return t*t*t-t-1

def digit_tree(f,p,n):
    roots=[a for a in range(p) if f(a)%p==0];mod=p
    widths=[len(roots)]
    for level in range(1,n):
        next_mod=mod*p
        roots=[r+digit*mod for r in roots for digit in range(p) if f(r+digit*mod)%next_mod==0]
        mod=next_mod;widths.append(len(roots))
    return sorted(roots),widths

def flat_rows(document):
    rows=document.get('Numbers',document.get('entries'))
    if isinstance(rows,dict):
        return [{'params':{'p':p,'k':k,'a':a},'number':value['number'] if isinstance(value,dict) else value}
                for p,byk in rows.items() for k,bya in byk.items() for a,value in bya.items()]
    return rows

def unpack(document):
    rows=flat_rows(document)
    result=[]
    for row in rows:
        m=re.fullmatch(r'(\d+) \+ O\((\d+)\^(\d+)\)',row['number'])
        assert m,'malformed p-adic value'
        u,p,n=map(int,m.groups());params={k:int(v) for k,v in row['params'].items()}
        result.append((params,u,p,n))
    return result

def validate(document):
    rows=unpack(document);expected=[];census=[];comparisons=[]
    primes=[p for p in range(2,30) if is_prime(p)]+[59]
    for p in primes:
        n=0;mod=1
        while mod<10**100:n+=1;mod*=p
        roots,widths=digit_tree(polynomial,p,n)
        residues=[a for a in range(p) if polynomial(a)%p==0]
        simple=[a for a in residues if (3*a*a-1)%p]
        multiple=[a for a in residues if not (3*a*a-1)%p]
        census.append({'p':p,'N':n,'residues':residues,'simple':simple,'multiple':multiple,'tree_counts':widths})
        for u in roots:
            a=u%p;assert a in simple
            expected.append((p,1,a))
            selected=[r for r in rows if r[0]=={'p':p,'k':1,'a':a}]
            assert len(selected)==1,'missing/duplicate/incorrect branch'
            params,v,q,m=selected[0]
            assert q==p and m==n and 0<v<mod and v%p==a
            assert v==u,'digit-tree disagreement'
            assert polynomial(v)%mod==0 and (3*v*v-1)%p
            assert p**(n-1)<10**100<=mod
            comparisons.append({'params':params,'N':n,'u':str(v),'match':True,'residual_modulus':'0'})
    identities=[tuple(r[0][k] for k in ['p','k','a']) for r in rows]
    assert identities==sorted(expected),'coverage or ordering differs'
    assert len(rows)==9
    rs=sorted(r[1] for r in rows if r[2]==59);mod=59**57
    vieta={'sum':sum(rs)%mod,'pair_sum':sum(rs[i]*rs[j] for i in range(3) for j in range(i+1,3))%mod,'product':rs[0]*rs[1]*rs[2]%mod}
    assert vieta=={'sum':0,'pair_sum':mod-1,'product':1}
    smaller=[p for p in range(2,59) if is_prime(p)]
    split_census=[{'p':p,'simple_residues':[a for a in range(p) if polynomial(a)%p==0 and (3*a*a-1)%p]} for p in smaller]
    assert all(len(r['simple_residues'])<3 for r in split_census)
    assert polynomial(10)==23*43 and (3*10*10-1)==23*13
    assert not [10+23*t for t in range(23) if polynomial(10+23*t)%529==0]
    return {'checked_entries':len(rows),'total_entries':len(rows),'census':census,'comparisons':comparisons,'vieta_59':vieta,'smaller_prime_split_census':split_census,'repeated_23_has_no_lift':True}

def run(document):
    roots,_=digit_tree(lambda x:x*x-1,7,12)
    assert roots==[1,7**12-1]
    nonsquare,_=digit_tree(lambda x:x*x-3,7,12);assert nonsquare==[]
    result=validate(document)
    negative=[]
    for kind in ['last_digit','branch_label','missing_branch','extra_branch','precision']:
        bad={'Numbers':copy.deepcopy(flat_rows(document))};rows=bad['Numbers'];r=rows[0]
        if kind=='last_digit':
            m=re.fullmatch(r'(\d+) \+ O\((\d+)\^(\d+)\)',r['number']);u,p,n=map(int,m.groups());r['number']=f'{(u+p**(n-1))%(p**n)} + O({p}^{n})'
        elif kind=='branch_label':r['params']['a']=str(int(r['params']['a'])+1)
        elif kind=='missing_branch':rows.pop()
        elif kind=='extra_branch':rows.append(copy.deepcopy(rows[0]))
        else:r['number']=r['number'].replace('^144)','^143)')
        try:validate(bad)
        except AssertionError:negative.append(kind)
        else:raise AssertionError('negative control accepted: '+kind)
    result.update(failures=[],known_answer_control=True,negative_control_rejected=len(negative)==5,negative_controls=negative,known_controls={'square_polynomial':'x^2-1','p':7,'N':12,'roots':[str(x) for x in roots],'nonsquare_polynomial':'x^2-3','nonsquare_has_no_roots':True},method='exhaustive integer digit-tree; no generator import',skill_manifest='skill-manifest.json')
    return result

if __name__=='__main__':
    args=sys.argv[1:];input_path=pathlib.Path(args[0]) if args else pathlib.Path('/work/checkpoint.json')
    result=run(json.loads(input_path.read_text()));text=json.dumps(result,indent=2)
    if len(args)>1:pathlib.Path(args[1]).write_text(text+'\n')
    print('CHECK_RESULTS_JSON='+json.dumps(result))