check_periods.py

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

7357 bytes, as of the version from 2026-11-16 02:28. Recorded here, not run.

"""T722 build check, independent Euler-integral series with rigorous tails.

Run with SageMath: sage -python check_periods.py computation.json
Or supply a website document with flat Numbers records, e.g. stored.json.
This checker does not import the generator and does not evaluate Gamma/Beta.
It is build evidence, not the separate critic's scientific verdict.
"""
import numberdb.sage as numberdb
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from sage.rings.real_mpfi import RealIntervalField
from sage.rings.rational_field import QQ
from numberdb._write import _as_interval,_exact
from itertools import product
from fractions import Fraction
from decimal import Decimal
from functools import lru_cache
from collections import Counter,defaultdict
import sys,json,math,os
R=RealBallField(680);C=ComplexBallField(680);I=RealIntervalField(680)
N=600

def endpoints(x):
    t=_as_interval(x)
    # exact_rational conversion refuses infinities and NaNs.
    return _exact(t.lower()),_exact(t.upper())

def decimal_interval(s):
    s=s.strip()
    if s.startswith('['):
        lo,hi=map(Fraction,s[1:-1].split(','));return lo,hi
    d=Decimal(s);c=Fraction(d);ulp=Fraction(10)**d.as_tuple().exponent
    return c-ulp,c+ulp

def stored_parts(s):
    parts=s.split(' + i * ')
    if len(parts)!=2:raise ValueError('Expected explicit real and imaginary parts')
    return [decimal_interval(x) for x in parts]

def narrow(x,digits=120):
    for part in (x.real(),x.imag()):
        lo,hi=endpoints(part)
        if lo==hi==0:continue
        if not lo*hi>0 or not (hi-lo)*10**digits<min(abs(lo),abs(hi)):return False
    return True

def accepted(value,text):
    if not narrow(value):return False
    try:return all(wl<=lo<=hi<=wh for (wl,wh),(lo,hi) in zip(stored_parts(text),map(endpoints,(value.real(),value.imag()))))
    except Exception:return False

def half_beta(a,b):
    # Integral on [0,1/2] of t^(a-1)(1-t)^(b-1).
    # At k>=N> b, successive absolute integrated terms have ratio <1/2.
    t=R(2)**(-R(a))/R(a);s=t
    for k in range(N-1):
        t=t*R(QQ(k+1)-b)/R(k+1)*R(a+k)/R(a+k+1)/2
        s+=t
        if k+1==b:return s
    k=N-1
    following=t*R(QQ(k+1)-b)/R(k+1)*R(a+k)/R(a+k+1)/2
    bound=_as_interval(2*abs(following)).upper()
    return R(_as_interval(s)+I(-bound,bound))

@lru_cache(None)
def beta(a,b):
    assert a>0 and b>0 and N>b and N>a
    return half_beta(a,b)+half_beta(b,a)

def integral_period(n,d,a):
    ss=[QQ(k)/d for k in a];A=sum(ss);mass=R(1);partial=ss[0]
    for s in ss[1:]:
        mass*=beta(partial,s);partial+=s
    # Independent trigonometric evaluation of the deck factor.
    for s in ss:mass*=(R.pi()*R(s)).sin()
    mass/=d**(n+1)
    if 2*sum(a)%d==0:
        phase=C(0,(-1)**int(A.floor()))
    else:
        theta=R.pi()*R(A);phase=C(theta.cos(),theta.sin())
    return C(mass)*C(0,-2)**(n+1)*phase

