"""Frobenius connection coefficients of equal-mass banana integrals; T721.

Requires SageMath (or passagemath with real/complex Arb) and numberdb.
  sage -pip install numberdb
  sage -python generate.py                 # verifies all stored entries
  sage -python generate.py --publish       # additive upload to the assigned draft
  sage -python generate.py --value 3 0     # computes another coefficient

(l,k) means loop order l>=1 and logarithm order 0<=k<=l. Masses and
propagator powers are one, D=2. The positive Feynman simplex amplitude is
continued to t+i0 through the upper half plane, with s=1/t on the lower
bank, principal log(s), and no 1/k! in s*log(s)^k. The finite enumeration
is the complete triangular prefix 1<=l<=12, 0<=k<=l.

Published Bönisch et al., JHEP09(2022)156, (4.33)-(4.35), (5.13), (5.21),
and p.81 give G(x)=-exp(-i*pi*x+sum_{odd j>=3}2*zeta(j)*x^j/j).
We use lambda(l,k)=(-1)^k*(l+1)!/k!*[x^(l-k)]G(x).
Only terms through degree l-k can affect that coefficient: no infinite
series tail is discarded at the requested degree. The exponential is
computed by its exact formal differential recurrence n*e_n=sum j*a_j*e_(n-j),
using Arb pi/zeta enclosures. This small recurrence also works in modular
Sage installations without symbolic-series exp(). Work starts at requested
bits plus 160 guard bits and increases if component accuracy is insufficient.
The diagonal is the exact integer (-1)^(l+1)*(l+1); zero components are exact.

Executable independent checks and argument-selection.md accompany this file.
Session credentials and assistant attribution are supplied by the caller.
"""
import argparse
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField

LOOP_LIMIT = 12
GUARD_BITS = 160

@lru_cache(maxsize=None)
def exponential_coefficients(degree, precision):
    R = RealBallField(precision)
    C = ComplexBallField(precision)
    a = [C(0)] * (degree + 1)
    if degree:
        a[1] = -C(0, 1) * R.pi()
    for j in range(3, degree + 1, 2):
        a[j] = C(2 * R(j).zeta() / ZZ(j))
    e = [C(1)]
    for n in range(1, degree + 1):
        e.append(sum((ZZ(j) * a[j] * e[n-j] for j in range(1, n+1)), C(0)) / ZZ(n))
    return tuple(e)

class BananaConnection(numberdb.Generator):
    table = 'T721'
    parameters = ('l', 'k')
    type = 'C'
    digits = 100
    rigour = 'proven'

    def enumerate(self, limit=LOOP_LIMIT):
        for l in range(1, int(limit)+1):
            for k in range(l+1):
                yield {'l': l, 'k': k}

    def value(self, params, digits):
        l, k = ZZ(params['l']), ZZ(params['k'])
        if l < 1 or k < 0 or k > l:
            raise ValueError('Require l>=1 and 0<=k<=l')
        if k == l:
            return ZZ((-1)**(l+1) * (l+1))
        degree = int(l-k)
        precision = numberdb.bits(digits, losing=GUARD_BITS)
        while True:
            e = exponential_coefficients(max(LOOP_LIMIT, degree), precision)
            scale = (-1)**(k+1) * (l+1).factorial() // k.factorial()
            result = scale * e[degree]
            components = (result.real(), result.imag())
            if all(c.is_finite() and (c.is_exact() or
                   (not c.contains_zero() and c.accuracy() >= numberdb.bits(digits)+32))
                   for c in components):
                return result
            precision *= 2
            if precision > 32768:
                raise ArithmeticError('Insufficient component accuracy')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--publish', action='store_true')
    parser.add_argument('--value', nargs=2, type=int, metavar=('L','K'))
    args = parser.parse_args()
    g = BananaConnection()
    if args.value:
        print(g.value(dict(zip(g.parameters,args.value)),g.digits))
    elif args.publish:
        g.publish()
    else:
        print(g.verify(sample=None))
