check_coefficients.py

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

10132 bytes, as of the version from 2026-11-30 19:04 (current). Recorded here, not run.

"""Separate bounded numerical check for T872 (no generator import).

sage -python check_coefficients.py --input coefficients.json --output check-results.json
Default input is coefficients.json beside this script; default output is stdout.
Use --input stored-entries.json with an export in the same row schema to check
read-back values. This is builder check evidence, not an independent actor verdict.

Evaluates H_p(u)=u*zeta_p(1+u) by binomial/Bernoulli sums and modular
integer principal-unit powers, then interpolates five nodes. Teichmuller roots
are Newton lifted explicitly. Bernoulli numbers use an exact defining recurrence,
independent of the generator's FLINT call. No logarithm or log-power polynomial
routine is used. See mathematics.md for truncation/extraction bounds.
"""
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.padics.factory import Qp
from sage.libs.pari import pari
import argparse,json,time,sys,math,hashlib
from pathlib import Path

PRIMES=(3,5,7,11,13,17,19,23,29,31)


def vp(x,p):
    return QQ(x).valuation(p)


def bernoulli_recurrence(limit):
    B=[QQ(1)]
    for n in range(1,limit):
        if n>1 and n%2:
            B.append(QQ(0));continue
        total=QQ(0);choose=1
        for j in range(n):
            total+=choose*B[j]
            choose=choose*(n+1-j)//(j+1)
        B.append(-total/ZZ(n+1))
    assert B[:5]==[1,-QQ(1)/2,QQ(1)/6,0,-QQ(1)/30]
    return B


def weights():
    # Exact rational Lagrange weights at the scaled nodes 0,1,2,3,4.
    W=[]
    for j in range(5):
        coeff=[QQ(1)];den=1
        for k in range(5):
            if k==j:continue
            nxt=[QQ(0)]*(len(coeff)+1)
            for r,b in enumerate(coeff):nxt[r]-=k*b;nxt[r+1]+=b
            coeff=nxt;den*=j-k
        W.append([c/ZZ(den) for c in coeff])
    return [[W[j][r] for j in range(5)] for r in range(5)]


WEIGHTS=weights()


def interpolate(vals):
    return [sum((w*y for w,y in zip(row,vals)),QQ(0)) for row in WEIGHTS]


def interpolation_controls():
    truth=[QQ(7),QQ(-3),QQ(2)/5,QQ(11)/7,QQ(-13)/2]
    vals=[sum((c*ZZ(j)**r for r,c in enumerate(truth)),QQ(0)) for j in range(5)]
    assert interpolate(vals)==truth
    assert interpolate([ZZ(j)**5 for j in range(5)])==[0,-24,50,-35,10]
    return {'degree_four_exact':True,'degree_five_alias_exact':True}


def lift_root(a,p,W):
    r=a;prec=1
    while prec<W:
        prec=min(2*prec,W);mod=p**prec
        f=(pow(r,p-1,mod)-1)%mod
        deriv=((p-1)*pow(r,p-2,mod))%mod
        r=(r-f*pow(deriv,-1,mod))%mod
    assert r%p==a and pow(r,p-1,p**W)==1
    return r


class Deflated:
    def __init__(self,p,P,B):
        self.p=p;self.P=P;self.W=P+1;self.mod=p**self.W;self.J=P+2
        self.moments=[]
        for k,b in enumerate(B[:self.J]):
            num=int(b.numerator());den=int(b.denominator());d=0
            while den%p==0:den//=p;d+=1
            assert d<=1 and k>=d
            self.moments.append((num*pow(den,-1,self.mod)*pow(p,k-d,self.mod))%self.mod)
        self.units=[]
        for a in range(1,p):
            omega=lift_root(a,p,self.W)
            q=(a*pow(omega,-1,self.mod))%self.mod
            assert q%p==1
            self.units.append((q,pow(a,-1,self.mod)))

    def scaled_value(self,u):
        # Returns p*H(u) mod p^(P+1), i.e. H(u) mod p^P.
        if u==0:return self.p-1
        mod=self.mod;p=self.p
        unit=1;valuation=0;binoms=[1]
        for k in range(1,self.J):
            num=-u-k+1
            if num==0:
                binoms.extend([0]*(self.J-k));break
            den=k;vn=0;vd=0
            while num%p==0:num//=p;vn+=1
            while den%p==0:den//=p;vd+=1
            valuation+=vn-vd
            assert valuation>=0
            unit=(unit*(num%mod)*pow(den,-1,mod))%mod
            binoms.append((unit*pow(p,valuation,mod))%mod)
        products=[(b*t)%mod for b,t in zip(binoms,self.moments)]
        total=0
        for q,ainv in self.units:
            s=0;ak=1
            for b in products:
                s=(s+b*ak)%mod;ak=(ak*ainv)%mod
            total=(total+pow(q,-u,mod)*s)%mod
        return total

    def value(self,u):
        return QQ(self.scaled_value(u))/ZZ(self.p)


def congruent(x,y,p,A):
    return vp(QQ(x)-QQ(y),p)>=A


