"""Generate T724, Bessel period determinants from odd rows.

Requires SageMath 10.9 and numberdb (sage -pip install numberdb).
    sage -python generate.py             # recompute and verify every entry
    sage -python generate.py --publish   # additive entry upload, explicit opt in
NUMBERDB_KEY_FROM_STDIN=1 reads the configured key from stdin.
NUMBERDB_PUBLISH=1 is equivalent to --publish for an authorized builder.

n is the total factor count; d=(n+1)//4 - (n%4==0). Rows i=1..d
use I0^(2i-1) K0^(n+1-2i), columns j=1..d use t^(2j-1).
Raw signed determinant, unit scale, positive-real path and principal K0.
The default n=3,5,...,16 is a practical complete prefix, not the domain.
Fresan--Sabbah--Yu, arXiv:2006.02702v2, Notation 8.2, fixes this
matrix and the final-row/final-column deletion when 4 divides n.

Method: complex Arb rigorous quadrature after t=exp(z), with analytic
callback restricted to Re(exp(z))>0. K0 is evaluated via
sqrt(pi)*exp(-t)*U(1/2,1,2t), DLMF 13.6.10; the native bessel_K
loses precision at moderate large arguments in this runtime (see probes).
DLMF 10.32.1 gives I0(t)<=exp(t).
DLMF 10.32.9 gives K0(t)<=sqrt(pi/(2t))*exp(-t), using cosh(u)>=1+u^2/2.
It also gives K0(t)<=E1(t/2)<=2-log(t) for 0<t<=1, using cosh(u)>=exp(u)/2.
Thus the omitted origin is bounded by exp(a exp(-A)) times
exp(-(r+1)A)/(r+1) * sum_{k=0}^b b!/(b-k)! (A+2)^(b-k)/(r+1)^k.
For p=r-b/2, g=b-a>0 and T>max(p,0)/g, the tail is bounded by
(pi/2)^(b/2) T^p exp(-gT)/(g-max(p,0)/T).
For p>=0 this follows from log(t/T)<=(t-T)/T; for p<0 use t^p<=T^p.
Finite integration, both omitted tails, and the determinant all carry balls.
The endpoint argument generalizes the checked T720 generator; its numerical
values are not inputs. No midpoint is used in a certified calculation.
At 100 digits: 525 working bits, A=240, T=(400+10(a+b))/(b-a),
absolute and relative segment tolerance 10^-140. Every final ball must retain
at least 357 relative bits. The evidence records observed accuracy and
cancellation, rather than assuming that this guard always suffices.
No local selection data or optional cache controls the default enumeration.
Credentials and agent/model declarations belong in the session environment.
"""
import os
import sys
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
import sage.rings.polynomial.laurent_polynomial_ring
from sage.matrix.constructor import matrix

DEFAULT_MAX_N = 16


def dimension(n):
    n = ZZ(n)
    if n != 3 and n < 5:
        raise ValueError('require n=3 or n>=5')
    return int((n+1)//4 - int(n % 4 == 0))


@lru_cache(maxsize=None)
def moment(a, b, r, digits=100):
    a, b, r = (int(ZZ(x)) for x in (a, b, r))
    if not (a >= 0 and b > a and r >= 1):
        raise ValueError('require integer a>=0, b>a and r>=1')
    bits = numberdb.bits(digits, losing=192)
    R, C = RealBallField(bits), ComplexBallField(bits)
    A = digits+140
    gap = b-a
    T = QQ(2*(digits+100)+10*(a+b))/gap
    p = QQ(r)-QQ(b)/2
    tol = R(10)**(-digits-40)
    evaluations = [0]
    def integrand(z, analytic):
        evaluations[0] += 1
        t = z.exp()
        if not t.real() > 0:
            return C('nan')
        K = C.pi().sqrt()*(-t).exp()*(2*t).hypergeometric_U(QQ(1)/2,1)
        return ((r+1)*z).exp() * t.bessel_I(0)**a * K**b
    total = C(0)
    upper = R(T).log()
    bounds = [-A, -16, -4, 0, 1, 2]+[k for k in range(3,20) if R(k) < upper]+[upper]
    for lo, hi in zip(bounds, bounds[1:]):
        q = C.integral(integrand, lo, hi, abs_tol=tol, rel_tol=tol,
                       eval_limit=200000, depth_limit=60, use_heap=True)
        if not (q.real().is_finite() and q.imag().is_finite()):
            raise ArithmeticError('nonfinite integration segment')
        total += q
    falling = ZZ(1)
    series = R(0)
    for k in range(b+1):
        series += falling * R(A+2)**(b-k) / R(r+1)**k
        falling *= b-k
    origin = (a*R(-A).exp()).exp() * R(-(r+1)*A).exp()*series/(r+1)
    denominator = R(gap)-max(p, QQ(0))/R(T)
    if not denominator > 0:
        raise ArithmeticError('tail bound requires positive exponential decay')
    tail = (R.pi()/2)**(QQ(b)/2)*R(T)**p * (-gap*R(T)).exp()/denominator
    v = total.real().add_error(origin+tail)
    if not total.imag().contains_zero() or not v.is_finite() or not v > 0:
        raise ArithmeticError('invalid positive moment enclosure')
    if v.accuracy() < numberdb.bits(digits, losing=24):
        raise ArithmeticError('moment enclosure too wide')
    return v, {'a':a,'b':b,'r':r,'working_bits':int(bits), 'A':A,'T':str(T),
               'origin_bound':str(origin.upper()), 'tail_bound':str(tail.upper()),
               'accuracy_bits':int(v.accuracy()),'evaluations':evaluations[0]}


def determinant(n, digits=100):
    n = int(ZZ(n)); d = dimension(n)
    R = RealBallField(numberdb.bits(digits, losing=192))
    entries = [[moment(2*i-1, n+1-2*i, 2*j-1, digits)[0]
                for j in range(1,d+1)] for i in range(1,d+1)]
    v = matrix(R, entries).determinant()
    if not v.is_finite() or not v > 0 or v.accuracy() < numberdb.bits(digits, losing=24):
        raise ArithmeticError('determinant enclosure insufficient; increase working precision')
    return v


class OddBesselPeriods(numberdb.Generator):
    table = 'T724'
    parameters = ('n',)
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self):
        for n in [3]+list(range(5,DEFAULT_MAX_N+1)):
            yield {'n':n}

    def value(self, params, digits):
        return determinant(params['n'], digits)


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    g = OddBesselPeriods()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(g.publish())
    else:
        result = g.verify(sample=None)
        print(result)
        sys.exit(0 if result.ok else 1)
