"""Tables A-D and figures 1-4 from saved statistics only; no model call. python -m experiments.mace_extension.scripts.build_outputs """ from __future__ import annotations import json import re import matplotlib matplotlib.use("Agg") import matplotlib.patheffects as pe # noqa: E402 import matplotlib.pyplot as plt # noqa: E402 import numpy as np # noqa: E402 import pandas as pd # noqa: E402 from .analyze import PR, ROOT, ST, TB # noqa: E402 FG = ROOT / "figures"; FG.mkdir(exist_ok=True) S = json.loads((ST / "extension_results.json").read_text()); B = json.loads((ST / "robustness_posthoc.json").read_text()) SP = (("iid", "IID"), ("ood", "Held-out")) OI = {"blue": "#0072B2", "green": "#009E73", "verm": "#D55E00", "gold": "#E69F00", "grey": "#8a8a8a", "ink": "#333333"} plt.rcParams["path.effects"] = [pe.Normal()] # outlines: AAAI bans Identity-H and Type 3 fonts plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 7.2, "axes.spines.top": False, "axes.spines.right": False, "axes.linewidth": 0.6, "pdf.fonttype": 42, "xtick.major.width": 0.6, "ytick.major.width": 0.6, "legend.frameon": False}) def f(x): return f"{x:.1f}" def ci(c): return f"{f(c['ci'][0])}, {f(c['ci'][1])}" def pm(c): return f"{c['est']:+.1f} [{c['ci'][0]:+.1f}, {c['ci'][1]:+.1f}]" def tex(rows, cols, name, caption, align, best=None): """SAGE table format: caption above, booktabs, best cell shaded bestgreen. Needs \\definecolor{bestgreen}.""" L = [r"\begin{table}[t]", r"\centering\small", rf"\caption{{{caption}}}", rf"\label{{tab:{name}}}", rf"\begin{{tabular}}{{{align}}}", r"\toprule", " & ".join(cols) + r" \\", r"\midrule"] for i, r in enumerate(rows): L.append(" & ".join(rf"\cellcolor{{bestgreen}}{v}" if best and (i, j) in best else str(v) for j, v in enumerate(r)) + r" \\") L += [r"\bottomrule", r"\end{tabular}", r"\end{table}"] (TB / f"{name}.tex").write_text(re.sub(r"(? 13 else OI["ink"]) a.set_title("Caption effect by crop (pts)", fontsize=7.6, loc="left"); a.tick_params(length=0); [s.set_visible(False) for s in a.spines.values()] fig.tight_layout(w_pad=0.6); save(fig, "fig2_retrieval_caption") def fig3(): G = pd.read_csv(TB / "fallback_calibration_grid.csv"); rule = json.loads((ROOT / "configurations/fallback_rule.json").read_text()); e = S["E3"] fig, ax = plt.subplots(1, 2, figsize=(7.0, 2.1), gridspec_kw={"width_ratios": [1.3, 1]}); a = ax[0] for s, g in G[G.kind == "crop_quantile"].groupby("signal"): g = g.sort_values("cal_fallback"); chosen = s == rule["rule"]["signal"] a.plot(g.cal_fallback * 100, g.cal_score, lw=1.4 if chosen else 0.7, color=OI["blue"] if chosen else "#c4c4c4", zorder=3 if chosen else 1, label="dino_top1 (selected)" if chosen else None) a.plot([], [], lw=0.7, color="#c4c4c4", label="Other continuous signals") a.axhline(rule["always_mace_cal"], lw=0.8, ls="--", color=OI["verm"], label="Always MACE"); a.scatter([rule["rule"]["cal_fallback"] * 100], [rule["rule"]["cal_score"]], s=18, color=OI["blue"], zorder=4) a.set_xlabel("Fallback rate on calibration rows (%)"); a.set_ylabel("Calibration accuracy (%)"); a.set_title("Threshold sensitivity (calibration only)", fontsize=7.6, loc="left"); a.legend(fontsize=6.4, loc="lower left") a = ax[1]; nm = (("sage", "SAGE"), ("mace", "MACE"), ("adaptive", "Fallback"), ("oracle", "Oracle bound")) for sp, col, mk, off, lb in (("iid", OI["ink"], "o", 0.13, "IID"), ("ood", OI["gold"], "D", -0.13, "Held-out")): x = np.array([e["acc"][sp][c]["acc"] for c, _ in nm]); lo = np.array([e["acc"][sp][c]["ci"][0] for c, _ in nm]); hi = np.array([e["acc"][sp][c]["ci"][1] for c, _ in nm]) a.errorbar(x, np.arange(4) + off, xerr=[x - lo, hi - x], fmt=mk, ms=3.6, color=col, lw=0.8, label=lb) a.set_yticks(range(4)); a.set_yticklabels([n for _, n in nm]); a.set_xlabel("Equal-crop accuracy (%)"); a.set_title("Scored once on hero queries", fontsize=7.6, loc="left"); a.legend(fontsize=6.4, loc="lower right"); a.grid(axis="x", lw=0.3, color="#ddd") fig.tight_layout(w_pad=0.8); save(fig, "fig3_fallback") def fig4(): T = pd.read_csv(TB / "table_D_collection_shift.csv").sort_values("covered"); fig, ax = plt.subplots(1, 2, figsize=(7.0, 2.4), gridspec_kw={"width_ratios": [1.15, 1]}); a = ax[0]; y = np.arange(len(T)) a.hlines(y, T.other_acc, T.mace_iid, lw=1.0, color="#c4c4c4"); a.scatter(T.sage_iid, y, s=13, marker="|", color=OI["ink"], label="SAGE", zorder=3); a.scatter(T.other_acc, y, s=15, color=OI["verm"], label="Other-collection bank", zorder=3); a.scatter(T.mace_iid, y, s=15, color=OI["blue"], label="Standard bank", zorder=3) a.set_yticks(y); a.set_yticklabels([f"{r.crop} ({r.covered:.0f}%)" for r in T.itertuples()], fontsize=6.4); a.set_xlabel("IID accuracy (%)"); a.set_title("IID, crops by disease coverage in other bank", fontsize=7.6, loc="left"); a.legend(fontsize=6.2, loc="upper left", handletextpad=0.1, borderaxespad=0.1); a.grid(axis="x", lw=0.3, color="#ddd") a = ax[1]; bw = T.ood_collection == "Bugwood" a.scatter(T[bw].dino_gap, T[bw].gain_ood, s=18, marker="o", color=OI["verm"], lw=0, label="Held-out = Bugwood"); a.scatter(T[~bw].dino_gap, T[~bw].gain_ood, s=20, marker="s", color=OI["blue"], lw=0, label="Other held-out collection"); a.axhline(0, lw=0.5, color=OI["grey"]) off = {"Corn": (4, 4), "Soybean": (4, -7), "Tomato": (4, 3), "Rice": (4, 0), "Mango": (4, 0), "Cucumber": (3, 3), "Potato": (-27, -2), "Wheat": (3, 3), "Grape": (-7, 4), "Apple": (-6, -8)} for r in T.itertuples(): a.annotate(r.crop, (r.dino_gap, r.gain_ood), xytext=off[r.crop], textcoords="offset points", fontsize=5.8) a.set_xlabel("DINOv2 nearest-bank similarity gap, IID minus held-out"); a.set_ylabel("Held-out MACE gain over SAGE (pts)"); a.set_title("Held-out gain and image shift (n = 10, post hoc)", fontsize=7.6, loc="left"); a.legend(fontsize=6.2, loc="upper right", handletextpad=0.1) fig.tight_layout(w_pad=0.8); save(fig, "fig4_collection_shift") def save(fig, name): fig.savefig(FG / f"{name}.pdf", bbox_inches="tight", pad_inches=0.02, dpi=600); fig.savefig(FG / f"{name}.png", bbox_inches="tight", pad_inches=0.02, dpi=600); plt.close(fig) if __name__ == "__main__": for fn in (table_a, table_b, table_c, table_d, fig1, fig2, fig3, fig4): fn()