check_values.py

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

9855 bytes, as of the version from 2026-12-02 04:36 (current). Recorded here, not run.

"""Builder's independent-formula checks; no independent-actor verdict.

Run with Sage alongside generate.py and optionally stored-check.json (a read-back snapshot
with a check_records list of flat params/number records). Writes check-results.json and prints CHECK_JSON.

Uses DLMF 23.9.1-5 and 23.5.4 with exact recurrence factors. Integrating
zeta=sigma'/sigma gives sigma(w)=w*exp(-sum G_4j*w^(4j)/(4j)).
Square symmetry eliminates other powers. Center to |Re w|,|Im w|<=1/2,
then restore the full-period multiplier. For J=200, the omitted logarithm
has modulus <=10*rho^(J+1)/(4*(J+1)*(1-rho)), rho=|w|^4<=1/4.
The bound follows from |G_4j|<=sum_{v!=0}|v|^-4<=8*zeta(3)<10:
max-norm shell k has 8*k points with |v|>=k; zeta(3)<5/4 follows by
bounding its tail from k=3 by integral_2^infinity x^-3 dx.
An independent proof of the recurrence follows by coefficient comparison
in wp''=6*wp^2-g2/2, with c2=g2/20, c3=g3/28.
The analytic logarithm of sigma(w)/w is zero at w=0; no branch is chosen
numerically. A complex box enclosing a disk of the tail radius is added
before exponentiation. The library and checker share Arb primitives.
"""
import json,re,sys,platform,subprocess
from pathlib import Path
from math import gcd
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from generate import SquareLatticeSigma
from numberdb._write import to_text

R=RealBallField(640);C=ComplexBallField(640);I=C(0,1);J=200
G=[]

def coefficients():
    if G:return G
    g2=R(QQ(1)/4).gamma()**8/(16*R.pi()**2)
    c=[R(0) for _ in range(2*J+1)];c[2]=g2/20
    for n in range(4,2*J+1,2):
        c[n]=(QQ(3)/((2*n+1)*(n-3)))*sum((c[m]*c[n-m] for m in range(2,n-1,2)),R(0))
    G.extend(c[2*j]/(4*j-1) for j in range(1,J+1))
    assert all(t.is_finite() and R(t.rad())<R(10)**-175 for t in G)
    return G

def multiplier(w,m,n):
    return (-1 if (m+n+m*n)%2 else 1)*(R.pi()*(m-I*n)*(w+(m+I*n)/2)).exp()

def independent(x,y):
    x,y=QQ(x),QQ(y)
    # floor(v+1/2) also handles negative and translated controls.
    m=int((x+QQ(1)/2).floor());n=int((y+QQ(1)/2).floor())
    u,v=x-m,y-n;w=C(u,v);rho=(u*u+v*v)**2
    assert rho<=QQ(1)/4
    tail=QQ(10)*rho**(J+1)/(4*(J+1)*(1-rho))
    h=C(0);power=w**4;step=power
    for j,g in enumerate(coefficients(),1):
        h-=g*power/(4*j);power*=step
    e=R(0).add_error(R(tail));h+=C(e,e)
    return w*h.exp()*multiplier(w,m,n),tail

def parts(text):
    from fractions import Fraction
    t=re.sub(r'\s+','',text).replace('?', '')
    def component(s):
        if not s:return (QQ(0),QQ(0))
        if '+/-' in s:
            mid,rad=s.split('+/-');m=Fraction(mid);r=Fraction(rad)
            return QQ((m-r).numerator)/(m-r).denominator,QQ((m+r).numerator)/(m+r).denominator
        if s.startswith('[') and s.endswith(']'):
            lo,hi=s[1:-1].split(',')
            return tuple(QQ(Fraction(t).numerator)/Fraction(t).denominator for t in (lo,hi))
        f=Fraction(s);q=QQ(f.numerator)/f.denominator
        if '.' not in s and 'e' not in s.lower():return (q,q)
        mant,_,exp=s.lower().partition('e');places=len(mant.partition('.')[2])
        unit=QQ(10)**(int(exp or '0')-places)
        return q-unit,q+unit
    if 'i*' not in t:return component(t),(QQ(0),QQ(0))
    a,b=t.split('i*');sign=-1 if a.endswith('-') else 1
    real=a[:-1] if a.endswith(('+','-')) else a
    lo,hi=component(b)
    imag=(lo,hi) if sign==1 else (-hi,-lo)
    return component(real),imag

