generate.py

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

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

"""Generate T872: regular Kubota-Leopoldt Laurent coefficients.

Requirements: SageMath (tested 10.9), numberdb (tested 0.1.10).
Install the client into an existing Sage environment:
  sage -pip install numberdb
  sage -python generate.py                 # check against the current table
  sage -python generate.py --compute       # offline JSONL checkpoints
  sage -python generate.py --publish       # explicitly submit entries only
Supply one's own API key and contribution provenance through the environment.

The branch is zeta_p(1+u)=((p-1)/p)/u+sum c_(p,n) u^n.
For m=n+1, c=(-1)^m/(p*m!) sum_a sum_k [t^k]F_a(t)^m B_k,
F_a(t)=log_p(a)+sum_(j>=1) (-1)^(j+1)(p/a)^j t^j/j.
The logarithm is independently bounded by its series at a^(p-1)-1.
Bernoulli numbers have B_1=-1/2 and are exact FLINT rationals.

For k>=1 the coefficient valuation is at least
ceil(((p-2)*k+m)/(p-1)); v_p(B_k)>=-1. Thus the omitted terms
starting at K have valuation at least E(K)=ceil(((p-2)*K+m)/(p-1))
-2-v_p(m!). Choose E(K)>=A. Work at W=A+8, encode the logarithm
series tail as O(p^W), and check actual propagated precision >=A.
After resolving v_p(c), retain N relative places, p^N>=10^digits.
Both cutoffs and arithmetic losses are recorded by --compute.
See mathematics.md for the derivation and independent-check limitations.
"""
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.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.arith.misc import bernoulli
import functools
import json
import sys
import time

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


def places(p,digits):
    N=0
    while ZZ(p)**N < ZZ(10)**digits:
        N+=1
    return N


def tail_bound(p,m,k):
    return ((p-2)*k+m+p-2)//(p-1)-2-int(ZZ(m).factorial().valuation(p))


def bounded_log(a,p,W,Q):
    if a==1:
        return Q(0),0
    z=ZZ(a)**(p-1)-1
    # j-v_p(j) >= ((p-2)j+1)/(p-1) for every j>=1.
    J=max(1,((p-1)*W-1+p-3)//(p-2))
    assert (p-2)*J+1 >= (p-1)*W
    zq=Q(z);power=Q(1);total=Q(0)
    for j in range(1,J):
        power*=zq
        total+=((-1)**(j+1))*power/ZZ(j)
    assert total.precision_absolute()>=W
    return total.add_bigoh(W)/ZZ(p-1),J


@functools.lru_cache(maxsize=None)
def compute_prime(p,digits=100):
    p=int(p);digits=int(digits)
    if p not in PRIMES and (p<3 or not ZZ(p).is_prime()):
        raise ValueError('p must be an odd prime')
    N=places(p,digits);A=N+12
    while True:
        W=A+8
        Q=Qp(p,prec=W,type='capped-rel',print_mode='val-unit')
        # Generic is a native Sage implementation. The optimized p-adic
        # polynomial backend has an NTL linkage failure on the tested builder.
        R=PolynomialRing(Q,'t',implementation='generic')
        cutoffs=[]
        for m in range(1,5):
            K=1
            while tail_bound(p,m,K)<A:K+=1
            cutoffs.append(K)
        Kmax=max(cutoffs)
        B=[bernoulli(k,algorithm='flint') for k in range(Kmax)]
        assert B[0]==1 and B[1]==-QQ(1)/2 and B[2]==QQ(1)/6
        assert all(type(b).__name__ in ('Integer','Rational') for b in B)
        sums=[Q(0) for _ in range(4)];log_cutoffs=[]
        for a in range(1,p):
            L,J=bounded_log(a,p,W,Q);log_cutoffs.append(J)
            f=[L];power=Q(1);ratio=Q(p)/ZZ(a)
            for j in range(1,Kmax):
                power*=ratio
                f.append(((-1)**(j+1))*power/ZZ(j))
            F=R(f);G=R(1)
            for m in range(1,5):
                G=(G*F).truncate(Kmax)
                sums[m-1]+=sum((G[k]*B[k] for k in range(cutoffs[m-1])),Q(0))
        vals=[];records=[];retry=False
        for m in range(1,5):
            c=((-1)**m)*sums[m-1]/(ZZ(p)*ZZ(m).factorial())
            assert c.precision_absolute()>=A,(p,m,'arithmetic loss',c.precision_absolute(),A)
            arithmeticA=int(c.precision_absolute())
            c=c.add_bigoh(A)
            if not c:raise ArithmeticError('coefficient unresolved at finite precision')
            v=int(c.valuation());outA=v+N
            if outA>A:
                A=outA+4;retry=True;break
            out=c.add_bigoh(outA)
            assert out.precision_relative()>=N
            vals.append(out)
            records.append({'p':p,'n':m-1,'valuation':v,'relative_places':N,
                'absolute_places':outA,'residue':str(out.lift()),'number':str(out),
                'working_places':W,'tail_absolute_bound':A,'K':cutoffs[m-1],
                'E_K':tail_bound(p,m,cutoffs[m-1]),'max_log_cutoff':max(log_cutoffs),
                'arithmetic_absolute_places':arithmeticA})
        if not retry:return vals,records


class LaurentCoefficients(numberdb.Generator):
    table='T872'
    parameters=['p','n']
    type='Qp'
    digits=100
    rigour='proven'

    def enumerate(self):
        for p in PRIMES:
            for n in range(4):yield {'p':p,'n':n}

    def value(self,params,digits):
        p=int(params['p']);n=int(params['n'])
        if not 0<=n<=3:raise ValueError('this implementation computes orders 0 through 3')
        return compute_prime(p,digits)[0][n]


if __name__=='__main__':
    g=LaurentCoefficients()
    if '--compute' in sys.argv:
        for p in PRIMES:
            started=time.monotonic();values,records=compute_prime(p)
            print(json.dumps({'p':p,'seconds':time.monotonic()-started,'entries':records}),flush=True)
    elif '--publish' in sys.argv:
        print(g.publish())
    else:
        print(g.verify(sample=None))