File size: 11,502 Bytes
6f423bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
"""Evaluate plotscribe on synthetic charts.

    python -m tests.evaluate --n 100 --tier clean            # generate + evaluate
    python -m tests.evaluate --data data/synth_clean --workers 8 --worst 10

Prints summary tables by chart type and by perturbation and writes
``<out>/results.json`` plus debug overlays of the worst cases to ``<out>/worst/``.
"""

from __future__ import annotations

import argparse
import json
import math
import shutil
import time
import traceback
from multiprocessing import Pool
from pathlib import Path
from typing import Any

import numpy as np
import pandas as pd

from plotscribe import pipeline
from tests import synth
from tests.metrics import AxisInfo, calibration_error, score_table, tick_recall

CATEGORICAL_KINDS = ("bar", "grouped_bar", "stacked_bar")


def axis_type(gt: dict[str, Any], axis: str) -> str:
    if axis == "x":
        return "categorical" if gt["categories"] else "linear"
    return "log" if gt["yscale"] == "log" else "linear"


ORACLE_TYPE = False


def _oracle(kind: str) -> str:
    return {"grouped_bar": "bar"}.get(kind, kind)


def evaluate_one(img_path: str) -> dict[str, Any]:
    """Run the pipeline on one synthetic chart and score every stage."""
    p = Path(img_path)
    gt = json.loads(p.with_suffix(".json").read_text())
    spec = gt["spec"]
    rec: dict[str, Any] = {
        "stem": p.stem, "path": img_path, "kind": spec["kind"], "tier": spec["tier"],
        "n_series": spec["n_series"], "log_y": spec["log_y"], "jpeg": spec["jpeg_quality"] is not None,
        "low_res": spec["dpi"] <= 72, "style": spec["style"], "markers": bool(spec["markers"]),
        "dashed": spec["linestyle"] != "-", "categorical_x": spec["categorical_x"],
        "legend": spec["legend_loc"] or "none", "negative": spec["negative"],
    }
    t0 = time.time()
    try:
        res = pipeline.run(img_path, chart_type=_oracle(spec["kind"]) if ORACLE_TYPE else None)
    except Exception as exc:  # noqa: BLE001 - evaluation must survive any failure
        rec.update(ok=False, error=f"{type(exc).__name__}: {exc}", trace=traceback.format_exc(limit=4))
        return rec
    rec["runtime_s"] = time.time() - t0
    rec["ok"] = True
    s = res.pre.scale
    ax = res.axes
    gtb = gt["plot_bbox"]
    from plotscribe.models import BBox

    rec["box_iou"] = ax.plot_box.scaled(1 / s).iou(BBox(*gtb)) if ax else 0.0
    tol = 1.5
    rec["xtick_recall"] = tick_recall([t / s for t in ax.x_ticks], [t["px"] for t in gt["xticks"]], tol)
    rec["ytick_recall"] = tick_recall([t / s for t in ax.y_ticks], [t["px"] for t in gt["yticks"]], tol)
    xa = AxisInfo(*sorted(gt["xlim"]))
    ya = AxisInfo(*sorted(gt["ylim"]), log=gt["yscale"] == "log")
    for name, cal, axinfo in (("x", res.x_cal, xa), ("y", res.y_cal, ya)):
        want = axis_type(gt, name)
        got = cal.kind if cal else "none"
        rec[f"{name}_axis_type_ok"] = got == want
        rec[f"{name}_axis_type"] = got
        rec[f"{name}_cal_conf"] = cal.confidence if cal else 0.0
        if cal is not None and cal.kind != "categorical":
            rec[f"{name}_cal_err"] = calibration_error(cal.rescaled(s), gt[f"{name}ticks"], axinfo)
        else:
            rec[f"{name}_cal_err"] = math.nan
    if gt["categories"] and res.x_cal is not None and res.x_cal.kind == "categorical":
        got = [c.lower() for c in res.x_cal.categories]
        want = [c.lower() for c in gt["categories"]]
        rec["x_cat_acc"] = float(np.mean([a == b for a, b in zip(got, want)])) if len(got) == len(want) else 0.0
    rec["chart_type"] = res.chart_type
    rec["chart_type_conf"] = res.chart_type_conf
    rec["type_ok"] = _family(res.chart_type) == _family(spec["kind"])
    rec["confidence"] = res.confidence
    rec["warnings"] = res.warnings
    rec["status"] = res.extra.get("status", "ok")
    if res.table is not None and any("[px]" in str(c) for c in res.table.columns):
        rec["has_table"] = False
        rec["median_err"] = math.nan
        return rec
    if res.table is not None:
        gt_df = synth.ground_truth_frame(gt)
        kind = "scatter" if spec["kind"] == "scatter" else ("categorical" if gt["categories"] else "numeric")
        sc = score_table(res.table, gt_df, kind, xa, ya)
        rec.update(sc.summary())
        rec["has_table"] = True
    else:
        rec["has_table"] = False
        rec["median_err"] = math.nan
    return rec


