"""T742: ordinary logarithmic Mahler measures of Boyd Family 3.2.

Install: sage -pip install numberdb mpmath
Check:   sage -python generate.py
Write entries to the authorized target: sage -python generate.py --publish
The default command writes nothing. NUMBERDB_API_KEY supplies private-draft
access. Publication/review offering is a separate website operation.

Definition and source: Bertin--Zudilin, arXiv:1601.07583, section 1
(The first family), equivalently the journal's section 2. For k>=0,
P_k=(x^2+x+1)y^2+k*x*(x+1)*y+x*(x^2+x+1).
Jensen's formula gives the real-log integral implemented below. Its
sqrt-discriminant contacts are split algebraically; a sin^2 endpoint map
removes square-root cusps. The branch D<0 contributes log|4*cos(th)^2-1|.
This retains that contribution instead of treating it as zero. The factor
2/pi accounts for symmetry. k=0 is proved exact by cyclotomic factorization.

Default selection: k=sqrt(n), 0<=n<=36, positive roots, square cases reduced
to integers, in increasing k. n is an enumeration device, not a parameter.
Only these exact-label forms are parsed by value(); limit extends the same
arithmetic family. See argument-selection.md for the source-based rationale.

For 100 requested digits, quadratures use 140 and 180 decimal digits.
Each exact input is enclosed with Sage real intervals and monotonicity of
p(k) propagates its lower/upper endpoints. Both quadrature endpoint results
are retained before union across precisions. Quadrature errors are NOT
certified: rigour is heuristic (agreement-checked), including the numerical
input propagation. Increased precision must agree; no library float is
presented as exact. Larger requested digits retain the same 40/80 guards.
No cached data is required. Numerical evidence records actual agreement,
independent derivative-integral checks, exact-zero and L-value controls.
"""
import argparse
import math
import re
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.real_mpfi import RealIntervalField
from sage.rings.rational_field import QQ
from mpmath import mp


def identity(n):
    root=math.isqrt(n)
    return str(root) if root*root==n else 'sqrt(%d)'%n


def parse_identity(key):
    text=str(key)
    if re.fullmatch(r'[0-9]+',text):
        return int(text)**2
    match=re.fullmatch(r'sqrt\(([0-9]+)\)',text)
    if match:
        return int(match.group(1))
    raise ValueError('Use a nonnegative integer or sqrt(n) for integer n>=0')


def mahler_at(k,dps):
    """Real-log numerator Jensen quadrature for a positive mpf k."""
    if not k:
        return mp.mpf(0)
    a=(mp.sqrt(k*k+16)-k)/8
    b=min(mp.mpf(1),(mp.sqrt(k*k+16)+k)/8)
    lo=mp.acos(b)
    hi=mp.acos(a)
    def f(theta):
        t=mp.cos(theta)
        D=k*k*t*t-(4*t*t-1)**2
        if D>=0:
            return mp.log(k*t+mp.sqrt(D))
        return mp.log(abs(4*t*t-1))
    bounds=sorted(set([mp.mpf(0),lo,hi,mp.pi/2]))
    total=mp.mpf(0)
    for left,right in zip(bounds,bounds[1:]):
        if right==left:
            continue
        def integrand(u):
            if u==0 or u==mp.pi/2:
                return mp.mpf(0)
            theta=left+(right-left)*mp.sin(u)**2
            return f(theta)*(right-left)*mp.sin(2*u)
        total+=mp.quad(integrand,[0,mp.pi/4,mp.pi/2])
    return 2*total/mp.pi


def endpoint_quadrature(n,working):
    """Propagate a rigorous input interval through heuristic quadrature."""
    F=RealIntervalField(numberdb.bits(working,losing=16))
    k=F(n).sqrt()
    # Exact rationals prevent binary endpoint conversion through a float.
    endpoints=[k.lower().exact_rational(),k.upper().exact_rational()]
    values=[]
    with mp.workdps(working+12):
        for endpoint in dict.fromkeys(endpoints):
            x=mp.mpf(str(endpoint.numerator()))/mp.mpf(str(endpoint.denominator()))
            with mp.workdps(working):
                y=mahler_at(x,working)
            values.append(mp.nstr(y,working))
    # Orientation is guaranteed mathematically by the positive-root acosh
    # formulation; min/max also retains small quadrature-rounding reversals.
    lo=min(F(v).lower() for v in values)
    hi=max(F(v).upper() for v in values)
    return F(lo,hi)


@lru_cache(maxsize=None)
def computed(n,digits):
    if n==0:
        return 0
    return numberdb.agreeing(lambda w:endpoint_quadrature(n,w),
                             at=(digits+40,digits+80))


class Boyd32(numberdb.Generator):
    table='T742'
    parameters=('k',)
    type='R'
    digits=100
    rigour='heuristic (agreement-checked)'

    def enumerate(self,limit=36):
        for n in range(int(limit)+1):
            yield {'k':identity(n)}

    def value(self,params,digits):
        n=parse_identity(params['k'])
        result={'number':computed(n,int(digits))}
        if math.isqrt(n)**2!=n:
            result['param-latex']=r'$\sqrt{%d}$'%n
        return result


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--publish',action='store_true')
    args=parser.parse_args()
    generator=Boyd32()
    if args.publish:
        print(generator.publish())
    else:
        print(generator.verify(sample=None))