def main():
    path=sys.argv[1] if len(sys.argv)>1 else '/work/computation.json'
    doc=json.load(open(path));records=doc.get('entries',doc.get('Numbers'))
    assert isinstance(records,list)
    bykey={(int(r['params']['n']),int(r['params']['d']),str(r['params']['a'])):r for r in records}
    failures=[];details=[];expansion=[];expected=set();counts=[];chainchecks=0
    controls={}
    for a,b,answer,name in [(QQ(1),QQ(1),R(1),'B(1,1)=1'),(QQ(1)/2,QQ(1)/2,R.pi(),'B(1/2,1/2)=pi')]:
        got=beta(a,b);delta=got-answer;lo,hi=endpoints(delta)
        controls[name]=lo<=0<=hi and endpoints(got)[1]-endpoints(got)[0]<Fraction(1,10**120)
    for n in (2,4):
        for d in range(3,7):
            tuples=[a for a in product(range(1,d),repeat=n+1) if sum(a)%d]
            reps=Counter(tuple(sorted(a)) for a in tuples)
            assert len(tuples)==((d-1)**(n+2)+(d-1))//d
            counts.append({'n':n,'d':d,'representatives':len(reps),'ordered':len(tuples)})
            for a in tuples:
                rep=tuple(sorted(a));S=sum(a)
                expansion.append([n,d,list(a),'.'.join(map(str,rep)),reps[rep],(-S)%d,S//d])
            # Exact chain/group-ring checks. Each face is fixed by its deck map.
            masks=list(product((0,1),repeat=n+1))
            coeff={b:(-1)**sum(b) for b in masks}
            for j in range(n+1):
                face=defaultdict(int);relation=defaultdict(int)
                for b,c in coeff.items():
                    face[b[:j]+b[j+1:]]+=c
                    for shift in range(d):
                        v=list(b);v[j]=(v[j]+shift)%d;relation[tuple(v)]+=c
                assert all(v==0 for v in face.values()) and all(v==0 for v in relation.values())
                chainchecks+=1
            for a in reps:
                key=(n,d,'.'.join(map(str,a)));expected.add(key)
                if key not in bykey:failures.append(['missing',key]);continue
                v=integral_period(n,d,a);ok=accepted(v,bykey[key]['number'])
                if not ok:failures.append(['containment',key,str(v)])
                if d%2==0 and all(x==d//2 for x in a):
                    known=16*R.pi()/d**3 if n==2 else 128*R.pi()**2/(3*d**5)
                    controls[str(key)+' exact-pi-control']=accepted(C(known,0),bykey[key]['number'])
                perturb=v+C(QQ(1)/10**90,QQ(1)/10**90)
                if accepted(perturb,bykey[key]['number']):failures.append(['negative perturbation accepted',key])
                if accepted(-v,bykey[key]['number']):failures.append(['wrong sign accepted',key])
                details.append({'params':list(key),'containment':bool(ok),'independent_enclosure':str(v)})
    if set(bykey)!=expected:failures.append(['identity mismatch',len(bykey),len(expected)])
    # Reduction P_(n,6)(2a)=P_(n,3)(a)/2^(n+1), directly on stored intervals.
    reductions=0
    for n,d,akey in sorted(bykey):
        if d!=3:continue
        a=list(map(int,akey.split('.')));other=(n,6,'.'.join(str(2*x) for x in a))
        for (lo,hi),(ol,oh) in zip(stored_parts(bykey[(n,d,akey)]['number']),stored_parts(bykey[other]['number'])):
            assert max(lo,ol*2**(n+1))<=min(hi,oh*2**(n+1))
        reductions+=1
    if not all(controls.values()):failures.append(['known-answer-control',controls])
    # Explicitly reject a huge finite enclosure and a nonfinite one.
    huge=C(R(I(-10**10,10**10)),0)
    controls['huge_ball_rejected']=not narrow(huge)
    try:invalid=narrow(C('nan'))
    except Exception:invalid=False
    controls['nan_rejected']=not invalid
    result={'checked_entries':len(details),'total_entries':len(records),'failures':failures,
      'known_answer_control':all(controls.values()),'negative_control_rejected':not any('negative' in str(f) or 'wrong sign' in str(f) for f in failures),
      'controls':controls,'counts':counts,'chain_relations_checked':chainchecks,'stored_reductions_checked':reductions,
      'independent_method':'Euler beta integrals split at 1/2; 600 integrated binomial terms; tail <= twice next absolute term; Arb 680 bits; trigonometric deck factors',
      'skill_manifest':'../20261116T021518Z-build-skills/manifest.json','comparisons':details,
      'ordered_expansion_columns':['n','d','ordered_a','representative_key','permutation_multiplicity','a0','q'],
      'ordered_expansion':expansion}
    print(json.dumps(result,indent=2));return 1 if failures else 0
if __name__=='__main__':sys.exit(main())