checks.py

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

12339 bytes, as of the version from 2026-11-16 21:12 (current). Recorded here, not run.

"""T727 build validation, not an independent scientific verdict.

sage -python checks.py                 # full offline mathematical checks
NUMBERDB_CHECK_STORED=1 sage -python checks.py  # authenticated readback

Download generate.py, hardy_arb.pyx, check.py, argument-selection.md and
skill-manifest.json beside this file. prefix-checkpoint.json and
prefix-provenance.json preserve the reusable finite indexing certificate. Uses Sage,
FLINT and mpmath. Emits checkpoint JSON records and a final EVIDENCE_JSON.
Root enclosures and all stored 100-digit intervals are compared with mpmath
Hardy derivatives at 130 and 165 digits; Cauchy contour extraction checks a
risk-based subset with an analytic complex extension. None of the mpmath or
contour comparisons is claimed as a rigorous enclosure. The FLINT computation
and serialization supply the proven interval bounds.
"""
import os,sys,json,time,hashlib,platform
from pathlib import Path
from decimal import Decimal
from math import factorial
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.env import SAGE_VERSION
import mpmath as mp
from generate import bridge,compute_zero,pair_value,endpoint_f,HardyZPreSchwarzianCondition,ZERO_INDICES,PAIR_INDICES,WORKING_GUARD
from check import exactness,exact_in_disguise,measure,names_its_rings
from numberdb._write import to_text
from numberdb._generate import _stored_entries

def rational(text):
    return QQ(str(Decimal(str(text)))) if '/' in str(text) else _decimal_rational(str(text))

def _decimal_rational(text):
    dec=Decimal(text); sign,digits,exponent=dec.as_tuple()
    integer=int(''.join(map(str,digits)) or '0')*(-1 if sign else 1)
    return QQ(integer)*QQ(10)**exponent

def interval(text):
    text = str(text).strip()
    if '+/-' in text:
        center, radius = text.strip('[]').split('+/-')
        a, r = _decimal_rational(center.strip()), _decimal_rational(radius.strip())
        return a-r, a+r
    if text.startswith('['):
        lo,hi = text.strip('[]').split(',')
        return _decimal_rational(lo.strip()),_decimal_rational(hi.strip())
    # A decimal has an implicit one-last-place radius.
    dec=Decimal(text); center=_decimal_rational(text)
    unit=QQ(10)**dec.as_tuple().exponent
    return center-unit,center+unit

def inside(value,text):
    lo,hi=interval(text)
    if hasattr(value,'is_finite'):
        return value.is_finite() and value>lo and value<hi
    return lo<value<hi

def mp_pair(a,b,derivatives):
    terms=[]
    for x in (a,b):
        d1,d2,d3=derivatives[x]
        terms.append(-d3/d1+(d2/d1)**2)
    return (b-a)**2*sum(terms)/3-2

