generate.py

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

5353 bytes, as of the version from 2026-11-28 03:17 (current). Recorded here, not run.

"""T842: p-adic logarithms of real quadratic fundamental units.

Requires SageMath with number fields and p-adics, and the numberdb client:
    sage -pip install numberdb
    sage -python generate.py             # verify all stored rows, no write
    sage -python generate.py --publish   # opt in to filling the authorized draft

D is a positive fundamental discriminant; p is an odd split prime. The unit
is the least real maximal-order unit >1, of either norm. The embedding sends
sqrt(D) to the Hensel lift of the smaller positive root residue modulo p.
Exact Newton lifting and proof-enabled unit groups supply the input; Sage's
precision-tracked log kills Teichmuller torsion. N is least with p^N >= 10^digits.
Working absolute precision starts at N+32 and grows if necessary. A value of
valuation v is returned with O(p^(v+N)), never padded. Input uncertainty is
preserved: log is 1-Lipschitz on p-adic units for odd p. Independent check code
bounds the power-series tail and certifies fundamental-unit minimality.

Default coverage is all positive fundamental D <=100 and all odd split p<=31,
in (D,p) order. These practical arithmetic reference cutoffs are noncanonical,
covering small field complexity and several completions per field. Credentials
and attribution belong in the calling environment. If NUMBERDB_WORKDIR is set,
row checkpoints include this generator's hash and are safely resumable.
"""
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.padics.factory import Qp
from sage.rings.number_field.number_field import QuadraticField
from sage.rings.qqbar import AA
from sage.arith.misc import prime_range, kronecker_symbol
from functools import lru_cache
from pathlib import Path
import os, sys, json, hashlib


def fundamental(D):
    return (D % 4 == 1 and ZZ(D).is_squarefree()) or (D % 4 == 0 and (D//4) % 4 in (2,3) and ZZ(D//4).is_squarefree())


def parameters():
    for D in range(5,101):
        if fundamental(D):
            for p in prime_range(3,32):
                if kronecker_symbol(D,p)==1:
                    yield {'D':D,'p':int(p)}


def digits_for(p,digits):
    N=0; power=1
    while power<10**digits: N+=1; power*=p
    return N


@lru_cache(None)
def unit_data(D):
    K=QuadraticField(D,'a'); assert K.discriminant()==D
    eps=K.unit_group(proof=True).gens_values()[1]
    real=K.hom([AA(D).sqrt()],AA)
    if real(eps)<0: eps=-eps
    if real(eps)<1: eps=1/eps
    t=ZZ(2*eps[0]); u=ZZ(2*eps[1]); norm=ZZ(eps.norm())
    assert real(eps)>1 and eps.is_integral() and t>0 and u>0
    assert norm in (-1,1) and t*t-D*u*u==4*norm
    return int(t),int(u),int(norm)


def root(D,p,A):
    r0=min(r for r in range(1,p) if (r*r-D)%p==0)
    r=r0; k=1
    while k<A:
        k=min(2*k,A); mod=p**k
        r=(r-(r*r-D)*pow(2*r,-1,mod))%mod
    assert (r*r-D)%(p**A)==0 and r%p==r0 and (2*r)%p
    return r,r0


def logarithm(D,p,digits=100):
    assert fundamental(D) and p>2 and ZZ(p).is_prime() and kronecker_symbol(D,p)==1
    t,u,norm=unit_data(D); N=digits_for(p,digits); W=N+32
    while True:
        rr,r0=root(D,p,W)
        F=Qp(p,W+2,print_mode='val-unit')
        r=F(rr).add_bigoh(W); e=(t+u*r)/ZZ(2)
        assert e.valuation()==0
        ell=e.log()
        if ell and ell.precision_relative()>=N:
            v=int(ell.valuation()); A=v+N; value=ell.add_bigoh(A)
            assert value.precision_absolute()==A and value.precision_relative()==N
            return value,dict(D=D,p=p,t=t,u=u,norm=norm,r0=r0,N=N,v=v,A=A,residue=str(value.lift()),working_A=W,root_residue=str(rr),input_A=int(e.precision_absolute()),log_A=int(ell.precision_absolute()))
        W+=32


def comment(data):
    return (rf'$t_D={data["t"]}$, $u_D={data["u"]}$, $n_D={data["norm"]}$, $r_0={data["r0"]}$; '
            rf'$v_p(\ell)={data["v"]}$, absolute precision ${data["A"]}$, relative precision ${data["N"]}$.')


class QuadraticUnitLog(numberdb.Generator):
    table=os.environ.get('NUMBERDB_TABLE','T842')
    parameters=('D','p')
    type='Qp'
    digits=100
    rigour='proven'

    def enumerate(self): return parameters()

    def value(self,params,digits):
        D=int(params['D']);p=int(params['p']);work=os.environ.get('NUMBERDB_WORKDIR')
        fingerprint=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
        cache=Path(work)/f'unit-log-{D}-{p}-{digits}.json' if work else None
        data=None
        if cache and cache.exists():
            candidate=json.loads(cache.read_text())
            if candidate.get('generator_sha256')==fingerprint:data=candidate
        if data is None:
            value,data=logarithm(D,p,digits);data['generator_sha256']=fingerprint
            if cache:
                temp=cache.with_suffix('.tmp');temp.write_text(json.dumps(data,indent=2));temp.replace(cache)
        else:value=Qp(p,data['A']+2,print_mode='val-unit')(ZZ(data['residue'])).add_bigoh(data['A'])
        return {'number':value,'comment':comment(data)}


if __name__=='__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':numberdb.configure(api_key=sys.stdin.read().strip())
    g=QuadraticUnitLog()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH')=='1':
        print(g.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill unit logarithms')),flush=True)
    else:print(g.verify(sample=None),flush=True)