check_zeros.py

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

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

"""Independent build checks for the NumberDB Riley-zero draft.

sage -python check_zeros.py [entries.json] [T813-before.json]
The default inputs sit beside this file. No generator import is used.
Checks: continuant polynomial, all roots, Sturm real isolation, rational
Rouche certificates, exact-component line gcds, conjugates, root ordering,
coverage, and deliberately invalid controls. Writes results and certificates
locally when permitted, and always prints a machine-readable RESULTS line.
"""
import sys,json,re,time,math
from pathlib import Path
from fractions import Fraction
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.number_field.number_field import QuadraticField
from sage.libs.pari import pari
P=PolynomialRing(QQ,'x');x=P.gen()
V=PolynomialRing(ZZ,'v');v=V.gen()
K=QuadraticField(-1,'ii');ii=K.gen()
Y=PolynomialRing(QQ,'y');y=Y.gen()
H=PolynomialRing(K,'h');h=H.gen()
BASE=Path(__file__).parent

def rational(s):
    return QQ(str(Fraction(str(s).strip())))

def component(s):
    s=s.strip()
    if s.startswith('[') and s.endswith(']'):
        a,b=s[1:-1].split(',');lo,hi=rational(a),rational(b)
        assert lo<=hi
        return lo,hi
    assert re.fullmatch(r'[+-]?(?:\d+/\d+|\d+|\d*\.\d+(?:e[+-]?\d+)?)',s), 'invalid/nonfinite number'
    c=rational(s)
    if '.' not in s and 'e' not in s:return c,c
    mantissa,_,exponent=s.partition('e')
    step=QQ(10)**(int(exponent or '0')-len(mantissa.split('.')[1]))
    return c-step,c+step

def parse(text):
    if ' + i * ' in text:
        a,b=text.split(' + i * ')
    else:a,b=text,'0'
    return component(a),component(b)

def narrow(bounds):
    lo,hi=bounds
    assert lo<=hi
    if lo==hi:return
    size=max(abs(lo),abs(hi))
    assert size>0 and hi-lo < size*QQ(10)**(-98), 'vacuous or insufficient precision'

