checks.py

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

9764 bytes, as of the version from 2026-11-18 07:04 (current). Recorded here, not run.

"""Reproducible build checks for T746 (no writes to NumberDB).

sage -python checks.py (beside generate.py, optionally stored-table.json)
Writes /tmp/chiral-potts-check-results.json and prints RESULTS_JSON for the
artifact runner. Set NUMBERDB_CHECK_OUTPUT for a different local output path.
Theorem-1 and Mellin evaluations use Arb enclosures; direct original-kernel
quadrature uses SciPy double precision and is explicitly a sampled check.
This is build evidence, not an independent actor's scientific verdict.
"""
import os,sys,json,math,time,itertools,hashlib,platform,importlib.metadata
from pathlib import Path
from collections import defaultdict
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
import generate
import scipy.integrate as integrate
from numberdb._write import to_text
from numberdb._generate import _stored_entries
R=RealBallField(3000); C=ComplexBallField(3000)
started=time.monotonic()
result={'stage':'build','table':'T746','failures':[],'known_answer_control':False,'negative_control_rejected':False,'comparisons':[],'quadrature':[], 'skill_manifest':'../20261118T055124Z-build-skills/manifest.json','skill_bundle_sha256':'d6e85d49873fac5bc748d068b0288cf242b0f9aebf3a9a0fff70295019227420'}

def narrow(x,digits=100):
 return x.is_finite() and R(x.rad()) < R(10)**(-digits)

def theorem_one(t,wrong_modulus=False):
 t=R(QQ(t));u=2/(t+(t*t-4).sqrt());a=u*u/(2*(1+(1-u*u).sqrt()))
 assert a > 0 and a < (R(2).sqrt()-1)**2
 def hyp(up,z):
  v=C(z).hypergeometric([QQ(x) for x in up],[2]*4)
  assert v.real().is_finite() and v.imag().is_finite() and v.imag().contains_zero()
  return v.real()
 common=['3/2','3/2','3/2','1','1']
 value=-(4*a*(1-a)**19*(1+a)**12).log()/2-R(11)/4*a*(1-a)*hyp(common,4*a*(1-a))-7*a/(4*(1-a)**2)*hyp(common,-4*a/(1-a)**2)+9*a*(1-a)**2/(4*(1+a)**4)*hyp(['5/4','3/2','7/4','1','1'],16*a*(1-a)**2/(1+a)**4)
 assert narrow(value,140), (str(t),str(value),str(value.rad()))
 return value,a

def numeric_ball(text):
 # Stored decimals represent centre +/- one unit of their last place.
 # Keep exact decimal rational endpoints, not a binary float conversion.
 text=str(text).strip()
 if '+/-' in text:
  a,b=text.split('+/-');return R(QQ(a.strip())).add_error(R(QQ(b.strip())))
 if text.startswith('['):
  a,b=text[1:-1].split(',');return R(QQ(a)).union(R(QQ(b)))
 if '.' not in text and 'e' not in text.lower():return R(QQ(text))
 mant,*exp=text.lower().split('e');expo=int(exp[0]) if exp else 0
 frac=len(mant.split('.')[1]) if '.' in mant else 0
 # QQ handles exact scientific decimal in this runtime; convert by integer digits instead.
 sign=-1 if mant.startswith('-') else 1;mant=mant.lstrip('+-')
 centre=QQ(sign*int(mant.replace('.','')))*QQ(10)**(expo-frac)
 radius=QQ(10)**(expo-frac)
 return R(centre).add_error(R(radius))

g=generate.ChiralPotts();params=list(g.enumerate());stored_path=Path(__file__).parent/'stored-table.json'
records=None
if stored_path.exists():
 records=_stored_entries(json.loads(stored_path.read_text()))

def lookup_stored(p):
 if records is not None:
  return records[p['t']+','+p['normalization']]
 return to_text(g.value(p,100),100)

# Check original Laurent kernel and signs by independent exact monomial multiplication.
H={}
for axis in range(3):
 for sign in [-1,1]:
  e=[0,0,0];e[axis]=sign;H[tuple(e)]=4
