checks.py

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

9306 bytes, as of the version from 2026-11-28 10:26 (current). Recorded here, not run.

"""Independent angular subtraction check for unit-ball Dirichlet determinants.

sage -python checks.py [--stored document.json] [--output check-results.json]

This reconstructs BGEK (4.7)-(4.13), without the reduced coefficients in
generate.py: exact Debye recurrence and cumulants, the derivatives of all
analytic asymptotic terms, and an absolutely convergent log-Gamma remainder.
For d=2 the nu=0 Bessel sector is separated explicitly. For d=1 the spectral
zeta is (2/pi)^(2s)*zeta(2s). The residual angular sum is split at K=80;
its tail is summed by Hurwitz zeta and the positive-real Stirling remainder
is bounded by the first omitted term, with absolute multiplicity coefficients.
This is mathematically the subtracted contour/log-Gamma representation, evaluated
by a rigorously bounded series instead of numerical endpoint quadrature.
It shares BGEK's spectral analysis with the closed forms, but recomputes the
angular regularization and never reads the generator's coefficient table.
"""
import argparse, json, pathlib, time
from decimal import Decimal
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.arith.misc import bernoulli, factorial

BITS=500
R=RealBallField(BITS); C=ComplexBallField(BITS)
P=PolynomialRing(QQ,'t'); t=P.gen()


@lru_cache(maxsize=None)
def debye(nmax):
    u=[P(1)]; D=[P(0)]
    for n in range(1,nmax+1):
        prev=u[-1]
        integrand=(1-5*t*t)*prev
        u.append(t*t*(1-t*t)*prev.derivative()/2+integrand.integral()/8)
        D.append(u[n]-sum(QQ(k)/n*D[k]*u[n-k] for k in range(1,n)))
    return tuple(D)


def angular(d):
    if d==2:return QQ(1),P(2)
    a=QQ(d-2)/2
    # h=(2l+d-2)/(d-2)! times (l+1)...(l+d-3), l=nu-a.
    h=2*t
    for j in range(1,d-2):h*=t-a+j
    return a,h/factorial(d-2)


def hz(s,a):return C(s).zeta(C(a)).real()


def hzd(s,a):
    # The starting a is integral or half-integral; reduce its derivative to
    # independent Hurwitz/Riemann shift identities, with exact rational shifts.
    if a.denominator()==1:
        m=int(a)
        return C(s).zetaderiv(1).real()+sum(R(k).log()*R(k)**(-s) for k in range(1,m))
    m=int(a-QQ(1)/2)
    base=(R(2)**s-1)*C(s).zetaderiv(1).real()+R(2)**s*R(2).log()*C(s).zeta().real()
    return base+sum(R(QQ(k)+QQ(1)/2).log()*R(QQ(k)+QQ(1)/2)**(-s) for k in range(m))


