"""Check the first gap and the moving Dirichlet eigenvalue of a cosine potential."""
import numpy as np


def spectral_values(strength, phase, modes, order):
    # Bloch boundary condition -1 over [0, pi]: odd plane-wave indices.
    wavenumbers = np.arange(-2*modes+1, 2*modes, 2)
    fourier = np.diag(wavenumbers.astype(complex)**2)
    off_diagonal = np.ones(len(wavenumbers)-1) * strength * np.exp(1j*phase)
    fourier += np.diag(off_diagonal, -1) + np.diag(off_diagonal.conjugate(), 1)
    edges = np.linalg.eigvalsh(fourier)[:2]
    z, weight = np.polynomial.legendre.leggauss(order)
    x, weight = (z+1)*np.pi/2, weight*np.pi/2
    n = np.arange(1, modes+1)
    sine = np.sqrt(2/np.pi) * np.sin(np.outer(n,x))
    potential = 2*strength*np.cos(2*x+phase)
    dirichlet = np.diag(n*n) + (sine*(weight*potential))@sine.T
    return *edges, np.linalg.eigvalsh(dirichlet)[0]


if __name__ == "__main__":
    for phase in [0, np.pi/3, np.pi/2, np.pi]:
        for eps in [0.05, 0.025]:
            values = spectral_values(eps, phase, 12, 96)
            refined = spectral_values(eps, phase, 24, 192)
            print(f"phase/pi={phase/np.pi:.4f} eps={eps:.3f}",
                  *(f"{v:.9f}" for v in refined),
                  "max refinement", f"{max(abs(a-b) for a,b in zip(values,refined)):.2e}")
