"""Log-log Chamfer against atoms, one panel per object, from ladder.csv; rings every step up of more than 0.5 %."""
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
import pandas as pd  # noqa: E402

R = Path(__file__).resolve().parent
d = pd.read_csv(R / "ladder.csv")
ORDER = ["mug", "mug_ace", "bowl", "bowl_serving", "bowl_dog", "flower_pot", "shoe", "jogger", "dino", "horse", "spring", "knot"]
STYLE = {"v5.5": dict(color="#2a78d6", marker="o", ls="-", label="v5.5 (7ccd2a39)"),
         "new": dict(color="#eb6834", marker="s", ls="--", label="new (ca4ad834)")}
plt.rcParams.update({"font.size": 11, "axes.edgecolor": "#888", "axes.labelcolor": "#222", "xtick.color": "#444", "ytick.color": "#444"})
fig, axes = plt.subplots(3, 4, figsize=(17, 11.5), sharex=True)
for ax, o in zip(axes.flat, ORDER):
    for v, st in STYLE.items():
        g = d[(d.object == o) & (d.version == v)].dropna(subset=["chamfer_pct"])
        x, y = g.atoms.values, g.chamfer_pct.values
        ax.plot(x, y, lw=1.8, ms=4.5, **st)
        for i in range(1, len(y)):
            if y[i] > y[i - 1] * 1.005:
                ax.plot([x[i]], [y[i]], "o", ms=12, mfc="none", mec="#222", mew=1.3)
                ax.annotate(f"+{100 * (y[i] / y[i - 1] - 1):.0f} %" if y[i] / y[i - 1] > 1.015 else f"+{100 * (y[i] / y[i - 1] - 1):.1f} %",
                            (x[i], y[i]), xytext=(9, 7) if v == "v5.5" else (-4, -19), textcoords="offset points", fontsize=9, color="#222")
    ax.set_xscale("log", base=2)
    ax.set_yscale("log")
    lo, hi = ax.get_ylim()
    ax.set_ylim(lo * 0.85, hi * 1.35)
    ax.set_xticks([2 ** k for k in range(3, 17, 3)], [f"{2 ** k:,}" for k in range(3, 17, 3)])
    ax.set_title(o.replace("_", " "), loc="left", fontsize=12)
    ax.grid(True, which="major", color="#e3e3e3", lw=0.8)
    ax.grid(True, which="minor", color="#f3f3f3", lw=0.4)
    ax.spines[["top", "right"]].set_visible(False)
for ax in axes[-1]:
    ax.set_xlabel("atoms kept")
for ax in axes[:, 0]:
    ax.set_ylabel("Chamfer, % of the diagonal")
axes[0, 0].legend(frameon=False, fontsize=10, loc="lower left")
fig.tight_layout()
fig.savefig(R / "ladder_monotonic.png", dpi=95, facecolor="white")
