#!/usr/bin/env python3
"""Plot results/bench.txt (median of runs) into ../bench-throughput.svg."""
import collections
import os
import re
import statistics

import matplotlib

matplotlib.use("svg")
import matplotlib.pyplot as plt  # noqa: E402

HERE = os.path.dirname(os.path.abspath(__file__))
plt.rcParams.update({
    "svg.hashsalt": "lockfree-stack",
    "font.family": "monospace",
    "font.size": 10,
    "figure.facecolor": "#2d333b",
    "axes.facecolor": "#2d333b",
    "axes.edgecolor": "#768390",
    "axes.labelcolor": "#adbac7",
    "text.color": "#adbac7",
    "xtick.color": "#adbac7",
    "ytick.color": "#adbac7",
    "grid.color": "#444c56",
    "legend.facecolor": "#2d333b",
    "legend.edgecolor": "#636e7b",
})

rows = collections.defaultdict(list)
with open(os.path.join(HERE, "results", "bench.txt")) as f:
    for line in f:
        d = dict(re.findall(r"(\w+)=(\S+)", line))
        rows[(d["impl"], int(d["threads"]))].append(d)


def med(impl, t, key):
    return statistics.median(float(r[key]) for r in rows[(impl, t)])


threads = [1, 2, 3, 4]
style = {
    "mutex": ("#768390", "s", "--"),
    "tagged": ("#f85149", "o", "-"),
    "backoff": ("#3fb950", "^", "-"),
    "elim": ("#388bfd", "D", "-."),
}
panels = [
    ("mops", "throughput (Mops/s, median of 5)"),
    ("cas_fail_per_op", "failed CAS on top per operation"),
    ("fin_ratio", "fairness: first / last thread finish"),
]
fig, axes = plt.subplots(1, 3, figsize=(13, 4.2))
for ax, (key, title) in zip(axes, panels):
    for impl, (color, marker, ls) in style.items():
        if key == "cas_fail_per_op" and impl == "mutex":
            continue
        ys = [med(impl, t, key) for t in threads]
        ax.plot(threads, ys, color=color, marker=marker, linestyle=ls, label=impl, linewidth=1.8)
    ax.set_title(title, color="#cdd9e5", fontsize=10)
    ax.set_xlabel("threads (CPUs 2, 11, 12, 13)")
    ax.set_xticks(threads)
    ax.grid(True, linewidth=0.5)
axes[0].set_ylim(bottom=0)
axes[1].set_ylim(bottom=0)
axes[2].set_ylim(0, 1.05)
axes[0].legend(loc="lower left", fontsize=9)
fig.tight_layout()
fig.savefig(os.path.join(HERE, "..", "bench-throughput.svg"), metadata={"Date": None})
