check_volumes.py

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

7784 bytes, as of the version from 2026-11-27 09:27 (current). Recorded here, not run.

"""Independent full-range volume check, run with SageMath's Python.

Usage: sage -python check_volumes.py [entries.json] [check-results.json]
The source of entries is a JSON list of flat params/number records.
This checker does not import generate.py. Schlaefli integration uses lengths
from Klein polar planes and Hurwitz-zeta endpoint anchors. It analytically
removes the logarithmic endpoint singularity before numerical quadrature.
The mpmath comparison is heuristic, separate from Arb certification.
Results are checkpointed on stdout so an authorized remote runner can retain
them. On a normal writable filesystem they are also written beside this file.
"""
import json,sys,itertools,pathlib,time
import numberdb.sage as numberdb
from sage.rings.real_arb import RealBallField
from sage.rings.rational_field import QQ
import sage.rings.polynomial.laurent_polynomial_ring
from sage.matrix.constructor import matrix
import mpmath as mp

DATA={'tetrahedron':(3,3,24,6,6,7),'cube':(3,4,48,12,6,7),
      'octahedron':(4,3,48,12,4,5)}
ROOT=pathlib.Path(__file__).resolve().parent

def independent_volume(cell,p,dps):
    with mp.workdps(dps):
        q,r,M,E,p0,minimum=DATA[cell];a0=mp.pi/p0;a=mp.pi/p;D=a0-a
        clausen=mp.sqrt(3)/72*(mp.zeta(2,mp.mpf(1)/6)+mp.zeta(2,mp.mpf(2)/6)
                     -mp.zeta(2,mp.mpf(4)/6)-mp.zeta(2,mp.mpf(5)/6))
        catalan=(mp.zeta(2,mp.mpf(1)/4)-mp.zeta(2,mp.mpf(3)/4))/16
        anchor={'tetrahedron':clausen,'cube':5*clausen,'octahedron':4*catalan}[cell]
        def regular(s):
            t=a0-s;c=mp.cos(2*t)
            if cell=='octahedron':
                A=1+c;B=2*mp.sin(2*s);ratio=4*mp.sinc(2*s)
            else:
                A=c if cell=='tetrahedron' else mp.mpf(1)
                ratio=4*mp.sin(a0+t)*mp.sinc(s);B=s*ratio
            return mp.log((A+mp.sqrt(A*A-B*B))/ratio)
        integral=(mp.quad(regular,[0,D/2,D])-D*mp.log(D)+D)/2
        return + (anchor+2*E*integral)

def plane_and_convention_checks(cell,p):
    R=RealBallField(512);q,r,M,E,p0,minimum=DATA[cell]
    a=R.pi()/p;c=(2*a).cos()
    if cell=='tetrahedron':
        rho2=3*(3*c-1)/(1+c);y=(rho2/3).sqrt()
        pts=[[y*i for i in signs] for signs in itertools.product([-1,1],repeat=3) if signs[0]*signs[1]*signs[2]==1]
        face_cos=(rho2+3)/(9-rho2);target=c/(2*c-1)
    elif cell=='cube':
        y2=c/(1+c);y=y2.sqrt();pts=[[y*i for i in s] for s in itertools.product([-1,1],repeat=3)]
        face_cos=y2/(1-y2);target=1/(2*c-1)
    else:
        y2=(1+3*c)/(1+c);y=y2.sqrt();pts=[[y*s if k==j else R(0) for k in range(3)] for j in range(3) for s in [-1,1]]
        face_cos=(y2-1)/(3-y2);target=(1+c)/(2*c)
    assert (face_cos-c).contains_zero()
    pairs=[]
    for i,j in itertools.combinations(range(len(pts)),2):
        x,y=pts[i],pts[j];xx=sum(t*t for t in x)-1;yy=sum(t*t for t in y)-1
        assert xx>0 and yy>0
        distance_cos=abs(sum(x[k]*y[k] for k in range(3))-1)/(xx*yy).sqrt()
        assert distance_cos>1 and distance_cos.is_finite()
        pairs.append(distance_cos)
    adjacent=min(pairs,key=lambda x:x.mid())
    assert (adjacent-target).contains_zero()
    G=matrix(R,[[1,-a.cos(),0,0],[-a.cos(),1,-(R.pi()/q).cos(),0],
                [0,-(R.pi()/q).cos(),1,-(R.pi()/r).cos()],
                [0,0,-(R.pi()/r).cos(),1]])
    H=G.inverse();h=(1-H[2,3]**2/(H[2,2]*H[3,3])).sqrt().arccosh()
    assert (h*2).cosh().overlaps(adjacent)
    return {'pairs':len(pairs),'all_ultraparallel':True,'angle_2alpha':True,
            'minimum_cosh_2h':str(adjacent),'height':str(h)}

