"""Lowest parity doublet of -h^2 d^2/dx^2 + (x^2-1)^2.

Run with Python, NumPy and SciPy. Space, h and energies are dimensionless.
"""
import numpy as np
from scipy.linalg import eigh_tridiagonal


def doublet(h, box, spacing):
    grid = np.linspace(-box, box, round(2 * box / spacing) + 1)
    x = grid[1:-1]  # Exclude Dirichlet endpoints.
    kinetic = (h / (grid[1] - grid[0]))**2
    diagonal = 2 * kinetic + (x*x - 1)**2
    off_diagonal = -kinetic * np.ones(len(x) - 1)
    energies, states = eigh_tridiagonal(diagonal, off_diagonal, select="i",
                                         select_range=(0, 1), tol=1e-14)
    parities = np.sum(states * states[::-1, :], axis=0)
    assert np.allclose(parities, [1, -1], atol=1e-5)
    return energies


if __name__ == "__main__":
    for h in (0.30, 0.20, 0.16):
        small_box = doublet(h, 3, 0.0025)
        coarse = doublet(h, 3.5, 0.0025)
        refined = doublet(h, 3.5, 0.00125)
        gap = refined[1] - refined[0]
        change_of_mesh = abs(np.diff(coarse)[0] - gap)
        change_of_box = abs(np.diff(small_box)[0] - np.diff(coarse)[0])
        asymptote = 16 * np.sqrt(2*h/np.pi) * np.exp(-4/(3*h))
        assert gap > 0 and change_of_mesh < 4e-7 and change_of_box < 1e-9
        print(f"h={h}, E_even={refined[0]:.8f}, E_odd={refined[1]:.8f}, "
              f"gap={gap:.9f}, change of mesh={change_of_mesh:.2e}, "
              f"change of box={change_of_box:.2e}, gap/asymptote={gap/asymptote:.6f}")
