checks.py

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

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

"""Independent spectrum/heat checks for T835; never writes to NumberDB.

sage -python checks.py reads check-input.json beside this source and emits JSON.
Input contains rows with a,b,c,det,logdet as stored decimal strings; obtain it
from the attached selection-values.json, or flatten the live table's entries.
Requires Sage/Arb, PARI and numberdb. No eta-product generator is imported.
The derivation and rigorous square-cutoff bound are in check-notes.md.
"""
import sys,json,re,math,collections
from pathlib import Path
import numberdb.sage as numberdb
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from sage.rings.rational_field import QQ
from sage.rings.integer_ring import ZZ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.libs.pari import pari
R=RealBallField(560); C=ComplexBallField(560); pi=R.pi()
WIDTH=R(10)**(-95)
INDEPENDENT_WIDTH=R(10)**(-110)


def decimal_interval(text):
    m=re.fullmatch(r'([+-]?)(\d+)\.(\d+)(?:[eE]([+-]?\d+))?',str(text))
    assert m,('expected a stored decimal',text)
    sign,whole,frac,exponent=m.groups();power=int(exponent or 0)-len(frac)
    scale=QQ(10)**power
    center=ZZ(('-' if sign=='-' else '')+whole+frac)*scale
    return R(center).add_error(R(scale))


def narrow(x):
    return x.is_finite() and R(x.rad())<WIDTH


def compatible(stored,independent):
    return narrow(stored) and narrow(independent) and stored.overlaps(independent)


def contains(stored,independent):
    return compatible(stored,independent) and R(independent.rad())<INDEPENDENT_WIDTH and independent in stored


def heat(a,b,c):
    d=4*a*c-b*b;alpha=R(d).sqrt()/(2*(a+c));t=pi*alpha
    assert alpha>0
    M=1;target=R(10)**(-135)
    while True:
        T=2*(-t*(M+1)**2).exp()/(1-(-t*(2*M+3)).exp())
        S=1+2*(-t).exp()/(1-(-3*t).exp())
        tail=4*T*S/(t*(M+1)**2)
        if tail<target:break
        M+=1
    counts=collections.Counter(a*m*m-b*m*n+c*n*n for m in range(-M,M+1)
                               for n in range(-M,M+1) if m or n)
    total=R(0)
    for k,multiplicity in sorted(counts.items()):
        assert type(k) is int and k>0 and type(multiplicity) is int
        z=2*pi*k/R(d).sqrt()
        total+=multiplicity*(R(0).gamma_inc(z)+(-z).exp()/z)
    L=(1+R.euler_constant()-(4*pi).log()-total).add_error(tail.upper())
    return L.exp(),L,{'cutoff':M,'distinct_norms':len(counts),'tail_bound':str(tail.upper()),
                       'det_radius':str(L.exp().rad()),'logdet_radius':str(L.rad())}