for e in itertools.product([-1,1],repeat=3):H[e]=-1
power={(0,0,0):1};moments={}
for n in range(1,9):
 nxt=defaultdict(int)
 for e,v in power.items():
  for f,w in H.items():nxt[tuple(a+b for a,b in zip(e,f))]+=v*w
 power=dict(nxt)
 if n%2==0:moments[str(n)]=power.get((0,0,0),0)
assert moments['2']==104 and moments['4']==17880
field,M,poly=generate.series_data(100)
for r in range(1,5):
 expected=QQ(moments[str(2*r)])/QQ(256)**r
 assert expected in (R(poly[r])*(2*r))
result['constant_terms']=moments
assert sorted({sum(c)-c[0]*c[1]*c[2] for c in itertools.product([-1,1],repeat=3)})==[-2,2]

# Full source-Theorem-1 comparison; source mathematics is shared, implementation is separate.
for t in generate.selected_arguments():
 if t=='2':
  independent=8*((R(2).zeta(R(QQ(1)/4))-R(2).zeta(R(QQ(3)/4)))/16)/R.pi()-3*R(2).log()
  alpha=None
 else: independent,alpha=theorem_one(t)
 for normalization in ['potts','mahler']:
  p={'t':t,'normalization':normalization};text=lookup_stored(p);saved=numeric_ball(text)
  oracle=independent if normalization=='potts' else independent+R(8).log()
  assert narrow(saved,98) and narrow(oracle,130)
  assert saved.overlaps(oracle), (p,saved,oracle)
  assert oracle in saved, (p,'stored interval did not contain narrow oracle')
  result['comparisons'].append({'params':p,'stored':text,'oracle_radius':str(oracle.rad()),'contained':True})
result['checked_entries']=len(result['comparisons']);result['total_entries']=len(params)
result['derivative_comparisons']=[]
for text in generate.selected_arguments()[1:]:
 t=R(QQ(text));z=4/t**2;_,a=theorem_one(text)
 hg=C(z).hypergeometric([QQ(1)/8,QQ(5)/8],[1]).real()
 direct=(1-z)**(-QQ(1)/4)*hg*hg/t
 K=C(a).elliptic_k().real()
 elliptic=8*(a*(1-a)).sqrt()*K*K/(R.pi()**2*(1-2*a))
 assert narrow(direct,130) and narrow(elliptic,130) and direct.overlaps(elliptic)
 tz=field(QQ(4)/QQ(text)**2)
 series=(1+2*tz*poly.derivative()(tz))/field(QQ(text))
 series=series.add_error(generate.geometric_majorant(tz,M)/field(QQ(text)))
 assert narrow(R(series),110) and R(series).overlaps(direct)
 result['derivative_comparisons'].append({'t':text,'elliptic_matches_hypergeometric':True,'enclosed_series_matches':True})
print('full comparison done',result['checked_entries'],flush=True)

# An independently implemented analytic integration of the third angle leaves two variables.
def quad_kernel(t,zero=False,reverse=False):
 def f(y,x):
  if zero:return math.log(t)
  sx=math.sin(x/2)**2;sy=math.sin(y/2)**2
  cx=math.cos(x);cy=math.cos(y)
  a=t-cx-cy
  b=1+cx*cy if reverse else 1-cx*cy
  if reverse:D=a*a-b*b
  else:D=(t-2+4*sx*sy)*(t-2+4*(sx+sy-sx*sy))
  return math.log((a+math.sqrt(D))/2)
 val,err=integrate.dblquad(f,0,math.pi,lambda x:0,lambda x:math.pi,epsabs=1e-11,epsrel=1e-11)
 return val/math.pi**2,err/math.pi**2
known,knownerr=quad_kernel(3,zero=True)
assert abs(known-math.log(3))<2e-13
for t in ['2','17/8','5/2','3','5','10','14','322']:
 v,e=quad_kernel(float(QQ(t)));s=numeric_ball(lookup_stored({'t':t,'normalization':'potts'}))
 delta=abs(v-float(s.center()));assert delta<2e-10
 result['quadrature'].append({'t':t,'integral':v,'reported_error':e,'absolute_difference':delta,'precision':'double precision, sampled, non-certified'})
