builder_check.py

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

10214 bytes, as of the version from 2026-11-20 01:33 (current). Recorded here, not run.

"""T769 builder checks, not an independent-actor verdict.

Run beside rows.json and numerical-evidence.json:
    sage -python builder_check.py > builder-check.jsonl
All rows: independent integer selection, exact class maps, serialized-interval
containment, conjugation and Fricke identities. Sampled numerical checks use
Hecke modular-symbol coefficients and direct radial Arb quadrature, following
the separate T732 builder-check component. Production instead uses elliptic
curve point counts and a termwise primitive. Shared: modularity, CM endpoint,
full lattice enclosure, and Arb. Complete per-integral JSON checkpoints support
resumption; preserve stdout as quadrature-checkpoints.jsonl if interrupted.
"""
import numberdb.sage as numberdb
from sage.rings.qqbar import _init_qqbar
_init_qqbar()
from sage.rings.rational_field import QQ
from sage.rings.integer_ring import ZZ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from sage.modular.modsym.modsym import ModularSymbols
from sage.quadratic_forms.binary_qf import BinaryQF
from sage.schemes.elliptic_curves.constructor import EllipticCurve
from numberdb._compare import _claim
from numberdb._write import to_text
from pathlib import Path
from functools import lru_cache
from fractions import Fraction
import json,math,time,re

R=RealBallField(500);C=ComplexBallField(500)
def emit(x):print(json.dumps(x,default=str),flush=True)
def ball(pair):
 lo,hi=map(QQ,pair);return R((lo+hi)/2,rad=R((hi-lo)/2).upper())
def box(parts):return C(ball(parts[0]),ball(parts[1]))
def ends(z):return [[str(QQ(x.lower())),str(QQ(x.upper()))] for x in [z.real(),z.imag()]]
def finite(z):return z.real().is_finite() and z.imag().is_finite()
def narrow(z):return finite(z) and all(R(x.rad())<R(10)**-105 for x in [z.real(),z.imag()])
def agree(a,b):return narrow(a) and narrow(b) and (a-b).contains_zero()
def textbounds(t):
 mid,rad=map(Fraction,_claim(t));return mid-rad,mid+rad
def textbox(s):
 parts=re.split(r'\s*\+\s*i\s*\*\s*',s);assert len(parts)==2
 return C(*(ball([str(x) for x in textbounds(t)]) for t in parts))
def serialized_contains(s,z):
 parts=re.split(r'\s*\+\s*i\s*\*\s*',s)
 for text,x in zip(parts,[z.real(),z.imag()]):
  lo,hi=textbounds(text)
  if not (QQ(lo.numerator)/lo.denominator<=QQ(x.lower()) and QQ(x.upper())<=QQ(hi.numerator)/hi.denominator):return False
 return True

