"""Lamé gap propagation and separated boundary states at m=1/2.

Run with Python 3, NumPy and SciPy. Energies h are in the Jacobi x coordinate.
SciPy takes the parameter m=k^2 for both ellipk and ellipj.
"""

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


M = 0.5
K = ellipk(M)
PERIOD = 2 * K


def propagate(index, energy, initial, distances, tolerance):
    def derivative(x, state):
        sine = ellipj(x, M)[0]
        potential = index * (index + 1) * M * sine**2
        return (state[1], (potential - energy) * state[0])

    result = solve_ivp(
        derivative, (0, distances[-1]), initial, t_eval=distances,
        method="DOP853", atol=tolerance / 10, rtol=tolerance,
    )
    if not result.success:
        raise RuntimeError(result.message)
    return result.y


def gap_check(tolerance):
    """Compare one-cell launches with composing the two reflected half cells."""
    halves = [propagate(1, 1.25, state, [K], tolerance)[:, 0]
              for state in ((1, 0), (0, 1))]
    half = np.column_stack(halves)
    reflect = np.diag([1, -1])
    full = reflect @ np.linalg.solve(half, reflect @ half)
    expected = np.linalg.eigvals(full)
    multipliers = []
    for slope in (np.sqrt(3) / 2, -np.sqrt(3) / 2):
        initial = np.array([1, slope])
        cells = np.arange(1, 4)
        states = propagate(1, 1.25, initial, cells * PERIOD, tolerance)
        multiplier = states[0, 0]
        np.testing.assert_allclose(states, initial[:, None] * multiplier**cells,
                                   atol=200 * tolerance, rtol=200 * tolerance)
        multipliers.append(multiplier)
    np.testing.assert_allclose(sorted(multipliers), sorted(expected),
                               rtol=20 * tolerance)
    np.testing.assert_allclose(np.prod(multipliers), 1, rtol=20 * tolerance)
    return np.array(multipliers)


def boundary_check():
    """Shoot from the left. The right endpoint is Neumann for all three roots."""
    cases = [("NN", (1, 1.5), 3 - np.sqrt(3), 0),
             ("DN", (2.5, 3.5), 3, 0),
             ("NN", (4.5, 5.2), 3 + np.sqrt(3), 1)]
    for pair, bracket, exact, expected_nodes in cases:
        initial = (1, 0) if pair[0] == "N" else (0, 1)

        def right_derivative(energy):
            return propagate(2, energy, initial, [K], 1e-12)[1, 0]

        energy = brentq(right_derivative, *bracket, xtol=1e-13)
        np.testing.assert_allclose(energy, exact, rtol=0, atol=5e-11)
        grid = np.linspace(0, K, 401)
        interior = propagate(2, energy, initial, grid, 1e-12)[0, 1:-1]
        nodes = np.count_nonzero(np.diff(np.signbit(interior)))
        assert nodes == expected_nodes
        print(f"{pair}: h={energy:.10f}, -q={energy / 2:.10f}, interior zeros={nodes}")

    # Complementary parities in the mapping article. Propagate over a full cell.
    for initial, energy, sign in [((0, 1), 4 + M, 1), ((1, 0), 1 + M, -1)]:
        end = propagate(2, energy, initial, [K, PERIOD], 1e-12)
        np.testing.assert_allclose(end[0, 0], 0, atol=8e-12)
        np.testing.assert_allclose(end[:, 1], sign * np.array(initial), atol=8e-12)


if __name__ == "__main__":
    coarse = gap_check(1e-9)
    fine = gap_check(1e-12)
    print("Gap multipliers:", fine, "decaying value at 3T:", fine[0]**3)
    print("Maximum change on refinement:", np.max(np.abs(coarse - fine)))
    boundary_check()
    # Set z=sin(theta)^2 in the physical squared norm of sqrt(z(1-z/2)).
    def density(theta):
        z = np.sin(theta)**2
        return 2 * z * (1 - z / 2) / np.sqrt(2 - z)

    norm_squared = quad(density, 0, np.pi / 2, epsabs=1e-13)[0]
    np.testing.assert_allclose(norm_squared, np.sqrt(2) * K / 3, atol=1e-13, rtol=0)
    print("Mixed ground-state squared norm in w dz:", norm_squared)
