"""T733: Riemann zeta heat trace, in the width alpha=4*pi*t convention.

Requires SageMath 10.9 (or compatible Sage with Arb/FLINT) and numberdb.
  sage -pip install numberdb
  sage -python generate.py                 # preview only; writes nothing
  sage -python generate.py --publish       # fill the already assigned draft

The default selection is every reduced a/b, 1<=a<=b<=12. The mathematical
function is defined for alpha>0. Work uses at least 512 bits and 40 decimal
absolute guard places for the quadrature; all 46 default outputs retain more
than 135 significant digits before serialization at 100 digits.

This is the unconditional Gaussian Weil explicit formula (Suzuki, Section
3.1, (3.3); Montgomery-Vaughan, Theorem 12.13), in Connes's heat convention
(arXiv:2402.13082v1, (13)-(15), (25)), with t=alpha/(4*pi).

The integrand is expm1(x/2-pi*x*x/alpha)/(2*sinh(x)), continuously 1/4 at 0.
At balls containing 0, 1F1(1;2;z)=(exp(z)-1)/z removes the singularity
analytically. Arb encloses the finite integral. Subtract atanh(exp(-L))
exactly for the exponential tail; the remaining positive Gaussian tail is
at most exp(-pi*L^2/alpha-L/2)/(2*(pi/alpha)*L*(1-exp(-2*L))).

Prime powers p^k<=M carry log(p), not log(p^k). For c=pi/alpha, the omitted
prime contribution is at most exp(alpha/(4*pi))*erfc(z), z=sqrt(c)*
(log(M)-alpha/(2*pi)), further bounded above by exp(alpha/(4*pi)-z*z)/
(sqrt(pi)*z). This follows from Lambda(n)/sqrt(n)<=1, the decreasing
integral test, completing a square and erfc(z)<=exp(-z*z)/(sqrt(pi)*z).
The final RealBall includes rounding, input uncertainty and both tails.
M>=100000 and L=12 are used for the default selection at 100 digits. Larger
precision/widths increase both cutoffs; workloads above 5,000,000 integers
are refused explicitly. No quantile or zero data is used by this generator.
The zero-based independent check is in check_values.py.
"""
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.complex_arb import ComplexBallField
from sage.arith.misc import prime_range


@lru_cache(maxsize=8)
def prime_powers(M):
    terms = []
    for p in prime_range(M + 1):
        p = int(p)
        n = p
        while n <= M:
            terms.append((n, p))
            n *= p
    return tuple(sorted(terms))


def components(alpha, digits=100, work_bits=None):
    alpha = QQ(alpha)
    if alpha <= 0:
        raise ValueError('alpha must be positive')
    prec = work_bits or max(512, numberdb.bits(digits, losing=160))
    R = RealBallField(prec)
    C = ComplexBallField(prec)
    a = R(alpha)
    pi = R.pi()
    c = pi / a
    goal = R(10) ** (-digits - 40)
    L = max(12, int(((digits + 90) * R(10).log() / c).sqrt().upper().ceil()))
    M = max(100000, int((((digits + 80) * R(10).log() / c).sqrt()
                         + a / (2 * pi)).exp().upper().ceil()))
    if M > 5000000:
        raise ValueError('prime cutoff exceeds documented workload limit')

    def kernel(z, analytic):
        u = z / 2 - c * z * z
        if z.contains_zero():
            # Entire quotients; no removable singularity remains at z=0.
            return ((QQ(1) / 2 - c * z) * u.hypergeometric([1], [2])
                    / (2 * (-z).exp() * (2 * z).hypergeometric([1], [2])))
        return (u.exp() - 1) / (z.exp() - (-z).exp())

    integral = C.integral(kernel, 0, L, abs_tol=goal, rel_tol=goal,
                          eval_limit=100000)
    if not (integral.real().is_finite() and integral.imag().is_finite()
            and integral.imag().contains_zero()):
        raise ArithmeticError('quadrature did not enclose a finite real integral')
    integral = integral.real() - (-R(L)).exp().arctanh()
    arch_tail = (-c * L * L - R(L) / 2).exp() / (
        2 * c * L * (1 - (-R(2 * L)).exp()))
    integral = integral.add_error(arch_tail)
    arch = ((4 * pi).log() + R.euler_constant() + 2 * integral) / a.sqrt()
    prime = R(0)
    for n, p in prime_powers(M):
        logn = R(n).log()
        prime += R(p).log() / R(n).sqrt() * (-c * logn * logn).exp()
    prime *= 2 / a.sqrt()
    z = c.sqrt() * (R(M).log() - a / (2 * pi))
    if not z > 0:
        raise ArithmeticError('prime tail inequality requires z>0')
    prime_tail = (a / (4 * pi) - z * z).exp() / (pi.sqrt() * z)
    prime = prime.add_error(prime_tail)
    pole = 2 * (a / (16 * pi)).exp()
    value = pole - arch - prime
    if not value.is_finite() or not R(value.rad()) < abs(value) * R(10) ** (-digits - 10):
        raise ArithmeticError('insufficient non-vacuous relative precision')
    return {'value': value, 'arch': arch, 'prime': prime, 'pole': pole,
            'arch_integral_tail': arch_tail, 'prime_tail': prime_tail,
            'M': M, 'L': L, 'work_bits': prec}


class HeatTrace(numberdb.Generator):
    table = 'T733'
    parameters = ['alpha']
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self):
        widths = sorted({QQ(a) / b for b in range(1, 13)
                         for a in range(1, b + 1)})
        for alpha in widths:
            yield {'alpha': str(alpha)}

    @lru_cache(maxsize=256)
    def _value(self, alpha, digits):
        return components(alpha, digits)['value']

    def value(self, params, digits):
        return self._value(str(params['alpha']), digits)


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    g = HeatTrace()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        g.publish()
    else:
        g.preview()
