generate.py

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

5166 bytes, as of the version from 2026-11-27 22:06 (current). Recorded here, not run.

"""Generate T837: p-adic square roots of squarefree integers.

Requires SageMath with p-adics and numberdb 0.1.10 or later.
    sage -pip install numberdb
    sage -python generate.py               # offline JSON checkpoint, no writes
    sage -python generate.py --verify      # verify all stored entries, read only
    sage -python generate.py --publish     # explicitly fill this existing draft

The default envelope is every signed squarefree d, 2 <= abs(d) <= 30,
at the first ten primes, and every Q_p branch. Parameters (d,p,k,a) isolate
alpha^2=d by alpha=a mod p^k: k=1 at odd p; k=2 and a in {1,3} at p=2.
Newton lifting uses integer modular arithmetic, never floating point. The
least N with p^N >= 10^digits is calculated by exact integer comparisons.
At odd p, f'(a) is a unit, giving the unique lift of each root mod p.
At 2, d=1 mod 8 and a odd satisfy v_2(f(a))>=3>2v_2(f'(a)). The final
residue is certified mod 2^(N+1), so it encloses the root mod 2^N.
See Keith Conrad, Hensel's lemma, Theorems 2.1, 4.1 and 4.5:
https://kconrad.math.uconn.edu/blurbs/gradnumthy/hensel.pdf

A precision-tracked Sage Qp element is returned, not an exact integer.
Credentials and agent provenance belong in the caller's environment.
"""
import argparse
import json
import os
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.arith.misc import prime_range
from sage.rings.padics.factory import Qp
from numberdb._write import to_text

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


def exponent(p, digits):
    n, modulus, target = 0, 1, 10**int(digits)
    while modulus < target:
        modulus *= p
        n += 1
    return n


def branches(d, p):
    if d % p == 0:
        return []
    if p == 2:
        return [(2, 1), (2, 3)] if d % 8 == 1 else []
    return [(1, a) for a in range(1, p) if (a*a-d) % p == 0]


def newton(d, p, k, a, n):
    """Canonical integer residue of the isolated root modulo p^n."""
    if (k, a) not in branches(d, p):
        raise ValueError('No branch with these parameters')
    x = a
    if p != 2:
        accuracy = 1
        while accuracy < n:
            accuracy = min(2*accuracy, n)
            modulus = p**accuracy
            x = (x - (x*x-d)*pow(2*x, -1, modulus)) % modulus
        assert (x*x-d) % (p**n) == 0
    else:
        accuracy = 2  # x approximates root modulo 2^accuracy
        while accuracy < n+1:
            accuracy = min(2*accuracy-1, n+1)
            modulus = 2**accuracy
            assert (x*x-d) % 2 == 0
            x = (x - ((x*x-d)//2)*pow(x, -1, modulus)) % modulus
        x %= 2**n
        assert (x*x-d) % (2**(n+1)) == 0
    assert x % (p**k) == a
    return x


class SquareRoots(numberdb.Generator):
    table = 'T837'
    parameters = ('d', 'p', 'k', 'a')
    type = 'Qp'
    digits = 100
    rigour = 'proven'

    def enumerate(self, radicand_bound=30, prime_bound=29):
        for m in range(2, int(radicand_bound)+1):
            if not ZZ(m).is_squarefree():
                continue
            for d in (m, -m):
                for p in prime_range(prime_bound+1):
                    p = int(p)
                    for k, a in branches(d, p):
                        yield dict(d=d, p=p, k=k, a=a)

    def value(self, params, digits):
        d, p, k, a = (int(params[s]) for s in self.parameters)
        if abs(d) <= 1 or not ZZ(abs(d)).is_squarefree() or not ZZ(p).is_prime():
            raise ValueError('The radicand must be nontrivial squarefree and p prime')
        n = exponent(p, digits)
        u = newton(d, p, k, a, n)
        value = Qp(p, prec=n, print_mode='terse')(ZZ(u), absprec=n)
        assert int(value.precision_absolute()) == n
        assert int(value.lift()) == u
        assert int(value.valuation()) == 0
        assert to_text(value, digits=digits) == '%s + O(%s^%s)' % (u, p, n)
        return value


def checkpoint():
    g = SquareRoots()
    records = []
    types = set()
    for params in g.enumerate():
        v = g.value(params, g.digits)
        types.add(type(v).__module__+'.'+type(v).__name__)
        records.append({'params': {k: str(params[k]) for k in g.parameters},
                        'number': to_text(v, digits=g.digits),
                        'certificate': {'p':params['p'], 'N':int(v.precision_absolute()),
                                        'residue':str(v.lift()),
                                        'residual_modulus_exponent':int(v.precision_absolute())+(params['p']==2)}})
    return {'table':g.table, 'records':records, 'environment':g.environment(),
            'native_return_types':sorted(types)}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    mode = parser.add_mutually_exclusive_group()
    mode.add_argument('--verify',action='store_true')
    mode.add_argument('--publish',action='store_true')
    args=parser.parse_args()
    if args.verify:
        print(SquareRoots().verify(sample=None))
    elif args.publish:
        print(SquareRoots().publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill checked p-adic square-root branches')))
    else:
        print(json.dumps(checkpoint(),sort_keys=False))