checks.py

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

6998 bytes, as of the version from 2026-10-25 06:26 (current). Recorded here, not run.

"""Independent checks of scaling dimensions -- numberdb.org/T475.

    sage -python checks.py                 # offline, using generator values
    sage -python checks.py --stored        # use database values; requires key
    sage -python checks.py --stored --key-stdin

Run beside generate.py, check.py, sources.json and optionally T472.json.
With --stored, both T475 and T472 are read afresh through NumberDB's API.
Without --stored, T472.json is a saved API snapshot, if present.
No bootstrap or Monte Carlo computation is repeated. Monte Carlo results from
separate primary papers provide independent numerical consistency checks.
"""
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_mpfi import RealIntervalField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from fractions import Fraction
from pathlib import Path
import json
import os
import re
import sys
from check import exactness, measure, names_its_rings, agrees_with, prose
from generate import ScalingDimensionsON

R = RealIntervalField(256)


def rational(text):
    value = Fraction(text)
    return QQ(value.numerator) / QQ(value.denominator)


def interval(text):
    centre, radius = map(rational, text.split(' +/- '))
    assert 0 < radius < QQ(1) / 100
    return R(centre - radius, centre + radius)


def parenthetical(text):
    centre, uncertainty = re.fullmatch(r'(\d+\.\d+)\((\d+)\)', text).groups()
    c = rational(centre)
    r = QQ(uncertainty) / QQ(10)**len(centre.split('.')[1])
    return c-r, c+r


def endpoints(text):
    c, r = map(rational, text.split(' +/- '))
    return c-r, c+r


def finite_narrow(value, width=QQ(1)/50):
    assert value.lower() > -100 and value.upper() < 100
    assert 0 <= value.upper() - value.lower() < width


def overlap(a, b):
    finite_narrow(a)
    finite_narrow(b)
    return max(a.lower(), b.lower()) <= min(a.upper(), b.upper())


def exponents(phi, singlet):
    return dict(nu=1/(3-singlet), eta=2*phi-1,
                beta=phi/(3-singlet), gamma=(3-2*phi)/(3-singlet),
                delta=(3-phi)/phi, alpha=2-3/(3-singlet))


def residuals(e):
    a,b,g,d,n,h = (e[x] for x in ('alpha','beta','gamma','delta','nu','eta'))
    return [a+2*b+g-2, g-b*(d-1), g-n*(2-h), 2-a-3*n, a+b*(1+d)-2]


def assert_relations(e):
    for residual in residuals(e):
        finite_narrow(residual)
        assert 0 in residual


def controls():
    # A point at a known rational and an interval with known transformed ends.
    assert parenthetical('1.2345(67)') == (QQ(12278)/10000, QQ(12412)/10000)
    a = R(QQ(1)/2, QQ(3)/4)
    b = 3 - 1/a
    assert b.lower() == 1
    assert b.upper() >= QQ(5)/3 and b.upper()-QQ(5)/3 < QQ(1)/10**70
    assert (1+R(0))/2 == R(QQ(1)/2)
    assert not overlap(R(1), R(2))
    try:
        finite_narrow(R(-10,10))
    except AssertionError:
        pass
    else:
        raise AssertionError('wide-interval control was not rejected')
    expected = dict(nu=QQ(1), eta=QQ(0), beta=QQ(1)/2,
                    gamma=QQ(2), delta=QQ(5), alpha=QQ(-1))
    assert exponents(QQ(1)/2, QQ(2)) == expected
    for r in residuals(expected):
        assert r == 0
    # Exact rational-function proof, independent of the stored parameter values.
    field = PolynomialRing(QQ, names=('p','s')).fraction_field()
    p,s = field.gens()
    assert all(r == 0 for r in residuals(exponents(p,s)))
    print('PASS: rational controls, disjoint/wide controls, five symbolic scaling relations')


def run(values, comparison=None):
    controls()
    g = ScalingDimensionsON()
    assert not names_its_rings(str(Path(__file__).with_name('generate.py')))
    assert not exactness(values)
    assert not prose(values)
    sources = json.loads(Path(__file__).with_name('sources.json').read_text())
    source_numbers = {(r['class'],r['operator']):r['quoted'] for r in sources['bootstrap']}
    assert set(values) == set(source_numbers)
    assert not agrees_with({k:endpoints(v['number']) for k,v in values.items()},
                           lambda key: parenthetical(source_numbers[key]))
    # This comparison uses input exponents from independent Monte Carlo work,
    # not the dimension centres in the generator or the bootstrap papers.
    mc = sources['monte_carlo']
    reports = []
    for cls in ('xy','heisenberg'):
        data = {op:interval(values[(cls,op)]['number']) for op in ('phi','s','t')}
        nu = R(*parenthetical(mc[cls]['nu']))
        eta = R(*parenthetical(mc[cls]['eta']))
        y2 = R(*parenthetical(mc[cls]['Y2']))
        independent = dict(phi=(1+eta)/2, s=3-1/nu, t=3-y2)
        for op in ('phi','s','t'):
            assert data[op].lower() > QQ(1)/2
            assert data[op].upper() < 3
            assert overlap(data[op], independent[op]), (cls,op)
            reports.append({'class':cls,'operator':op,
                            'stored':values[(cls,op)]['number'],
                            'monte_carlo_dimension_bounds':[
                                str(independent[op].lower()),str(independent[op].upper())],
                            'overlap':True})
        assert data['phi'].upper() < data['t'].lower() < data['s'].lower()
        e = exponents(data['phi'],data['s'])
        assert_relations(e)
        if comparison:
            ce = {k:interval(comparison['Numbers'][cls][k]['number']) for k in e}
            assert_relations(ce)
            for name in e:
                assert overlap(e[name],ce[name]), (cls,name)
        print('PASS:',cls,'three Monte Carlo overlaps and five interval scaling relations')
    print('PASS: all six conservative source intervals transcribed exactly')
    if comparison:
        print('PASS: twelve leading exponents overlap T472; its ten scaling residuals contain zero')
    print('SIZE:',json.dumps(measure(values)))
    print('EVIDENCE:',json.dumps(reports))


if __name__ == '__main__':
    reading = '--stored' in sys.argv or os.environ.get('NUMBERDB_CHECK_STORED') == '1'
    # NUMBERDB_PUBLISH is only interpreted by this checking script as read-back.
    reading = reading or os.environ.get('NUMBERDB_PUBLISH') == '1'
    if reading:
        if '--key-stdin' in sys.argv or os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
            client = numberdb.Client(api_key=sys.stdin.read().strip())
        else:
            client = numberdb.Client()
        document = numberdb.table('T475',client=client)
        values = {(cls,op):v for cls,group in document['Numbers'].items() for op,v in group.items()}
        comparison = numberdb.table('T472',client=client)
        print('Checking values read back from T475 and T472')
    else:
        g = ScalingDimensionsON()
        values = {(p['class'],p['operator']):g.value(p,g.digits) for p in g.enumerate()}
        path = Path(__file__).with_name('T472.json')
        comparison = json.loads(path.read_text()) if path.exists() else None
        print('Checking generated values without writing')
    run(values,comparison)