theta_check.py

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

8639 bytes, as of the version from 2026-11-15 20:42 (current). Recorded here, not run.

"""Independent theta-Mellin check for T719; executable builder evidence.

    sage -pip install numberdb python-flint
    sage -python theta_check.py > theta-results.log

No zeta, L-function, Gamma or library character evaluation computes the
moments. The elementary Kronecker/Jacobi code is reused from the checked
family component, but every central moment is newly computed. FLINT ball
arithmetic and exp are shared with production. The 26 checkpoint lines
encode exact binary midpoint/radius pairs and are safe to resume.
The finite Gaussian series and infinite integral each have an absolute
bound added explicitly, including m! and all logarithmic moment weights.
See numerical-evidence.md for the derivation. Controls are part of this
builder evidence, not the controller's independent scientific verdict.
"""
import sys,json,time,math
from pathlib import Path
import numberdb.sage as numberdb
from flint import arb,acb,ctx,dirichlet_char

BITS=640
ORDER=20
U=9

def kronecker(D,r):
    if r == 0:
        return int(abs(D)==1)
    sign=1
    while r%2==0:
        if D%2==0:return 0
        if D%8 in (3,5):sign=-sign
        r//=2
    a=D%r
    while a:
        while a%2==0:
            a//=2
            if r%8 in (3,5):sign=-sign
        if a%4==r%4==3:sign=-sign
        a,r=r%a,a
    return sign if r==1 else 0


def squarefree(d):
    d=abs(d)
    return d>0 and all(d%(r*r) for r in range(2,math.isqrt(d)+1))


