checks.py

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

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

"""Independent executable builder checks, not an independent actor verdict.

sage -python checks.py [stored.json] > check-output.log
The CHECK_RESULTS_JSON line is machine readable. The checker does not import
or call generate.py. It interpolates harmonic binomial counts and evaluates a
finite-part Euler--Maclaurin expression with a proved derivative remainder.
The heat-trace constant separately checks Z(0) and the radius exponent.
See validation-method.md for the derivation, independence and limitations.
"""
import sys,json,math
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
R=RealBallField(700)
N=128
M=120

def mul(a,b,limit=None):
    k=len(a)+len(b)-1
    if limit is not None:k=min(k,limit)
    c=[QQ(0)]*k
    for i,x in enumerate(a):
        for j,y in enumerate(b):
            if i+j<k:c[i+j]+=x*y
    return c

def harmonic_count(d,n):
    return math.comb(n+d-1,d-1)-(math.comb(n+d-3,d-1) if n>=2 else 0)

@lru_cache(None)
def interpolated_coefficients(d):
    # Newton interpolation at n=1,...,d-1, from the literal source binomials.
    diff=[QQ(harmonic_count(d,n)) for n in range(1,d)]
    p=[QQ(0)]*(d-1);basis=[QQ(1)]
    for k in range(d-1):
        for j,b in enumerate(basis):p[j]+=diff[0]*b
        diff=[diff[j+1]-diff[j] for j in range(len(diff)-1)]
        basis=[b/QQ(k+1) for b in mul(basis,[QQ(-k-1),QQ(1)])]
    return tuple(p)

@lru_cache(None)
def bernoullis():
    b=[QQ(1)]
    for n in range(1,2*M+1):
        b.append(-sum((QQ(math.comb(n+1,k))*b[k] for k in range(n)),QQ(0))/QQ(n+1))
    assert b[1]==-QQ(1)/2 and b[2]==QQ(1)/6 and b[4]==-QQ(1)/30
    return b

@lru_cache(None)
def em_tail_derivative(j):
    # Derivative at s=0 of the tail of sum n^(j-s), n>=N.
    ln=R(N).log();a=QQ(-j-1)
    out=R(N)**(j+1)*(-ln/a-QQ(1)/(a*a))-R(N)**j*ln/2
    b=bernoullis()
    for r in range(1,M+1):
        v=QQ(1);dv=QQ(0)
        for k in range(2*r-1):dv,v=dv*(k-j)+v,v*(k-j)
        out+=QQ(b[2*r])/QQ(math.factorial(2*r))*R(N)**(j+1-2*r)*(dv-v*ln)
    bound=4*R(math.factorial(j))*math.factorial(2*M-j-1)/(2*R.pi())**(2*M)*R(N)**(j-2*M+1)/QQ(2*M-j-1)
    return out+R(0,bound.upper()),bound

@lru_cache(None)
def independent_logdet(d):
    p=interpolated_coefficients(d)
    # Finite sum uses the source counts, not the interpolated polynomial.
    out=sum((R(harmonic_count(d,n))*R(n).log() for n in range(1,N)),R(0))
    totalbound=R(0)
    for j,a in enumerate(p):
        tail,bound=em_tail_derivative(j);out-=a*tail;totalbound+=abs(a)*bound
    return out,totalbound

def heat_zeta_zero(d):
    # Constant term of (1+e^-t)/(1-e^-t)^(d-1)-1, exact formal arithmetic.
    k=d-1
    e=[QQ((-1)**j)/QQ(math.factorial(j)) for j in range(k+2)]
    den=[-e[j+1] for j in range(k+1)] # (1-exp(-t))/t
    inv=[QQ(1)]
    for j in range(1,k+1):inv.append(-sum((den[i]*inv[j-i] for i in range(1,j+1)),QQ(0)))
    powr=[QQ(1)]
    for _ in range(k):powr=mul(powr,inv,k+1)
    return mul([1+e[0]]+e[1:k+1],powr,k+1)[k]-1

def zeta_zero_polynomial(d):
    b=bernoullis();p=interpolated_coefficients(d)
    # zeta(0)=-1/2, zeta(-j)=(-1)^j B_(j+1)/(j+1), j>=1.
    return -p[0]/2+sum((p[j]*QQ((-1)**j)*b[j+1]/QQ(j+1) for j in range(1,len(p))),QQ(0))

def narrow(v,digits=110):
    return bool(v.is_finite() and R(v.rad())<max(abs(v),R(1))*R(10)**(-digits))

def close(a,b):
    return narrow(a) and narrow(b) and bool(a.overlaps(b))