def _family(kind: str) -> str:
    return "bar" if "bar" in kind else kind


def summarise(df: pd.DataFrame, by: str) -> pd.DataFrame:
    """Aggregate metrics per group."""
    def agg(g: pd.DataFrame) -> pd.Series:
        ok = g[g["ok"]]
        out = {
            "n": len(g), "crash": int((~g["ok"]).sum()),
            "box_iou": ok["box_iou"].median() if "box_iou" in ok else math.nan,
            "xtick_rec": ok["xtick_recall"].mean(), "ytick_rec": ok["ytick_recall"].mean(),
            "x_type_ok": ok["x_axis_type_ok"].mean(), "y_type_ok": ok["y_axis_type_ok"].mean(),
            "y_cal_err_med": ok["y_cal_err"].median(), "y_cal_err_p90": ok["y_cal_err"].quantile(0.9),
            "y_cal_fail": float((ok["y_cal_err"].isna() | (ok["y_cal_err"] > 0.01)).mean()) if len(ok) else math.nan,
        }
        if "x_cal_err" in ok and ok["x_cal_err"].notna().any():
            out["x_cal_err_med"] = ok["x_cal_err"].median()
        if "type_ok" in ok:
            out["type_acc"] = ok["type_ok"].mean()
        if "status" in ok:
            out["status_ok"] = float((ok["status"] == "ok").mean())
            out["abstain"] = float(ok["status"].isin(["uncalibrated", "failed"]).mean())
        if "has_table" in ok and ok["has_table"].any():
            t = ok[ok["has_table"]]
            # Silent failure: reported status ok, but the numbers are wrong.
            bad = (t["median_err"] > 0.02) | (t["recall"] < 0.5)
            out["silent_fail"] = float((bad & (t["status"] == "ok")).sum()) / max(len(g), 1)
            out["table"] = len(t) / max(len(g), 1)
            out["med_err"] = t["median_err"].median()
            out["p90_chart_med"] = t["median_err"].quantile(0.9)
            out["recall"] = t["recall"].mean()
            out["series_ok"] = t["series_count_ok"].mean()
        return pd.Series(out)

    out = pd.DataFrame({k: agg(g) for k, g in df.groupby(by)}).T
    order = ["n", "crash", "status_ok", "abstain", "silent_fail", "box_iou", "xtick_rec", "ytick_rec",
             "x_type_ok", "y_type_ok", "y_cal_err_med", "y_cal_err_p90", "y_cal_fail", "x_cal_err_med",
             "type_acc", "table", "series_ok", "recall", "med_err", "p90_chart_med"]
    return out[[c for c in order if c in out.columns]]


def perturbation_table(df: pd.DataFrame) -> pd.DataFrame:
    rows = {}
    for col in ("jpeg", "low_res", "log_y", "markers", "dashed", "negative", "categorical_x"):
        for val in (True, False):
            sub = df[df[col] == val]
            if len(sub):
                rows[f"{col}={val}"] = summarise(sub.assign(_all="all"), "_all").iloc[0]
    sty = df[df["tier"] == "perturbed"]
    for st in sorted(sty["style"].unique()) if len(sty) else []:
        rows[f"style={st}"] = summarise(sty[sty["style"] == st].assign(_all="all"), "_all").iloc[0]
    return pd.DataFrame(rows).T


