"""T756: values of the Riemann zeta screw function g=-Psi.

Requires SageMath (or modular passagemath with real Arb) and numberdb.
  sage -pip install numberdb
  sage -python generate.py                 # reproduce/check every stored value
  sage -python generate.py --publish       # fill this existing private draft
The second command requires authorized NumberDB credentials and provenance in
its environment. It writes entries; it does not offer or publish a draft.

The default selection is t=0 and log(q) for all prime powers 2<=q<=256.
Arguments stay symbolic in their identities; all logarithms are natural.
Suzuki, arXiv:2206.03682v4, (1.1),(1.8), defines the signed value g=-Psi.
The finite prime support is determined exactly, and the m=q term is zero.

At d decimal digits, work at ceil(d*log2(10))+180 bits. The Lerch series at
z=q^-2 is truncated with the positive geometric upper bound
 z^N / ((N+1/4)^2*(1-z)); the bound is added to the ball. All argument and
arithmetic errors propagate in Arb. The origin is the mathematically exact 0.
See numerical-evidence.md for measured precision and independent validation.
"""
import os
import sys
import re
from functools import lru_cache
from math import isqrt
import numberdb.sage as numberdb
from sage.rings.real_arb import RealBallField
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ

BOUND = 256

@lru_cache(maxsize=None)
def prime_powers(bound=BOUND):
    """Sieve prime bases, then generate their positive powers."""
    sieve = [True] * (bound + 1)
    sieve[0:2] = [False, False]
    for p in range(2, isqrt(bound) + 1):
        if sieve[p]:
            for m in range(p*p, bound+1, p):
                sieve[m] = False
    powers = {}
    for p in range(2, bound+1):
        if sieve[p]:
            q = p
            while q <= bound:
                powers[q] = p
                q *= p
    return tuple(sorted(powers.items()))

def identities():
    return ('0',) + tuple('log(%d)' % q for q, p in prime_powers())

@lru_cache(maxsize=None)
def evaluate(q, digits=100):
    if q == 1:
        return ZZ(0)
    if q not in dict(prime_powers()):
        raise ValueError('The default generator evaluates selected prime-power knots')
    bits = numberdb.bits(digits, losing=180)
    R = RealBallField(bits)
    t = R(q).log()
    z = R(1) / ZZ(q)**2
    phi, power, n = R(0), R(1), 0
    while True:
        phi += power / (R(n) + QQ(1)/4)**2
        n += 1
        power *= z
        tail = power / ((R(n) + QQ(1)/4)**2 * (1-z))
        if tail < R(2)**(-(bits-32)):
            break
    phi = phi.add_error(tail)
    arithmetic = R(0)
    for m, p in prime_powers():
        if m >= q:
            break
        arithmetic += R(p).log() / R(m).sqrt() * (t-R(m).log())
    psi = (4*((t/2).exp()+(-t/2).exp()-2) - arithmetic
           + t/2*(R(QQ(1)/4).psi()-R.pi().log())
           + (R.pi()**2+8*R.catalan_constant()-(-t/2).exp()*phi)/4)
    result = -psi
    if not result.is_finite() or result.accuracy() < numberdb.bits(digits, losing=24):
        raise ArithmeticError('Insufficient finite ball accuracy')
    return result

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

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

    def value(self, params, digits):
        t = str(params['t'])
        if t == '0':
            return ZZ(0)
        match = re.fullmatch(r'log\(([1-9][0-9]*)\)', t)
        if not match:
            raise ValueError('Expected the exact identity log(q)')
        return evaluate(int(match.group(1)), digits)

if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        key = sys.stdin.read().strip()
        if '=' in key and key.split('=',1)[0].isidentifier():
            key = key.split('=',1)[1].strip().strip('\"\'')
        os.environ['NUMBERDB_API_KEY'] = key
    gen = ScrewValues()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(gen.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill checked values of g=-Psi')))
    else:
        print(gen.verify(sample=None))
