"""One-ninth constant and Varga's reciprocal -- numberdb.org/T502.

Run with SageMath:
    sage -pip install numberdb
    sage -python generate.py                 # verify all stored entries
    sage -python generate.py --publish       # fill the existing draft

The write command needs NUMBERDB_API_KEY. Reading an unpublished draft also
needs that key. Sending entries does not publish the draft or offer review.

Lambda is the unique zero in (0,1) of
    G(q) = sum_{k>=0} (2*k+1)^2 * (-q)^(k*(k+1)/2).
See Magnus and Meinguet, Numerical Algorithms 24 (2000), 117-139,
https://doi.org/10.1023/A:1019141226189, equations (30)-(32).

Bisection keeps exact rational endpoints in [1/10,1/9]; only strictly signed
Arb enclosures decide a step. If terms k>=N are omitted, the absolute tail
is bounded by (9/8)*(2*N+1)^2 * 9^(-N*(N+1)/2): consecutive absolute terms
have ratio <= 9*(1/9)^(k+1) <= 1/9 for k>=1. This bound includes every omitted
term, irrespective of its sign. The known uniqueness identifies the root.

At 100 digits the calculation uses 429 working bits (96 guard bits), with
bisection to a width below 2^-365 (32 extra bits). The final bracket, enlarged
by Arb's rounding, encloses Lambda; ball division encloses its reciprocal.
The two forms are an invertible change of convention, not separate quantities.
"""
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

WORKING_GUARD = 96
BRACKET_GUARD = 32


def theta_residual(q, field, terms):
    """An enclosure of G(q) for 0 <= q <= 1/9."""
    assert 0 <= q <= QQ(1)/9
    x = field(q)
    total = field(0)
    for k in range(terms):
        exponent = k*(k+1)//2
        total += (2*k+1)**2 * (-x)**exponent
    exponent = terms*(terms+1)//2
    tail = QQ(9)/8 * (2*terms+1)**2 / QQ(9)**exponent
    return total + field(0, field(tail).upper())


@lru_cache(maxsize=None)
def lambda_ball(digits):
    working = numberdb.bits(digits, losing=WORKING_GUARD)
    target = numberdb.bits(digits, losing=BRACKET_GUARD)
    field = RealBallField(working)
    terms = 2
    while QQ(9)**(terms*(terms+1)//2) < QQ(2)**(working+32)*(2*terms+1)**2:
        terms += 1
    lo, hi = QQ(1)/10, QQ(1)/9
    assert theta_residual(lo, field, terms) > 0
    assert theta_residual(hi, field, terms) < 0
    while hi-lo > QQ(2)**(-target):
        mid = (lo+hi)/2
        value = theta_residual(mid, field, terms)
        if value > 0:
            lo = mid
        elif value < 0:
            hi = mid
        else:
            raise ArithmeticError('A bisection sign is unresolved; increase the working guard.')
    assert theta_residual(lo, field, terms) > 0
    assert theta_residual(hi, field, terms) < 0
    return field((lo+hi)/2, field((hi-lo)/2).upper())


class OneNinthConstant(numberdb.Generator):
    table = 'T502'
    files = ('generate.py', 'checks.py')
    parameters = ('form',)
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self):
        yield {'form': 'Lambda'}
        yield {'form': 'V'}

    def value(self, params, digits):
        q = lambda_ball(digits)
        if params['form'] == 'Lambda':
            return {'number': q, 'param-latex': r'$\Lambda$',
                    'comment': 'The one-ninth constant, also called the Halphen constant.'}
        if params['form'] == 'V':
            return {'number': 1/q, 'param-latex': '$V$',
                    'comment': r"Varga's constant, the reciprocal $1/\Lambda$."}
        raise ValueError('Unknown reciprocal convention.')


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        os.environ['NUMBERDB_API_KEY'] = sys.stdin.read().strip()
    generator = OneNinthConstant()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish(message='Enclose the one-ninth constant and its reciprocal in Arb.'))
    else:
        result = generator.verify(sample=None)
        print(result)
        sys.exit(0 if result.ok else 1)
