theta_check.py

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

7713 bytes, as of the version from 2026-11-15 23:03 (current). Recorded here, not run.

"""Independent theta-Mellin check of quadratic Li coefficients.

Run in the Sage Python environment after installing numberdb and python-flint:
    sage -python theta_check.py > theta-results.log
Optional positional arguments restrict the discriminants for a pilot.
No L-function, Hurwitz-zeta, log-Gamma or Dirichlet-character library is used
in the checker. Character values use the elementary Jacobi algorithm.
Arb's validated complex quadrature encloses the theta moments; see
numerical-evidence.md for both truncation bounds and the normalization.
JSON checkpoint lines preserve every completed discriminant. The comparison
uses log-derivative division and a binomial sum, independently of the
production logarithm series. Production and checker share FLINT ball arithmetic.
This is builder evidence, not the separate scientific-review verdict.
"""
import sys,json,time,math
import numberdb.sage as numberdb
from flint import arb,acb,ctx,dirichlet_char

BITS=512
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 theta_jet(D):
    q=abs(D); a=int(D<0); c=arb.pi()/q
    # c*N^2 >= 520, outward-safe by incrementing the integer.
    N=1
    while not c*N*N>520:N+=1
    weights=[r**a*kronecker(D,r) for r in range(1,N+1)]
    C=c.sqrt() if a else arb(1)
    M=N+1;rho=(-c*(2*M+1)).exp()
    gaussian=4*(1/c+1/c**2)*(-c*M*M).exp()*(M/(1-rho)+rho/(1-rho)**2)
    T=arb(U).exp()
    integral_tail=4*(-c*T).exp()*(T/c+1/c**2)/(1-(-3*c*T).exp())**2
    tail=gaussian+integral_tail
    assert tail<arb(2)**-650
    coeff=[];calls=0
    for k in range(0,ORDER+1,2):
        factorial=math.factorial(k)
        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
            A=(u*(1+a)/2).exp()
            B=(u*a/2).exp()
            # k even; pack coefficient k and odd coefficient k+1.
            t=u/2
            f0=(A+B)*t**k/factorial
            f1=(A-B)*t**(k+1)/(factorial*(k+1))
            return C*theta*(f0+acb(0,1)*f1)
        result=acb.integral(fun,0,U,rel_tol=arb(2)**-450,
                            abs_tol=arb(2)**-450,eval_limit=1000000)
        assert result.is_finite(),(D,k,result)
        for x in [result.real,result.imag]:
            coeff.append(x+arb(0,tail))
    coeff=coeff[:ORDER+1]
    assert all(narrow(x,380) for x in coeff),(D,[x.rel_accuracy_bits() for x in coeff])
    # log-derivative recurrence: j*F_j=sum_{i=0}^{j-1} h_i*F_{j-1-i}.
    h=[]
    for j in range(1,ORDER+1):
        h.append((j*coeff[j]-sum((h[i]*coeff[j-1-i] for i in range(j-1)),arb(0)))/coeff[0])
    values=[]
    for n in range(1,ORDER+1):
        values.append(sum((math.comb(n,j)*h[j-1] for j in range(1,n+1)),arb(0)))
    assert all(narrow(x,365) for x in values)
    return values,coeff,{'D':D,'N':N,'U':U,'gaussian_tail':str(gaussian),
                         'integration_tail':str(integral_tail),'integrand_calls':calls,
                         'minimum_value_accuracy_bits':min(x.rel_accuracy_bits() for x in values)}


def transform_controls():
    from fractions import Fraction as Q
    F=[Q(5,4),Q(1),Q(1)]+[Q(0)]*18
    h=[];actual=[];expected=[]
    zre,zim=Q(1),Q(0)
    for j in range(1,21):
        h.append((j*F[j]-sum(h[i]*F[j-1-i] for i in range(j-1)))/F[0])
        actual.append(sum(math.comb(j,k)*h[k-1] for k in range(1,j+1)))
        zre,zim=(3*zre-4*zim)/5,(4*zre+3*zim)/5
        expected.append(2-2*zre)
    assert actual==expected
    assert all(actual[n-1]/n!=expected[n-1] for n in range(2,21))
    return {'synthetic_entire_function':'F(s)=(s-1/2)^2+1',
            'method':'exact Fraction log-derivative recurrence versus conjugate-zero powers',
            'orders':list(range(1,21)),
            'known_answer_control':True,'negative_control_rejected':True,
            'wrong_control':'Keiper lambda_n/n rejected for n=2,...,20',
            'values':[str(x) for x in actual]}


def main():
    ctx.prec=BITS
    import generate
    ds=[int(s) for s in sys.argv[1:]] or discriminants()
    assert discriminants()==generate.discriminants()
    results=[];failures=[];known=[]
    synthetic=transform_controls()
    for D in ds:
        start=time.time()
        vals,coeff,stats=theta_jet(D)
        original=generate.li_balls(D)
        checks=[]
        for n,(x,v) in enumerate(zip(vals,original),1):
            from sage.rings.real_mpfi import RealIntervalField
            interval=RealIntervalField(BITS)(v)
            lower=interval.lower().exact_rational();upper=interval.upper().exact_rational()
            y=(arb(int(lower.numerator()))/int(lower.denominator())).union(
                arb(int(upper.numerator()))/int(upper.denominator()))
            okay=agrees(x,y)
            checks.append(okay)
            if not okay:failures.append({'D':D,'n':n,'theta':str(x),'production':str(y)})
        # Independent finite Conrey-label matching against the hand-coded symbol.
        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],
                      'completed_jet':[encode(x) for x in coeff]})
        if D in (-3,-4,5):
            expected=arb.pi().sqrt()/(3 if D==-3 else 2) if D<0 else 2*((1+arb(5).sqrt())/2).log()
            known.append(agrees(coeff[0],expected))
        results.append(stats)
        print('CHECKPOINT '+json.dumps(stats),flush=True)
    x=decode(results[0]['values'][0]); y=x+arb(10)**-60
    bad=[y,arb('nan'),arb(0,10**20)]
    controls={'known_answer_control':bool(known) and all(known),
              'negative_control_rejected':all(not agrees(x,b) for b in bad) and synthetic['negative_control_rejected']}
    out={'checked_entries':sum(r['checked_entries'] for r in results),
         'total_entries':20*len(ds),'failures':failures,**controls,
         'bits':BITS,'quadrature_tolerance_bits':450,
         'shared_dependency':'FLINT 3.6.0 ball arithmetic; no shared L-series algorithm',
         'discriminants':ds,'minimum_accuracy_bits':min(r['minimum_value_accuracy_bits'] for r in results)}
    print('RESULT '+json.dumps(out),flush=True)
    assert not failures and all(controls.values())

if __name__=='__main__':main()