"""Run beside fit-curves.csv: python replot.py. Requires pandas and matplotlib."""
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
root = Path(__file__).resolve().parent
data = pd.read_csv(root / "fit-curves.csv")
x, y = data.iloc[:, 0], data.iloc[:, 1]
mask_record = pd.read_csv(root / "background-reference.csv").set_index("x")["masked"]
excluded = x.map(mask_record).fillna(0).astype(bool)
fig, (ax, residual) = plt.subplots(2, 1, sharex=True, gridspec_kw={"height_ratios": [3, 1]})
ax.plot(x[~excluded], y[~excluded], ".", ms=2, color="0.45", label="Data after background subtraction")
ax.plot(x[excluded], y[excluded], "x", ms=4, color="0.7", label="Masked / excluded from fit")
for name in data.columns:
    if name.startswith("Component_"):
        ax.plot(x, data[name], lw=1, label=name.replace("Component_", ""))
ax.plot(x, data["Total_fit"], color="black", lw=1.4, label="Total fit")
residual.plot(x[~excluded], data.loc[~excluded, "Residual_data_minus_fit"], ".", ms=2)
residual.axhline(0, color="0.5", lw=.7)
residual.set(xlabel="Raman shift / cm$^{-1}$", ylabel="Residual")
ax.set(ylabel="Intensity / a.u.")
ax.legend(fontsize=7)
fig.tight_layout()
fig.savefig(root / "replotted-fit.png", dpi=160)
print(root / "replotted-fit.png")