def angular_remainder(d,a,h,D,K=80,M=100):
    N=d-1
    value=R(0)
    for j in range(K):
        v=R(a+j)
        term=C(v+1).log_gamma().real()+v-(v+R(QQ(1)/2))*v.log()-(2*R.pi()).log()/2
        term+=sum(R(D[n](1))/v**n for n in range(1,N+1))
        value+=R(h(a+j))*term
    b=a+K
    for k in range((N+1)//2+1,M):
        coeff=bernoulli(2*k)/(ZZ(2*k)*ZZ(2*k-1))
        value+=R(coeff)*sum(R(h[alpha])*hz(2*k-1-alpha,b) for alpha in range(h.degree()+1) if h[alpha])
    coeff=abs(bernoulli(2*M)/(ZZ(2*M)*ZZ(2*M-1)))
    bound=R(coeff)*sum(R(abs(h[alpha]))*hz(2*M-1-alpha,b) for alpha in range(h.degree()+1) if h[alpha])
    assert bound>0 and bound<R(10)**(-150)
    return value+R(0,bound.upper()),bound


def contour_derivative(d):
    a,h=angular(d); D=debye(d-1)
    e=h.list(); log2=R(2).log()
    # A_-1 and A_0 at mass zero (BGEK 4.10-4.11).
    asym=sum(R(e[alpha])*((log2-1)*hz(-1-alpha,a)-hzd(-1-alpha,a)-hzd(-alpha,a)/2)
             for alpha in range(len(e)) if e[alpha])
    # A_i: 1/Gamma(s)=s+gamma*s^2+...; at i-alpha=1,
    # zeta_H(1+2s,a)=1/(2s)-psi(a)+..., so the pole must be removed.
    gamma=R.euler_constant()
    for i in range(1,d):
        coeff=D[i](1)
        for alpha in range(len(e)):
            if not e[alpha]:continue
            if i-alpha==1:
                psi_a=C(a).psi().real()
                weighted=sum(R(D[i][i+2*b])*(C(QQ(i)/2+b).psi().real()+gamma) for b in range(i+1))
                asym+=R(e[alpha])*(R(coeff)*psi_a-weighted/2)
            elif coeff:
                asym-=R(e[alpha]*coeff)*hz(i-alpha,a)
    remainder,bound=angular_remainder(d,a,h,D)
    radial0=-(2*R.pi()).log()/2 if d==2 else R(0)
    return asym+remainder+radial0,{'asymptotic':str(asym),'angular_remainder':str(remainder),'tail_bound':str(bound),'radial_nu_zero':str(radial0),'multiplicity_polynomial':str(h),'angular_origin':str(a)}


def sound(x):
    return x.is_finite() and R(x.rad())<R(10)**(-105)


def close(x,y):
    return sound(x) and sound(y) and x.overlaps(y)


def bounds(text):
    """Exact rational bounds for this generator's exact/decimal wire forms."""
    text=str(text)
    if '.' not in text and 'e' not in text.lower():
        q=QQ(text); return q,q
    dec=Decimal(text);parts=dec.as_tuple()
    coefficient=int(''.join(map(str,parts.digits)))*(-1 if parts.sign else 1)
    unit=QQ(10)**parts.exponent
    centre=coefficient*unit
    return centre-unit,centre+unit


def encloses(text,expected):
    lo,hi=bounds(text)
    if lo==hi:return close(R(lo),expected)
    return sound(expected) and lo<QQ(expected.lower()) and QQ(expected.upper())<hi


def run(stored=None):
    from generate import BallDirichlet
    gen=BallDirichlet();details=[];failures=[];computed={}
    # Spectral interval formula from Z(s)=(2/pi)^(2s)*zeta(2s).
    interval=-(2*(R(2)/R.pi()).log()*C(0).zeta().real()+2*C(0).zetaderiv(1).real())
    computed[1]=interval
    known=close(interval,R(4).log()) and close(R(4).log().exp(),R(4))
    # Exact Debye coefficients at t=1 must cancel the Stirling terms.
    for n,p in enumerate(debye(5)[1:],1):
        expected=-bernoulli(n+1)/(ZZ(n)*ZZ(n+1)) if n%2 else QQ(0)
        assert p(1)==expected
    for d in range(2,7):
        start=time.monotonic();derivative,components=contour_derivative(d)
        computed[d]=-derivative
        details.append({'d':d,'logdet':str(computed[d]),'elapsed_seconds':time.monotonic()-start,**components})
        print('contour',d,str(computed[d]),flush=True)
    entries=list(gen.enumerate())
    stored_rows=[]
    if stored:
        # The API's Numbers has one mapping for each d then convention.
        doc=json.loads(pathlib.Path(stored).read_text())
        data=doc['Numbers']
        assert list(doc['Parameters'])==list(gen.parameters)
        stored_identities=[(str(d),c) for d,rows in data.items() for c in rows]
        assert stored_identities==[(str(p['d']),p['convention']) for p in entries]
    for p in entries:
        v=gen.value(p,gen.digits)
        expected=computed[p['d']]
        if p['convention']=='det':expected=expected.exp()
        actual=R(v)
        if not close(actual,expected):failures.append({'params':p,'actual':str(actual),'expected':str(expected)})
        if stored:
            row=data[str(p['d'])][p['convention']]
            raw=str(row['number'] if isinstance(row,dict) else row)
            from numberdb._compare import digits_of
            if not encloses(raw,expected):failures.append({'params':p,'stored':raw,'expected':str(expected)})
            if p=={'d':1,'convention':'det'}:assert raw=='4'
            else:assert digits_of(raw)>=100
            lo,hi=bounds(raw)
            assert not encloses(str(lo+1 if lo==hi else lo+10*(hi-lo)),expected)
            stored_rows.append({'params':p,'number':raw,'independent_ball':str(expected),'contained':bool(encloses(raw,expected))})
    # Additional independent conformal effective-action control, DA (12),(14).
    z=lambda n:C(n).zetaderiv(1).real()
    hemisphere=QQ(3)/8*z(-2)-z(-1)/4-QQ(1)/16+R(2).log()/24
    da3=2*(hemisphere+QQ(7)/64)
    known=known and close(da3,computed[3])
    # Mutations are tested on nontrivial dimensions and on a value of known sign.
    negatives={
        'wrong_sign':not close(-computed[2],computed[2]),
        'half_multiplicity':not close(computed[3]/2,computed[3]),
        'wrong_radius':not close(computed[2]-R(2).log()/3,computed[2]),
        'nan':not close(R('nan'),computed[2]),
        'wide':not close(R(0,R(1).upper()),computed[2]),
        'wrong_exact_interval':not close(R(2),R(4))}
    return {'checked_entries':len(entries),'total_entries':len(entries),'failures':failures,
            'known_answer_control':bool(known),'negative_control_rejected':all(negatives.values()),
            'negative_controls':negatives,'precision_bits':BITS,'K':80,'M':100,
            'mode':'offline' if stored is None else 'stored','dimensions':details,'stored_rows':stored_rows,
            'method':'BGEK general asymptotic subtraction plus convergent angular log-Gamma series; no reduced coefficient table',
            'limitations':'Shared underlying BGEK spectral analysis; checker is builder evidence, not an independent actor verdict.'}


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--stored');parser.add_argument('--output',default='check-results.json')
    args=parser.parse_args()
    results=run(args.stored)
    pathlib.Path(args.output).write_text(json.dumps(results,indent=2))
    print(json.dumps({k:v for k,v in results.items() if k!='dimensions'},indent=2))
    raise SystemExit(bool(results['failures']) or not results['known_answer_control'] or not results['negative_control_rejected'])