"""Compare the numerical Laplacian with an analytical derivative and plot both."""
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np

from flodi import RadialGrid

FIGURE_DIRECTORY = Path("figures")


def main():
    # 1. Sample a smooth function, including its outer-face values.
    grid = RadialGrid.uniform(n_r=200, r_max=6.0)
    f = grid.sample(lambda c: np.exp(-c.r**2))

    # 2. Compute the numerical and analytical Laplacians.
    numerical = grid.laplacian(f)
    exact = grid.sample(lambda c: (4 * c.r**2 - 6) * np.exp(-c.r**2))

    # 3. Measure the error using physical volumes.
    error = numerical - exact
    l2_error = np.sqrt(grid.integrate(error.conj(), error).real)
    print(f"Volume-weighted L2 error: {l2_error:.3e}")

    # 4. Show agreement and the smaller difference on separate axes.
    plot_result(grid.r, numerical.values, exact.values, error.values)


def plot_result(r, numerical, exact, error):
    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, (ax, difference) = plt.subplots(2, 1, figsize=(5.4, 3.8), sharex=True,
                                            gridspec_kw={"height_ratios": [3, 1]}, layout="constrained")
        ax.plot(r, exact, color="black", linewidth=1.5, label="Exact")
        ax.plot(r[::6], numerical[::6], "o", markersize=4, markerfacecolor="white",
                color="#b8312f", label="FLODI")
        ax.set(ylabel=r"$\nabla^2 f\,/\,a_0^{-2}$", yticks=[-6, -3, 0])
        ax.legend(frameon=False, fontsize=10, loc="lower right")
        difference.axhline(0, color="#aaa69e", linewidth=0.7)
        difference.plot(r, error, color="#b8312f", linewidth=1.4)
        difference.set(xlabel=r"$r/a_0$", ylabel="Error", yticks=[0, 0.005],
                       xticks=[0, 1, 2, 3, 4], xlim=(0, 4))
        difference.ticklabel_format(axis="y", style="sci", scilimits=(0, 0), useMathText=True)
        FIGURE_DIRECTORY.mkdir(parents=True, exist_ok=True)
        for extension in ("png", "svg"):
            fig.canvas.draw()
            fig.savefig(FIGURE_DIRECTORY / f"laplacian_gaussian.{extension}", dpi=260,
                        transparent=True, bbox_inches="tight", pad_inches=0.12)
        plt.close(fig)


if __name__ == "__main__":
    main()
