"""Integrate a normalized Gaussian and plot its accumulated integral."""
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. Choose the resolution and domain.
    grid = RadialGrid.uniform(n_r=200, r_max=6.0)

    # 2. Sample a Gaussian with infinite-space integral one.
    f = grid.sample(lambda c: np.exp(-c.r**2) / np.pi**1.5)

    # 3. Integrate with physical cell volumes and compare.
    integral = grid.integrate(f)
    print(f"Integral: {integral:.10f}")
    print(f"Absolute error against infinite-space integral: {abs(integral - 1):.3e}")

    # 4. Accumulate shell contributions at cell faces and compare with the exact integral.
    radius = grid.r_faces[1:]
    accumulated = np.cumsum(f.values * grid.cell_volumes)
    exact = erf(radius) - 2 * radius * np.exp(-radius**2) / np.sqrt(np.pi)
    plot_result(radius, accumulated, exact)


def plot_result(radius, accumulated, exact):
    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 = plt.subplots(figsize=(5.4, 3.0), layout="constrained")
        ax.plot(radius, exact, color="black", linewidth=1.5, label="Exact")
        ax.plot(radius[::8], accumulated[::8], "o", markersize=4,
                markerfacecolor="white", color="#b8312f", label="FLODI")
        ax.set(xlabel=r"$R/a_0$", ylabel=r"$\int_0^R 4\pi r^2 f(r)\,dr$",
               xlim=(0, 4), ylim=(0, 1.06), xticks=[0, 1, 2, 3, 4], yticks=[0, 0.5, 1])
        ax.legend(frameon=False, fontsize=10, loc="lower right")
        FIGURE_DIRECTORY.mkdir(parents=True, exist_ok=True)
        for extension in ("png", "svg"):
            fig.canvas.draw()
            fig.savefig(FIGURE_DIRECTORY / f"integrate_gaussian.{extension}", dpi=260,
                        transparent=True, bbox_inches="tight", pad_inches=0.12)
        plt.close(fig)


if __name__ == "__main__":
    main()
