"""T744: Ordinary logarithmic Mahler measures of the elliptic R family.

Install: sage -pip install numberdb mpmath
Check: sage -python generate.py
Fill an authorized draft: sage -python generate.py --publish
The default command only verifies; neither command offers or publishes a draft.

R_k=x^3+y^3-x-y+k*x*y, k>=0, normalized Haar measure and natural log.
Bertin and Zudilin, arXiv:1601.07583, The third family, gives
-y^3 R_k(x/y,1/(x*y))=(x+x^-1)y^2-k*y-(x^3+x^-3).
This determinant -2 torus map preserves Haar integrals (it is a finite cover).
Jensen's formula includes BOTH roots. The leading coefficient has measure 0.
We integrate a numerator expression after adding log(2*t), whose mean is 0,
where t=sin(theta). All discriminant and unit-circle contacts are split;
a sine-squared substitution smooths algebraic endpoint singularities. k=0
uses the direct root-modulus formula, with no artificial log singularity.

Selection: sqrt(n), 0<=n<=36, plus 16/(3*sqrt(3)), in increasing order.
Square roots are positive and square cases have integer identities.
See argument-selection.md for the arithmetic model and intrinsic thresholds.

For 100 requested digits, work at 140 and 180 DECIMAL digits. Exact algebraic
input intervals are recomputed and both endpoints numerically propagated.
This sensitivity check and precision agreement do not certify quadrature.
Rigour: heuristic (agreement-checked). No data file is needed to recompute.
Credentials and session attribution belong in the calling environment.
"""
import argparse
import math
import re
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.real_mpfi import RealIntervalField
from mpmath import mp

THRESHOLD='16/(3*sqrt(3))'

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

def parse_key(k):
    k=str(k)
    if k==THRESHOLD:return None
    if re.fullmatch(r'\d+',k):return int(k)**2
    m=re.fullmatch(r'sqrt\((\d+)\)',k)
    if not m:raise ValueError('Use a nonnegative integer, sqrt(n), or '+THRESHOLD)
    return int(m.group(1))

def argument_interval(n,working):
    F=RealIntervalField(numberdb.bits(working,losing=48))
    return F(16)/(3*F(3).sqrt()) if n is None else F(n).sqrt()

def contacts(k):
    points=[mp.mpf(0),mp.mpf(1),mp.sqrt(mp.mpf(1)/2)]
    if k<=3:
        d=mp.sqrt(max(mp.mpf(0),9-k*k))
        points.extend([mp.sqrt((3-d)/8),mp.sqrt((3+d)/8)])
    kap=16/(3*mp.sqrt(3))
    if 0<k<=kap:
        alpha=mp.asin(min(mp.mpf(1),k/kap))/3
        points.extend([2/mp.sqrt(3)*mp.sin(alpha),2/mp.sqrt(3)*mp.sin(mp.pi/3-alpha)])
    return sorted(set(mp.asin(t) for t in points if 0<=t<=1))

def mahler_at(k):
    if k==0:
        return 2/mp.pi*mp.quad(lambda a:mp.log(3-4*mp.sin(a)**2),[0,mp.pi/4])
    bounds=contacts(k)
    def numerator(a):
        t=mp.sin(a);D=k*k-48*t*t+64*t**4
        if D<0:
            return mp.log(2*t)+max(mp.mpf(0),mp.log(3-4*t*t))
        large=(k+mp.sqrt(D))/2
        small=abs(2*t*(3-4*t*t)/large)
        return mp.log(max(2*t,large))+mp.log(max(mp.mpf(1),small))
    total=mp.mpf(0)
    for left,right in zip(bounds,bounds[1:]):
        if right-left<mp.eps:continue
        def mapped(u):
            if u==0 or u==mp.pi/2:return mp.mpf(0)
            a=left+(right-left)*mp.sin(u)**2
            if a==0:return mp.mpf(0)
            return numerator(a)*(right-left)*mp.sin(2*u)
        total+=mp.quad(mapped,[0,mp.pi/4,mp.pi/2])
    return 2*total/mp.pi

def endpoint_quadrature(n,working):
    k=argument_interval(n,working);F=k.parent()
    endpoints=[k.lower().exact_rational(),k.upper().exact_rational()]
    values=[]
    for endpoint in dict.fromkeys(endpoints):
        with mp.workdps(working+25):
            x=mp.mpf(str(endpoint.numerator()))/mp.mpf(str(endpoint.denominator()))
            with mp.workdps(working): y=mahler_at(x)
            values.append(mp.nstr(y,working))
    return F(min(F(v).lower() for v in values),max(F(v).upper() for v in values))

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

class EllipticR(numberdb.Generator):
    table='T744'
    parameters=('k',)
    type='R'
    digits=100
    rigour='heuristic (agreement-checked)'
    def enumerate(self,limit=36):
        for n in range(int(limit)+1):
            yield {'k':key(n)}
            if n==9:yield {'k':THRESHOLD}
    def value(self,params,digits):
        n=parse_key(params['k']);result={'number':computed(n,int(digits))}
        if n is None:result['param-latex']=r'$\frac{16}{3\sqrt{3}}$'
        elif math.isqrt(n)**2!=n:result['param-latex']=r'$\sqrt{%d}$'%n
        return result

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--publish',action='store_true');a=p.parse_args();g=EllipticR()
    print(g.publish() if a.publish else g.verify(sample=None))