def finite_narrow(z,threshold=110):
    return bool(all(t.is_finite() for t in (z.real(),z.imag())) and all(R(t.rad())<R(10)**(-threshold) for t in (z.real(),z.imag())))

def match(a,b):
    return finite_narrow(a) and finite_narrow(b) and bool(a.overlaps(b))

def number_of(v):
    return v['number'] if isinstance(v,dict) else v

def run(document=None):
    gen=SquareLatticeSigma();planned=list(gen.enumerate())
    # Independent arithmetic enumeration: exact additive order of each lift.
    keys=[];counts={}
    for N in range(2,9):
        for a in range(N):
            for b in range(N):
                order=next(k for k in range(1,N+1) if (k*a)%N==0 and (k*b)%N==0)
                if order==N:keys.append((N,a,b))
        counts[str(N)]=sum(k[0]==N for k in keys)
    assert keys==[tuple(p[k] for k in ('N','a','b')) for p in planned]
    assert list(counts.values())==[3,8,12,24,24,48,48]
    if document is not None:
        # Flattening happens outside Sage; see offline.py/readback_check.py.
        rows=document['check_records']
        assert [tuple(int(p['params'][k]) for k in ('N','a','b')) for p in rows]==keys
    else:
        rows=[dict(params=p,number=to_text(number_of(gen.value(p,100)),100)) for p in planned]
    failures=[];comparisons=[];maxprod=R(0);maxcheck=R(0);maxtail=QQ(0)
    for row,key in zip(rows,keys):
        N,a,b=key;p=dict(zip(('N','a','b'),key));prod=number_of(gen.value(p,100))
        check,tail=independent(QQ(a)/N,QQ(b)/N)
        bounds=parts(row['number'])
        contained=finite_narrow(check) and all(QQ(lo)<=v.lower().exact_rational() and v.upper().exact_rational()<=QQ(hi) for (lo,hi),v in zip(bounds,(check.real(),check.imag())))
        # Exact zero components are proved independently; the checker may have
        # a harmless tiny radius there. Confirm the stored singleton exactly.
        if a==0 or (N==4 and (a,b)==(1,3)):
            contained=finite_narrow(check) and bounds[0]==(0,0) and check.real().contains_zero() and QQ(bounds[1][0])<=check.imag().lower().exact_rational() and check.imag().upper().exact_rational()<=QQ(bounds[1][1])
        if b==0 or (N==4 and (a,b)==(3,1)):
            contained=finite_narrow(check) and bounds[1]==(0,0) and check.imag().contains_zero() and QQ(bounds[0][0])<=check.real().lower().exact_rational() and check.real().upper().exact_rational()<=QQ(bounds[0][1])
        good=bool(contained and match(C(prod),check))
        if not good:failures.append('Failed '+str(key))
        for t in (prod.real(),prod.imag()): maxprod=max(maxprod,R(t.rad()))
        for t in (check.real(),check.imag()):maxcheck=max(maxcheck,R(t.rad()))
        maxtail=max(maxtail,tail)
        comparisons.append({'key':list(key),'contained':bool(contained),'overlaps':bool(C(prod).overlaps(check)),'checker_ball':str(check),'stored':row['number'],'tail_bound':str(tail)})
    W=R(2)**(QQ(5)/4)*R.pi().sqrt()*(R.pi()/8).exp()/R(QQ(1)/4).gamma()**2
    half=independent(QQ(1)/2,0)[0]
    small=QQ(1)/10**30;derivative=independent(small,0)[0]/small
    controls={'zero':bool(independent(0,0)[0].is_zero()),'half_period_gamma':match(half,C(W)),
        'imaginary_half_period':match(independent(0,QQ(1)/2)[0],I*W),
        'source_prefix':bool(R(QQ(4749493799)/10**10)<half.real()<R(QQ(4749493800)/10**10)),
        'derivative_at_zero':bool((derivative-C(1)).abs()<R(10)**-115)}
    # Check both algorithms at non-axis, half-period and boundary inputs.
    for x,y in [(QQ(1)/2,0),(QQ(1)/3,QQ(2)/3),(QQ(7)/8,QQ(5)/8)]:
        z=C(x,y);f=independent(x,y)[0];name=str((x,y))
        controls[name+' oddness']=match(independent(-x,-y)[0],-f)
        controls[name+' conjugation']=match(independent(x,-y)[0],f.conjugate())
        controls[name+' rotation']=match(independent(-y,x)[0],I*f)
        for m,n in [(1,0),(0,1),(1,1),(-1,1)]:
            controls[name+' translate '+str((m,n))]=match(independent(x+m,y+n)[0],multiplier(z,m,n)*f) and match((z+m+I*n).elliptic_sigma(I),multiplier(z,m,n)*C(z.elliptic_sigma(I)))
    z=C(QQ(1)/3,QQ(2)/3);true=independent(QQ(1)/3,QQ(2)/3)[0];lib=z.elliptic_sigma(I)
    wrong={'doubled_periods':2*(z/2).elliptic_sigma(I),'period_pi_misread':(z/R.pi()).elliptic_sigma(I),
      'missing_exponential':lib*(-R.pi()*z*z/2).exp(),'flipped_imaginary':lib.conjugate(),
      'unjustified_periodicity':(z+1).elliptic_sigma(I),'corrupt_90th_digit':lib+C(R(10)**-90),
      'nan':C('nan'),'vacuous_ball':C(R('0 +/- 10'),R('0 +/- 10'))}
    rejected={k:not match(v,true) for k,v in wrong.items()}
    if not all(controls.values()):failures.append('Known-answer/symmetry control failed')
    if not all(rejected.values()):failures.append('Negative control accepted')
    versions={'python':platform.python_version(),'numberdb':numberdb.__version__}
    from sage.env import SAGE_VERSION
    versions['sage']=SAGE_VERSION
    for n in ['flint','mpfr','gmp']:
        try:
            p=subprocess.run(['pkg-config','--modversion',n],capture_output=True,text=True)
            if p.returncode==0:versions[n]=p.stdout.strip()
        except FileNotFoundError:pass
    return {'checked_entries':len(rows),'total_entries':167,'failures':failures,
        'known_answer_control':all(controls.values()),'negative_control_rejected':all(rejected.values()),
        'counts_by_order':counts,'controls':controls,'negative_controls_rejected':rejected,
        'maximum_production_component_radius':str(maxprod),'maximum_checker_component_radius':str(maxcheck),
        'maximum_log_tail_bound':str(maxtail),'comparisons':comparisons,'versions':versions,
        'method':'512-bit FLINT theta production versus 640-bit Gamma-invariant Laurent recurrence, J=200 and rigorously bounded log tail; all exact-order lifts.',
        'independence':'Different formula and implementation; shared Arb primitives and classical lattice normalization. Builder evidence, not independent-actor verdict.',
        'skill_manifest':'agents/runs/20261202T040331Z-build-skills/manifest.json'}

if __name__=='__main__':
    path=Path(__file__).with_name('stored-check.json')
    result=run(json.loads(path.read_text()) if path.exists() else None)
    Path(__file__).with_name('check-results.json').write_text(json.dumps(result,indent=2))
    print('CHECK_JSON='+json.dumps(result,sort_keys=True))
    sys.exit(bool(result['failures']))