checks.py

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

6188 bytes, as of the version from 2026-10-31 12:22 (current). Recorded here, not run.

"""Independent checks for numberdb.org/T638.

Run: sage -python checks.py
Optional: sage -python checks.py --stored (requires draft access via API key).
Required adjacent files: moments.json, T637.json; --stored reads T638 afresh.

This checker does not import the generator. It evaluates the Fock integral
(d'Eon and McCormick, equation 52) and directly integrates H against the
angular weight, using scipy double precision rather than the phase-series
method. These checks validate normalization and coefficient extraction to
about 11 digits, not the stored 100-digit precision. The 100-digit precision
claim is separately checked by 150/200-digit computations in the generator.
"""
import json,math,sys,os,time,pathlib
import numberdb.sage as numberdb
import numpy as np
import scipy
from scipy.integrate import quad
from scipy.special import hyp2f1, roots_legendre, gamma
import mpmath as mp

HERE=pathlib.Path(__file__).resolve().parent


def log_b(d,k):
    # B=(1-K_d(k))(1+k^2)/k^2. Hypergeometric identity avoids small-k subtraction.
    if k<2:
        return math.log((1+k*k)*hyp2f1(1,1.5,d/2+1,-k*k)/d)
    inv=1/(k*k)
    if d%2==0:
        kernel=1/math.sqrt(1+k*k); start=2
    else:
        kernel=math.atan(k)/k; start=3
    for j in range(start,d,2):
        kernel=j/(j-1)*((1+inv)*kernel-inv)
    return math.log1p(-kernel)+math.log1p(inv)


def fock_h(d,mu,tolerance=2e-13):
    if mu==0: return 1.0
    integrand=lambda v: log_b(d,math.tan(v)/mu)
    val=quad(integrand,0,math.pi/2,epsabs=tolerance,epsrel=tolerance,
             points=[math.atan(mu)],limit=150)[0]
    return (1+mu)*math.exp(-val/math.pi)


def direct_moments(d,degree=64,tolerance=2e-13):
    # mu=sin(phi) removes the d=2 inverse-square-root endpoint singularity.
    nodes,weights=roots_legendre(degree)
    breaks=[0,1e-6,1e-4,0.01,0.1,math.pi/2]
    accum=np.zeros(9)
    norm=2*gamma(d/2)/(math.sqrt(math.pi)*gamma((d-1)/2))
    for a,b in zip(breaks,breaks[1:]):
        for x,w in zip((a+b)/2+(b-a)/2*nodes,(b-a)/2*weights):
            mu=math.sin(x)
            weight=w*norm*math.cos(x)**(d-2)
            h=fock_h(d,mu,tolerance)
            accum += weight*h*mu**np.arange(9)
    return accum


def read_reference(stored=False):
    if stored:
        if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':
            numberdb.configure(api_key=sys.stdin.read().strip())
        doc=numberdb.table('T638')
        out={}
        block=doc['Numbers']
        if isinstance(block,dict):
            for d,ns in block.items():
                for n,v in ns.items():
                    out[(int(d),int(n))]=v['number'] if isinstance(v,dict) else v
        else:
            for row in block:
                out[(int(row['params']['d']),int(row['params']['n']))]=row['number']
        return out
    doc=json.loads((HERE/'moments.json').read_text())
    return {(d,n):doc[str(d)]['moments'][n] for d in range(2,11) for n in range(2,9)}


def main():
    start=time.monotonic(); refs=read_reference('--stored' in sys.argv)
    assert set(refs)=={(d,n) for d in range(2,11) for n in range(2,9)}
    # Nonzero known quadrature control, before trusting numerical checks.
    control=quad(math.sin,0,math.pi/2,epsabs=1e-13)[0]
    assert abs(control-1)<1e-14
    mp.mp.dps=170
    flatland_control=float(mp.sqrt(2)*mp.exp(2*mp.catalan/mp.pi))
    controls={'sin_integral_error':abs(control-1),
              'H2_at_1_error':abs(fock_h(2,1)-flatland_control),
              'H3_at_1_published_error':abs(fock_h(3,1)-2.907810529078606)}
    assert max(controls.values())<2e-12
    print('CONTROLS',json.dumps(controls),flush=True)
    direct={}; worst=0; worst_lower=0; worst_refine=0
    for d in range(2,11):
        coarse=direct_moments(d,48,1e-12)
        fine=direct_moments(d,80,2e-13)
        errors={str(n):abs(fine[n]-float(refs[d,n])) for n in range(2,9)}
        lower=max(abs(fine[0]-2),abs(fine[1]-2/math.sqrt(d)))
        refinement=max(abs(fine-coarse))
        assert lower<1e-10 and max(errors.values())<1e-10 and refinement<1e-10
        worst=max(worst,max(errors.values()));worst_lower=max(worst_lower,lower)
        worst_refine=max(worst_refine,refinement)
        direct[str(d)]={'direct':list(fine),'errors':errors,'lower_error':lower,'refinement':refinement}
        print('DIRECT',d,json.dumps(direct[str(d)]),flush=True)
    # Independent algebraic moment identity (Busbridge), n=1,...,4,
    # and z0 relation on the reference values, including read-back values.
    t637=json.loads((HERE/'T637.json').read_text())['Numbers']
    residual=mp.mpf(0); distance=mp.mpf(0)
    for d in range(2,11):
        aa=[mp.mpf(2),2/mp.sqrt(d)]+[mp.mpf(refs[d,n]) for n in range(2,9)]
        assert all(aa[k]>aa[k+1]>0 for k in range(8))
        for j in range(1,5):
            g=mp.gamma(mp.mpf(d)/2)*mp.gamma(mp.mpf(j)+mp.mpf(1)/2)/(mp.sqrt(mp.pi)*mp.gamma(mp.mpf(d)/2+j))
            error=abs(4*g+mp.fsum((-1)**k*aa[2*j-k]*aa[k] for k in range(1,2*j)))
            residual=max(residual,error)
        z=t637[str(d)];z=z.get('number') if isinstance(z,dict) else z
        distance=max(distance,abs(mp.sqrt(d)*aa[2]/2-mp.mpf(z)))
    assert residual<mp.mpf('1e-98') and distance<mp.mpf('1e-98')
    # Two exact low-dimensional formulas and independent published 3D digits.
    closed=max(abs(mp.mpf(refs[2,2])-mp.sqrt(2)*(mp.mpf(1)/2+1/mp.pi)),
               abs(mp.mpf(refs[4,2])-2/mp.pi))
    assert closed<mp.mpf('1e-99')
    printed={2:'0.820352482149125',3:'0.637818268031518',4:'0.522227303791946'}
    published=max(abs(mp.mpf(refs[3,n])-mp.mpf(v)) for n,v in printed.items())
    assert published<mp.mpf('1e-15')
    print('SUMMARY',json.dumps({'stored':'--stored' in sys.argv,'entries':len(refs),
      'max_direct_error':worst,'max_lower_control_error':worst_lower,'max_refinement':worst_refine,
      'max_busbridge_residual':mp.nstr(residual,12),'max_distance_discrepancy':mp.nstr(distance,12),
      'max_closed_form_error':mp.nstr(closed,12),'max_published_3d_discrepancy':mp.nstr(published,12),
      'scipy':scipy.__version__,'numpy':np.__version__,'mpmath':mp.__version__,
      'seconds':time.monotonic()-start}),flush=True)

if __name__=='__main__': main()