"""Publication figures from completed exact/certified phase-three outputs.""" import argparse from fractions import Fraction import json from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np BLUE, RED, TEAL, VIOLET, GRAY = "#0F4D92", "#B64342", "#42949E", "#9A4D8E", "#555555" def val(x): return float(Fraction(x["rational"] if isinstance(x, dict) else x)) def style(): plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 19, "axes.labelsize": 22, "axes.titlesize": 20, "xtick.labelsize": 18, "ytick.labelsize": 18, "legend.fontsize": 18, "legend.frameon": False, "axes.spines.top": False, "axes.spines.right": False, "axes.linewidth": 1.5, "lines.linewidth": 2.8, "lines.markersize": 8, "axes.titlepad": 14, "pdf.fonttype": 42, "ps.fonttype": 42, "savefig.facecolor": "white"}) def save(fig, folder, name): folder.mkdir(parents=True, exist_ok=True) for ext in ("pdf", "png"): fig.savefig(folder / f"{name}.{ext}", dpi=300, bbox_inches="tight", pad_inches=.16) plt.close(fig) def schedules(data, folder): assert data["status"] == "complete" and data["self_test"]["passed"] rows = data["rows"] n = max(r["n"] for r in rows) specs = [("geometric", "tv_exact", "Geometric, fixed labels", BLUE, "o", "-"), ("equal", "tv_exact", "Equal, fixed labels", RED, "s", "-"), ("best_fixed", "tv_exact", "Best fixed-label batches", TEAL, "^", "-"), ("best_symmetrized", "symmetrized_tv_exact", "Best batches + random labels", VIOLET, "x", "--")] fig, axes = plt.subplots(1, 2, figsize=(14.2, 7.5)) fig.subplots_adjust(left=.09, right=.985, bottom=.37, top=.87, wspace=.30) for ax, K in zip(axes, (3, 4)): group = sorted((r for r in rows if r["n"] == n and r["K"] == K), key=lambda r: Fraction(r["budget"])) B = [val(r["budget"]) for r in group] for key, field, label, color, marker, line in specs: ax.plot(B, [val(r[key][field]) for r in group], color=color, marker=marker, ls=line, label=label) lo = np.array([val(r["all_policy"]["lower"]) for r in group]) hi = np.array([val(r["all_policy"]["upper"]) for r in group]) mid = (lo+hi)/2 ax.errorbar(B, mid, yerr=np.array([mid-lo, hi-mid]), color=GRAY, fmt="d:", capsize=5, markerfacecolor="white", zorder=6, label="Certified all-policy optimum") ax.set(xlabel="Joint-KL budget $B$", ylabel="Full-output TV", title=rf"$n={n}$ pairs, $K={K}$ rounds", xticks=B) ax.set_ylim(bottom=0) h, l = axes[0].get_legend_handles_labels() fig.legend(h, l, loc="lower center", bbox_to_anchor=(.53,.055), ncol=2, columnspacing=1.5, handlelength=2.6, fontsize=18) fig.text(.53, .015, "One frozen model per budget; identical model across round counts.", ha="center", fontsize=17, color=GRAY) save(fig, folder, "fixed_schedule_benchmark") fig, axes = plt.subplots(1, 2, figsize=(13.8, 6.4)) fig.subplots_adjust(left=.10, right=.985, bottom=.27, top=.86, wspace=.30) for ax, K in zip(axes, (3, 4)): for n, color, marker in zip(sorted({r["n"] for r in rows}), (BLUE, RED, TEAL), ("o", "s", "^")): group = sorted((r for r in rows if r["n"] == n and r["K"] == K), key=lambda r: Fraction(r["budget"])) lo = np.array([val(r["geometric_excess_over_optimum_lower"]) for r in group]) hi = np.array([val(r["geometric_excess_over_optimum_upper"]) for r in group]) mid = (lo+hi)/2 ax.errorbar([val(r["budget"]) for r in group], mid, yerr=np.array([mid-lo,hi-mid]), fmt=marker+"-", color=color, capsize=5, label=rf"$n={n}$") ax.axhline(0, color=GRAY, lw=1, ls=":") ax.set(xlabel="Joint-KL budget $B$", ylabel="TV above all-policy optimum", title=rf"Geometric fixed labels: $K={K}$", xticks=[.02,.05,.10]) ax.ticklabel_format(axis="y", style="plain", useOffset=False) h,l = axes[0].get_legend_handles_labels() fig.legend(h,l,loc="lower center",bbox_to_anchor=(.54,.07),ncol=3,fontsize=20) fig.text(.54,.015,"Arithmetic enclosures; connecting lines are guides, not fitted laws.", ha="center",fontsize=17,color=GRAY) save(fig,folder,"geometric_schedule_overhead") def biased(data, folder): cases = [c for c in data["cases"] if c.get("status") == "certified"] if not cases: raise ValueError("No certified biased cases available for a result figure") ns = sorted({c["n"] for c in cases}) fig, axes = plt.subplots(1, 2, figsize=(13.8, 7.2)) fig.subplots_adjust(left=.10,right=.985,bottom=.34,top=.86,wspace=.31) round_specs = [(2,BLUE,"o"),(3,RED,"s"),(4,TEAL,"^")] for ax,n in zip(axes,ns[:2]): group = [c for c in cases if c["n"] == n] model = next(m for m in data["models"] if m["n"] == n) biases = sorted({Fraction(c["a"]) for c in data["cases"] if c["n"] == n}) for K,color,marker in round_specs: if not any(c["K"] == K for c in data["cases"] if c["n"] == n): continue found = {Fraction(c["a"]):c for c in group if c["K"] == K} lo = np.array([val(found[a]["certificate"]["tv_lower"]) if a in found else np.nan for a in biases]) hi = np.array([val(found[a]["certificate"]["tv_upper"]) if a in found else np.nan for a in biases]) mid=(lo+hi)/2 ax.errorbar(list(map(float,biases)),mid,yerr=np.array([mid-lo,hi-mid]), fmt=marker+"-",color=color,capsize=5,label=rf"$K={K}$") ax.axhline(val(model["diagnostics"]["model_tv"]),color=GRAY,ls="--",label="Serial model TV") ax.set(xlabel="Representative bias $a$",ylabel="Certified optimum TV", title=rf"$n={n}$ pairs",xticks=list(map(float,biases))) endpoints = [val(model["diagnostics"]["model_tv"])] endpoints += [val(c["certificate"][key]) for c in group for key in ("tv_lower","tv_upper")] span = max(endpoints)-min(endpoints) padding = max(span*.16, .0005) ax.set_ylim(min(endpoints)-padding,max(endpoints)+padding) missing = sum(c.get("status") != "certified" for c in data["cases"] if c["n"] == n) if missing: ax.text(.04,.04,f"{missing} missing cases (see report)",transform=ax.transAxes,fontsize=17) if len(ns)==1: n=ns[0] group=sorted((m for m in data["models"] if m["n"]==n),key=lambda m:Fraction(m["a"])) axes[1].plot([float(Fraction(m["a"])) for m in group], [val(m["diagnostics"]["all_context_head_error"]) for m in group], color=VIOLET,marker="d") axes[1].axhline(.25,color=GRAY,ls=":") axes[1].set(xlabel="Representative bias $a$",ylabel="Worst conditional-head TV", title="All-context accuracy check",xticks=[.25,.4,.5]) axes[1].set_ylim(bottom=0) h,l=axes[0].get_legend_handles_labels() fig.legend(h,l,loc="lower center",bbox_to_anchor=(.54,.14),ncol=4,fontsize=18) fig.text(.54,.015,"Vertical axes zoomed; n=6 evaluated at K=3,4 only.\nFixed mismatch mixture and KL at each n.\nUniform head errors are measured, not assumed equal across biases.", ha="center",va="bottom",fontsize=17,color=GRAY,linespacing=1.2) save(fig,folder,"biased_depth_sensitivity") if __name__ == "__main__": parser=argparse.ArgumentParser() parser.add_argument("--run-dir",type=Path,required=True) parser.add_argument("--figure-dir",type=Path) args=parser.parse_args() style() output=args.figure_dir or args.run_dir/"figures" schedules(json.loads((args.run_dir/"schedules.json").read_text()),output) biased(json.loads((args.run_dir/"biased_results.json").read_text()),output) print("Exported three PDF/PNG figure pairs.",flush=True)