"""Independent numerical checks for Milne distances -- numberdb.org/T637.

Run: sage -python checks.py > numerical-evidence.json
The distance integral is independent of the generator's phase quadrature.
No API access or credentials are needed. Source-limited controls and approximate
moment checks are separate from the high-precision agreement measurements.
"""
import numberdb.sage as numberdb
import mpmath as mp
import json
import platform
import time
from generate import MilneDistances, phase_distance


def direct_distance(d, working=170):
    """d'Eon--McCormick (176), with t=tan(u) and cancelled small-t terms.

    For F=2F1(1/2,1;d/2;-t^2), use
      1-F=t^2 A/d, A=2F1(3/2,1;d/2+1;-t^2),
      A-1=-3t^2 B/(d+2), B=2F1(5/2,1;d/2+2;-t^2).
    Thus d/t^2+3-1/(1-F) = 3-3d B/((d+2)A).
    These follow termwise from the hypergeometric series and continuation.
    This removes cancellation at t=0; the angular change treats the entire
    infinite integration interval without a manually truncated tail.
    """
    with mp.workdps(working):
        q = mp.mpf
        def integrand(u):
            x = mp.tan(u)**2
            a = mp.hyp2f1(q(3)/2, 1, q(d)/2+1, -x)
            b = mp.hyp2f1(q(5)/2, 1, q(d)/2+2, -x)
            return 3-q(3*d)/(d+2)*b/a
        return mp.quad(integrand, [0, mp.pi/4, mp.pi/2])/mp.pi


def closed_form(d):
    if d == 1:
        return mp.mpf(1)
    if d == 2:
        return mp.mpf(1)/2+1/mp.pi
    if d == 4:
        return 2/mp.pi
    if d == 6:
        return -3/(4*mp.sqrt(2))+3/mp.pi+3*mp.atan(1/(2*mp.sqrt(2)))/(2*mp.sqrt(2)*mp.pi)
    raise ValueError(d)


def moment_checks():
    """Separate float64 quadrature check of angular normalization and moments.

    A sine substitution removes the Flatland square-root angular endpoint.
    This checks the H-factorization normalization and z0=sqrt(d)*alpha2/2;
    it supplies no additional high-precision digits. Known alpha0 and alpha1
    are mandatory nonzero controls before the alpha2 comparisons are accepted.
    """
    import numpy as np
    import scipy
    from scipy.special import roots_legendre, gamma, hyp2f1
    output = {'scipy': scipy.__version__, 'numpy': np.__version__, 'rows': []}
    for size in (256, 512):
        nodes, weights = roots_legendre(size)
        t = (nodes+1)/2
        wt = weights/2
        u = (nodes+1)*np.pi/4
        wu = weights*np.pi/4
        mu = np.sin(u)
        for d in range(2,11):
            gpref = 2*gamma(d/2)/(np.sqrt(np.pi)*gamma((d-1)/2))
            lam = hyp2f1(1,1-d/2,0.5,t*t)
            imag = np.pi*t*gpref*(1-t*t)**((d-3)/2)/2
            phase = np.arctan2(imag,lam)
            h = np.sqrt(d)*(1+mu)*np.exp(-np.sum(wt*phase/(mu[:,None]+t),axis=1)/np.pi)
            angular = gpref*np.cos(u)**(d-2)
            moments = [float(np.sum(wu*angular*mu**n*h)) for n in range(3)]
            errors = [abs(moments[0]-2), abs(moments[1]-2/np.sqrt(d))]
            assert max(errors)<2e-7, (d,size,moments)
            estimate = np.sqrt(d)*moments[2]/2
            error = abs(estimate-float(phase_distance(d,150)))
            assert error<2e-7, (d,size,error)
            output['rows'].append({'d':d,'nodes':size,'alpha':moments,
                                   'control_errors':errors,'distance_error':error})
    return output


def main():
    started = time.time()
    evidence = {'table':'T637', 'rigour':'heuristic (agreement-checked)',
        'skill_manifest':'../20261031T110316Z-build-skills/manifest.json',
        'skill_sha256':'a2b28d9953264d7b0ca62663785c2952190c5be6d6d3597fd695d9a54d606278',
        'versions':{'numberdb':numberdb.__version__,'mpmath':mp.__version__,
                    'python':platform.python_version()}, 'controls':[], 'rows':[]}
    # Controls precede acceptance of other measurements.
    with mp.workdps(210):
        for d in (1,2,4,6):
            primary = phase_distance(d,150)
            other = direct_distance(d)
            exact = closed_form(d)
            error = max(abs(primary-exact),abs(other-exact))
            assert error<mp.mpf('1e-140'), (d,error)
            evidence['controls'].append({'d':d,'closed_form_max_error':mp.nstr(error,12)})
        gen = MilneDistances()
        for p in gen.enumerate():
            d = int(p['d']); a = phase_distance(d,150); b = phase_distance(d,200,True)
            c = direct_distance(d)
            assert max(abs(a-b),abs(b-c))<mp.mpf('1e-140')
            entry = gen.value(p,100)
            evidence['rows'].append({'d':d, 'entry':entry,
                'phase150':mp.nstr(a,155),'phase200_refined':mp.nstr(b,205),
                'distance_integral170':mp.nstr(c,175),
                'phase_refinement_difference':mp.nstr(abs(a-b),12),
                'independent_difference':mp.nstr(abs(b-c),12)})
        hopf_reference = mp.mpf('0.710446089598763072732524141699153671993201333958785239092798')
        # Appendix A3 prints 60 decimals, rounded at the last place.
        discrepancy = abs(phase_distance(3,200,True)-hopf_reference)
        assert discrepancy < mp.mpf('1e-60')
        evidence['kawabata_A3_difference']=mp.nstr(discrepancy,12)
        reference = ['1.0000000000','0.8183098862','0.7104460896','0.6366197724',
                     '0.5819457611','0.5393348406','0.5049086837','0.4763395251']
        assert all(abs(phase_distance(d,150)-mp.mpf(x))<mp.mpf('5e-11')
                   for d,x in enumerate(reference,1))
        evidence['dEM_table2_all_eight_rounded_values']='pass'
    evidence['moments']=moment_checks()
    evidence['elapsed_seconds']=round(time.time()-started,3)
    evidence['limitations']='No rigorous quadrature error bounds. Moment checks use float64 and only test normalization and the identity at their recorded accuracy.'
    print(json.dumps(evidence,indent=2))

if __name__ == '__main__':
    main()
