"""Regular paperfolding numbers (T895).

Install SageMath (or passagemath with real ball arithmetic) and numberdb:
    sage -pip install numberdb
    sage -python generate.py             # verify all stored entries; no writes
    sage -python generate.py --publish   # fill this draft, with configured access

The one parameter b is an integer radix, b >= 2. Default coverage is the
contiguous reference prefix b=2,...,16; 16 is a budget cutoff, not a theorem.
Digits start at n=1 with f=1101100111001001..., valleys 1 and ridges 0.

Coons and Vrbik, JIS 15 (2012), Article 12.1.6, sections 1-2, equations (1)-(2):
F(z)=sum(f_n*z^n,n>=1)=F(z^2)+z/(1-z^4). Iterate this equation with z=1/b.
After grouped terms m=1,2,...,2^(J-1), the remainder F(b^(-2^J)) lies in
[0, 1/(b^(2^J)-1)], since every digit is 0 or 1. All grouped terms and this
bound are exact rationals. The returned Arb ball encloses their midpoint and
half width, including conversion error. At 100 digits the field uses 453 bits;
the tail is at most 10^(-130)/b. No external decimal data is used.

The attached check_values.py builds the digit word by a separate folding
recursion and checks every serialized/stored interval with an exact tail bound.
"""
import os
import sys
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField


def grouped_bounds(b, digits=100):
    """Return exact lower bound, tail bound and number of grouped terms."""
    b = ZZ(b)
    if b < 2:
        raise ValueError('b must be an integer >= 2')
    threshold = QQ(1) / (ZZ(10)**(int(digits) + 30) * b)
    total = QQ(0)
    m = ZZ(1)
    count = 0
    tail = QQ(1) / (b**m - 1)
    while tail > threshold:
        total += QQ(b**(3*m)) / (b**(4*m) - 1)
        m *= 2
        count += 1
        tail = QQ(1) / (b**m - 1)
    return total, tail, count


class Paperfolding(numberdb.Generator):
    table = 'T895'
    parameters = ('b',)
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self, max_base=16):
        for b in range(2, int(max_base) + 1):
            yield {'b': b}

    def value(self, params, digits):
        lower, tail, unused_count = grouped_bounds(params['b'], digits)
        field = RealBallField(numberdb.bits(digits, losing=120))
        result = field(lower + tail/2).add_error(field(tail/2))
        if not result.is_finite() or result.rad() <= 0:
            raise ArithmeticError('Expected a finite, nonzero-width enclosure')
        return result


if __name__ == '__main__':
    client = None
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        token = sys.stdin.read().strip()
        if '=' in token and token.split('=', 1)[0].isupper():
            token = token.split('=', 1)[1].strip().strip('\'"')
        client = numberdb.Client(api_key=token)
    generator = Paperfolding()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish(client=client))
    else:
        print(generator.verify(sample=None, client=client))
