generate.py

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

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

"""Reproduce T859: Pinson cross-topology probability on rectangular tori.

Install SageMath (tested with 10.9) and `sage -pip install numberdb`.
  sage -python generate.py --offline  # compute the default selection
  sage -python generate.py            # verify all stored values, read only
  sage -python generate.py --publish  # explicitly fill the authorized draft
For a private draft set NUMBERDB_API_KEY, or NUMBERDB_KEY_FROM_STDIN=1 and
pipe the key. Engine/model/run provenance belongs in the upload environment.

r is height/width, with no twist and one occupied color. The definition is
the analytic Pinson expression, not a claim of a proved percolation limit.
Ziff--Lorenz--Kleban (1999), (9), becomes the theta expression here by
Poisson summation T(t)=T(1/t)/sqrt(t). Exact rational shapes enter ball
arithmetic before evaluation. Gaussian tails are bounded geometrically;
the omitted eta product differs from 1 by at most sum_{k>M}q^k.
All these errors propagate through the signed numerator and denominator.
Working precision is bits(digits)+180; insufficient accuracy raises rather
than silently lowering the requested precision. At 100 digits the finite
selection's actual precision and cancellation are recorded in metrics.json.
"""
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():
    for r in sorted({QQ(u)/v for u in range(1,7) for v in range(1,u+1)}):
        yield {'r':str(r)}


def theta(t,F,tolerance):
    """Enclose T(t); the small-argument transformation uses the positive root."""
    t=QQ(t)
    if t<1:
        v,details=theta(1/t,F,tolerance)
        return v/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
    v=F(1)+2*sum(((-c*k*k).exp() for k in range(1,n+1)),F(0))
    return v.add_error(tail),{'terms_each_side':n,'tail_bound':str(tail.upper()),'transformed':False}


def eta(r,F,tolerance):
    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
    assert bound.upper()<1
    value=(-F.pi()*F(r)/12).exp()*product*F(1).add_error(bound)
    return value,{'factors':m,'omitted_product_bound':str(bound.upper())}


@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).')
    if r<1: r=1/r
    bits=numberdb.bits(digits,losing=180); F=RealBallField(bits)
    tolerance=F(2)**(-bits+32)
    arguments=[QQ(3)*r/8,QQ(8)*r/3,QQ(3)*r/2,QQ(2)*r/3]
    values=[]; specs=[]
    for t in arguments:
        v,detail=theta(t,F,tolerance); values.append(v); specs.append(dict(detail,argument=str(t)))
    left=values[0]*values[1]; right=values[2]*values[3]
    e,edetail=eta(r,F,tolerance); numerator=left-right
    result=numerator/(2*e**2)
    if not result.is_finite() or result.lower()<=0 or result.upper()>=1:
        raise ArithmeticError('Require a finite probability strictly inside (0,1).')
    relative=result.rad_as_ball()/abs(result)
    if not relative.upper()<(F(10)**(-digits-15)).lower():
        raise ArithmeticError('Insufficient relative accuracy for the requested digits.')
    return result,{'bits':bits,'accuracy_bits':int(result.accuracy()),'theta':specs,'eta':edetail,
        'relative_radius_upper':str(relative.upper()),
        'cancellation_bits_upper':str(((abs(left)+abs(right))/abs(numerator)).log(2).upper())}


class PinsonCross(numberdb.Generator):
    table='T859'
    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=PinsonCross()
    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))
    else:
        result=g.verify(sample=None); print(result)
        if not result.ok: raise SystemExit(1)

if __name__=='__main__': main()