"""Find spherically symmetric Dirichlet eigenmodes of -Laplacian on a ball.

Regularity at r=0 and f(R)=0 give k_n=n*pi/R and eigenvalues k_n**2.
These are the radial (angularly constant) modes, not the full angular spectrum.
"""
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
from scipy.sparse.linalg import eigsh

from flodi import RadialGrid

FIGURE_DIRECTORY = Path("figures")


def main():
    # 1. Fix the physical boundary and choose a radial resolution.
    radius = 6.0
    grid = RadialGrid.uniform(n_r=200, r_max=radius)

    # 2. Supply a linear field action. The adapter imposes zero outer values
    #    and uses volume-weighted solver vectors for the physical inner product.
    operator = grid.linear_operator(lambda f: -grid.laplacian(f))
    initial = np.random.default_rng(7).normal(size=grid.r.size)
    eigenvalues, vectors = eigsh(operator, k=3, which="SA", tol=1e-11, v0=initial)
    order = np.argsort(eigenvalues)
    eigenvalues, vectors = eigenvalues[order], vectors[:, order]

    # 3. Recover the lowest physical mode and compare with the exact solution.
    mode = grid.from_vector(vectors[:, 0])
    exact = grid.sample(
        lambda c: np.sqrt(np.pi / (2 * radius**3)) * np.sinc(c.r / radius)
    )
    # Eigenvectors have an arbitrary sign: align it before comparing profiles.
    if grid.integrate(mode, exact) < 0:
        mode = -mode
    reference = (np.arange(1, 4) * np.pi / radius)**2
    residual = -grid.laplacian(mode) - eigenvalues[0] * mode
    residual_norm = np.sqrt(grid.integrate(residual, residual))
    print(f"Lowest eigenvalue: {eigenvalues[0]:.10f} a0^-2")
    print(f"Analytical eigenvalue: {reference[0]:.10f} a0^-2")
    print(f"Physical norm: {grid.integrate(mode, mode):.10f}")
    print(f"Volume-weighted residual norm: {residual_norm:.3e}")

    # 4. Recover and sign-align all three modes to reveal their nodal structure.
    modes, exact_modes = [], []
    for index in range(3):
        n = index + 1
        numerical_mode = grid.from_vector(vectors[:, index])
        exact_mode = grid.sample(
            lambda c: n * np.sqrt(np.pi / (2 * radius**3)) * np.sinc(n * c.r / radius)
        )
        if grid.integrate(numerical_mode, exact_mode) < 0:
            numerical_mode = -numerical_mode
        modes.append(numerical_mode.values)
        exact_modes.append(exact_mode.values)
    plot_result(grid.r, modes, exact_modes)


def plot_result(r, modes, exact_modes):
    with plt.rc_context({
        "font.family": "sans-serif", "font.sans-serif": ["Liberation Sans", "DejaVu Sans"],
        "font.size": 11, "mathtext.fontset": "stixsans", "axes.labelsize": 11,
        "axes.spines.top": False, "axes.spines.right": False, "axes.linewidth": 0.7,
        "axes.edgecolor": "#aaa69e", "axes.labelcolor": "#444444", "text.color": "#444444",
        "xtick.color": "#77736b", "ytick.color": "#77736b",
        "xtick.labelsize": 10, "ytick.labelsize": 10, "svg.fonttype": "path",
        "figure.facecolor": "none", "axes.facecolor": "none",
    }):
        fig, axes = plt.subplots(3, 1, figsize=(5.4, 4.4), sharex=True, layout="constrained")
        for index, ax in enumerate(axes):
            ax.axhline(0, color="#aaa69e", linewidth=0.7)
            ax.plot(r, exact_modes[index], color="black", linewidth=1.5, label="Exact")
            ax.plot(r[::8], modes[index][::8], "o", markersize=3.5,
                    markerfacecolor="white", color="#b8312f", label="FLODI")
            ax.set(ylabel=f"$f_{index + 1}$", xlim=(0, 6), xticks=[0, 2, 4, 6])
        axes[0].legend(frameon=False, fontsize=10, loc="upper right", ncol=2)
        axes[-1].set_xlabel(r"$r/a_0$")
        FIGURE_DIRECTORY.mkdir(parents=True, exist_ok=True)
        for extension in ("png", "svg"):
            fig.canvas.draw()
            fig.savefig(FIGURE_DIRECTORY / f"eigenmodes_ball.{extension}", dpi=260,
                        transparent=True, bbox_inches="tight", pad_inches=0.12)
        plt.close(fig)


if __name__ == "__main__":
    main()
