stored_check.py

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

6168 bytes, as of the version from 2026-11-19 01:06 (current). Recorded here, not run.

"""Independent T761 stored-interval checks; no generator is imported.
Run: sage -python stored_check.py (stored-document.json beside this file).
The final RESULT_JSON line contains the reproducible machine-readable report.
"""
import json,re,pathlib,platform,hashlib
from fractions import Fraction
import mpmath as mp
ROOT=pathlib.Path(__file__).resolve().parent
D=json.loads((ROOT/'stored-document.json').read_text())


def decimal_interval(text):
    text=text.strip()
    if not re.fullmatch(r'[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?',text):
        raise ValueError('unsupported stored component '+text)
    c=Fraction(text)
    if '.' not in text and 'e' not in text:return c,c
    mant,_,exp=text.partition('e')
    places=len(mant.partition('.')[2])
    ulp=Fraction(10)**(int(exp or '0')-places)
    return c-ulp,c+ulp


def rectangle(text):
    split=re.fullmatch(r'(.+?)\s+([+-])\s+i\s*\*\s*(.+)',text)
    if split:
        re_part,sign,im_part=split.groups()
        lo,hi=decimal_interval(im_part)
        if sign=='-':lo,hi=-hi,-lo
        return decimal_interval(re_part),(lo,hi)
    return decimal_interval(text),(Fraction(0),Fraction(0))


def mpq(q):
    q=Fraction(q);return mp.mpf(q.numerator)/q.denominator


def enclosed(rect,value):
    if not mp.isfinite(value):return False
    for (lo,hi),v in zip(rect,[mp.re(value),mp.im(value)]):
        if not lo<=hi or mpq(hi-lo)>mp.mpf('1e-95')*max(1,abs(v)):
            return False
        if not mpq(lo)<=v<=mpq(hi):return False
    return True


def formula(template,z,dps):
    with mp.workdps(dps):
        a=mpq({'2.2.2':Fraction(1,2),'2.3':Fraction(1,3),
                '2.4':Fraction(1,4),'2.6':Fraction(1,6)}[template]);x=mpq(z)
        if x==1:
            return mp.pi/(mp.gamma(1-a/2)*mp.gamma((1+a)/2))**2
        result=mp.hyp2f1(a/2,(1-a)/2,1,x)**2
        return mp.conj(result) if x>1 else result


def unit(q):
    q=Fraction(q)
    if not q:return False
    for n in (abs(q.numerator),q.denominator):
        for p in (2,3):
            while n%p==0:n//=p
        if n!=1:return False
    return True


def records_of(d):
    ns=d['Numbers']
    if isinstance(ns,list):return ns
    return [{'params':{'template':t,'z':z},**(record if isinstance(record,dict) else {'number':record})}
            for t,rows in ns.items() for z,record in rows.items()]


mp.mp.dps=230
rows=records_of(D)
zs=sorted({Fraction(u,v) for u in range(-9,10) for v in range(1,10)
           if unit(Fraction(u,v)) and unit(1-Fraction(u,v))}|{Fraction(1)})
expected={(t,str(z)) for t in ['2.2.2','2.3','2.4','2.6'] for z in zs}
observed={(row['params']['template'],row['params']['z']) for row in rows}
assert observed==expected and len(rows)==88
failures=[];results=[];series_count=0;elliptic_count=0
for row in rows:
    p=row['params'];t=p['template'];z=Fraction(p['z']);rect=rectangle(row['number'])
    v160=formula(t,z,160);v210=formula(t,z,210)
    ok=enclosed(rect,v160) and enclosed(rect,v210)
    if abs(v210-v160)>mp.mpf('1e-150')*max(1,abs(v210)):ok=False
    extra=[]
    a=mpq({'2.2.2':Fraction(1,2),'2.3':Fraction(1,3),'2.4':Fraction(1,4),'2.6':Fraction(1,6)}[t])
    if abs(z)<1:
        # Independently sum the defining 3F2 recurrence, without squaring 2F1.
        x=mpq(z);term=mp.mpf(1);s=term;n=0
        while True:
            term*=((n+mp.mpf('0.5'))*(n+a)*(n+1-a)*x)/(n+1)**3
            s+=term;n+=1
            if abs(term)<mp.mpf('1e-220'):break
            assert n<20000
        series_ok=enclosed(rect,s);ok=ok and series_ok
        series_count+=1;extra.append({'direct_series':series_ok,'terms':n+1})
    if t=='2.2.2':
        x=mpq(z)
        w=(1+1j*mp.sqrt(x-1))/2 if x>1 else (1-mp.sqrt(1-x))/2
        e=(2*mp.ellipk(w)/mp.pi)**2
        eok=enclosed(rect,e);ok=ok and eok;elliptic_count+=1;extra.append({'elliptic':eok})
    if not ok:failures.append(p)
    results.append({'params':p,'contained_at_160_and_210_dps':enclosed(rect,v160) and enclosed(rect,v210),
                    'precision_difference':mp.nstr(abs(v210-v160),8),'extra':extra})
# The interval checker must accept known nonzero values and reject errors.
known=enclosed(rectangle('1.25'+'0'*100),mpq(Fraction(5,4)))
negative=(not enclosed(rectangle('1.25'+'0'*100),mpq(Fraction(5,4))+mp.mpf('1e-5'))
    and not enclosed(((Fraction(0),Fraction(10)),(Fraction(0),Fraction(0))),mp.mpf(1))
    and not enclosed(rectangle('1.25'+'0'*100),mp.nan))
assert known and negative
# A conjugate is specifically a wrong answer for the declared bank.
row=next(x for x in rows if x['params']=={'template':'2.4','z':'2'})
assert not enclosed(rectangle(row['number']),mp.conj(formula('2.4',Fraction(2),210)))
# Known hypergeometric normalization and a nontrivial elementary identity.
assert mp.hyp2f1(mp.mpf('0.25'),mp.mpf('0.25'),1,0)**2==1
assert abs(mp.hyp2f1(1,1,2,mp.mpf('0.5'))-2*mp.log(2))<mp.mpf('1e-225')
# Cross-context lattice endpoint; source is T393's gamma formula, not a sibling.
bcc=mp.gamma(mp.mpf(1)/4)**4/(4*mp.pi**3)
row=next(x for x in rows if x['params']=={'template':'2.2.2','z':'1'})
assert enclosed(rectangle(row['number']),bcc)
report={'checked_entries':len(rows),'total_entries':len(rows),'failures':failures,
 'known_answer_control':known,'negative_control_rejected':negative,
 'upper_bank_conjugate_control_rejected':True,'enumeration_matches':True,
 'method':'mpmath half-parameter Clausen square at 160/210 dps; gamma endpoints; direct defining recurrence at |z|<1; elliptic and BCC controls',
 'independence':'No builder code imported; separate mpmath implementation and formula from quadratic-pullback Arb generator. Shared exact mathematical definitions and published identities.',
 'direct_series_entries':series_count,'elliptic_entries':elliptic_count,
 'versions':{'python':platform.python_version(),'mpmath':mp.__version__},'comparisons':results,
 'skill_manifest':'../20261118T213826Z-build-skills/manifest.json',
 'stored_document_sha256':hashlib.sha256((ROOT/'stored-document.json').read_bytes()).hexdigest(),
 'stored_numbers_sha256':hashlib.sha256(json.dumps(D['Numbers'],sort_keys=True).encode()).hexdigest()}
print('RESULT_JSON '+json.dumps(report),flush=True)
assert not failures