independent_check.py

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

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

"""T776: fresh theta-integral xi minus an independent gamma-factor trend.

SageMath 10.9, Arb/FLINT and numberdb; no generator import and no production
zeta or eta series supplies the independent values. Reuses the inspected
quadrature structure of published T757's checker, not its numerical data.
Shared substrate: completed-xi theory, Sage and Arb/FLINT ball arithmetic.
  sage -python independent_check.py
Place production.json or stored-document.json alongside this source for a
full comparison. theta-checkpoint.json is optional; a valid partial checkpoint
resumes the 100 integrals instead of repeating expensive work. Each new
coefficient is also printed as a durable JSON line for remote checkpointing.
The checker writes check-results.json; it is build evidence, not an independent
actor's scientific or argument-selection verdict.

DLMF 25.5.13--14: xi(1+u)=1/2+(u+u^2)*A(u)/2, where
A_j=integral_1^infinity (sqrt(x)+(-1)^j)*(log(x)/2)^j*theta(x)/(j!*x) dx.
All j>=0 satisfy (log(x)/2)^j/j! <= sqrt(x), x>=1, hence the absolute
integrand is at most 2*theta(x). With theta=sum_{m>=1} exp(-pi*m*m*x),
the omitted x>=L tail is bounded by
2 exp(-pi L)/(pi*(1-exp(-3*pi L))), and omitted m>=a=M+1 by
2 exp(-pi*a*a)/(pi*a*a*(1-exp(-pi*(2*a+1)))). These follow by termwise
integration and m*m>=1+3*(m-1), respectively
m*m>=a*a+(2*a+1)*(m-a). These are uniform bounds including all log weights.
"""
import json,pathlib,time,hashlib
from math import factorial,comb
from fractions import Fraction
import numberdb.sage as numberdb
from sage.rings.complex_arb import ComplexBallField
from sage.rings.real_arb import RealBallField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.rational_field import QQ

VERSION='theta-xi-minus-gamma-li-v1'
BITS=1024;M=14;LIMIT=192;NMAX=100;TOL_BITS=760
C=ComplexBallField(BITS);R=RealBallField(BITS)
CONFIG={'version':VERSION,'working_bits':BITS,'M':M,'limit':LIMIT,'nmax':NMAX,'tol_bits':TOL_BITS}

def narrow(x,bits=400):
    return bool(x.is_finite() and not x.contains_zero() and x.accuracy()>=bits)

def compare(a,b,minimum=400):
    return bool(narrow(a,minimum) and narrow(b,minimum) and (a-b).contains_zero())

def inside(v,lo,hi):
    return bool(narrow(v) and v>R(lo) and v<R(hi) and v.rad_as_ball()<R(hi-lo)/1000)

def stored_bounds(s):
    s=str(s)
    if '+/-' in s:
        c,r=s.split('+/-');c=Fraction(c.strip());r=Fraction(r.strip())
        return QQ(c-r),QQ(c+r)
    if s.startswith('['):
        a,b=s[1:-1].split(',');return QQ(Fraction(a)),QQ(Fraction(b))
    f=Fraction(s)
    if '.' not in s and 'e' not in s.lower():return QQ(f),QQ(f)
    mant,_,exp=s.lower().partition('e');places=len(mant.split('.')[1]) if '.' in mant else 0
    ulp=Fraction(10)**(int(exp or 0)-places)
    return QQ(f-ulp),QQ(f+ulp)

def theta_coefficients(work):
    cp=work/'theta-checkpoint.json';A=[]
    if cp.exists():
        data=json.loads(cp.read_text())
        assert all(data[k]==v for k,v in CONFIG.items()),'Checkpoint convention mismatch'
        A=[R(x) for x in data['coefficients']]
        assert len(A)<=NMAX and all(x.is_finite() for x in A)
    pi=C.pi()
    tx=2*(-R.pi()*LIMIT).exp()/(R.pi()*(1-(-3*R.pi()*LIMIT).exp()))
    a=M+1
    tm=2*(-R.pi()*a*a).exp()/(R.pi()*a*a*(1-(-R.pi()*(2*a+1)).exp()))
    tail=(tx+tm).upper()
    for j in range(len(A),NMAX):
        def f(x,analytic):
            # sqrt and log are analytic throughout the right half-plane.
            if analytic and x.real().lower()<=0:return C('nan')
            theta=sum(((-pi*m*m*x).exp() for m in range(1,M+1)),C(0))
            return (x.sqrt()+(-1)**j)*(x.log()/2)**j*theta/(x*factorial(j))
        z=C.integral(f,1,LIMIT,abs_tol=R(2)**(-TOL_BITS),rel_tol=R(2)**(-TOL_BITS),eval_limit=100000,depth_limit=30)
        assert z.real().is_finite() and z.imag().is_finite() and z.imag().contains_zero(),('Quadrature',j)
        value=z.real()+R(0,rad=tail)
        assert value.is_finite()
        A.append(value)
        record=dict(CONFIG,index=j,ball=str(value))
        print('THETA_COEFFICIENT_JSON '+json.dumps(record),flush=True)
        data=dict(CONFIG,coefficients=[str(v) for v in A],tail_x=str(tx),tail_m=str(tm))
        try:cp.write_text(json.dumps(data,indent=2))
        except OSError:pass
    return A,tx,tm

