File size: 7,661 Bytes
7c6d5e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""Plot development progress from saved evaluation results.

    python -m tests.plot_progress            # writes docs/progress.png

Every metric is recomputed from ``eval_out/*/results.json`` with the same chart
exclusions (degenerate ground truth) for every run, so the points are comparable.
"""

from __future__ import annotations

import json
from pathlib import Path

import matplotlib

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

EVAL = Path("eval_out")
PLOTQA = Path("data/benchmarks/plotqa")

# Iterations on the PlotQA test split (tuning set), oldest first.
TEST_RUNS = [
    ("plotqa_base", "baseline"),
    ("plotqa_v1", "rotated labels,\nrotated titles,\ndotted lines"),
    ("plotqa_v2", "outline colours,\nyear categories"),
    ("plotqa_v3", "scatter on\ncategories"),
    ("plotqa_final_test", "clipping check,\nguards"),
]
HELDOUT = [("plotqa_train300_baseline", "before"), ("plotqa_final_train300", "after")]
# Synthetic perturbed tier, silent-failure rate per milestone (EVAL_LOG.md; the
# last point is recomputed from eval_out/final2_perturbed when present).
SYNTH_SILENT = [("first\nmeasured", 28.5), ("panels,\nclipped labels", 12.0), ("log axes", 9.0),
                ("bar categories", 8.0)]

# Validated palette (dataviz skill, light mode) and chart chrome.
SLOTS = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"]
INK, INK2, MUTED, GRID, AXIS, SURFACE = "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#c3c2b7", "#fcfcfb"
BASELINE_GREY = "#c3c2b7"


def _degenerate(split: str, chart: str) -> bool:
    p = PLOTQA / split / f"{chart}.csv"
    if not p.exists():
        return False
    y = pd.read_csv(p).iloc[:, 1].to_numpy(float)
    return bool(np.ptp(y) == 0)


def plotqa_metrics(run: str) -> dict[str, float] | None:
    f = EVAL / run / "results.json"
    if not f.exists():
        return None
    recs = [r for r in json.loads(f.read_text())
            if not _degenerate("test" if r["chart"].startswith("test") else "train", r["chart"])]
    n = len(recs)

    def val(r: dict, k: str) -> float:
        v = r.get(k)
        return float(v) if isinstance(v, (int, float)) and v == v else np.nan

    rnss = np.mean([0.0 if np.isnan(val(r, "rnss")) else val(r, "rnss") for r in recs])
    recall = np.mean([0.0 if np.isnan(val(r, "recall")) else val(r, "recall") for r in recs])
    ok = np.mean([r.get("status") == "ok" for r in recs])
    within = np.mean([val(r, "median_err") < 0.01 for r in recs])
    silent = np.mean([r.get("status") == "ok" and not r.get("abstain") and
                      ((val(r, "median_err") > 0.02) or (val(r, "recall") < 0.5)) for r in recs])
    return {"n": n, "RNSS": 100 * rnss, "Point recall": 100 * recall, "Within 1% error": 100 * within,
            "Status ok": 100 * ok, "Silent failures": 100 * silent}


def synth_silent_now() -> float | None:
    f = EVAL / "final2_perturbed" / "results.json"
    if not f.exists():
        return None
    recs = [r for r in json.loads(f.read_text()) if r.get("ok")]
    bad = [r for r in recs if r.get("has_table") and r.get("status") == "ok"
           and ((r.get("median_err") or 0) > 0.02 or (r.get("recall") or 0) < 0.5)]
    return 100 * len(bad) / max(len(json.loads(f.read_text())), 1)


def _style(ax: plt.Axes, title: str) -> None:
    ax.set_facecolor(SURFACE)
    ax.grid(True, axis="y", color=GRID, lw=0.6)
    ax.set_axisbelow(True)
    for side in ("top", "right"):
        ax.spines[side].set_visible(False)
    for side in ("left", "bottom"):
        ax.spines[side].set_color(AXIS)
    ax.tick_params(colors=MUTED, labelsize=8)
    ax.set_title(title, color=INK, fontsize=10, loc="left", pad=10)


def main() -> None:
    metrics = ["RNSS", "Point recall", "Within 1% error", "Status ok"]
    fig, axes = plt.subplots(1, 3, figsize=(15, 5.2), dpi=150, gridspec_kw={"width_ratios": [1.5, 1, 1]})
    fig.patch.set_facecolor(SURFACE)

    # 1. PlotQA test split across iterations.
    ax = axes[0]
    runs = [(lab, plotqa_metrics(r)) for r, lab in TEST_RUNS]
    runs = [(lab, m) for lab, m in runs if m]
    xs = np.arange(len(runs))
    ends = []
    for name, col in zip(metrics, SLOTS):
        ys = [m[name] for _, m in runs]
        ax.plot(xs, ys, color=col, lw=2, marker="o", ms=5, label=name)
        ends.append([ys[-1], ys[-1], name])
    # De-overlap the end labels: keep at least ~5 units between them.
    ends.sort(key=lambda e: -e[0])
    for i in range(1, len(ends)):
        ends[i][1] = min(ends[i][1], ends[i - 1][1] - 5)
    for y, ly, name in ends:
        ax.annotate(f"{name} {y:.0f}%", (xs[-1], y), xytext=(xs[-1] + 0.15, ly), textcoords="data",
                    va="center", fontsize=8, color=INK2)
    ax.set_xticks(xs, [lab for lab, _ in runs], fontsize=7)
    ax.set_xlim(-0.3, len(runs) - 1 + 1.4)
    ax.set_ylim(0, 102)
    ax.set_ylabel("% of charts / points", color=MUTED, fontsize=8)
    n_test = runs[0][1]["n"] if runs else 0
    _style(ax, f"PlotQA test split ({n_test} charts): progress per iteration")
    ax.legend(frameon=False, fontsize=7, labelcolor=INK2, loc="lower right")

    # 2. Held-out PlotQA: before vs after.
    ax = axes[1]
    held = [(lab, plotqa_metrics(r)) for r, lab in HELDOUT]
    held = [(lab, m) for lab, m in held if m]
    if len(held) == 2:
        width = 0.38
        xs = np.arange(len(metrics))
        for j, ((lab, m), col) in enumerate(zip(held, [BASELINE_GREY, SLOTS[0]])):
            vals = [m[k] for k in metrics]
            bars = ax.bar(xs + (j - 0.5) * width, vals, width - 0.04, color=col, label=lab)
            for b, v in zip(bars, vals):
                ax.annotate(f"{v:.0f}", (b.get_x() + b.get_width() / 2, v), xytext=(0, 2),
                            textcoords="offset points", ha="center", fontsize=7, color=INK2)
        ax.set_xticks(xs, [k.replace(" ", "\n", 1) for k in metrics], fontsize=8)
        ax.set_ylim(0, 108)
        ax.legend(frameon=False, fontsize=8, labelcolor=INK2, loc="upper left", ncol=2)
        _style(ax, f"Held-out PlotQA ({held[0][1]['n']} unseen charts)")

    # 3. Silent failures (status ok but wrong) - the safety metric.
    ax = axes[2]
    pts = list(SYNTH_SILENT)
    now = synth_silent_now()
    if now is not None:
        pts.append(("now", now))
    xs = np.arange(len(pts))
    ys = [v for _, v in pts]
    ax.plot(xs, ys, color=SLOTS[1], lw=2, marker="o", ms=5, label="synthetic, perturbed styles (200)")
    for x, y in zip(xs, ys):
        ax.annotate(f"{y:.1f}%", (x, y), xytext=(0, 6), textcoords="offset points", ha="center",
                    fontsize=7, color=INK2)
    hb, hn = [m for _, m in held][:2] if len(held) == 2 else (None, None)
    if hb and hn:
        ax.plot([xs[-2], xs[-1]], [hb["Silent failures"], hn["Silent failures"]], color=SLOTS[0], lw=2,
                marker="o", ms=5, label="held-out PlotQA (287)")
    ax.set_xticks(xs, [lab for lab, _ in pts], fontsize=7)
    ax.set_ylim(0, max(ys + [10]) * 1.2)
    ax.set_ylabel("% of charts reported 'ok' but wrong", color=MUTED, fontsize=8)
    ax.legend(frameon=False, fontsize=7, labelcolor=INK2, loc="upper right")
    _style(ax, "Silent failures (lower is better)")

    fig.suptitle("plotscribe accuracy progress", x=0.01, ha="left", color=INK, fontsize=12)
    fig.tight_layout()
    out = Path("docs/progress.png")
    out.parent.mkdir(exist_ok=True)
    fig.savefig(out, facecolor=SURFACE)
    print(f"wrote {out}")
    for lab, m in runs + held:
        print(f"  {lab.replace(chr(10), ' '):40s} " + "  ".join(f"{k}={m[k]:.1f}" for k in metrics + ["Silent failures"]))


if __name__ == "__main__":
    main()