"""T747: Chiral Potts lattice Green function, real exterior branch.

Install: sage -pip install numberdb
Check without writes: sage -python generate.py
Fill the existing authorized draft: sage -python generate.py --publish
Private reads/writes need NUMBERDB_API_KEY. Session engine/model attribution
comes from the caller. This program never offers or publishes a draft.

G(t) = pi^(-3) integral_[0,pi]^3 1/(t-c1-c2-c3+c1*c2*c3) dtheta,
cj=cos(theta_j), t>2. The default bounded reference selection is t=m0/8,
17<=m0<=80, together with 14 and 322; see argument-selection.md.

Guttmann and Rogers, J. Phys. A 46 (2013), 045202, journal (3),(4):
G(t)=B(4/t^2)/t, B(z)=(1-z)^(-1/4)*2F1(1/8,5/8;1;z)^2.
All coefficients of each factor are in [0,1], since their successive positive
ratios are <=1. Therefore 0<=b_r<=binomial(r+2,2) for B(z)=sum b_r*z^r.
Arb polynomial convolution encloses b_0,...,b_M; the exact geometric-majorant
formula bounds every omitted term. Rational inputs, arithmetic, convolution
and the tail are enclosed. Working bits and truncation are chosen explicitly,
not inferred from agreement of two precisions. At unlisted t closer to 2 the
truncation is recomputed. Full checks and measured errors are attached.
"""
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(17,81)) + ('14','322')


def geometric_majorant(z, M):
    """Sum_{r>M} binomial(r+2,2)*z^r, for 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-25)
    M = 32
    while not geometric_majorant(zmax, M) < 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)
    return field, M, product


@lru_cache(maxsize=1024)
def green(t_text, digits=100):
    t = QQ(t_text)
    if t <= 2:
        raise ValueError('The real exterior domain is t>2; G diverges at 2.')
    zq = 4/t**2
    zmax = max(QQ(256)/289, zq)
    field, M, polynomial = series_data(digits,str(zmax))
    z = field(zq)
    partial = polynomial(z)/field(t)
    tail = geometric_majorant(z,M)/field(t)
    result = partial.add_error(tail)
    assert result.is_finite() and result > 0
    assert field(result.rad()) < abs(result)*field(10)**(-digits-10)
    return result


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

    def enumerate(self):
        for t in selected_arguments():
            yield {'t':t}

    def value(self,params,digits):
        return green(str(params['t']),digits)


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 = ChiralPottsGreen()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill checked Green-function values with generator')))
    else:
        print(generator.verify(sample=None))