def main():
    start=time.monotonic(); rows=[]; controls=[]; counts=[]
    R=RealBallField(600)
    ev={'table':'T727','stage':'build','versions':{'python':platform.python_version(),'sage':SAGE_VERSION,'flint':bridge().flint_version(),'mpmath':mp.__version__,'numberdb':numberdb.__version__},'skill_manifest':'../20261116T204524Z-build-skills/manifest.json','working_guard_bits':WORKING_GUARD,'mpmath_dps':[130,165],'rows':rows,'controls':controls,'counts':counts,'failures':[]}
    # Independently derive exact polynomial controls rather than use rounded oracles.
    P=PolynomialRing(QQ,'t');t=P.gen()
    for f,expected in [(t*(t-1),QQ(2)/3),(t*(t-1)*(t-3),QQ(28)/27)]:
        ds=[tuple(f.derivative(k)(x) for k in [1,2,3]) for x in [0,1]]
        got=sum(-v[2]/v[0]+(v[1]/v[0])**2 for v in ds)/3-2
        assert got==expected
        wrong_coefficient=sum(-v[2]/v[0]+QQ(3)/4*(v[1]/v[0])**2 for v in ds)/3-2
        assert wrong_coefficient!=expected
        # A wrong factorial/taylor conversion and wrong coefficient must be detected.
        wrong=sum(-(v[2]/6)/v[0]+QQ(3)/4*((v[1]/2)/v[0])**2 for v in ds)/3-2
        assert wrong!=expected
        controls.append({'polynomial':str(f),'expected':str(expected),'result':str(got),'wrong_factorials_rejected':True,'wrong_coefficient_rejected':True})
    assert bridge().count(0,128)==0 and bridge().count(20,128)==1
    c=bridge().jet(R(0),4,500)
    assert c[0].real().overlaps(R(QQ(1)/2).zeta()) and -2<c[0].real()<-1
    assert c[1].contains_zero() and c[3].contains_zero()
    controls.append({'hardy_origin':'Z(0)=zeta(1/2) in (-2,-1); odd derivatives zero','count_control':'N(0)=0,N(20)=1'})
    # All critical-line roots through the largest endpoint, not a truncated neighbor count.
    print('certifying complete finite prefix through zero 6712',flush=True)
    checkpoint = Path(__file__).with_name('prefix-checkpoint.json')
    if checkpoint.exists():
        saved = json.loads(checkpoint.read_text())['roots']
        from sage.rings.complex_arb import ComplexBallField
        C = ComplexBallField(96)
        prefix = [C(QQ(1)/2, RealBallField(96)(x.split('[',1)[1].rsplit(']',1)[0])) for x in saved]
        assert len(prefix)==6712
        print('resuming certified root enclosures from preserved checkpoint',flush=True)
    else:
        prefix=bridge().zero_prefix(6712,96)
    previous=R(0)
    for root in prefix:
        assert root.real()==QQ(1)/2 and root.imag().is_finite() and root.imag()>previous
        previous=root.imag()
    nextroot=bridge().zero(6713,96).imag()
    cutoff=(previous.center().exact_rational()+nextroot.center().exact_rational())/2
    assert previous<cutoff<nextroot
    assert bridge().count(cutoff,128)==6712
    rootstrings=[str(x) for x in prefix]
    print('prefix root-list SHA-256',hashlib.sha256('\n'.join(rootstrings).encode()).hexdigest(),flush=True)
    ev['finite_indexing_certificate']={'reuse':'Certified FLINT prefix enclosures from the family input artifact; ordering, overlap and total counting rechecked in this build; see prefix-provenance.json','critical_line_distinct_roots':6712,'root_precision_bits':96,'N_at_cutoff':6712,'cutoff':str(cutoff),'last_root':str(previous),'next_root':str(nextroot),'root_list_sha256':hashlib.sha256('\n'.join(rootstrings).encode()).hexdigest(),'conclusion':'All nontrivial zeros below the cutoff are these distinct critical-line roots and are simple, by counting with multiplicity.'}
    print('finite prefix certificate complete',flush=True)
    selected=list(range(1,101))+list(range(6707,6712))
    assert tuple(selected)==PAIR_INDICES
    assert list(HardyZPreSchwarzianCondition().enumerate())==[{'n':str(n)} for n in selected]
    endpoints=sorted(set(selected)|{n+1 for n in selected})
    t3=_stored_entries(numberdb.table('T3')); t584=_stored_entries(numberdb.table('T584'))
    companion=_stored_entries(numberdb.table('T726')) if os.environ.get('NUMBERDB_API_KEY') else None
    native={};gammas={};texts={};minbits=10000
    for n in endpoints:
        gamma,d=compute_zero(n,100);gammas[n]=gamma
        assert gamma.overlaps(prefix[n-1].imag())
        assert d[0]*(-1)**(n+1)>0
        if n<=101: assert inside(gamma,t3[str(n)])
        if n<=100 or n in [6709,6710]:
            for k in [1,2,3]: assert inside(d[k-1],t584[f'{n},{k}'])
        gammah,dh=compute_zero(n,120)
        assert gamma.overlaps(gammah)
        for v,vh in zip(d,dh): assert v.overlaps(vh) and v.is_finite() and vh.is_finite()
        center=gamma.center().exact_rational(); delta=QQ(1)/10**6
        assert bridge().count(center-delta,128)==n-1 and bridge().count(center+delta,128)==n
        counts.append({'n':n,'left_count':n-1,'right_count':n,'offset':'1/1000000'})
        # Save exact bounds for root/derivative checkpoints, not just midpoints.
        print('ZERO_JSON '+json.dumps({'n':n,'gamma':str(gamma),'derivatives':list(map(str,d))}),flush=True)
    stored=None
    if os.environ.get('NUMBERDB_CHECK_STORED')=='1':
        stored=_stored_entries(numberdb.table('T727'))
        assert list(stored)==list(map(str,selected))
    for n in selected:
        v=pair_value(n,100);vh=pair_value(n,120)
        assert v.overlaps(vh) and vh.accuracy()>400
        assert type(v).__name__=='RealBall'
        text=stored[str(n)] if stored is not None else to_text(v,100)
        assert inside(v,text) and inside(vh,text)
        native[str(n)]=v;texts[n]=text;minbits=min(minbits,int(v.accuracy()))
        a,da=compute_zero(n,100);b,db=compute_zero(n+1,100)
        aval=(b-a)**2*sum(-d[2]/d[0]+QQ(3)/4*(d[1]/d[0])**2 for d in [da,db])/3-2
        difference=(b-a)**2*sum((d[1]/d[0])**2 for d in [da,db])/12
        assert difference>0 and (v-aval-difference).contains_zero()
        if companion is not None: assert inside(aval,companion[str(n)])
        rows.append({'n':n,'number':text,'ball':str(v),'accuracy_bits':int(v.accuracy())})
    assert not exactness(native) and not exact_in_disguise(native) and not names_its_rings(str(Path(__file__).with_name('generate.py')))
    assert not inside(native['1']+QQ(1)/10**90,texts[1])
    assert not inside(native['2'],texts[1])
    controls.append({'perturbation':'value(n=1)+1e-90','rejected':True,'wrong_pair_index_rejected':True})
    # mpmath's independent zeta/log-gamma implementation at two precisions.
    for dps in [130,165]:
        with mp.workdps(dps):
            zs={}; ds={}
            for n in endpoints:
                z=mp.im(mp.zetazero(n));zs[n]=z
                assert abs(_decimal_rational(mp.nstr(z,dps))-gammas[n])<R(10)**(-120)
                ds[z]=tuple(mp.siegelz(z,derivative=k) for k in [1,2,3])
            for row in rows:
                n=row['n'];v=mp_pair(zs[n],zs[n+1],ds)
                assert inside(_decimal_rational(mp.nstr(v,dps)),texts[n])
                row[f'mpmath_{dps}dps']=mp.nstr(v,dps)
            print('MPMATH_JSON '+json.dumps({'dps':dps,'rows':[{k:v for k,v in row.items() if k in ['n',f'mpmath_{dps}dps']} for row in rows]}),flush=True)
        print(f'all 105 mpmath comparisons at {dps} dps complete; {time.monotonic()-start:.1f}s',flush=True)
    # Cauchy coefficients use analytic log-gamma at BOTH arguments, never abs(Gamma).
    sample=[1,34,100,6707,6708,6709,6710,6711]
    contour_endpoints=sorted(set(sample)|{n+1 for n in sample})
    contour=[]
    for dps,N in [(130,96),(165,128)]:
        with mp.workdps(dps):
            radius=mp.mpf(1)/4; cj={};zz={}
            def analytic_Z(z):
                theta=(mp.loggamma(mp.mpf(1)/4+mp.j*z/2)-mp.loggamma(mp.mpf(1)/4-mp.j*z/2))/(2*mp.j)-z*mp.log(mp.pi)/2
                return mp.exp(mp.j*theta)*mp.zeta(mp.mpf(1)/2+mp.j*z)
            for n in contour_endpoints:
                z=mp.im(mp.zetazero(n));zz[n]=z
                samples=[analytic_Z(z+radius*mp.exp(2*mp.pi*mp.j*j/N)) for j in range(N)]
                deriv=[]
                for k in [1,2,3]:
                    v=factorial(k)*sum(samples[j]*mp.exp(-2*mp.pi*mp.j*j*k/N) for j in range(N))/(N*radius**k)
                    assert abs(mp.im(v))<mp.mpf(10)**(-115)
                    deriv.append(mp.re(v))
                cj[z]=tuple(deriv)
            for n in sample:
                v=mp_pair(zz[n],zz[n+1],cj)
                assert inside(_decimal_rational(mp.nstr(v,dps)),texts[n])
                record={'n':n,'dps':dps,'points':N,'radius':'1/4','value':mp.nstr(v,dps)}
                contour.append(record)
                print('CONTOUR_JSON '+json.dumps(record),flush=True)
        print(f'Cauchy subset {dps}dps/{N} points complete; {time.monotonic()-start:.1f}s',flush=True)
    assert inside(native['34'],'1.08') and inside(native['6709'],'0.67')
    ev.update({'total_entries':105,'checked_entries':105,'known_answer_control':True,'negative_control_rejected':True,'minimum_value_accuracy_bits':minbits,'native_return_type':'sage.rings.real_arb.RealBall','contour_checks':contour,'contour_pair_indices':sample,'size':measure(texts),'stored_values_read_back':stored is not None,'corpus_comparison':'All 101 overlapping T3 roots and 306 overlapping T584 signed derivatives contained in their recorded intervals','seconds':time.monotonic()-start})
    ev['source_sha256']={x:hashlib.sha256(Path(__file__).with_name(x).read_bytes()).hexdigest() for x in ['generate.py','hardy_arb.pyx','checks.py','check.py','argument-selection.md','skill-manifest.json']}
    print('EVIDENCE_JSON '+json.dumps(ev,sort_keys=True),flush=True)

if __name__=='__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1': os.environ['NUMBERDB_API_KEY']=sys.stdin.read().strip()
    main()