generate.py

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

5348 bytes, as of the version from 2026-12-02 04:01 (current). Recorded here, not run.

"""Reproduce T861: either-direction wrapping on an untwisted rectangular torus.

Requires SageMath (tested 10.9) and `sage -pip install numberdb`.
  sage -python generate.py --offline  # compute default selection, no writes
  sage -python generate.py            # verify every stored value, read only
  sage -python generate.py --publish  # explicitly fill the authorized draft
Private reads need NUMBERDB_API_KEY, or NUMBERDB_KEY_FROM_STDIN=1 with a
key piped on stdin. Supply upload engine/model/run provenance in the environment.

The exact input r is height/width. R_e=1-X, where X is the Pinson cross-topology expression.
The complement is no occupied winding, which has the same probability as X.
This includes diagonal winding and cross topology, with one occupied color.
It defines an analytic CFT prediction, not a proved physical scaling limit.
Sources: Pruessner--Moloney (2003), (1)--(6); Ziff--Lorenz--Kleban
(1999), (9); Newman--Ziff (2001), III.1, (11)--(15). All roots are positive.

Explicit Gaussian tails and an eta omitted-product bound are propagated by
real ball arithmetic. For eta and the cross expression, use verified modular reciprocity when
r<1. Working precision is bits(digits)+180, with an explicit relative-radius
check. At 100 digits actual errors and cancellation are in metrics.json.
The parameter bound six is a noncanonical exploratory geometric reference
choice; the function domain is all positive real r.
"""
import argparse
from functools import lru_cache
import json, os, 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:
        yield {'r':str(r)}


def theta(t,F,tolerance):
    """Enclose T(t)=sum exp(-pi*t*k^2), including an explicit tail."""
    t=QQ(t)
    if t<1:
        value,details=theta(1/t,F,tolerance)
        return value/F(t).sqrt(),dict(details,transformed=True)
    c=F.pi()*F(t); n=0
    while True:
        tail=2*(-c*(n+1)**2).exp()/(1-(-c*(2*n+3)).exp())
        if tail.upper()<tolerance.lower(): break
        n+=1
    value=F(1)+2*sum(((-c*k*k).exp() for k in range(1,n+1)),F(0))
    return value.add_error(tail),{'terms_each_side':n,'tail_bound':str(tail.upper()),'transformed':False}


def eta(r,F,tolerance):
    if r<1:
        value,details=eta(1/r,F,tolerance)
        return value/F(r).sqrt(),dict(details,reciprocal=True)
    q=(-2*F.pi()*F(r)).exp(); m=0
    while True:
        bound=q**(m+1)/(1-q)
        if bound.upper()<tolerance.lower(): break
        m+=1
    product=F(1)
    for k in range(1,m+1): product*=1-q**k
    # For 0<q<1, 1-sum(q^k) <= product(1-q^k) <= 1.
    assert bound.upper()<1
    return (-F.pi()*F(r)/12).exp()*product*F(1).add_error(bound),{
        'factors':m,'omitted_product_bound':str(bound.upper()),'reciprocal':False}


def cross(r,F,tolerance):
    s=max(r,1/r); values=[]; details=[]
    for t in [QQ(3)*s/8,QQ(8)*s/3,QQ(3)*s/2,QQ(2)*s/3]:
        v,d=theta(t,F,tolerance);values.append(v);details.append(dict(d,argument=str(t)))
    e,ed=eta(s,F,tolerance)
    left=values[0]*values[1];right=values[2]*values[3]
    return (left-right)/(2*e**2),{'theta':details,'eta':ed,'evaluated_r':str(s)}


@lru_cache(maxsize=256)
def compute(r_text,digits=100):
    r=QQ(r_text)
    if r<=0:raise ValueError('Require exact rational r>0 (height/width).')
    bits=numberdb.bits(digits,losing=180);F=RealBallField(bits)
    tolerance=F(2)**(-bits+32)
    x,xd=cross(r,F,tolerance)
    result=1-x
    relative=result.rad_as_ball()/abs(result)
    if not result.is_finite() or result.lower()<=0 or result.upper()>=1:
        raise ArithmeticError('Require a finite probability strictly inside (0,1).')
    if not relative.upper()<(F(10)**(-digits-15)).lower():
        raise ArithmeticError('Insufficient relative accuracy for requested digits.')
    return result,{'bits':bits,'accuracy_bits':int(result.accuracy()),
        'relative_radius_upper':str(relative.upper()),'cross':xd,
        'subtraction_condition_bits_upper':str(((1+abs(x))/result).log(2).upper())}


class EitherWrapping(numberdb.Generator):
    table='T861'
    parameters=('r',)
    type='R'
    digits=100
    rigour='proven'
    def enumerate(self):yield from selected_parameters()
    def value(self,params,digits):return compute(str(params['r']),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=EitherWrapping()
    if args.offline:
        print(json.dumps([{'params':p,'number':to_text(g.value(p,g.digits),g.digits)} for p in g.enumerate()],indent=2))
    elif args.publish:
        print(g.publish(removing=False))
        if os.environ.get('NUMBERDB_TABLE_RESULT_FILE'):
            from pathlib import Path
            Path(os.environ['NUMBERDB_TABLE_RESULT_FILE']).write_text(json.dumps({'tid':g.table})+'\n')
    else:
        result=g.verify(sample=None);print(result)
        if not result.ok:raise SystemExit(1)

if __name__=='__main__':main()