def squarefree(n):return all(n%(p*p) for p in range(2,math.isqrt(n)+1))
def fundamental(D):return (D%4==1 and squarefree(-D)) or (D%4==0 and (D//4)%4 in [2,3] and squarefree(-D//4))
def reduced_forms(D):
 out=[]
 for a in range(1,math.isqrt((-D)//3)+1):
  for b in range(-a,a+1):
   if (b*b-D)%(4*a):continue
   c=(b*b-D)//(4*a)
   if c<a or math.gcd(a,math.gcd(b,c))!=1:continue
   if (abs(b)==a or a==c) and b<0:continue
   out.append((a,b,c))
 return out

def expected():
 for N in [11,14,15,17,19,20,21,24,27,32,36,49]:
  for d in range(3,61):
   D=-d
   if not fundamental(D) or math.gcd(D,N)!=1:continue
   for beta in range(2*N):
    if (beta*beta-D)%(4*N):continue
    for a,b,c in reduced_forms(D):yield dict(N=N,D=D,beta=beta,a=a,b=b,c=c)

def key(p):return tuple(int(p[k]) for k in ['N','D','beta','a','b','c'])
def reduce(z,w1,w2):
 v=z.imag()/w2.imag();u=(z.real()-v*w2.real())/w1.real()
 shifts=[]
 for x in [u,v]:
  a,b=ZZ((x+R(1)/2).lower().floor()),ZZ((x+R(1)/2).upper().floor())
  assert a==b;shifts.append(a)
 return z-shifts[0]*w1-shifts[1]*w2

@lru_cache(None)
def coefficients(N,M):
 f=ModularSymbols(N,2,sign=1).cuspidal_submodule().q_eigenform(M+1,names='a')
 return [QQ(f[n]) for n in range(M+1)]
cache={}
cp=Path(__file__).with_name('quadrature-checkpoints.jsonl')
if cp.exists():
 for line in cp.read_text().splitlines():
  if line.startswith('{'):
   r=json.loads(line)
   if r.get('kind')=='quadrature':cache[tuple(r['argument'])]=r
@lru_cache(None)
def integrate(N,A,B,D):
 arg=(N,A,B,D)
 if arg in cache:return box(cache[arg]['enclosure'])
 q=(2*C.pi()*C.gen(0)*C(-QQ(B)/(2*A),R(-D).sqrt()/(2*A))).exp();rho=R(q.abs().upper())
 M=max(1,int(math.ceil((-420*math.log(2)+math.log(float(1-rho))-math.log(2))/math.log(float(rho)))))
 tail=2*rho**(M+1)/(1-rho)
 while not tail<R(2)**-420:M+=1;tail=2*rho**(M+1)/(1-rho)
 an=coefficients(N,M);calls=[0];block=16
 def integrand(t,analytic):
  # The polynomial is entire, satisfying acb_calc's analytic contract.
  calls[0]+=1;z=q*t;powers=[z**j for j in range(block)];step=z**block;v=C(0)
  for k in reversed(range((M+block-1)//block)):
   part=sum((an[n+1]*powers[n-k*block] for n in range(k*block,min((k+1)*block,M)) if an[n+1]),C(0));v=v*step+part
  return q*v
 start=time.time();z=C.integral(integrand,0,1,abs_tol=R(2)**-385,rel_tol=R(2)**-385,eval_limit=200000)
 z+=C(R(0,rad=tail.upper()),R(0,rad=tail.upper()));assert narrow(z)
 emit(dict(kind='quadrature',argument=arg,enclosure=ends(z),value=to_text(z,110,form='decimal'),terms=M,tail=str(tail),calls=calls[0],seconds=time.time()-start))
 return z

if __name__=='__main__':
 start=time.time();directory=Path(__file__).parent;rows=json.loads((directory/'rows.json').read_text());evidence=json.loads((directory/'numerical-evidence.json').read_text());periods={p['N']:p for p in evidence['summary']['periods']};lookup={key(r['params']):r for r in rows};assert [r['params'] for r in rows]==list(expected())
 failures=[];checks=[]
 for row in rows:
  p=row['params'];N,D,beta,a,b,c=key(p);A,B,Cc=row['form'];s,t,u,v=row['level_to_reduced']
  assert s*v-t*u==1
  assert (A*s*s+B*s*u+Cc*u*u,2*A*s*t+B*(s*v+t*u)+2*Cc*u*v,A*t*t+B*t*v+Cc*v*v)==(a,b,c)
  assert A%N==0 and B%(2*N)==beta and B*B-4*A*Cc==D and math.gcd(A//N,math.gcd(B,Cc*N))==1
  z=box(row['enclosure']);assert narrow(z) and serialized_contains(row['number'],z)
  w1,w2=box(periods[N]['omega1']),box(periods[N]['omega2'])
  inverse=tuple(map(int,BinaryQF([a,-b,c]).reduced_form()));other=lookup[(N,D,(-beta)%(2*N),*inverse)]
  assert agree(reduce(z.conjugate(),w1,w2),box(other['enclosure']))
  frlabel=tuple(map(int,BinaryQF([N*Cc,-B,A//N]).reduced_form()));fr=lookup[(N,D,(-beta)%(2*N),*frlabel)]
  assert agree(reduce(QQ(periods[N]['kappa'])*w1-z,w1,w2),box(fr['enclosure']))
 emit(dict(kind='all-row-checks',entries=len(rows),selection=True,exact_class_transform=True,serialized_containment=True,conjugation=True,fricke_cusp_translation=True))
 for N,pp in periods.items():
  m=EllipticCurve(pp['model']).period_lattice().basis(prec=560);w1,w2=box(pp['omega1']),box(pp['omega2'])
  residual=[abs(w1.real().center()-m[0].real()),abs(w2.real().center()-m[1].real()),abs(w2.imag().center()-m[1].imag())]
  assert all(t<R(10)**-130 for t in map(R,residual));emit(dict(kind='period-comparison',N=N,residual=list(map(str,residual)),limitation='Numerical agreement only; production full-lattice certificate is integral homology.'))
 samples=[]
 for N in periods:
  group=[r for r in rows if r['params']['N']==N]
  candidates=[group[0],group[-1]]
  neg=[r for r in group if r['params']['b']<0]
  if neg:candidates.append(neg[-1])
  candidates +=[r for r in group if r['params']['D'] in [-3,-4]]
  for r in candidates:
   if key(r['params']) not in [key(s['params']) for s in samples]:samples.append(r)
 # Additional difficult cases: closest boundary in either lattice shape.
 for delta in [0,1]:
  group=[r for r in rows if periods[r['params']['N']]['delta']==delta]
  def margin(r):
   z=box(r['enclosure']);pp=periods[r['params']['N']];w1,w2=box(pp['omega1']),box(pp['omega2']);v=z.imag()/w2.imag();u=(z.real()-v*w2.real())/w1.real();return min(float(abs(u-R(1)/2).lower()),float(abs(u+R(1)/2).lower()),float(abs(v-R(1)/2).lower()),float(abs(v+R(1)/2).lower()))
  r=min(group,key=margin)
  if key(r['params']) not in [key(s['params']) for s in samples]:samples.append(r)
 emit(dict(kind='sample-plan',params=[r['params'] for r in samples],rationale='Each level: first point, largest discriminant final class, a negative-b class where present, every D=-3,-4; closest boundary for both lattice shapes.'))
 for row in samples:
  p=row['params'];N,D,beta,a,b,c=key(p);A,B,Cc=row['form'];raw=integrate(N,A,B,D);w1,w2=box(periods[N]['omega1']),box(periods[N]['omega2']);red=reduce(raw,w1,w2)
  rawok=agree(raw,box(row['raw_enclosure']));ok=rawok and agree(red,box(row['enclosure'])) and serialized_contains(row['number'],red)
  result=dict(params=p,raw_agreement=rawok,reduced_agreement=ok,independent_representative=to_text(red,110,form='decimal'))
  checks.append(result);emit(dict(kind='sample-check',**result))
  if not ok:failures.append(p)
 # Known zero and nonzero analytic/cusp controls; checker rejects deliberate faults.
 polynomial=C.integral(lambda z,analytic:z*z,0,1)
 w1,w2=box(periods[11]['omega1']),box(periods[11]['omega2']);critical=2*integrate(11,11,0,-44)
 known=agree(polynomial,C(QQ(1)/3)) and agree(critical,w1/5) and agree(reduce(w1+w2,w1,w2),C(0))
 nonreal=next(r for r in rows if r['params']['b']<0);p=nonreal['params'];N,D,beta,a,b,c=key(p);z=box(nonreal['enclosure']);w1,w2=box(periods[N]['omega1']),box(periods[N]['omega2']);inverse=tuple(map(int,BinaryQF([a,-b,c]).reduced_form()));wrong=lookup[(N,D,beta,*inverse)]
 different=lookup[(N,D,beta,*reduced_forms(D)[0])]
 controls={'wrong_class':not agree(z,box(different['enclosure'])),'class_inversion':not agree(z,box(wrong['enclosure'])),'sign':not agree(z,-z),'wrong_sublattice':not agree(reduce(3*w1/4,w1*2,w2*2),reduce(3*w1/4,w1,w2)),'lost_cusp_torsion':not agree(reduce(z-QQ(periods[N]['kappa'])*w1,w1,w2),z),'period_shifted_representative':not agree(z,z+w1),'nan':not agree(z,C('nan')),'vacuous':not agree(z,C(R(0,rad=R(100).upper()),R(0,rad=R(100).upper())))}
 emit(dict(kind='controls',known_answer_control=known,negative_controls=controls))
 assert known and all(controls.values())
 emit(dict(kind='summary',checked_entries=len(checks),total_entries=len(rows),all_row_checks=len(rows),failures=failures,known_answer_control=known,negative_control_rejected=all(controls.values()),checks=checks,seconds=time.time()-start,limitations='Builder method check, not an independent-actor verdict. Quadrature sampled; endpoint labels, production period enclosures, modularity and Arb are shared. No exact algebraic CM-image reconstruction.'))
 assert not failures