"""Compare an isolated Gaussian potential with erf(r)/r and plot the error."""
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
from scipy.special import erf

from flodi import RadialGrid

FIGURE_DIRECTORY = Path("figures")


def main():
    # 1. Sample a source per unit physical volume.
    grid = RadialGrid.uniform(n_r=200, r_max=6.0)
    source = grid.sample(lambda c: np.exp(-c.r**2) / np.pi**1.5)

    # 2. Solve with the default isolated, decaying exterior.
    potential = grid.poisson(source)

    # 3. Check the potential error and discrete residual separately.
    exact = grid.sample(lambda c: erf(c.r) / c.r)
    error = potential - exact
    residual = grid.laplacian(potential) + 4 * np.pi * source
    print(f"Maximum potential error: {np.max(np.abs(error.values)):.3e}")
    print(f"Maximum discrete residual: {np.max(np.abs(residual.values)):.3e}")

    # 4. Plot the potential and its error; the residual is a separate check.
    plot_result(grid.r, potential.values, exact.values, error.values)


def plot_result(r, potential, 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], potential[::6], "o", markersize=4, markerfacecolor="white",
                color="#b8312f", label="FLODI")
        ax.set(ylabel=r"$V/E_{\mathrm{h}}$", yticks=[0, 0.5, 1])
        ax.legend(frameon=False, fontsize=10)
        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.00025],
                       xticks=[0, 2, 4, 6], xlim=(0, 6))
        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"poisson_gaussian.{extension}", dpi=260,
                        transparent=True, bbox_inches="tight", pad_inches=0.12)
        plt.close(fig)


if __name__ == "__main__":
    main()