def signed_forms(d):
    # Different enumeration: discriminant first and c determined by a,b.
    forms=[]
    for a in range(1,math.isqrt(d//3)+1):
        for b in range(-a+1,a+1):
            numerator=d+b*b
            if numerator%(4*a):continue
            c=numerator//(4*a)
            if c<a or (c==a and b<0) or math.gcd(math.gcd(a,b),c)!=1:continue
            forms.append((a,b,c))
    return forms


def height(delta):
    # Barquero-Sanchez et al., Theorem 1.3, directly in its e(p) convention.
    Delta=ZZ(delta)
    fieldD=Delta.squarefree_part()
    if fieldD%4!=1:fieldD*=4
    f=ZZ(Delta//fieldD).isqrt();assert f*f*fieldD==Delta
    d=abs(fieldD);h=int(pari(fieldD).qfbclassno());w=6 if fieldD==-3 else 4 if fieldD==-4 else 2
    hst=R(abs(Delta)).log()/4-pi.log()/2
    for k in range(1,int(d)):
        chi=fieldD.kronecker(k)
        if chi:hst-=QQ(chi*w)/(4*h)*R(QQ(k)/d).log_gamma()
    for p,v in f.factor():
        chi=fieldD.kronecker(p)
        e=QQ((1-p**v)*(1-chi))/(p**(v-1)*(1-p)*(chi-p))
        hst+=e*R(p).log()/2
    return hst


def eta_library(a,b,c):
    y=R(4*a*c-b*b).sqrt()/(2*a);tau=C(-R(b)/(2*a),y)
    return y*abs(tau.modular_eta())**4


def main():
    rows=json.loads((Path(__file__).parent/'check-input.json').read_text())['rows']
    expected=[];proper={}
    for d in range(3,101):
        fs=signed_forms(d)
        if not fs:continue
        proper[d]=fs
        expected.extend((d,*x) for x in sorted(set((a,abs(b),c) for a,b,c in fs)))
    actual=[(4*r['a']*r['c']-r['b']**2,r['a'],r['b'],r['c']) for r in rows]
    assert actual==expected
    assert len(rows)==107 and len(proper)==50
    assert sum(len(x) for x in proper.values())==132
    assert sum(r['b']==0 for r in rows)==35
    # Validate both nonzero known answers and deliberately invalid controls first.
    known=[]
    for form,answer in [((1,0,1),R(QQ(1)/4).gamma()**4/(16*pi**3)),
                        ((1,1,1),3*R(QQ(1)/3).gamma()**6/(32*pi**4))]:
        D,L,meta=heat(*form)
        assert compatible(D,answer) and compatible(L,answer.log())
        known.append({'form':form,'gamma_det':str(answer),'heat_det':str(D),'passed':True})
    D,L,_=heat(2,1,3);y=R(23).sqrt()/4
    bad={
        'unscaled_area_y_squared':not compatible(D,D*y),
        'missing_spectral_4pi_squared':not compatible(L,L+(4*pi*pi).log()),
        'flipped_log_sign':not compatible(L,-L),
        'interior_perturbation':not compatible(L,L+R(QQ(1)/10**50)),
        'vacuously_wide_ball':not compatible(D,D.add_error(100)),
        'nonfinite_ball':not compatible(D,R('nan')),
    }
    assert all(bad.values())
    evidence=[];class_sums=collections.defaultdict(lambda:R(0));modular_checks=0
    for row in rows:
        a,b,c=(row[k] for k in ('a','b','c'));d=4*a*c-b*b
        D,L,meta=heat(a,b,c)
        storedD=decimal_interval(row['det']);storedL=decimal_interval(row['logdet'])
        assert contains(storedD,D),('det mismatch',a,b,c,str(D),row['det'])
        assert contains(storedL,L),('logdet mismatch',a,b,c,str(L),row['logdet'])
        assert compatible(storedD,storedL.exp())
        for transformed in [(a,-b,c),(c,-b,a),(a,b+2*a,c+a+b)]:
            assert contains(storedD,eta_library(*transformed)),('modular',a,b,c,transformed)
            modular_checks+=1
        mu=1 if b==0 or b==a or a==c else 2
        class_sums[d]+=mu*L
        evidence.append({'form':[a,b,c],'d':d,'det_contained':True,'logdet_contained':True,
                         'heat_det':str(D),'heat_logdet':str(L),**meta})
        print('checked',len(evidence),'of',len(rows),file=sys.stderr,flush=True) if len(evidence)%20==0 else None
    class_checks=[]
    P=PolynomialRing(ZZ,'x')
    companions=Path(__file__).parent/'companions.json'
    comp=json.loads(companions.read_text()) if companions.exists() else None
    for d,fs in proper.items():
        h=len(fs);assert h==int(pari(-d).qfbclassno())
        hst=height(-d);rhs=-2*h*(hst+(2*pi).log())
        assert compatible(class_sums[d],rhs),('class sum',d,str(class_sums[d]),str(rhs))
        if comp:
            assert P(comp['T129'][str(-d)]['number']).degree()==h
            assert contains(decimal_interval(comp['T670'][str(-d)]['number']),hst)
        class_checks.append({'Delta':-d,'proper_classes':h,'height':str(hst),
                             'weighted_logdet':str(class_sums[d]),'gamma_conductor_rhs':str(rhs),'passed':True})
    # A=3/2 spectral scaling. E(0)=-1 implies the log shift; a nonsquare is included.
    scaling=[]
    for form in [(1,0,1),(2,1,3)]:
        D,L,_=heat(*form);A=R(QQ(3)/2)
        assert compatible((L+A.log()).exp(),A*D)
        scaling.append({'form':form,'area':'3/2','passed':True})
    result={'table':'T835','checked_entries':2*len(rows),'total_entries':2*len(rows),'failures':[],
            'known_answer_control':True,'negative_control_rejected':all(bad.values()),
            'known_controls':known,'negative_controls':bad,'individual_checks':evidence,
            'enumeration':{'shapes':len(rows),'discriminants':len(proper),'proper_classes':sum(map(len,proper.values())),
                           'rectangular':35,'nonrectangular':72,'method':'discriminant-first signed primitive reduced forms, sign folding'},
            'modular_checks':modular_checks,'class_checks':class_checks,'scaling_checks':scaling,
            'companion_stored_checks':comp is not None,'working_bits':560,
            'method':'heat/Mellin continuation with explicit Gaussian square tail; Gamma/conductor class averages',
            'limitations':'Builder checks, not an independent-session verdict. Area scaling test is an analytic law plus arithmetic consistency, not a separately computed rescaled spectrum.',
            'skill_manifest':'20261127T183759Z-build-skills/manifest.json'}
    print(json.dumps(result))

if __name__=='__main__':main()