generate.py

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

5836 bytes, as of the version from 2026-12-02 03:42 (current). Recorded here, not run.

"""T858: Pinson winding probabilities on an untwisted rectangular torus.

Requires SageMath 10.9 (Arb real balls) and numberdb 0.1.10 or later.
    sage -pip install numberdb
    sage -python generate.py --offline       # compute the reference selection
    sage -python generate.py                 # verify every stored entry
    sage -python generate.py --publish       # fill the authorized existing table

The default never writes. Private reads and explicit writes need the user's
NumberDB key, configured normally or piped with NUMBERDB_KEY_FROM_STDIN=1.
Engine/model/run attribution belongs to the execution environment, not here.

The torus has width 1 and height r; (a,b) counts horizontal/vertical windings.
P is Pruessner--Moloney (2003), equations (8)--(9), for at least one cluster
in one primitive signed class, excluding cross topology. Its physical
scaling-limit interpretation is a CFT prediction; the enclosed analytic value
is what this generator certifies. Opposite slopes are not summed.

Production uses three Gaussian series with their constant terms cancelled
algebraically, and an eta product, with geometric tail enclosures. At d digits
it uses bits(d, losing=160) bits. The omitted positive Gaussian sum is at most
exp(-pi*t*(N+1)^2)/(1-exp(-pi*t*(2*N+3))). For q=exp(-2*pi*r), the omitted eta
product lies in [1-q^(M+1)/(1-q),1]. All arithmetic and exact rational inputs
are enclosed. Negative tails are propagated through the signed combination.
For r<1, axis exchange first gives an equivalent case with ratio 1/r.
The finite reference bounds are noncanonical: reduced u/v with 1<=v<=u<=6,
and all nonnegative primitive (a,b) with a^2/r+b^2*r<=10.
"""
import argparse
from functools import lru_cache
from math import gcd
import os
import sys
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from numberdb._write import to_text


def selected_parameters():
    shapes = sorted({QQ(u)/v for u in range(1, 7) for v in range(1, u+1)})
    for r in shapes:
        amax = 0
        while QQ((amax+1)**2) <= 10*r:
            amax += 1
        bmax = 0
        while QQ((bmax+1)**2)*r <= 10:
            bmax += 1
        pairs = [(a,b) for a in range(amax+1) for b in range(bmax+1)
                 if gcd(a,b)==1 and QQ(a*a)/r+b*b*r<=10]
        pairs.sort(key=lambda ab: (ab[0]*ab[1]!=0,
                                  QQ(ab[0]**2)/r+ab[1]**2*r, ab))
        for a,b in pairs:
            yield {'r':str(r), 'a':a, 'b':b}


def positive_gaussian(t, F, tolerance):
    """Enclose sum_{k>=1} exp(-pi*t*k^2), including its omitted tail."""
    c=F.pi()*t
    n=0
    while True:
        tail=(-c*(n+1)**2).exp()/(1-(-c*(2*n+3)).exp())
        if tail.upper()<tolerance.lower():
            break
        n+=1
    result=sum(((-c*k*k).exp() for k in range(1,n+1)),F(0))
    return result.add_error(tail),n,tail


def eta_product(r,F,tolerance):
    q=(-2*F.pi()*r).exp()
    n=0
    while True:
        tail=q**(n+1)/(1-q)
        if tail.upper()<tolerance.lower():
            break
        n+=1
    product=F(1)
    for k in range(1,n+1):
        product*=1-q**k
    assert tail.upper()<1
    value=(-F.pi()*r/12).exp()*product*F(1).add_error(tail)
    return value,n,tail


@lru_cache(maxsize=512)
def compute(r_text,a,b,digits=100):
    r=QQ(r_text); a=int(a); b=int(b)
    if r<=0 or gcd(a,b)!=1 or not (a>0 or (a==0 and b==1)):
        raise ValueError('Require r>0 and a primitive representative a>0 or (a,b)=(0,1).')
    if r<1:
        r,a,b=1/r,abs(b),a
        if a==0: b=1
    bits=numberdb.bits(digits,losing=160)
    F=RealBallField(bits); tolerance=F(2)**(-bits+32)
    A=QQ(a*a)/r+b*b*r
    eta,m,etail=eta_product(F(r),F,tolerance)
    specs=((3,QQ(6)),(-4,QQ(8)/3),(1,QQ(2)/3))
    bracket=F(0); ns=[]; tails=[]
    magnitude=F(0)
    for coefficient,g in specs:
        s,n,tail=positive_gaussian(F(g*A),F,tolerance)
        bracket+=coefficient*s
        magnitude+=abs(coefficient)*abs(s)
        ns.append(n); tails.append(str(tail.upper()))
    value=(F(QQ(2)/(3*r))).sqrt()*bracket/eta**2
    if not value.is_finite() or value.lower()<=0 or value.upper()>=1:
        raise ArithmeticError('Probability must be a finite enclosure strictly inside (0,1).')
    if not value.rad_as_ball()/abs(value) < F(10)**(-digits-15):
        raise ArithmeticError('Insufficient relative precision for the requested digits.')
    return value,{'bits':bits,'accuracy_bits':int(value.accuracy()),
                  'gaussian_terms':ns,'gaussian_tail_bounds':tails,'eta_factors':m,
                  'eta_product_tail_bound':str(etail.upper()),
                  'relative_radius_upper':str((value.rad_as_ball()/abs(value)).upper()),
                  'cancellation_bits_upper':str((magnitude/abs(bracket)).log(2).upper())}


class PinsonWinding(numberdb.Generator):
    table='T858'
    parameters=('r','a','b')
    type='R'
    digits=100
    rigour='proven'
    def enumerate(self):
        yield from selected_parameters()
    def value(self,params,digits):
        return compute(str(params['r']),int(params['a']),int(params['b']),digits)[0]


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--offline',action='store_true')
    parser.add_argument('--publish',action='store_true')
    args=parser.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    g=PinsonWinding()
    if args.offline:
        for params in g.enumerate():
            print(params,to_text(g.value(params,g.digits),g.digits))
    elif args.publish:
        print(g.publish(removing=False))
    else:
        result=g.verify(sample=None); print(result)
        if not result.ok: raise SystemExit(1)

if __name__=='__main__':
    main()