build_check.py

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

8530 bytes, as of the version from 2026-11-20 06:18 (current). Recorded here, not run.

"""Executable builder checks; stdout is a resumable JSON-lines checkpoint.

Run with SageMath and generate.py, roster.json in the same directory.
An optional checkpoint.json contains prior unmodified records from this code.
Each record is bound to the SHA-256 of these three input files. This builder
check is evidence for a fresh critic, not an independent review verdict.
"""
import hashlib
import json
from decimal import Decimal
from fractions import Fraction
from pathlib import Path

import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_mpfr import RealField
from sage.libs.pari import pari
from numberdb._write import to_text
import generate

BASE=Path(__file__).resolve().parent
DIGEST=hashlib.sha256(b''.join((BASE/n).read_bytes() for n in
                            ('generate.py','build_check.py','roster.json'))).hexdigest()


def emit(record):
    record['input_sha256']=DIGEST
    print('CHECKPOINT '+json.dumps(record,sort_keys=True),flush=True)


def rational(text):
    f=Fraction(Decimal(text))
    return QQ(f.numerator)/ZZ(f.denominator)


def decimal_interval(text):
    d=Decimal(text)
    x=rational(text)
    e=d.as_tuple().exponent
    u=QQ(10)**e
    return x-u,x+u


def accepts(text,reference):
    lo,hi=decimal_interval(text)
    return bool(lo<reference<hi and hi-lo<QQ(1)/ZZ(10)**97)


def brute_ap(ainvs,p):
    a1,a2,a3,a4,a6=ainvs
    count=1
    for x in range(p):
        for y in range(p):
            if (y*y+a1*x*y+a3*y-x**3-a2*x*x-a4*x-a6)%p==0:
                count+=1
    return p+1-count


