"""Quartic ground doublet from the discrete half-line Green identity.

Python 3, NumPy, SciPy, mpmath. Compare independent parity eigenvalues with
the boundary product of their eigenvectors and with high-precision shooting.
Units and well spacing are fixed.
"""
import mpmath as mp
import numpy as np
from scipy.linalg import eigh_tridiagonal


def parity_gap(h, box, spacing):
    n = round(box / spacing)
    d = box / n
    x = np.arange(n) * d  # omit the Dirichlet point at x=box
    t = (h / d)**2
    diagonal = 2*t + (x*x - 1)**2
    off = np.full(n - 1, -t)
    options = dict(select="i", select_range=(0, 0), tol=1e-14)
    # The even orthonormal basis contains the center and symmetric pairs.
    # The odd basis starts at x=d. Its center coupling is zero.
    Eo, odd = eigh_tridiagonal(diagonal[1:], off[1:], **options)
    off[0] *= np.sqrt(2.)
    Ee, even = eigh_tridiagonal(diagonal, off, **options)
    e, o = even[:, 0], odd[:, 0]
    boundary_gap = np.sqrt(2.)*t*e[0]*o[0] / (e[1:] @ o)
    return boundary_gap, Eo[0] - Ee[0]


def shooting_gap(h, edge, step, order):
    """Match the midpoint and outer boundary solutions at x=1."""
    h, step = mp.mpf(h), mp.mpf(step)
    count = int(mp.nint(1/step))
    outside = int(mp.nint((mp.mpf(edge)-1)/step))

    def slope_ratio(energy, x, dx, steps, value, slope):
        # Taylor-expand in the local dimensionless coordinate (x_new-x)/dx.
        for _ in range(steps):
            q = x*x-1
            coefficients = (q*q-energy, 4*x*q*dx, (6*x*x-2)*dx**2,
                            4*x*dx**3, dx**4)
            a = [value, slope*dx]
            for n in range(order-1):
                product = sum(coefficients[j]*a[n-j] for j in range(min(n, 4)+1))
                a.append((dx/h)**2 * product / ((n+1)*(n+2)))
            value = sum(a)
            slope = sum(i*c for i, c in enumerate(a)) / dx
            x += dx
        return slope/value

    def level(value, slope):
        def mismatch(energy):
            left = slope_ratio(energy, 0, step, count, value, slope)
            right = slope_ratio(energy, mp.mpf(edge), -step, outside, 0, 1)
            return left - right

        return mp.findroot(mismatch, (mp.mpf('1.94')*h, 2*h), tol=mp.mpf('1e-38'))

    return level(0, 1) - level(1, 0)


if __name__ == "__main__":
    for h in (.16, .08, .05, .03):
        gaps = [parity_gap(h, 3., d)[0] for d in (.0025, .00125, .000625)]
        fine, difference = parity_gap(h, 3.5, .000625)
        asymptotic = 16*np.sqrt(2*h/np.pi)*np.exp(-4/(3*h))
        print("h, boundary product, direct subtraction, ratio to leading formula:",
              h, fine, difference, fine/asymptotic)
        correction = abs(gaps[1]/gaps[2] - 1)
        refinement = abs(gaps[0]/gaps[1] - 1) / correction
        print("Relative last mesh change, refinement factor, relative box change:",
              correction, refinement, abs(fine/gaps[2]-1))
        assert 3.7 < refinement < 4.3 and abs(fine/gaps[2]-1) < 2e-7
        if h >= .08:
            assert abs(fine - difference) < 2e-11
    with mp.workdps(45):
        first = shooting_gap('.03', '2', '.1', 40)
        refined = shooting_gap('.03', '2.2', '.05', 50)
        print("Independent shooting, successive box/step/order:", first, refined)
        assert abs(first/refined - 1) < mp.mpf('1e-10')