def badness(r: dict[str, Any]) -> float:
    """Sort key for the worst cases (crashes and missing tables first)."""
    if not r.get("ok"):
        return 1e9
    if r.get("has_table") and r.get("median_err") == r.get("median_err"):
        return float(r["median_err"]) + (1 - float(r.get("recall", 0)))
    ce = r.get("y_cal_err")
    return 10.0 + (ce if ce == ce and ce is not None else 5.0)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=50)
    ap.add_argument("--tier", default="clean", choices=["clean", "perturbed", "mixed"])
    ap.add_argument("--data", type=Path, default=None)
    ap.add_argument("--out", type=Path, default=Path("eval_out"))
    ap.add_argument("--workers", type=int, default=8)
    ap.add_argument("--worst", type=int, default=8)
    ap.add_argument("--start-seed", type=int, default=1000)
    ap.add_argument("--kind", default=None, help="only evaluate this chart kind")
    ap.add_argument("--kinds", default=None, help="comma-separated kinds to generate (default: all)")
    ap.add_argument("--oracle-type", action="store_true", help="pass the true chart type to the pipeline")
    a = ap.parse_args()
    global ORACLE_TYPE
    ORACLE_TYPE = a.oracle_type

    kinds = tuple(a.kinds.split(",")) if a.kinds else synth.KINDS
    tag = "" if kinds == synth.KINDS else "_" + "-".join(kinds)
    data = a.data or Path(f"data/synth_{a.tier}_{a.n}_{a.start_seed}{tag}")
    if not data.exists() or not any(data.glob("*.json")):
        print(f"generating {a.n} {a.tier} charts into {data} ...")
        synth.generate_set(a.n, data, a.tier, a.start_seed, kinds)
    imgs = sorted(str(p) for p in data.iterdir() if p.suffix in (".png", ".jpg") and not p.name.endswith(".debug.png"))
    if a.kind:
        imgs = [p for p in imgs if json.loads(Path(p).with_suffix(".json").read_text())["spec"]["kind"] == a.kind]
    t0 = time.time()
    with Pool(a.workers, initializer=_init_worker, initargs=(a.oracle_type,)) as pool:
        recs = pool.map(evaluate_one, imgs, chunksize=1)
    print(f"evaluated {len(recs)} charts in {time.time() - t0:.0f}s")
    a.out.mkdir(parents=True, exist_ok=True)
    (a.out / "results.json").write_text(json.dumps(recs, indent=1, default=str))
    df = pd.DataFrame(recs)
    pd.set_option("display.width", 250, "display.max_columns", 40, "display.precision", 4)
    print("\n== by chart type ==")
    print(summarise(df, "kind").to_string())
    print("\n== by tier ==")
    print(summarise(df, "tier").to_string())
    if (df["tier"] == "perturbed").any():
        print("\n== by perturbation ==")
        print(perturbation_table(df).to_string())
    if "has_table" in df and df["has_table"].any():
        t = df[df["has_table"]]
        allerr = np.concatenate([[r["median_err"]] for _, r in t.iterrows()])
        print(f"\nOVERALL median of per-chart median error: {np.nanmedian(allerr):.4%}")

    worst = sorted(recs, key=badness, reverse=True)[: a.worst]
    wdir = a.out / "worst"
    shutil.rmtree(wdir, ignore_errors=True)
    wdir.mkdir(parents=True)
    print("\n== worst cases ==")
    for r in worst:
        msg = r.get("error") or (f"med_err={r.get('median_err')!s:.6} recall={r.get('recall', 0):.2f} "
                                 f"y_cal_err={r.get('y_cal_err')!s:.6} type={r.get('chart_type')}")
        print(f"  {r['stem']}: {msg}")
        for w in (r.get("warnings") or [])[:6]:
            print(f"      {w}")
        _save_debug(r, wdir)


def _init_worker(oracle: bool) -> None:
    global ORACLE_TYPE
    ORACLE_TYPE = oracle


def _save_debug(rec: dict[str, Any], wdir: Path) -> None:
    """Re-run a case and save its debug overlay next to the original image."""
    src = Path(rec["path"])
    shutil.copy(src, wdir / src.name)
    if not rec.get("ok"):
        (wdir / f"{src.stem}.error.txt").write_text(rec.get("trace", ""))
        return
    try:
        from plotscribe import export

        res = pipeline.run(str(src), chart_type=_oracle(rec["kind"]) if ORACLE_TYPE else None)
        export.write_debug_overlay(res, wdir / f"{src.stem}.debug.png")
    except Exception:  # noqa: BLE001
        (wdir / f"{src.stem}.error.txt").write_text(traceback.format_exc())


if __name__ == "__main__":
    main()