def main():
    cache={}
    if (BASE/'checkpoint.json').exists():
        for r in json.loads((BASE/'checkpoint.json').read_text()):
            assert r['input_sha256']==DIGEST, 'Checkpoint dependencies changed'
            cache[r['kind'],r.get('label','')]=r
    failures=[]
    classes={r['cremona_class']:r for r in generate.ROWS if r['curve_number']==1}
    # Exact algebraic input checks on all 284 curves, not only the 76 outputs.
    for row in generate.ROWS:
        label=row['cremona_label']
        if ('curve',label) in cache:
            emit(cache['curve',label]);continue
        P=pari(row['ainvs']).ellinit()
        rank=P.ellrank()
        bounds=[int(rank[0]),int(rank[1])]
        assert bounds==[0,0], ('Unresolved algebraic rank',label,str(rank))
        red=P.ellglobalred()
        assert int(red[0])==row['N']
        change=[str(x) for x in red[1]]
        assert change[0]=='1'
        minimal,minimal_change=P.ellminimalmodel()
        assert [int(x) for x in list(minimal)[:5]]==row['ainvs']
        assert [int(P[9]),int(P[10]),int(P.disc())]==[row['c4'],row['c6'],row['discriminant']]
        tors=P.elltors()
        assert int(tors[0])==row['source_torsion']
        assert sorted(int(x) for x in tors[1])==sorted(row['source_torsion_structure'])
        source_point_checks=[]
        for xyz,order in zip(row['source_torsion_generators'],row['source_torsion_structure']):
            X,Y,Z=xyz
            a1,a2,a3,a4,a6=row['ainvs']
            assert Y*Y*Z+a1*X*Y*Z+a3*Y*Z*Z==X**3+a2*X*X*Z+a4*X*Z*Z+a6*Z**3
            assert Z!=0
            point=[QQ(X)/ZZ(Z),QQ(Y)/ZZ(Z)]
            assert int(P.ellorder(point))==order
            source_point_checks.append({'point':xyz,'order':order})
        local=[]
        for p in generate.prime_sieve(row['N']):
            if row['N']%p==0:
                info=P.elllocalred(p)
                ap=int(P.ellap(p))
                assert generate.count_ap(row['ainvs'],p)==ap
                assert ap in (-1,0,1)
                local.append({'p':p,'conductor_exponent':int(info[0]),
                              'kodaira_code':int(info[1]),'tamagawa':int(info[3]),
                              'a_p':ap,'euler_factor':[1,-ap],
                              'reduction':'additive' if ap==0 else ('split multiplicative' if ap==1 else 'nonsplit multiplicative')})
        rep=classes[row['cremona_class']]
        repP=pari(rep['ainvs']).ellinit()
        aprimes={str(p):int(P.ellap(p)) for p in generate.prime_sieve(97)}
        assert all(ap==int(repP.ellap(int(p))) for p,ap in aprimes.items())
        emit({'kind':'curve','label':label,'lmfdb_label':row['lmfdb_label'],
              'ainvs':row['ainvs'],'params':{k:row[k] for k in ('N','c4','c6')},
              'source_class':row['cremona_class'],'L_value_params':{k:rep[k] for k in ('N','c4','c6')},
              'source_rank':0,'algebraic_rank_bounds':bounds,'rank_method':'PARI ellrank 2-descent, effort=0',
              'rank_raw':str(rank),'global_model_change':change,
              'minimal_model_unchanged':True,'differential_scale':'1',
              'torsion_order':int(tors[0]),'torsion_structure':[int(x) for x in tors[1]],
              'source_torsion_points_checked':source_point_checks,
              'real_components':2 if row['discriminant']>0 else 1,
              'rank_zero_regulator':'1','bad_local_data':local,
              'small_prime_ap':aprimes,'root_number':int(P.ellrootno())})
    for row in classes.values():
        label=row['cremona_label']
        if ('value',label) in cache:
            emit(cache['value',label]);continue
        params={k:row[k] for k in ('N','c4','c6')}
        ball,info=generate.evaluate(**params)
        assert type(ball).__name__=='RealBall'
        text=to_text(ball,digits=100)
        lo,hi=decimal_interval(text)
        assert lo<=QQ(info['lower'])<=QQ(info['upper'])<=hi
        P=pari(row['ainvs']).ellinit()
        approx={}
        values=[]
        for bits in [832,1024]:
            pari.set_real_precision_bits(bits)
            v=P.lfun(1,precision=bits)
            assert int(v.bitprecision())>=bits
            real=RealField(bits)(v)
            assert not (real.is_NaN() or real.is_infinity())
            exact=real.exact_rational()
            assert accepts(text,exact)
            approx[str(bits)]=str(v)
            values.append(exact)
        assert abs(values[0]-values[1])<QQ(10)**(-230)
        coeff,fac=generate.euler_coefficients(row['ainvs'],row['discriminant'],info['M'])
        paricoeff=[0]+[int(x) for x in P.ellan(info['M'])]
        assert coeff==paricoeff
        independent_ap={}
        for p in generate.prime_sieve(97):
            b=brute_ap(row['ainvs'],p)
            assert b==int(P.ellap(p))==generate.count_ap(row['ainvs'],p)
            independent_ap[str(p)]=b
        # Both wrong sign and omitted factor two must be rejected by the
        # exact same comparison routine used for positive data.
        assert not accepts(text,-values[-1])
        assert not accepts(text,values[-1]/2)
        emit({'kind':'value','label':label,'params':params,'number':text,
              'enclosure':info,'pari_lfun':approx,
              'all_euler_coefficients_checked':info['M'],
              'independent_brute_ap_through_97':independent_ap,
              'wrong_sign_rejected':True,'omitted_factor_two_rejected':True})
    # Independent published positive control at a supported precision.
    row=next(r for r in generate.ROWS if r['cremona_label']=='11a1')
    ball,_=generate.evaluate(row['N'],row['c4'],row['c6'])
    known=rational('0.25384186085591068433775892335090946104')
    assert abs(ball-known)<generate.RealBallField(640)(QQ(10)**(-38))
    P=pari(row['ainvs']).ellinit()
    pari.set_real_precision_bits(1024)
    periods=P.ellperiods(precision=1024)
    real_periods=[w.real() for w in periods if w.imag()==0 and w.real()>0]
    assert len(real_periods)==1
    ratio=RealField(1024)(P.lfun(1,precision=1024)/real_periods[0])
    assert abs(ratio-QQ(1)/5)<QQ(10)**(-280)
    # Membership checks alone would miss this deliberately invalid float.
    assert type(2/1) is float
    emit({'kind':'summary','label':'','checked_entries':len(classes),'total_entries':len(classes),
          'checked_curve_inputs':len(generate.ROWS),'failures':failures,
          'known_answer_control':True,'negative_control_rejected':True,
          'control_11a1_ratio':'1/5','control_ratio_error':str(abs(ratio-QQ(1)/5)),
          'control_period_selection':'unique positive real member of PARI period basis',
          'pari_version':str(pari.version()),'precision_bits':[640,832,1024],
          'limitations':'PARI lfun checks are nonrigorous approximations; they do not supply the production bound. Shared PARI library supplies conductor, minimal-model checks, roots and descent. No Sha order was computed.'})


if __name__=='__main__':
    main()