check_green.py

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

6901 bytes, as of the version from 2026-11-18 08:38 (current). Recorded here, not run.

"""T749 builder cross-checks; not an independent critic verdict.

With numberdb, Arb-enabled SageMath, mpmath, NumPy and SciPy installed:
    sage -python check_green.py
Place a NumberDB readback export named values-for-check.json beside this file,
as {"records": [{"params": {"k": "8"}, "number": "1.393..."}, ...]}.
The final RESULT JSON is the durable report. Series/gamma enclosures test the
entire written interval; double quadrature is explicitly heuristic.
"""
import json,pathlib,math,itertools,sys,importlib.metadata
from decimal import Decimal
from collections import Counter
from fractions import Fraction
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
import mpmath as mp
from scipy.integrate import dblquad

R=RealBallField(600)

def exact_decimal(s):
    f=Fraction(Decimal(s))
    return QQ(f.numerator)/f.denominator


def written_bounds(s):
    centre=exact_decimal(s)
    exponent=Decimal(s).as_tuple().exponent
    ulp=QQ(10)**exponent
    return centre-ulp,centre+ulp,centre,ulp


def contains_written(s,v):
    assert v.is_finite() and v.accuracy()>440
    lo,hi,mid,ulp=written_bounds(s)
    # Strict comparisons account for uncertainty in both ball endpoints.
    ok=bool(v>R(lo) and v<R(hi))
    return ok,str(abs(v-R(mid))/R(ulp)),int(v.accuracy())


def moment_sum(k):
    x=QQ(64)/(QQ(k)**2)
    if not 0<=x<1:raise ValueError('Exterior argument required')
    N=1
    while x**(N+1)/(1-x)>QQ(1)/10**155:N*=2
    total=R(0);power=R(1);xb=R(x)
    # Coefficients are computed independently with exact integer binomials,
    # rather than any elliptic routine or its transformation.
    for n in range(N+1):
        coeff=QQ(math.comb(2*n,n)**3)/(QQ(2)**(6*n))
        assert type(coeff).__name__=='Rational'
        total+=R(coeff)*power
        power*=xb
    tail=x**(N+1)/(1-x)
    enclosure=(total+R(tail)/2).add_error(R(tail)/2)
    return enclosure,N,str(R(tail))


def angular_green(k,kernel=8):
    # After integrating the third original angle, reflect the square to
    # [0,pi/2]^2 and split into its two triangles. Set (s,t)=(r,r*v).
    # The Jacobian r removes the inverse-radius corner singularity at k=8.
    # sin^2 r+cos^2 r sin^2(rv) avoids cancellation in 1-cos^2 r cos^2(rv).
    def f(v,r):
        if r==0:
            return 1/math.sqrt(1+v*v) if k==kernel else 0
        d=k*k-kernel*kernel+kernel*kernel*(math.sin(r)**2+math.cos(r)**2*math.sin(r*v)**2)
        return k*r/math.sqrt(d)
    val,err=dblquad(f,0,math.pi/2,lambda r:0,lambda r:1,epsabs=2e-12,epsrel=2e-12)
    return val*8/math.pi**2,err*8/math.pi**2