def decimal_record(text):
    text=text.strip().rstrip('?');m=mp.mpf(text)
    exponent=int(text.lower().split('e')[1]) if 'e' in text.lower() else 0
    mantissa=text.lower().split('e')[0];places=len(mantissa.split('.')[1]) if '.' in mantissa else 0
    return m,mp.power(10,exponent-places)

def acceptable(text,expected):
    m,u=decimal_record(text)
    return bool(mp.isfinite(m) and mp.isfinite(expected) and u>0 and u<abs(m)*mp.mpf('1e-95') and abs(m-expected)<u)

def main():
    mp.mp.dps=145;rows=json.loads(pathlib.Path(sys.argv[1] if len(sys.argv)>1 else ROOT/'entries.json').read_text())
    expected_ids=[(cell,p,n) for cell,(*_,minimum) in DATA.items() for p in range(minimum,31) for n in ['cell','chamber']]
    assert [(r['params']['cell'],int(r['params']['p']),r['params']['normalization']) for r in rows]==expected_ids
    output={'checked_entries':0,'total_entries':len(rows),'failures':[], 'known_answer_control':False,'negative_control_rejected':False,'comparisons':[],'geometry':{},'methods':'regularized Schlaefli quadrature at 115 and 135 dps; coordinate polar planes; Hurwitz-zeta anchors','limitations':'mpmath quadrature is an independent numerical cross-check, not a rigorous error certificate.'}
    # Nonzero integration and anchor controls independent of Kellerhals.
    assert abs(mp.quad(lambda x:1+x*x,[0,1])-mp.mpf(4)/3)<mp.mpf('1e-140')
    cat=(mp.zeta(2,mp.mpf(1)/4)-mp.zeta(2,mp.mpf(3)/4))/16
    assert abs(cat-mp.catalan)<mp.mpf('1e-140')
    cl=mp.sqrt(3)/72*sum(s*mp.zeta(2,mp.mpf(k)/6) for k,s in [(1,1),(2,1),(4,-1),(5,-1)])
    assert str(cl).startswith('1.014941606409653625021202554274520285941689')
    h6=mp.acosh(mp.mpf(3)/2)/2
    assert abs(h6-mp.log((1+mp.sqrt(5))/2))<mp.mpf('1e-140')
    output['known_answer_control']=True
    # Published rounded chamber-volume controls, with half-ULP plus 1e-9 allowance.
    source={'tetrahedron':{7:'0.08856',8:'0.10721',9:'0.11825',20:'0.14636'},'cube':{7:'0.16297337',8:'0.18789693',9:'0.20295023',20:'0.24206876'},'octahedron':{5:'0.16596371',6:'0.19616337',7:'0.21217704',20:'0.24655736'}}
    cached={}
    for cell,(*_,minimum) in DATA.items():
        for p in range(minimum,31):
            v1=independent_volume(cell,p,115);v2=independent_volume(cell,p,135)
            assert abs(v1-v2)<mp.mpf('1e-110')
            cached[cell,p]=v2;output['geometry'][cell+','+str(p)]=plane_and_convention_checks(cell,p)
            if p in source[cell]:
                s=source[cell][p];m,u=decimal_record(s)
                assert abs(v2/DATA[cell][2]-m)<u*mp.mpf('0.51')+mp.mpf('1e-9')
            print('CHECKPOINT',cell,p,mp.nstr(v2,25),flush=True)
    for row in rows:
        a=row['params'];cell=a['cell'];p=int(a['p']);norm=a['normalization'];v=cached[cell,p]
        want=v if norm=='cell' else v/DATA[cell][2]
        m,u=decimal_record(row['number']);error=abs(m-want)/u
        if not acceptable(row['number'],want):output['failures'].append(str(a))
        output['comparisons'].append({'params':a,'schlaefli':mp.nstr(want,133),'error_last_places':mp.nstr(error,15)})
        output['checked_entries']+=1
    first=rows[0];x=cached['tetrahedron',7]
    negatives={'omit_M':not acceptable(first['number'],x/24),
               'perturb_result':not acceptable(first['number'],x+mp.mpf('1e-80')),
               'nan':not acceptable(first['number'],mp.nan),
               'wide_interval':not acceptable('2.1',x),
               'wrong_full_angle':not acceptable(first['number'],independent_volume('tetrahedron',14,115)),
               'swapped_q_r':not acceptable(next(r['number'] for r in rows if r['params']==dict(cell='cube',p=7,normalization='cell')),cached['octahedron',7])}
    assert all(negatives.values()),negatives
    output['negative_controls']=negatives;output['negative_control_rejected']=True
    output['maximum_error_last_places']=max((r['error_last_places'] for r in output['comparisons']),key=mp.mpf)
    print('CHECK_RESULTS_JSON='+json.dumps(output),flush=True)
    destination=pathlib.Path(sys.argv[2] if len(sys.argv)>2 else ROOT/'check-results.json')
    try:destination.write_text(json.dumps(output,indent=2))
    except OSError:pass
    assert not output['failures']
if __name__=='__main__':main()