def poly(p,q):
    # Independently enumerate signs by quotient/remainder, not generator code.
    signs=[]
    for j in range(1,p):
        quotient,remainder=divmod(j*q,p)
        assert 0<remainder<p
        signs.append((-1)**quotient)
    assert signs==list(reversed(signs))
    a,b=V.one(),V.zero()
    for e in signs:
        a,b=e*v*a-b,a
    D=(-1)**((p-1)//2)*a
    assert all(D[j]==0 for j in range(1,p,2))
    f=P([(-1)**j*D[2*j] for j in range((p+1)//2)])
    assert f.degree()==(p-1)//2 and f.is_monic() and f[0]==1
    assert f.gcd(f.derivative())==1
    return f

def sturm_count(f,lo,hi):
    assert lo<hi and f(lo)!=0 and f(hi)!=0
    return int(pari(f).polsturm([lo,hi]))

def round_rational(a,places=130):
    scale=ZZ(10)**places
    return QQ((a*scale).round())/scale

def parts(c):return QQ(c[0]),QQ(c[1])
def upper(c):
    a,b=parts(c);return abs(a)+abs(b)
def lower(c):
    a,b=parts(c);return max(abs(a),abs(b))

def rouche(f,bounds):
    (rl,rh),(il,ih)=bounds
    c=K((rl+rh)/2)+ii*((il+ih)/2)
    for _ in range(3):
        assert f.derivative()(c)!=0
        c=c-f(c)/f.derivative()(c)
        a,b=parts(c);c=K(round_rational(a))+ii*round_rational(b)
    r=QQ(1)/ZZ(10)**120
    expansion=f(c+h)
    lhs=lower(expansion[1])*r
    rhs=upper(expansion[0])+sum(upper(expansion[j])*r**j for j in range(2,f.degree()+1))
    assert lhs>rhs, 'Rouche inequality fails'
    cr,ci=parts(c)
    assert abs(ci)>r, 'disk must be nonreal'
    for lo,hi,center in [(rl,rh,cr),(il,ih,ci)]:
        if lo!=hi:assert lo<center-r and center+r<hi, 'disk outside stored interval'
    # Singleton coordinates need a separate exact argument; a disk alone
    # cannot fit inside a zero-width rectangle. Restrict f to that line,
    # take the gcd of its two rational component polynomials, isolate by Sturm.
    for coordinate,(lo,hi) in enumerate(bounds):
        if lo!=hi:continue
        if coordinate==0:
            expression=f(K(lo)+ii*h); other=bounds[1]
        else:
            expression=f(h+ii*lo); other=bounds[0]
        real=Y([parts(t)[0] for t in expression]);imag=Y([parts(t)[1] for t in expression])
        line=real.gcd(imag)
        assert line.degree()>0
        if other[0]==other[1]:assert line(other[0])==0
        else:
            assert sturm_count(line,*other)==1, 'exact component unsupported'
            # The line root is in the certified disk: a tighter interval
            # with radius r/2 around the other center lies wholly in it.
            center=ci if coordinate==0 else cr
            assert abs((cr if coordinate==0 else ci)-lo)<r/2
            assert sturm_count(line,center-r/2,center+r/2)==1
    return {'center_real':str(cr),'center_imag':str(ci),'radius':str(r),'margin_ratio_lower_bound':str((lhs/rhs).floor()) if rhs else 'infinite'}

def certify_group(f,records):
    assert len(records)==f.degree(), 'missing or excess roots'
    certs=[];bounds=[]
    for record in records:
        b=parse(record['number'])
        for part in b:narrow(part)
        (rl,rh),(il,ih)=b
        if il==ih==0:
            if rl==rh:
                assert f(rl)==0
                cert={'method':'exact rational','center_real':str(rl),'center_imag':'0','radius':'0'}
            else:
                assert sturm_count(f,rl,rh)==1, 'stored real bracket fails'
                cert={'method':'Sturm','lower':str(rl),'upper':str(rh),'center_real':str((rl+rh)/2),'center_imag':'0','radius':str((rh-rl)/2)}
        else:
            cert={'method':'Rouche',**rouche(f,b)}
        cert['params']=record['params'];certs.append(cert);bounds.append(b)
    # Disjoint disks or real intervals and total degree account for ALL roots.
    for i,c in enumerate(certs):
        for d in certs[:i]:
            assert max(abs(rational(c['center_real'])-rational(d['center_real'])),abs(rational(c['center_imag'])-rational(d['center_imag'])))>rational(c['radius'])+rational(d['radius']), 'overlapping isolators'
    # Exact conjugacy follows from real coefficients and conjugate isolated
    # regions, then uniqueness. This also certifies the equal real-part ties.
    def conjugate_pair(a,b):
        return a[0]==b[0] and a[1]==(-b[1][1],-b[1][0])
    for i,b in enumerate(bounds):
        if b[1]!=(QQ.zero(),QQ.zero()):
            partners = [j for j,a in enumerate(bounds) if conjugate_pair(b,a)]
            assert partners, 'missing conjugate'
            c = certs[i]
            assert any(rational(c['center_real'])==rational(certs[j]['center_real'])
                       and rational(c['center_imag'])==-rational(certs[j]['center_imag'])
                       and c['radius']==certs[j]['radius'] for j in partners), 'disks are not exact conjugates'
    for a,b in zip(bounds,bounds[1:]):
        if a[0][1]<b[0][0]:continue
        same_exact_real=a[0][0]==a[0][1]==b[0][0]==b[0][1]
        assert same_exact_real or conjugate_pair(a,b), 'unproved real-part tie/order'
        assert a[1][1]<b[1][0], 'incorrect imaginary order'
    return certs

def expect_failure(function,*args):
    try:function(*args)
    except (AssertionError,ValueError,ZeroDivisionError):return True
    raise AssertionError('negative control was accepted')

def main():
    started=time.monotonic()
    assert sturm_count(x*x-2,QQ(1),QQ(2))==1
    assert sturm_count(x*x-2,QQ(2),QQ(3))==0
    assert sturm_count(x*x+1,QQ(-10),QQ(10))==0
    records=json.loads(Path(sys.argv[1] if len(sys.argv)>1 else BASE/'entries.json').read_text())
    anchor=json.loads(Path(sys.argv[2] if len(sys.argv)>2 else BASE/'T813-before.json').read_text())
    expected=[];groups={}
    for p in range(3,26):
        if p%2==0:continue
        for q in range(1,p):
            if q%2==1 and math.gcd(p,q)==1:
                for k in range(1,(p+1)//2):expected.append({'p':p,'q':q,'k':k})
    assert [r['params'] for r in records]==expected
    for r in records:
        groups.setdefault((int(r['params']['p']),int(r['params']['q'])),[]).append(r)
    f=poly(5,3);assert f==x*x-x+1
    assert poly(3,1)==x+1 and poly(5,1)==x*x+3*x+1
    known=certify_group(f,[{'params':{'p':5,'q':3,'k':k},'number':r['number']} for k,r in enumerate(groups[5,3],1)])
    # Known exact component and algebraic identity sqrt(3)/2.
    for rec in groups[5,3]:
        (rl,rh),(il,ih)=parse(rec['number']);assert rl==rh==QQ(1)/2
        assert sturm_count(x*x-QQ(3)/4,il,ih)==1
    assert groups[3,1][0]['number']=='-1'
    controls={}
    def check_polynomial(candidate,expected):
        assert candidate==expected, 'polynomial mismatch'
    check_polynomial(poly(5,3),x*x-x+1)
    controls['changed_coefficient']=expect_failure(check_polynomial,poly(5,3)+1,x*x-x+1)
    controls['coordinate_sign']=expect_failure(check_polynomial,poly(5,3)(-x),x*x-x+1)
    bad=[dict(r) for r in groups[5,3]];bad[0]['number']='1/2 + i * -0.8'+'0'*99
    controls['changed_root']=expect_failure(certify_group,f,bad)
    controls['missing_conjugate']=expect_failure(certify_group,f,groups[5,3][:-1])
    controls['NaN']=expect_failure(parse,'nan + i * 1')
    controls['vacuous']=expect_failure(narrow,(-QQ(10)**40,QQ(10)**40))
    certificates=[];degree_max=0;polys=[]
    for (p,q),rows in groups.items():
        f=poly(p,q);degree_max=max(degree_max,int(f.degree()))
        assert f==P(anchor['Numbers'][str(p)][str(q)]), 'anchor mismatch'
        certs=certify_group(f,rows);certificates.extend(certs)
        polys.append({'p':p,'q':q,'coefficients':[str(c) for c in f]})
        print('GROUP_CHECKED',p,q,len(rows),flush=True)
    result={'checked_entries':len(records),'total_entries':len(expected),'failures':[],
        'known_answer_control':True,'negative_control_rejected':all(controls.values()),
        'controls':controls,'presentations':len(groups),'max_degree':degree_max,
        'methods':{name:sum(c['method']==name for c in certificates) for name in ['exact rational','Sturm','Rouche']},
        'ordering':'Disjoint real projections, exact rational real components, or unique conjugate roots; imaginary projections separate ties.',
        'exact_conjugate_disks_checked':sum(c['method']=='Rouche' for c in certificates),
        'all_68_anchor_polynomials_match':True,'elapsed_seconds':time.monotonic()-started,
        'numberdb':numberdb.__version__,'python':sys.version.split()[0],
        'skill_manifest':'../20261127T124522Z-build-skills/manifest.json',
        'skill_bundle_sha256':'f20b09e3db5fd443660c0c6b29391ee369b7c710a43e22d8abb971ec3f54dd14'}
    evidence={'results':result,'certificates':certificates,'determinant_polynomials':polys}
    try:(BASE/'check-evidence.json').write_text(json.dumps(evidence,indent=2))
    except OSError:pass
    print('RESULTS '+json.dumps(evidence),flush=True)

if __name__=='__main__':main()