def discriminants():
    return sorted([D for D in range(-40,41) if D not in (0,1)
                   and ((D%4==1 and squarefree(D)) or
                        (D%4==0 and (D//4)%4 in (2,3) and squarefree(D//4)))],
                  key=lambda D:(abs(D),D<0))


def encode(x):
    m,e=x.mid().man_exp(); r,f=x.rad().man_exp()
    return [[int(m),int(e)],[int(r),int(f)]]


def decode(p):
    return arb(tuple(p[0]),tuple(p[1]))


def narrow(x,bits=370):
    return x.is_finite() and x.rel_accuracy_bits()>=bits


def agrees(x,y,bits=350):
    return narrow(x,bits) and narrow(y,bits) and x.overlaps(y)


def tails(D):
    q=abs(D);c=arb.pi()/q
    N=1
    while not c*N*N>650:N+=1
    M=N+1;rho=(-c*(2*M+1)).exp();T=arb(U).exp()
    scale=4*math.factorial(ORDER)
    gaussian=scale*(1/c+1/c**2)*(-c*M*M).exp()*(M/(1-rho)+rho/(1-rho)**2)
    integration=scale*(-c*T).exp()*(T/c+1/c**2)/(1-(-3*c*T).exp())**2
    assert gaussian+integration<arb(2)**-800
    return N,gaussian,integration


def theta_moments(D):
    q=abs(D);a=int(D<0);c=arb.pi()/q
    N,gaussian,integration=tails(D)
    weights=[r**a*kronecker(D,r) for r in range(1,N+1)]
    C=c.sqrt() if a else arb(1)
    coeff=[];calls=0
    for m in range(0,ORDER+1,2):
        def fun(u,analytic):
            nonlocal calls
            calls+=1
            ct=c*u.exp();g=(-ct).exp();delta=(-3*ct).exp();step=(-2*ct).exp()
            theta=acb(0)
            for w in weights:
                if w:theta+=w*g
                g*=delta;delta*=step
            v=u/2
            f0=v**(2*m)*math.factorial(m)/math.factorial(2*m)
            f1=v**(2*m+2)*math.factorial(m+1)/math.factorial(2*m+2)
            return 2*C*theta*(u*(2*a+1)/4).exp()*(f0+acb(0,1)*f1)
        r=acb.integral(fun,0,U,rel_tol=arb(2)**-550,abs_tol=arb(2)**-550,eval_limit=1000000)
        assert r.is_finite(),(D,m,r)
        for x in [r.real,r.imag]:coeff.append(x+arb(0,gaussian+integration))
    coeff=coeff[:ORDER+1]
    assert all(narrow(x,390) for x in coeff),(D,[x.rel_accuracy_bits() for x in coeff])
    return coeff,{'D':D,'N':N,'U':U,'gaussian_tail':str(gaussian),'integration_tail':str(integration),
                  'integrand_calls':calls,'minimum_value_accuracy_bits':min(x.rel_accuracy_bits() for x in coeff)}


def theta_at_one(D):
    q=abs(D);a=int(D<0);c=arb.pi()/q;N,B1,B2=tails(D)
    C=c.sqrt() if a else arb(1);weights=[r**a*kronecker(D,r) for r in range(1,N+1)]
    def fun(u,analytic):
        ct=c*u.exp();g=(-ct).exp();delta=(-3*ct).exp();step=(-2*ct).exp();theta=acb(0)
        for w in weights:
            if w:theta+=w*g
            g*=delta;delta*=step
        return C*theta*((u*(1+a)/2).exp()+(u*a/2).exp())
    r=acb.integral(fun,0,U,rel_tol=arb(2)**-550,abs_tol=arb(2)**-550)
    assert r.is_finite() and r.imag.contains(0)
    return r.real+arb(0,B1+B2)


def controls():
    known=[]
    for D in [-3,-4,5]:
        actual=theta_at_one(D)
        expected=arb.pi().sqrt()/(3 if D==-3 else 2) if D<0 else 2*((1+arb(5).sqrt())/2).log()
        known.append({'D':D,'actual':encode(actual),'expected':encode(expected),'passed':agrees(actual,expected,400)})
    # Analytic quadrature moment controls on [0,infinity):
    # integral exp(-u)*(u/2)^(2m)*m!/(2m)! du = m!/4^m.
    # Truncate at V=1024; integration by parts gives the exact tail.
    synthetic=[];V=1024
    for m in [0,1,2,20]:
        k=2*m
        f=lambda u,analytic: (-u).exp()*(u/2)**k*math.factorial(m)/math.factorial(k)
        val=acb.integral(f,0,V,rel_tol=arb(2)**-550,abs_tol=arb(2)**-550).real
        tail=arb(-V).exp()*sum((arb(V)**j/math.factorial(j) for j in range(k+1)),arb(0))*math.factorial(m)/4**m
        val+=arb(0,tail)
        expected=arb(math.factorial(m))/4**m
        synthetic.append({'m':m,'passed':agrees(val,expected,400),'actual':encode(val),'expected':encode(expected)})
    x=decode(known[0]['actual']);bad=[x+arb(10)**-60,arb('nan'),arb(0,10**20)]
    return {'known_answer_control':all(r['passed'] for r in known+synthetic),
            'negative_control_rejected':all(not agrees(x,y) for y in bad),
            'at_one':known,'analytic_moments':synthetic,
            'bad_controls':['shift by 1e-60','NaN','radius 1e20']}


def main():
    ctx.prec=BITS
    import generate
    ds=discriminants();assert ds==generate.discriminants()
    old={}
    checkpoint=Path(__file__).parent/'theta-checkpoints.json'
    if checkpoint.exists():
        old={r['D']:r for r in json.loads(checkpoint.read_text())}
    ctl=controls();assert ctl['known_answer_control'] and ctl['negative_control_rejected']
    print('CONTROLS '+json.dumps(ctl),flush=True)
    rows=[];failures=[];wrong_controls=[]
    for D in ds:
        start=time.time()
        if D in old:
            stats=old[D];vals=[decode(v) for v in stats['values']]
        else:
            vals,stats=theta_moments(D)
        original=generate.completed_jet(D)
        checks=[]
        for m,x in enumerate(vals):
            y=original[2*m].real*math.factorial(m)
            okay=agrees(x,y,390);checks.append(okay)
            if not okay:failures.append({'D':D,'m':m,'theta':str(x),'production':str(y)})
        matches=[]
        for label in range(1,abs(D)):
            if math.gcd(label,abs(D))!=1:continue
            chi=dirichlet_char(abs(D),label)
            if all(chi(r)==kronecker(D,r) for r in range(abs(D))):matches.append(label)
        assert len(matches)==1 and dirichlet_char(abs(D),matches[0]).is_primitive()
        stats.update({'seconds':time.time()-start,'conrey':matches[0],
                      'checked_entries':sum(checks),'values':[encode(x) for x in vals]})
        # Deliberate convention mutations at nonzero coefficients.
        if D in [-3,-4,5]:
            tests={'imaginary_axis_sign':-vals[1], 'ordinary_coefficient':vals[2]/2,
                   'raw_derivative':vals[2]*12,'index_shift':vals[2]}
            expected={'imaginary_axis_sign':original[2].real,'ordinary_coefficient':original[4].real*2,
                      'raw_derivative':original[4].real*2,'index_shift':original[2].real}
            if D<0:
                tests['alternative_completion']=vals[0]*(arb(abs(D))/arb.pi()).sqrt();expected['alternative_completion']=original[0].real
            wrong_controls.extend({'D':D,'mutation':k,'rejected':not agrees(v,expected[k],390)} for k,v in tests.items())
        rows.append(stats);print('CHECKPOINT '+json.dumps(stats),flush=True)
    out={'checked_entries':sum(r['checked_entries'] for r in rows),'total_entries':21*len(ds),
         'failures':failures,'known_answer_control':ctl['known_answer_control'],
         'negative_control_rejected':ctl['negative_control_rejected'] and all(r['rejected'] for r in wrong_controls),
         'bits':BITS,'quadrature_tolerance_bits':550,'discriminants':ds,
         'minimum_accuracy_bits':min(r['minimum_value_accuracy_bits'] for r in rows),
         'convention_negative_controls':wrong_controls,
         'shared_dependency':'FLINT 3.6.0 ball arithmetic and elementary exponentials; no shared L-series algorithm'}
    print('RESULT '+json.dumps(out),flush=True)
    assert not failures and out['known_answer_control'] and out['negative_control_rejected']

if __name__=='__main__':main()