"""Real zeros of the Riemann xi Hermite combinations -- numberdb.org/T705.

Run with SageMath and the numberdb client:
    sage -pip install numberdb
    sage -python generate.py             # verify every stored entry
    sage -python generate.py --fill      # fill this existing draft
Set NUMBERDB_API_KEY locally for a private draft. No command offers, reviews
or publishes the draft. Generator.publish() only submits its entries.

We use xi(s)=s(s-1)*pi^(-s/2)*Gamma(s/2)*zeta(s)/2 and
P^(d,n)(X)=sum binomial(d,j)*gamma_(n+j)*H_(d-j)(X), with
exp(2*X*t-t*t)=sum H_r(X)*t^r/r! and gamma_m=m!*[z^(2m)]xi(1/2+z).
See argument-selection.md for all three discrete indices and finite cutoffs.

Arb analytic power series at 896 bits enclose the coefficients. Hermite
polynomials use exact integer recurrence arithmetic. Complex ball root
finding supplies candidates only: strict opposite endpoint signs on d
disjoint real brackets certify all d roots, their simplicity and ordering.
The bracket radius is 2^-400 times max(1,abs(candidate)). Each returned ball
must retain at least 350 relative accuracy bits for 100 significant digits.
Measured precision and independent theta-integral checks are recorded in
numerical-evidence.json and certification.md. Values are recomputed, never
loaded from those evidence files. The series method follows the public
T659 generator, retrieved from numberdb.org/files/T659/generate.py on
2026-11-10; the Hermite construction and root certification are explicit here.
"""
import os
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.integer_ring import ZZ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing

WORKING_BITS = 896
BRACKET_BITS = 400
MAX_DEGREE = 10
MAX_SHIFT = 10


def finite_narrow(x, bits=350):
    assert not x.is_NaN() and not x.is_infinity(), 'nonfinite enclosure'
    assert x.accuracy() >= bits, ('insufficient relative accuracy', x.accuracy(), bits)


@lru_cache(None)
def coefficients(max_index=20, 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 f[j].contains_zero()
    gamma = []
    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
        gamma.append(g)
    return tuple(gamma)


@lru_cache(None)
def hermite_coefficients(d):
    P = PolynomialRing(ZZ, 'X')
    X = P.gen()
    h = [P(1), 2*X]
    for r in range(1, d):
        h.append(2*X*h[-1] - 2*r*h[-2])
    return tuple(tuple(h[r][i] for i in range(r+1)) for r in range(d+1))


def polynomial_coefficients(d, n, gamma):
    R = gamma[0].parent()
    result = [R(0)]*(d+1)
    H = hermite_coefficients(d)
    for j in range(d+1):
        for i, h in enumerate(H[d-j]):
            result[i] += comb(d,j)*gamma[n+j]*h
    assert result[-1] > 0
    return result


def horner(c, x):
    value = x.parent()(0)
    for a in reversed(c):
        value = value*x + a
    return value


def opposite(a,b):
    return (a < 0 and b > 0) or (a > 0 and b < 0)


def certify_roots(c):
    d = len(c)-1
    R = c[0].parent()
    C = ComplexBallField(R.precision())
    P = PolynomialRing(C, 'X')
    candidates = sorted(P(c).roots(multiplicities=False),
                        key=lambda z: z.real().mid())
    assert len(candidates) == d
    roots = []
    for z in candidates:
        finite_narrow(z.real(), BRACKET_BITS+20)
        assert z.imag().contains_zero()
        mid = z.real().mid()
        radius = R(2)**(-BRACKET_BITS)*max(R(1), abs(R(mid)))
        ball = R(mid, radius.upper())
        left, right = R(ball.lower()), R(ball.upper())
        assert left < right and opposite(horner(c,left),horner(c,right))
        if roots:
            assert roots[-1].upper() < ball.lower()
        finite_narrow(ball)
        roots.append(ball)
    return tuple(roots)


@lru_cache(None)
def roots(d, n, bits=WORKING_BITS):
    return certify_roots(polynomial_coefficients(d,n,coefficients(MAX_DEGREE+MAX_SHIFT,bits)))


class HermiteCombinationRoots(numberdb.Generator):
    table = 'T705'
    parameters = ('d', 'n', 'k')
    type = 'R'
    digits = 100
    rigour = 'proven'
    files = ('generate.py', 'checks.py', 'argument-selection.md',
             'certification.md', 'numerical-evidence.json', 'skill-evidence.json',
             'T15.json', 'T103.json', 'T659.json', 'sources.json')

    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 increasing digits.'
        d,n,k = (int(params[p]) for p in self.parameters)
        assert 1 <= d <= MAX_DEGREE and 0 <= n <= MAX_SHIFT and 1 <= k <= d
        return roots(d,n)[k-1]


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