def run(rows):
    assert len(rows)==40
    assert [(int(r['p']),int(r['n'])) for r in rows]==[(p,n) for p in PRIMES for n in range(4)]
    controls=interpolation_controls();failures=[];details=[];checkpoints=[]
    plan={}
    for p in PRIMES:
        group=[r for r in rows if int(r['p'])==p];A=max(int(r['absolute_places']) for r in group)
        lam=int(ZZ(24).valuation(p));M=A+2+lam;P=A+4*M+lam+2
        plan[p]=(A,lam,M,P)
    started=time.monotonic();B=bernoulli_recurrence(max(P+2 for A,lam,M,P in plan.values()))
    print('BERNOULLI_RECURRENCE '+json.dumps({'count':len(B),'seconds':time.monotonic()-started}),flush=True)
    prefix={3:(19410,10),5:(4662880,10),7:(42713662,10),
        11:(1+10*11+2*11**2+11**3+5*11**4+5*11**5+4*11**6,7),
        13:(4*13+7*13**3+8*13**4+7*13**5+6*13**6+4*13**7,8)}
    for p in PRIMES:
        start=time.monotonic();group=[r for r in rows if int(r['p'])==p]
        A,lam,M,P=plan[p];ev=Deflated(p,P,B);h=ZZ(p)**M
        # Exact branch/scale controls at nonzero interpolation integers.
        branch=[]
        for k in [p-1,2*(p-1)]:
            expected=(1-ZZ(p)**(k-1))*B[k]
            ok=congruent(ev.value(-k),expected,p,P)
            assert ok,(p,'branch control',k)
            branch.append({'k':k,'absolute_places':P,'ok':ok})
        assert ev.value(0)==QQ(p-1)/p
        assert B[1]==-QQ(1)/2
        vals=[QQ(p-1)/p]+[ev.value(int(j*h)) for j in range(1,5)]
        poly=interpolate(vals)
        # Include an additional independently implemented library node check.
        Q=Qp(p,prec=55,print_mode='val-unit');uu=ZZ(p)**3
        reference=Q(uu)*Q(pari(Q(1+uu)).zeta())
        assert reference.precision_absolute()>=40
        assert (Q(ev.value(int(uu)))-reference).valuation()>=40
        extracted=[];rowchecks=[]
        for n,r in enumerate(group):
            order=n+1;coefficient=poly[order]/h**order
            outA=int(r['absolute_places']);original=QQ(r['residue'])
            alias_bound=M-1-lam
            arithmetic_bound=P-order*M-lam
            assert alias_bound>=outA+1 and arithmetic_bound>=outA+2
            ok=congruent(original,coefficient,p,outA)
            perturb=original+ZZ(p)**(outA-1)
            negative=not congruent(perturb,coefficient,p,outA)
            omitted_scale=not congruent(p*original,coefficient,p,outA)
            # Replacing only H(0)'s residue by 1 corrupts the extraction.
            wrong_residue=coefficient+WEIGHTS[order][0]*(1-QQ(p-1)/p)/h**order
            bad_residue=not congruent(original,wrong_residue,p,outA)
            wrong_sign=True
            if order%2:wrong_sign=not congruent(-original,coefficient,p,outA)
            wrong_factorial=True
            if order>1:wrong_factorial=not congruent(ZZ(order).factorial()*original,coefficient,p,outA)
            assert negative and omitted_scale and bad_residue and wrong_sign and wrong_factorial
            if not ok:failures.append({'p':p,'n':n,'reason':'independent coefficient mismatch'})
            q=Qp(p,prec=outA+10,print_mode='val-unit')(coefficient).add_bigoh(outA)
            rec={'p':p,'n':n,'absolute_places':outA,'residue':str(q.lift()),
                'ok':bool(ok),'perturbation_rejected':negative,'omitted_disk_scale_rejected':omitted_scale,
                'wrong_residue_rejected':bad_residue,'wrong_sign_control':wrong_sign,'wrong_sign_applicable':bool(order%2),
                'wrong_factorial_control':wrong_factorial,'wrong_factorial_applicable':bool(order>1),'alias_bound':alias_bound,
                'arithmetic_bound':arithmetic_bound}
            extracted.append(rec);rowchecks.append(rec)
        r=group[0];Ac=int(r['absolute_places']);QG=Qp(p,prec=Ac+15,print_mode='val-unit')
        gamma=-QG(pari(QG(1)).psi())
        assert gamma.precision_absolute()>=Ac
        gamma_ok=(gamma-QG(QQ(r['residue']))).valuation()>=Ac
        assert gamma_ok,(p,'Morita psi')
        prefix_ok=None
        if p in prefix:
            residue,places=prefix[p];prefix_ok=congruent(r['residue'],residue,p,places)
            assert prefix_ok,(p,'published prefix')
        checkpoint={'p':p,'seconds':time.monotonic()-start,'A':A,'M':M,'P':P,'J':P+2,
            'branch_controls':branch,'gamma_absolute_places':Ac,'gamma_ok':bool(gamma_ok),
            'published_prefix_ok':prefix_ok,'pari_zeta_node_places':40,'entries':rowchecks}
        print('CHECKPOINT '+json.dumps(checkpoint),flush=True);checkpoints.append(checkpoint);details.extend(extracted)
    result={'version':1,'table':'T872','checked_entries':len(details),'total_entries':40,
        'failures':failures,'known_answer_control':True,'negative_control_rejected':True,
        'interpolation_controls':controls,'entries':details,'prime_checkpoints':checkpoints,
        'method':'modular binomial deflated zeta, exact Bernoulli recurrence, Newton Teichmuller roots, five-node rational interpolation; independent PARI Morita psi and zeta controls',
        'independence':'No primary logarithm-power code; shared Volkenborn/Bernoulli theory, Sage exact arithmetic and prime choices. Builder validation is not an independent scientific verdict.',
        'skill_manifest':'../20261130T185226Z-build-skills/manifest.json',
        'program_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
    return result


if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('--input',type=Path,default=Path(__file__).with_name('coefficients.json'));parser.add_argument('--output',type=Path)
    args=parser.parse_args();result=run(json.loads(args.input.read_text())['entries'])
    result['input_sha256']=hashlib.sha256(args.input.read_bytes()).hexdigest()
    if args.output:args.output.write_text(json.dumps(result,indent=2))
    print('RESULT '+json.dumps(result),flush=True)
    if result['failures']:raise SystemExit(1)