print('quadrature done',flush=True)

# Independent Mellin evaluation of L(eta(2tau)^3 eta(6tau)^3,3).
# eta inversion gives f(iy)=12^(-3/2)y^(-3) f(i/(12y)).
# Split the Mellin integral at y0=1/sqrt(12); transform its lower half.
result['theorem_working_bits']=3000
R=RealBallField(560); C=ComplexBallField(560)
y0=1/R(12).sqrt();Y=R(64);N=110;c=1/(R(12)**QQ('3/2'));rate=2*R.pi()
def eta_integrand(y,analytic):
 q2=(-4*C.pi()*y).exp();q6=q2**3
 p=C(1);a=q2;b=q6
 for n in range(1,N+1):
  p*=(1-a)**3*(1-b)**3;a*=q2;b*=q6
 return (-2*C.pi()*y).exp()*p*(y*y+C(c)/y)
I=C.integral(eta_integrand,C(y0),C(Y))
assert I.real().is_finite() and I.imag().is_finite() and I.imag().contains_zero()
def tail_integral(B):
 return (-rate*B).exp()*((B*B+QQ(1)/12)/rate+2*B/rate**2+2/rate**3)
q2=(-4*R.pi()*y0).exp();q6=q2**3
product_error=3*(q2**(N+1)/(1-q2)+q6**(N+1)/(1-q6))*tail_integral(y0)
err=product_error+tail_integral(Y)
L=4*R.pi()**3*I.real().add_error(err)
assert narrow(L,140)
dirichlet=(R(2).zeta(R(QQ(1)/3))-R(2).zeta(R(QQ(2)/3)))/9
j_control=24*R(3).sqrt()/R.pi()**3*L+15*R(3).sqrt()/(4*R.pi())*dirichlet-3*R(2).log()
stored25=numeric_ball(lookup_stored({'t':'5/2','normalization':'potts'}))
assert j_control in stored25
result['arithmetic_control']={'t':'5/2','L_eta':str(L),'J_arithmetic':str(j_control),'stored_contains':True,'product_terms':N,'upper_endpoint':str(Y),'integral_tail_bound':str(err),'method':'Arb analytic quadrature of eta Mellin integral with eta inversion and explicit product/upper-tail bounds'}
print('arithmetic done',flush=True)

# Validate rejection sensitivity with actual wrong conventions, not only a changed last digit.
right=numeric_ball(lookup_stored({'t':'5','normalization':'potts'}));wrong,_=quad_kernel(5,reverse=True)
assert abs(wrong-float(right.center()))>1e-4
assert not right.overlaps(right+1)
assert not right.overlaps(right+R(8).log())
t=R(3);_,alpha=theorem_one('3');u=2/(t+(t*t-4).sqrt())
K=C(alpha).elliptic_k().real();wrongK=C(alpha*alpha).elliptic_k().real()
green=8*(alpha*(1-alpha)).sqrt()/(R.pi()**2*(1-2*alpha))*K*K
wrong_green=8*(alpha*(1-alpha)).sqrt()/(R.pi()**2*(1-2*alpha))*wrongK*wrongK
assert not green.overlaps(wrong_green)
result['known_answer_control']=True
result['negative_control_rejected']=True
result['controls']={'zero_kernel':{'observed':known,'expected':math.log(3),'absolute_difference':abs(known-math.log(3))},'reversed_triple_product':{'t':5,'wrong_integral':wrong,'right':str(right)},'omitted_probability_normalization_rejected':abs(float(right.center())*math.pi**3-float(right.center()))>1,'wrong_elliptic_parameter_rejected':True,'normalization_shift_rejected':True,'unit_perturbation_rejected':True}
result['seconds']=time.monotonic()-started
result['uses_live_stored_values']=records is not None
result['versions']={'python':sys.version,'platform':platform.platform()}
for name in ['numberdb','scipy','mpmath']:
 result['versions'][name]=importlib.metadata.version(name)
path=Path(os.environ.get('NUMBERDB_CHECK_OUTPUT','/tmp/chiral-potts-check-results.json'));path.write_text(json.dumps(result,indent=2))
print('RESULTS_JSON '+json.dumps(result))