generate.py

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

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

"""Reproduce NumberDB T857: expected horizontal crossing clusters.

Install numberdb in SageMath, then run:
    sage -pip install numberdb
    sage -python generate.py             # read-only verification of all entries
    sage -python generate.py --offline   # print the default selection locally
    sage -python generate.py --publish   # explicitly fill this existing target

Configure your own NUMBERDB_API_KEY for private-draft reads or authorized writes.
Session agent/model attribution belongs in the calling environment. The opt-in
publish() is additive (removing=False); it neither offers nor publishes a draft.

N(r) is the scaling-limit expected number of distinct open clusters joining the
left and right sides of a free-boundary rectangle of width r and height one in
critical triangular-lattice site percolation, one chosen color, p=1/2. Count a
cluster once even if it has many paths or touches all four sides. Configurations
without a horizontal crossing contribute zero. This is the unconditioned count,
not the two-color count or Hongler--Smirnov's weighted boundary observable.

The natural domain is real r>0. This implementation accepts exact positive
rational inputs. The default selection is every reduced a/b with max(a,b)<=8
(43 values): square first, then s,1/s in increasing s>1. The square is intrinsic;
the other shapes form exploratory reference coverage with a noncanonical bound.

Let x=lambda(i*r), C(x) be Cardy's probability, and
D(x)=sqrt(3)/(2*pi)*x*3F2(1,1,4/3;2,5/3;x). Then
N(r)=C(x)-D(x)/2-sqrt(3)/(4*pi)*log(1-x).
Source: Hongler--Smirnov arXiv:0909.4490v1, section 3.2, Proposition 1;
Maier arXiv:math-ph/0210013v4, Formula 2.3 and Corollary 2.3.1.
Kleban--Zagier DOI 10.1023/A:1026012600583, equations (3),(8),(12),(13),
fixes the lambda/theta geometry (nome exp(-pi*r), elliptic parameter convention).

For stability set s=max(r,1/r) and y=lambda(i*s)<=1/2. For r>=1 use the
formula above at y. For r<1 use Maier's equivalent direct formula
N(r)=1/2-D(y)/2-sqrt(3)/(4*pi)*log(y), avoiding a rounded 1-y near one.
The complementary identities C(1-y)=1-C(y) and
D(1-y)=1-2*C(y)+D(y) justify the equivalence. The square's x=C=1/2
are exact identities; N(1) remains an inexact real enclosure.

Sage/FLINT ball arithmetic at numberdb.bits(digits, losing=128) bits encloses
exact rational inputs, lambda, gamma and hypergeometric evaluations. At 100
decimal digits this is 461 bits. All fractional powers are positive real;
0<y<=1/2 avoids hypergeometric cuts. Realness follows from these real formulas,
not solely imaginary-zero containment. Return values must be finite, exceed
Cardy's probability, and have radius <abs(N)*10^(-digits-15). Executable
offline evidence measures cancellation and accuracy and supplies independent
Maier/integral checks plus explicitly bounded theta/positive-series checks.
"""
import argparse
from math import gcd

import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField

GUARD_BITS = 128


def real_enclosure(value):
    real, imag = value.real(), value.imag()
    if not real.is_finite() or not imag.is_finite() or not imag.contains_zero():
        raise ArithmeticError('Expected a finite enclosure of a real value')
    return real


def mean_components(r, digits=100):
    r = QQ(r)
    if r <= 0:
        raise ValueError('The width/height ratio must be positive')
    s = r if r >= 1 else 1/r
    precision = numberdb.bits(digits, losing=GUARD_BITS)
    R = RealBallField(precision)
    C = ComplexBallField(precision)
    a, b, c = QQ(1)/3, QQ(2)/3, QQ(4)/3
    y = R(QQ(1)/2) if s == 1 else real_enclosure(C(0, R(s)).modular_lambda())
    if not (y > 0 and y < 1):
        raise ArithmeticError('Cross-ratio must be inside (0,1)')
    h2 = real_enclosure(C(y).hypergeometric([a, b], [c]))
    cardy_s = R(QQ(1)/2) if s == 1 else R(b).gamma()/(R(c).gamma()*R(a).gamma())*y**a*h2
    h3 = real_enclosure(C(y).hypergeometric([1, 1, c], [2, QQ(5)/3]))
    k = R(3).sqrt()/(4*R.pi())
    difference_s = 2*k*y*h3
    if r >= 1:
        logarithm = (-y).log1p()
        cardy = cardy_s
        result = cardy_s - difference_s/2 - k*logarithm
        magnitude_sum = abs(cardy_s) + abs(difference_s/2) + abs(k*logarithm)
    else:
        logarithm = y.log()
        cardy = 1-cardy_s
        result = R(QQ(1)/2) - difference_s/2 - k*logarithm
        magnitude_sum = R(QQ(1)/2) + abs(difference_s/2) + abs(k*logarithm)
    if not all(v.is_finite() for v in (y, cardy, difference_s, result)):
        raise ArithmeticError('Nonfinite value')
    if not (result > cardy and 0 < cardy < 1 and difference_s > 0):
        raise ArithmeticError('Expected count/probability bounds failed')
    if not R(result.rad().exact_rational()) < abs(result)*R(10)**(-digits-15):
        raise ArithmeticError('Insufficient relative ball accuracy')
    return result, y, cardy, difference_s, magnitude_sum


class ExpectedCrossingClusters(numberdb.Generator):
    table = 'T857'
    parameters = ('r',)
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self, height=8):
        if type(height) is not int or height < 1:
            raise ValueError('height must be a positive integer')
        yield {'r': '1'}
        for s in sorted(QQ(a)/b for a in range(2, height+1)
                        for b in range(1, a) if gcd(a, b) == 1):
            yield {'r': str(s)}
            yield {'r': str(1/s)}

    def value(self, params, digits):
        return mean_components(params['r'], digits)[0]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    flags = parser.add_mutually_exclusive_group()
    flags.add_argument('--publish', action='store_true')
    flags.add_argument('--offline', action='store_true')
    parser.add_argument('--height', type=int, default=8)
    options = parser.parse_args()
    generator = ExpectedCrossingClusters()
    if options.publish:
        print(generator.publish(height=options.height, removing=False))
    elif options.offline:
        from numberdb._write import to_text
        for params in generator.enumerate(height=options.height):
            print(params['r'], to_text(generator.value(params, generator.digits), generator.digits))
    else:
        print(generator.verify(sample=None))


if __name__ == '__main__':
    main()