"""T746: Chiral Potts logarithmic integral and Mahler measure.

Install: sage -pip install numberdb
Check (no writes): sage -python generate.py
Fill the authorized existing draft: sage -python generate.py --publish
Private-table reads/writes require NUMBERDB_API_KEY. Attribution is supplied
by the invoking session, never by this reusable file. No offering/publication.

The default selection is 67 t's and two additive normalizations (134 entries).
For t>2, source equation (4) gives B(z)=(1-z)^(-1/4)*2F1(1/8,5/8;1;z)^2,
z=4/t^2. If B(z)=sum b_r z^r, then integrating G(t)=B(4/t^2)/t with
J(t)-log(t)->0 gives J(t)=log(t)-sum_{r>=1} b_r z^r/(2r).
All three factor coefficients are in [0,1], so b_r<=binomial(r+2,2).
The closed polynomial-geometric tail below bounds the omitted sum; no
precision assertion comes merely from repeated working precision. Arb balls
propagate rational-input, arithmetic, convolution and logarithm error. At t=2
use the source's Catalan evaluation (2). Add log(8) for the Mahler convention.

Source: A. J. Guttmann and M. D. Rogers, J. Phys. A 46 (2013), 045202,
DOI 10.1088/1751-8113/46/4/045202, arXiv:1208.3345, eqs. (1),(2),(4).
See argument-selection.md and numerical-evidence.md for rationale and checks.
"""
import os
import sys
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing


def selected_arguments():
    return tuple(str(QQ(m)/8) for m in range(16,81)) + ('14','322')


def geometric_majorant(z, M):
    """Sum_{r>M} binomial(r+2,2) z^r, for a real ball 0<z<1."""
    L = M+1
    q = 1-z
    return z**L/2*((L+1)*(L+2)/q+(2*L+3)*z/q**2+z*(1+z)/q**3)


@lru_cache(maxsize=8)
def series_data(digits, zmax_text='256/289'):
    field = RealBallField(numberdb.bits(digits+30, losing=32))
    zmax = field(QQ(zmax_text))
    assert zmax > 0 and zmax < 1
    target = field(10)**(-digits-20)
    M = 32
    while not geometric_majorant(zmax, M)/(2*(M+1)) < target:
        M += 128
    aa = [field(1)]
    dd = [field(1)]
    for n in range(1,M+1):
        aa.append(aa[-1] * QQ(8*n-7)*QQ(8*n-3)/(64*n*n))
        dd.append(dd[-1] * QQ(4*n-3)/(4*n))
    ring = PolynomialRing(field,'z')
    square = (ring(aa)*ring(aa)).truncate(M+1)
    product = (square*ring(dd)).truncate(M+1)
    coefficients = [field(0)] + [product[r]/(2*r) for r in range(1,M+1)]
    return field, M, ring(coefficients)


@lru_cache(maxsize=1024)
def potts(t_text, digits=100):
    t = QQ(t_text)
    if t < 2:
        raise ValueError('The real exterior domain is t>=2.')
    if t == 2:
        field = RealBallField(numberdb.bits(digits+30,losing=32))
        return 8*field.catalan_constant()/field.pi()-3*field(2).log()
    # The default shared coefficients serve every selected exterior input.
    # A closer, unlisted argument receives its own enclosing truncation.
    zq = 4/t**2
    zmax = QQ(256)/289 if zq <= QQ(256)/289 else zq
    field, M, polynomial = series_data(digits,str(zmax))
    z = field(zq)
    partial = field(t).log() - polynomial(z)
    tail = geometric_majorant(z,M)/(2*(M+1))
    result = partial.add_error(tail)
    assert result.is_finite() and field(result.rad()) < field(10)**(-digits-10)
    return result


class ChiralPotts(numberdb.Generator):
    table = 'T746'
    parameters = ('t','normalization')
    type = 'R'
    digits = 100
    rigour = 'proven'
    files = ('generate.py',)

    def enumerate(self):
        for t in selected_arguments():
            for normalization in ('potts','mahler'):
                yield {'t':t,'normalization':normalization}

    def value(self,params,digits):
        result = potts(str(params['t']),digits)
        if params['normalization'] == 'mahler':
            result += result.parent()(8).log()
        elif params['normalization'] != 'potts':
            raise ValueError('normalization must be potts or mahler')
        return result


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        key = sys.stdin.read().strip()
        if '=' in key:
            key=key.split('=',1)[1].strip().strip('\"\'')
        numberdb.configure(api_key=key)
    generator = ChiralPotts()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill checked values with attached generator')))
    else:
        print(generator.verify(sample=None))
