"""Bernstein's constant beta -- numberdb.org/T503.

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

A draft requires its author's NUMBERDB_API_KEY for either operation.
For a protected key on stdin set NUMBERDB_KEY_FROM_STDIN=1.

This reproduces the 50-digit transcription, not the original computation.
The source is Varga and Carpenter, Constructive Approximation 1 (1985),
333-348, equations (1.18) and (5.3), DOI 10.1007/BF01890040.
They applied Richardson extrapolation in 1/n^2 to Remez minimax errors
2*n*E_(2n) for n=1,...,52, evaluated at 100 decimal working digits.
The last 50-digit estimate is heuristic, not a certified enclosure.
No digits beyond those explicitly printed by the source are supplied.
"""
import os
import sys
import numberdb.sage as numberdb

SOURCE_DIGITS = '28016949902386913303643649123067200004248213981236'


class BernsteinConstant(numberdb.Generator):
    table = 'T503'
    parameters = ()
    type = 'R'
    digits = 50
    rigour = 'heuristic'
    files = ('generate.py', 'checks.py', 'remez_check.py', 'check.py',
             'b073001.txt', 'remez-evidence.json', 'source-notes.md',
             'source-sha256.json', 'preflight.log')

    def enumerate(self):
        yield {}

    def value(self, params, digits):
        if params:
            raise ValueError('This is one constant with no parameters.')
        if digits > 50:
            raise ValueError('The source supplies only 50 heuristic digits.')
        return '0.' + SOURCE_DIGITS


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    generator = BernsteinConstant()
    if '--fill' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish(message='Transcribe the 50-digit Bernstein estimate of Varga and Carpenter'))
    else:
        report = generator.verify(sample=None)
        print(report)
        sys.exit(0 if report.ok else 1)
