"""Two independent cell calculations for H = -d²/dx² + 2m sn²(x|m).

Requires NumPy and SciPy. Run "python3 lame_bands.py" for the dossier's m=1/2
example. Try "python3 lame_bands.py --parameter 0.3 --phase-in-pi 0.75"
to change the elliptic parameter and the Bloch multiplier exp(i*phase).
The union over all phases is the spectrum on the real line.
"""

import argparse

import numpy as np
from scipy.integrate import solve_ivp
from scipy.special import ellipj, ellipk


def cell_energies(m, phase, cutoff):
    """Lowest three energies in a plane-wave basis with the chosen twist."""
    period = 2 * ellipk(m)
    # Quadrature nodes exclude the duplicate endpoint of the periodic cell.
    size = 16 * (2 * cutoff + 1)
    x = period * np.arange(size) / size
    potential = 2 * m * ellipj(x, m)[0]**2
    fourier = np.fft.fft(potential) / size
    modes = np.arange(-cutoff, cutoff + 1)
    momenta = (2 * np.pi * modes + phase) / period
    differences = modes[:, None] - modes[None, :]
    hamiltonian = np.diag(momenta**2) + fourier[differences % size]
    return np.linalg.eigvalsh(hamiltonian)[:3]


def monodromy(m, energy, tolerance):
    """Integrate two independent initial data over a cell; return trace, det."""
    def equation(x, state):
        coefficient = 2 * m * ellipj(x, m)[0]**2 - energy
        u, du, v, dv = state
        return du, coefficient * u, dv, coefficient * v

    solution = solve_ivp(equation, (0, 2 * ellipk(m)), (1, 0, 0, 1),
                         method="DOP853", rtol=tolerance, atol=tolerance / 100)
    if not solution.success:
        raise RuntimeError(solution.message)
    u, du, v, dv = solution.y[:, -1]
    return u + dv, u * dv - v * du


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--parameter", type=float, default=0.5, help="elliptic parameter m")
    parser.add_argument("--phase-in-pi", type=float, default=0.5, help="phase divided by pi")
    args = parser.parse_args()
    m = args.parameter
    if not 0 < m < 1 or not np.isfinite(args.phase_in_pi):
        parser.error("choose 0 < parameter < 1 and a finite phase")
    # Use inversion and phase periodicity to display the first Brillouin zone.
    phase = np.pi * abs((args.phase_in_pi + 1) % 2 - 1)
    print(f"m={m:g}, cell length={2 * ellipk(m):.10f}")
    for twist in np.unique([0, phase, np.pi]):
        coarse = cell_energies(m, twist, 8)
        fine = cell_energies(m, twist, 16)
        error = max(abs(fine - coarse))
        print(f"phase/pi={twist/np.pi:.4f}: lowest energies {fine.round(9)}; "
              f"max change at cutoffs 8,16: {error:.2e}")
    edges = np.r_[cell_energies(m, 0, 16)[0], cell_energies(m, np.pi, 16)[:2]]
    print(f"Max error against the three exact edges m, 1, 1+m: "
          f"{max(abs(edges - [m, 1, 1 + m])):.2e}")

    # Test a first-band energy, a gap energy, and the numerically measured
    # lowest energy of the chosen cell. det M=1 makes |tr M|=2 a band edge.
    first_energy = cell_energies(m, phase, 16)[0]
    for label, energy in [("band midpoint", (m + 1) / 2),
                          ("gap midpoint", 1 + m / 2), ("chosen twist", first_energy)]:
        coarse, _ = monodromy(m, energy, 1e-9)
        trace, det = monodromy(m, energy, 1e-12)
        print(f"{label}, E={energy:.9f}: tr M={trace:.10f}, "
              f"trace refinement={abs(trace-coarse):.1e}, |det M-1|={abs(det-1):.1e}")
        if label == "chosen twist":
            print(f"  Independent check |tr M-2 cos(phase)|={abs(trace-2*np.cos(phase)):.2e}")

    # With m=0 the potential vanishes and the transfer trace is known at any E.
    free_energy = 0.75
    trace, _ = monodromy(0, free_energy, 1e-12)
    exact = 2 * np.cos(np.pi * np.sqrt(free_energy))
    print(f"Free-particle control at E={free_energy:g}: |tr M-exact|={abs(trace-exact):.2e}")


if __name__ == "__main__":
    main()