def checker(rows):
    assert list(rows)==[str(k) for k in range(8,33)]
    groups=[{'8'},{'9'},{str(k) for k in range(10,33)}]
    assert set.union(*groups)==set(rows) and sum(map(len,groups))==len(rows)
    results={'checked_entries':0,'total_entries':len(rows),'failures':[],
             'enclosing_checks':[],'angular_checks':[],'selection_checked':True}
    for sk,text in rows.items():
        k=int(sk)
        if k==8:
            v=R(QQ(1)/4).gamma()**4/(4*R.pi()**3)
            method='Gamma(1/4)^4/(4*pi^3)';N=None;tail=None
        else:
            v,N,tail=moment_sum(k);method='direct exact binomial moments with geometric remainder'
        ok,ulps,accuracy=contains_written(text,v)
        rec={'k':k,'method':method,'N':N,'tail_bound':tail,'accuracy_bits':accuracy,'difference_ulps_enclosure':ulps,'strictly_inside_written_interval':ok,'enclosure':str(v)}
        results['enclosing_checks'].append(rec);results['checked_entries']+=1
        if not ok:results['failures'].append('enclosing '+sk)
        val,err=angular_green(k);diff=abs(val-float(text))
        ok=math.isfinite(val) and err<1e-10 and diff<1e-11
        rec={'k':k,'value':val,'estimated_absolute_error':err,'difference':diff,'pass':ok}
        results['angular_checks'].append(rec)
        if not ok:results['failures'].append('angular '+sk)
        print('ROW',k,'enclosure',results['enclosing_checks'][-1]['strictly_inside_written_interval'],'quadrature',ok,flush=True)
    # Independently enumerate actual walks, rather than algebraic moments.
    steps=list(itertools.product([-1,1],repeat=3));counts={};paths=Counter({(0,0,0):1})
    for n in range(1,5):
        nxt=Counter()
        for a,c in paths.items():
            for b in steps:nxt[tuple(x+y for x,y in zip(a,b))]+=c
        paths=nxt;counts[str(n)]=paths[(0,0,0)]
    assert list(counts.values())==[0,8,0,216]
    results['direct_walk_counts']=counts
    zero,zeroerr=angular_green(9,0)
    results['known_answer_control']=abs(zero-1)<1e-13 and zeroerr<1e-11
    with mp.workdps(180):
        k=mp.mpf(9);z=8/k;x=z*z;a=(1-mp.sqrt(1-x))/2;expected=mp.mpf(rows['9'])
        wrong={
          'omitted_kernel_factor_8':mp.mpf(angular_green(9,1)[0]),
          'wrong_z_power':mp.hyper([mp.mpf('0.5')]*3,[1,1],z),
          'modulus_parameter_swap':(2*mp.ellipk(mp.sqrt(a))/mp.pi)**2,
          'unnormalized_resolvent':expected/k,
          'zero_always':mp.mpf(0),
          'last_place_perturbation':expected+mp.mpf('1e-98')}
        controls={name:{'difference':mp.nstr(abs(v-expected),30),'rejected':bool(abs(v-expected)>(mp.mpf('1e-99') if name=='last_place_perturbation' else mp.mpf('1e-5')))} for name,v in wrong.items()}
    # Exercise the exact interval checker too, not only large wrong formulas.
    good=R(QQ(1)/4).gamma()**4/(4*R.pi()**3)
    controls['interval_checker_known']={'rejected':contains_written(rows['8'],good)[0]}
    controls['interval_checker_shift']={'rejected':not contains_written(rows['8'],good+R(QQ(1)/10**98))[0]}
    rejected=[]
    for v in [R('nan'),R(1).add_error(R(10)**18)]:
        try:contains_written(rows['9'],v);rejected.append(False)
        except AssertionError:rejected.append(True)
    controls['nan_and_vacuous_balls']={'rejected':all(rejected)}
    results['negative_controls']=controls
    results['negative_control_rejected']=all(v['rejected'] for v in controls.values())
    results['max_angular_difference']=max(v['difference'] for v in results['angular_checks'])
    results['limitations']='Original-kernel double quadrature uses IEEE doubles and is heuristic, testing approximately eleven decimal places. Full written precision is checked by rigorous series enclosures at k>8 and a separately derived gamma formula at k=8; these share the integral definition but do not invoke elliptic K. This is builder evidence, not an independent session verdict.'
    return results

if __name__=='__main__':
    p=pathlib.Path(__file__).parent
    doc=json.loads((p/'values-for-check.json').read_text())
    rows={str(r['params']['k']):str(r['number']) for r in doc['records']}
    result=checker(rows)
    print('RESULT '+json.dumps(result),flush=True)
    assert not result['failures'] and result['known_answer_control'] and result['negative_control_rejected']