"""Generator for T730: logarithmic Mahler measures of triangular P_d.

Requires SageMath (tested 10.9) and numberdb. Install and run:
  sage -pip install numberdb
  sage -python generate.py             # compute and check, no writes
  sage -python generate.py --publish   # explicitly fill the assigned draft
Default selection: every integer 1 <= d <= 100; extend with enumerate(max_degree=N).
The mathematical domain is d >= 1. The practical bound 100 is noncanonical.
Formula: Bertin and Mehrabdollahei, arXiv:2407.20634v3, equation (18).
Roots of unity are evaluated from exact rational angles using Arb complex
balls. Only upper-half-plane roots are used; conjugation pairs the remaining
signed terms. The -1 term is exactly zero. The imaginary part of Li_2 on the
unit circle is the classical Bloch-Wigner dilogarithm. Using it at a ball
containing the exact root is justified by inclusion and the principal branch.
Working precision: numberdb.bits(digits, losing=160), 493 bits at 100 digits.
Every result must be finite with relative ball accuracy >= ceil(digits*log2(10)).
The returned ball propagates angle, function, cancellation and pi uncertainty.
No session attribution or credentials are embedded in this reusable source.
"""
import argparse
from functools import lru_cache
import math
import os
import sys
import numberdb.sage as numberdb
from numberdb._write import to_text
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField

@lru_cache(maxsize=None)
def S(r, precision):
    R = RealBallField(precision)
    C = ComplexBallField(precision)
    total = R(0)
    for k in range(1, (r + 1) // 2):
        z = (C(0, 1) * R.pi() * (QQ(2*k) / r)).exp()
        total += (r - 2*k) * z.polylog(2).imag()
    return 6 * total

class MahlerPd(numberdb.Generator):
    table = 'T730'
    parameters = ('d',)
    type = 'R'
    digits = 100
    rigour = 'proven'
    files = ('generate.py',)

    def enumerate(self, max_degree=100):
        for d in range(1, max_degree + 1):
            yield {'d': d}

    def value(self, params, digits):
        d = int(params['d'])
        if d < 1 or str(d) != str(params['d']):
            raise ValueError('d must be an integer >= 1')
        precision = numberdb.bits(digits, losing=160)
        R = RealBallField(precision)
        result = (S(d+2, precision)/(d+1) - S(d+1, precision)/(d+2))/(2*R.pi())
        if not result.is_finite() or result.accuracy() < math.ceil(digits*math.log2(10)):
            raise ArithmeticError('finite enclosure with requested precision required')
        return result

if __name__ == '__main__':
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--publish', action='store_true')
    args = p.parse_args()
    g = MahlerPd()
    if args.publish:
        print(g.publish())
    else:
        for params in g.enumerate():
            print(params, to_text(g.value(params, g.digits), digits=g.digits))
