"""Milne extrapolation distances -- numberdb.org/T637.

Run with SageMath (mpmath is included):
    sage -pip install numberdb
    sage -python generate.py                 # verify every stored entry
    sage -python generate.py --fill          # fill the existing draft
For a private draft, set NUMBERDB_API_KEY in the environment. The campaign
can instead pipe a token into stdin with NUMBERDB_KEY_FROM_STDIN=1.
Filling sends entries; it does not publish the draft or offer it for review.

Distances use unit mean exponential free paths, isotropic conservative
scattering, and a vacuum half-space boundary. See argument-selection.md for
the discrete geometry index and noncanonical cutoff. The phase formula is
the c -> 1 limit of d'Eon--McCormick (2019), equations (67) and (191).
The nonnegative phase is evaluated with atan2, including its second quadrant.

At the default 100 significant digits, compute at 150 and 200 decimal working
digits with different interval subdivisions. Require 120-digit absolute
agreement before rounding to 100 significant digits. These are heuristic
agreement checks, not rigorous quadrature error bounds. checks.py independently
evaluates the distance integral (176) and checks source controls and moments.
"""
import numberdb.sage as numberdb
import mpmath as mp
from functools import lru_cache
import os
import re
import sys


@lru_cache(maxsize=None)
def phase_distance(d, working, refined=False):
    """Return the conservative distance from the continuous nonnegative phase."""
    if d == 1:
        return mp.mpf(1)
    if d < 2:
        raise ValueError('Spatial dimension must be a positive integer')
    with mp.workdps(working):
        q = mp.mpf
        prefactor = mp.sqrt(mp.pi) * mp.gamma(q(d)/2) / mp.gamma(q(d-1)/2)

        def phase(t):
            if t == 0:
                return q(0)
            if t >= 1:
                return mp.pi/2 if d == 2 else mp.pi
            real = mp.hyp2f1(1, 1-q(d)/2, q(1)/2, t*t)
            imag = prefactor * t * ((1-t)*(1+t))**(q(d-3)/2)
            return mp.atan2(imag, real)

        knots = ([0, q(1)/4, q(1)/2, q(3)/4, q(9)/10, q(99)/100, 1]
                 if refined else [0, q(1)/2, q(9)/10, 1])
        return 1 - mp.quad(phase, knots, method='tanh-sinh')/mp.pi


class MilneDistances(numberdb.Generator):
    table = 'T637'
    parameters = ('d',)
    type = 'R'
    digits = 100
    rigour = 'heuristic (agreement-checked)'
    files = ('generate.py', 'checks.py', 'argument-selection.md',
             'numerical-evidence.json', 'skill-evidence.json', 'derivation.md')

    def enumerate(self, max_dimension=10):
        for d in range(1, int(max_dimension)+1):
            yield {'d': str(d)}

    def value(self, params, digits):
        d = int(params['d'])
        if d == 1:
            return {'number': 1, 'comment': 'The two-direction rod has extrapolation distance exactly one.'}
        a = phase_distance(d, digits+50)
        b = phase_distance(d, digits+100, True)
        with mp.workdps(digits+110):
            if not (mp.isfinite(a) and mp.isfinite(b)):
                raise ArithmeticError('Nonfinite quadrature result')
            if abs(a-b) >= mp.power(10, -digits-20):
                raise ArithmeticError('Insufficient agreement between quadratures')
            text = mp.nstr(b, digits, strip_zeros=False)
        comments = {
            2: r'Flatland: $z_0(2)=1/2+1/\pi$.',
            3: r'The Hopf constant, also called the Hopf extrapolation length.',
            4: r'$z_0(4)=2/\pi$.',
        }
        return {'number': text, **({'comment': comments[d]} if d in comments else {})}


def authenticated_client():
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        key = sys.stdin.read().strip()
        if re.match(r'^[A-Z_][A-Z0-9_]*\s*=', key):
            key = key.split('=', 1)[1].strip().strip('\"\'')
        return numberdb.Client(api_key=key)
    return numberdb.Client()


if __name__ == '__main__':
    client = authenticated_client()
    generator = MilneDistances()
    if '--fill' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish(client=client,
              message='Fill conservative Milne distances in dimensions one through ten'))
    report = generator.verify(sample=None, client=client)
    print(report)
    sys.exit(0 if report.ok else 1)
