compute-v1.py

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

5583 bytes, as of the version from 2026-11-26 02:34 (current). Recorded here, not run.

"""Find rational positive test polynomials; independently certify their inequalities.
No API writes. Exact test coefficients and root endpoints are emitted as JSON.
"""
import numberdb.sage as numberdb
import sage.all
from sage.rings.rational_field import QQ
from sage.rings.real_mpfr import RealField
from sage.rings.real_arb import RealBallField
from sage.matrix.constructor import matrix
from sage.modules.free_module_element import vector
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
import json,time,sys

N=160; R=RealField(700); B=RealBallField(1400)
P=PolynomialRing(R,'x'); x=P.gen()

def candidate(alphabet,guess):
    start=time.time();n=N
    theta=[R.pi()*(2*j+1)/(2*n) for j in range(n)]
    nodes=[t.cos() for t in theta];xs=[(u+1)/2 for u in nodes]
    factors=[(-1 if j%2 else 1)*theta[j].sin()/n for j in range(n)]
    basis=[];logs=[]
    for a in alphabet:
        ba=[];la=[]
        for xi in xs:
            y=2/(a+xi)-1
            tn=(n*y.arccos()).cos()
            ba.append([factors[j]*tn/(y-nodes[j]) for j in range(n)])
            la.append((a+xi).log())
        basis.append(ba);logs.append(la)
    s=R(guess)
    for it in range(9):
        weights=[[( -2*s*l).exp() for l in la] for la in logs]
        W=matrix(R,n,n,lambda i,j:sum(weights[k][i]*basis[k][i][j] for k in range(len(alphabet))))
        D=matrix(R,n,n,lambda i,j:sum(-2*logs[k][i]*weights[k][i]*basis[k][i][j] for k in range(len(alphabet))))
        H=W-1;A=H[1:,1:];v=vector(R,[1]+list(A.solve_right(-H[1:,0].column(0))))
        residual=(H*v)[0]
        dv=vector(R,[0]+list(A.solve_right(-(D*v)[1:])))
        deriv=(D*v+H*dv)[0]
        correction=residual/deriv
        print('NEWTON',alphabet,it,'correction',float(correction),'sec',round(time.time()-start,2),flush=True)
        if abs(correction)<R(10)**(-145):break
        s-=correction
    else:raise ValueError('Newton did not converge')
    coeff=[sum(v[j]*(k*theta[j]).cos() for j in range(n))*(R(1)/n if k==0 else R(2)/n) for k in range(n)]
    f=P(coeff[0]);t0=P(1);t1=2*x-1
    for k in range(1,n):
        if k==1:tk=t1
        else:tk=2*(2*x-1)*t1-t0;t0,t1=t1,tk
        f+=coeff[k]*tk
    exact=[q.exact_rational() for q in f.list()]
    base=10**104;k=int((s*base).floor());lo=QQ(k-1)/base;hi=QQ(k+2)/base
    return {'alphabet':list(alphabet),'lo':str(lo),'hi':str(hi),'coefficients':[str(q) for q in exact],'nodes':n,'candidate_bits':700,'certificate_bits':1400,'elapsed_candidate':time.time()-start}

def certify(cert,subdivisions=16,order=200):
    # On each disk |z-c|<=rho=1/2, bound |g(z)| by sum |c_k|/(a+c-rho)^(2s+k)
    # plus sum |c_k|(c+rho)^k. Cauchy bounds tail by M*(h/rho)^order/(1-h/rho).
    # All Taylor coefficients and Cauchy majorants are outward-rounded balls.
    coeff=[B(QQ(v)) for v in cert['coefficients']];n=len(coeff);rho=B(1)/2;h=B(1)/(2*subdivisions)
    evidence=[]
    for endpoint,direction in [('lo',1),('hi',-1)]:
        s=B(QQ(cert[endpoint]));worst=None;worst_f=None;max_tail=B(0)
        for interval in range(subdivisions):
            c=B(QQ(2*interval+1)/(2*subdivisions))
            # polynomial Taylor coefficients at c, by binomial recursion per monomial.
            ft=[B(0)]*max(n,order)
            for k,ck in enumerate(coeff):
                term=ck
                for j in range(k,-1,-1):
                    ft[j]+=term
                    if j:term*=c*j/(k-j+1)
            gt=[-ft[j] for j in range(order)]
            major=sum(abs(ck)*(c+rho)**k for k,ck in enumerate(coeff))
            for a in cert['alphabet']:
                q=B(a)+c;qm=q-rho
                major+=sum(abs(ck)*qm**(-2*s-k) for k,ck in enumerate(coeff))
                for k,ck in enumerate(coeff):
                    term=ck*q**(-2*s-k)
                    for j in range(order):
                        gt[j]+=term
                        term*=(-2*s-k-j)/(q*(j+1))
            ratio=h/rho;tail=major*ratio**order/(1-ratio)
            error=tail+sum(abs(gt[j])*h**j for j in range(1,order))
            lower=direction*gt[0]-error
            flower=ft[0]-sum(abs(ft[j])*h**j for j in range(1,n))
            if not lower>0 or not flower>0:
                print('CERT_FAIL',cert['alphabet'],endpoint,interval,'margin',lower,'f',flower,'tail',tail,flush=True)
                return False
            if worst is None or lower<worst:worst=lower
            if worst_f is None or flower<worst_f:worst_f=flower
            if tail>max_tail:max_tail=tail
        evidence.append({'endpoint':endpoint,'minimum_residual_margin':str(worst),'minimum_f':str(worst_f),'maximum_tail':str(max_tail)})
    cert['certification']={'subdivisions':subdivisions,'order':order,'rho':'1/2','results':evidence}
    return True

if __name__=='__main__':
    samples=[([1,2],'0.53128050627720514162'),(list(range(1,11)),'0.92573759088754612367')]
    if len(sys.argv)>1 and sys.argv[1]=='all':
        guesses=['.5312805063','.7056609080','.7889455575','.8368294437','.8676191732','.8889553164','.9045526893','.9164211134','.9257375909']
        samples=[(list(range(1,a+1)),g) for a,g in zip(range(2,11),guesses)]+[([2,4,6,8,10],'.5173570309'),([1,4,9],'.5007902321'),([2,3,6,9],'.5003228006')]
    for alphabet,guess in samples:
        t=time.time();cert=candidate(alphabet,guess);print('CANDIDATE_JSON '+json.dumps(cert),flush=True)
        assert certify(cert),'certificate failed'
        cert['elapsed_total']=time.time()-t
        print('CERT_JSON '+json.dumps(cert),flush=True)
        print('DONE',alphabet,'seconds',round(time.time()-t,2),flush=True)