"""Leading EBK levels for -psi''/2 + x**4 psi/4 on the line (hbar = 1).

Compare a sine-basis projection in two boxes with an independently refined
position grid. Requires Python, NumPy and SciPy.
"""

import numpy as np
from scipy.linalg import eigh, eigh_tridiagonal
from scipy.special import beta, roots_legendre


def sine_levels(radius, modes, last):
    # Normalized Dirichlet modes on [-radius, radius]. In the potential
    # integral the normalized basis and the change of variable cancel.
    t, weights = roots_legendre(2 * modes + 16)
    indices = np.arange(1, modes + 1)
    basis = np.sin(np.pi * (t[:, None] + 1) * indices / 2)
    potential = basis.T @ ((weights * (radius * t)**4 / 4)[:, None] * basis)
    energies = (np.pi * indices / (2 * radius))**2 / 2
    return eigh(np.diag(energies) + potential, eigvals_only=True,
                subset_by_index=(0, last))


def grid_levels(radius, intervals, last):
    x = np.linspace(-radius, radius, intervals + 1)[1:-1]
    dx = 2 * radius / intervals
    return eigh_tridiagonal(1 / dx**2 + x**4 / 4,
                            np.full(len(x) - 1, -0.5 / dx**2),
                            eigvals_only=True, select="i", select_range=(0, last))


def main():
    labels = np.array([0, 3, 7, 15, 23])
    last = labels[-1]
    coarse = sine_levels(8, 100, last)
    fine = sine_levels(9, 140, last)
    assert np.max(np.abs(coarse - fine)) < 2e-10
    grid = [grid_levels(9, n, last) for n in (2048, 4096, 8192)]
    extrapolated = (4 * grid[2] - grid[1]) / 3
    ratios = (grid[0] - grid[1]) / (grid[1] - grid[2])
    assert np.all((ratios > 3.9) & (ratios < 4.1))
    assert np.max(np.abs(extrapolated - fine)) < 5e-7
    ebk = (np.pi * (labels + 0.5) / beta(0.25, 1.5))**(4/3)
    for n, estimate in zip(labels, ebk):
        print(f"n={n:2d}  EBK {estimate:.9f}  spectrum {fine[n]:.9f}  "
              f"relative shortfall {1 - estimate/fine[n]:.7g}")
    print("Maximum basis/box change:", np.max(np.abs(coarse - fine)))
    print("Maximum extrapolated position-grid discrepancy:", np.max(np.abs(extrapolated - fine)))


if __name__ == "__main__":
    main()