def decimal_rational(s):
    from decimal import Decimal
    tup=Decimal(s).as_tuple();n=int(''.join(map(str,tup.digits)) or '0')*(-1 if tup.sign else 1)
    return QQ(n)*QQ(10)**tup.exponent

def stored_interval(s):
    # Entries from this build use plain decimals with one last-place ULP.
    from decimal import Decimal
    s=str(s)
    if '/' in s:return R(QQ(s))
    if '.' not in s and 'e' not in s.lower():return R(QQ(s))
    exp=Decimal(s).as_tuple().exponent
    return R(decimal_rational(s))+R(0,R(QQ(10)**exp).upper())

def bounds(s):
    from decimal import Decimal
    s=str(s)
    if '.' not in s and 'e' not in s.lower():
        return QQ(s),QQ(s)
    unit=QQ(10)**Decimal(s).as_tuple().exponent
    centre=decimal_rational(s)
    return centre-unit,centre+unit

def contained_bounds(lo,hi,reference):
    return bool(narrow(reference) and lo<QQ(reference.lower()) and QQ(reference.upper())<hi)

def contained(stored,reference):
    return contained_bounds(*bounds(stored),reference)

def records(doc):
    out=[]
    for d,block in doc['Numbers'].items():
        for convention,row in block.items():
            if isinstance(row,dict):number=row['number']
            else:number=row
            out.append((int(d),convention,number))
    return out

def run(stored=None):
    vals={};rows=[];fail=[];tail_bounds=[];heats=[]
    for d in range(2,21):
        v,b=independent_logdet(d);vals[d]=v;tail_bounds.append(str(b))
        assert narrow(v)
        p=interpolated_coefficients(d)
        assert all(sum((a*QQ(n)**j for j,a in enumerate(p)),QQ(0))==harmonic_count(d,n) for n in range(1,2*d+20))
        hz=heat_zeta_zero(d);pz=zeta_zero_polynomial(d)
        heats.append({'d':d,'heat_constant':str(hz),'polynomial_zeta_zero':str(pz),'equal':hz==pz})
        if hz!=pz:fail.append('heat constant d='+str(d))
        rows.append({'d':d,'logdet':str(v),'accuracy_bits':v.accuracy(),'tail_bound':str(b)})
        print('Checked d',d,'accuracy',v.accuracy(),flush=True)
    # Known nonzero and exact source-count controls; independent disk closed form.
    known=close(vals[2],(2*R.pi()).log()) and harmonic_count(3,3)==7 and harmonic_count(4,3)==16
    controls={
      'wrong_log_sign':not close(-vals[2],vals[2]),
      'wrong_multiplicity':not close(vals[2]/2,vals[2]),
      'wrong_radius':not close(vals[2]-heat_zeta_zero(2)*R(2).log(),vals[2]),
      'wrong_order_squared':not close(2*vals[3],vals[3]),
      'nan':not close(R('nan'),vals[2]),
      'wide_ball':not close(R(0,R(10).upper()),vals[2]),
      'heat_zero_mode':heat_zeta_zero(2)!=heat_zeta_zero(2)+1}
    if not known:fail.append('known-answer control')
    if not all(controls.values()):fail.append('negative control')
    storedrows=[]
    if stored:
        doc=stored if isinstance(stored,dict) else json.load(open(stored));rs=records(doc)
        assert [(d,c) for d,c,n in rs]==[(d,c) for d in range(2,21) for c in ('det','logdet')]
        for d,c,n in rs:
            ref=vals[d].exp() if c=='det' else vals[d];st=stored_interval(n)
            ok=contained(n,ref)
            lo,hi=bounds(n);shift=QQ(1)/10**90
            perturb=not contained_bounds(lo+shift,hi+shift,ref)
            storedrows.append({'d':d,'convention':c,'stored':str(n),'contained':ok,'stored_radius':str(st.rad()),'reference_radius':str(ref.rad()),'perturbed_rejected':perturb})
            if not ok or not perturb:fail.append('stored mismatch '+str((d,c)))
    return {'method':'Independent harmonic-binomial interpolation and direct Euler-Maclaurin finite part; exact heat-trace constant','working_bits':700,'N':N,'M':M,'checked_entries':len(storedrows) if stored else 38,'total_entries':38,'failures':fail,'known_answer_control':bool(known),'negative_control_rejected':all(controls.values()),'controls':controls,'dimensions':rows,'heat_checks':heats,'stored_rows':storedrows,'limitations':'Shared spectral theorem and Arb arithmetic, independent multiplicity construction and continuation evaluation; this is builder evidence, not an independent critique.'}

if __name__=='__main__':
    result=run(sys.argv[1] if len(sys.argv)>1 else None)
    print('CHECK_RESULTS_JSON',json.dumps(result,default=str))
    assert not result['failures']