"""Real zeros of the Riemann xi Jensen polynomials -- numberdb.org/T659.

Run with SageMath and the numberdb client:
    sage -pip install numberdb
    sage -python generate.py             # verify every stored entry
    sage -python generate.py --fill      # write entries to this existing draft

The exact convention is xi(1/2+z) = sum gamma_j*z^(2*j)/j! and
J^(d,n)(X) = sum binomial(d,j)*gamma_(n+j)*X^j. Degrees 1..8,
shifts 0..20, and all increasing root indices are enumerated.

Arb analytic power series enclose the coefficients. Complex root balls
supply candidates, but strict real endpoint signs in d disjoint intervals
certify d distinct real roots of a degree-d polynomial, hence completeness
and simplicity without an RH assumption. All signs and coefficients remain
in ball arithmetic. The return value is the certified real interval.

896 working bits exceed the measured cancellation in the xi product.
The dry run measures the actual retained accuracy; output is 100 digits.
See argument-selection.md, certification.md and checks.py for the coverage
rationale, proof of the independent integral bounds, and independent checks.
No command here publishes, offers, or reviews a draft.
"""
import sys
from functools import lru_cache
from math import comb, factorial
import numberdb.sage as numberdb
from sage.rings.complex_arb import ComplexBallField
from sage.rings.real_arb import RealBallField
from sage.rings.rational_field import QQ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing

WORKING_BITS = 896
MAX_DEGREE = 8
MAX_SHIFT = 20


def finite_narrow(x, bits=350):
    assert not x.is_NaN() and not x.is_infinity() and x.accuracy() >= bits, (x, bits)


@lru_cache(None)
def coefficients(max_index=28, bits=WORKING_BITS):
    C = ComplexBallField(bits)
    P = PolynomialRing(C, 'z')
    s = C(1)/2 + P.gen()
    length = 2*max_index + 1
    f = (s*(s-1)/2 * ((-s/2)*C.pi().log())._exp_series(length)
         * (s/2)._gamma_series(length) * s._zeta_series(length))
    for j in range(1, length, 2):
        assert not f[j].real().is_NaN() and not f[j].real().is_infinity() and f[j].contains_zero()
    result = []
    for j in range(max_index+1):
        assert f[2*j].imag().contains_zero()
        g = f[2*j].real()*factorial(j)
        finite_narrow(g)
        assert g > 0
        result.append(g)
    return tuple(result)


def polynomial_coefficients(d, n, gamma):
    return [comb(d, j)*gamma[n+j] for j in range(d+1)]


def evaluate(coeffs, x):
    result = x.parent()(0)
    for a in reversed(coeffs):
        result = result*x + a
    return result


def certify_bracket(coeffs, lo, hi):
    assert lo < hi < 0
    left, right = evaluate(coeffs, lo), evaluate(coeffs, hi)
    assert not left.is_NaN() and not right.is_NaN() and not left.is_infinity() and not right.is_infinity()
    assert (left > 0 and right < 0) or (left < 0 and right > 0)


@lru_cache(None)
def roots(d, n, bits=WORKING_BITS):
    assert 1 <= d <= MAX_DEGREE and 0 <= n <= MAX_SHIFT
    C, R = ComplexBallField(bits), RealBallField(bits)
    coeffs = polynomial_coefficients(d, n, coefficients(28, bits))
    P = PolynomialRing(C, 'X')
    candidates = sorted(P(coeffs).roots(multiplicities=False),
                        key=lambda v: v.real().mid())
    assert len(candidates) == d
    result = []
    for candidate in candidates:
        assert not candidate.real().is_NaN() and not candidate.real().is_infinity() and candidate.imag().contains_zero()
        x = candidate.real()
        finite_narrow(x)
        # Widen the candidate to a dyadic bracket with ample room for signs.
        radius = R(2)**(-390)*max(R(1), abs(R(x.mid())))
        bracket = R(x.mid(), radius.upper())
        lo, hi = R(bracket.lower()), R(bracket.upper())
        certify_bracket(coeffs, lo, hi)
        if result:
            assert result[-1].upper() < bracket.lower()
        finite_narrow(bracket)
        result.append(bracket)
    return tuple(result)


class JensenRoots(numberdb.Generator):
    table = 'T659'
    parameters = ('d', 'n', 'k')
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self):
        for d in range(1, MAX_DEGREE+1):
            for n in range(MAX_SHIFT+1):
                for k in range(1, d+1):
                    yield {'d': d, 'n': n, 'k': k}

    def value(self, params, digits):
        assert digits <= 100, 'Reassess working precision before extending precision.'
        return roots(int(params['d']), int(params['n']))[int(params['k'])-1]


if __name__ == '__main__':
    if '--stdin-key' in sys.argv or __import__('os').environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    generator = JensenRoots()
    if '--fill' in sys.argv or __import__('os').environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish(message='Fill all 756 certified Jensen roots at 100 digits'))
    else:
        report = generator.verify(sample=None)
        print(report)
        sys.exit(0 if report.ok else 1)