def from_theta(A):
    q=[R(QQ(1)/2)]
    for j in range(1,NMAX+1):q.append((A[j-1]+(A[j-2] if j>=2 else 0))/2)
    # Substitute u=w/(1-w), then logarithm by the derivative recurrence.
    b=[q[0]]+[sum((comb(n-1,j-1)*q[j] for j in range(1,n+1)),R(0)) for n in range(1,NMAX+1)]
    lam=[R(0)]
    for n in range(1,NMAX+1):
        lam.append((n*b[n]-sum((lam[k]*b[n-k] for k in range(1,n)),R(0)))/b[0])
    # Independent gamma-factor series, with no zeta call.
    P=PolynomialRing(R,'u');u=P.gen()
    gamma=(R(QQ(3)/2)+u/2)._lgamma_series(NMAX+1)-(1+u)*R.pi().log()/2
    trend=[R(0)]+[sum((j*comb(n,j)*gamma[j] for j in range(1,n+1)),R(0)) for n in range(1,NMAX+1)]
    return [lam[n]-trend[n] for n in range(1,NMAX+1)],lam,trend

def run():
    work=pathlib.Path(__file__).parent;start=time.time()
    A,tx,tm=theta_coefficients(work);values,lam,trend=from_theta(A)
    tol=R(2)**(-TOL_BITS);pi=C.pi()
    quad=C.integral(lambda x,_:(-pi*x).exp(),1,LIMIT,abs_tol=tol,rel_tol=tol).real()
    exact=((-R.pi()).exp()-(-R.pi()*LIMIT).exp())/R.pi()
    lambda1=1+(R.euler_constant()-(4*R.pi()).log())/2
    known=bool(compare(quad,exact,650) and compare(lam[1],lambda1,600) and compare(values[0],R.euler_constant(),600))
    wrong={'sign':(values[16],-values[16]),'division by n':(values[16],values[16]/17),
           'order shift':(values[16],values[17]),'incorrect pole deflation constant':(values[0],values[0]/2),
           'NaN':(values[0],R('nan')),'vacuous ball':(values[0],R('0 +/- 1e100'))}
    source=work/'stored-document.json'
    if not source.exists():source=work/'production.json'
    doc=json.loads(source.read_text())
    if 'Numbers' in doc:
        numbers=doc['Numbers']
        if isinstance(numbers,dict):
            rows=[{'params':{'n':str(k)},'number':v['number'] if isinstance(v,dict) else v} for k,v in numbers.items()]
        else:rows=numbers
    else:rows=doc['entries']
    production=work/'production.json'
    if production.exists():
        e=[R(x) for x in json.loads(production.read_text())['eta']]
        wrong['omitted binomial weights']=(values[16],-sum(e[:17],R(0)))
        wrong['eta index shifted by one']=(values[16],-sum((comb(17,m)*e[m] for m in range(1,18)),R(0)))
    rejected={name:not compare(a,b) for name,(a,b) in wrong.items()}
    lo,hi=stored_bounds(rows[0]['number']);shift=100*(hi-lo)
    rejected['shifted stored interval']=not inside(values[0],lo+shift,hi+shift)
    result=dict(CONFIG,checked_entries=0,total_entries=100,failures=[],known_answer_control=known,
                negative_control_rejected=all(rejected.values()),negative_controls=rejected,
                known_controls={'nonzero exponential quadrature':compare(quad,exact,650),
                                'lambda1 closed form':compare(lam[1],lambda1,600),
                                'C1 Euler constant':compare(values[0],R.euler_constant(),600)},
                minimum_relative_bits=min(int(v.accuracy()) for v in values),
                values=[str(v) for v in values],li_coefficients=[str(v) for v in lam[1:]],
                trend=[str(v) for v in trend[1:]],tail_x=str(tx),tail_m=str(tm),
                input_sha256=hashlib.sha256(source.read_bytes()).hexdigest(),input_file=source.name,
                shared_substrate='Sage/Arb/FLINT and completed-xi identities; fresh theta inputs, no production zeta series',
                seconds=time.time()-start)
    assert [int(row['params']['n']) for row in rows]==list(range(1,101)),'Selection differs'
    comparisons=[]
    for row in rows:
        n=int(row['params']['n']);lo,hi=stored_bounds(row['number']);v=values[n-1]
        ok=inside(v,lo,hi)
        comparisons.append({'n':n,'stored_contains_independent_ball':ok,'relative_bits':int(v.accuracy())})
        if not ok:result['failures'].append('Stored C_'+str(n))
    result['checked_entries']=100;result['comparisons']=comparisons
    if not known or not all(rejected.values()):result['failures'].append('Control failed')
    if not all(narrow(v) for v in values):result['failures'].append('Insufficient precision')
    print('CHECK_RESULTS_JSON '+json.dumps(result),flush=True)
    try:(work/'check-results.json').write_text(json.dumps(result,indent=2))
    except OSError:pass
    if result['failures']:raise SystemExit('Independent checks failed')
if __name__=='__main__':run()