File size: 5,333 Bytes
83d5975 | 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 | """Large-label figures from a mechanically normalized phase-2 result file."""
import argparse
import json
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
BLUE="#0F4D92"
RED="#B64342"
TEAL="#42949E"
VIOLET="#9A4D8E"
def style():
# Visual reference: github.com/ChenLiu-1996/figures4papers (2026-09-16).
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/(name+"."+ext),dpi=300,bbox_inches="tight",pad_inches=.12)
plt.close(fig)
def main(folder):
data=json.loads((folder/"plot_data.json").read_text())
rows=data["rows"]
out=folder/"figures"
style()
n=max(r["n"] for r in rows)
budgets=sorted({r["budget"] for r in rows})[-2:]
fig,axs=plt.subplots(1,2,figsize=(13.4,5.8))
fig.subplots_adjust(left=.10,right=.985,bottom=.28,top=.86,wspace=.33)
for ax,B in zip(axs,budgets):
selected=[r for r in rows if r["n"]==n and abs(r["budget"]-B)<1e-10]
if len(selected)!=1:
raise ValueError("Expected one frozen finalist per n,budget")
row=selected[0]
cases=sorted(row["cases"],key=lambda c:c["K"])
K=np.array([c["K"] for c in cases])
lo=np.array([c["L"] for c in cases]);hi=np.array([c["U"] for c in cases])
if np.any(hi<lo):
raise ValueError("Invalid certified interval")
middle=(lo+hi)/2
ax.errorbar(K,middle,yerr=np.stack([middle-lo,hi-middle]),fmt="o-",
color=BLUE,capsize=6,capthick=2,label="Certified optimum interval")
ax.axhline(row["model_tv"],color=RED,ls="--",label="Model TV (serial baseline)")
ax.fill_between(K,row["model_tv"],lo,where=lo>row["model_tv"],
color=TEAL,alpha=.14,label="Certified excess over serial baseline")
ax.set(xlabel="Allowed rounds $K$",ylabel="Total variation",xticks=[2,3,4],
title=rf"$n={n},\ B={B:g}$")
ax.set_ylim(bottom=0)
kl_note=f"Certified KL upper ≈ {row['actual_kl']:.5f}"
if not row["budget_matched"]:
kl_note+="\nBudget inactive (weight cap)"
ax.text(.04,.05,kl_note,transform=ax.transAxes,
fontsize=18,color="#4D4D4D",va="bottom",linespacing=1.2)
handles,labels=axs[0].get_legend_handles_labels()
fig.legend(handles,labels,loc="lower center",bbox_to_anchor=(.54,.01),ncol=2,fontsize=18)
save(fig,out,"certified_depth_cost")
fig,ax=plt.subplots(figsize=(8.8,6.3))
fig.subplots_adjust(left=.18,right=.98,bottom=.19,top=.88)
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],key=lambda r:r["budget"])
gaps=[next(c["gap_lower"] for c in r["cases"] if c["K"]==3) for r in group]
ax.plot([r["budget"] for r in group],gaps,color=color,marker=marker,label=rf"$n={n}$")
ax.axhline(0,color="#767676",lw=1,ls=":")
ax.set(xlabel="Joint-KL budget $B$",ylabel="Excess TV lower bound",
title="Selected finite-depth witnesses ($K=3$)")
ax.set_xticks(sorted({r["budget"] for r in rows}))
ax.legend(loc="best",fontsize=20)
save(fig,out,"certified_execution_gap")
candidates=data["candidates"]
fig,axs=plt.subplots(1,2,figsize=(13.4,6.2))
fig.subplots_adjust(left=.10,right=.985,bottom=.34,top=.85,wspace=.32)
specs=[("single","Single alternative",RED,"^"),
("manuscript","Theorem ladder",BLUE,"D"),
("relaxed","Relaxed two-level",TEAL,"o")]
for ax,n in zip(axs,[min(r["n"] for r in rows),max(r["n"] for r in rows)]):
for family,label,color,marker in specs:
group=[r for r in candidates if r["n"]==n and r["family"]==family]
ax.scatter([r["actual_kl"] for r in group],[r["gap"] for r in group],
c=color,marker=marker,s=90,label=label,alpha=.9,
edgecolors="white",linewidths=.5)
ax.axhline(0,color="#767676",ls=":",lw=1)
ax.set(xlabel="Actual joint KL",ylabel="Excess TV (LP screening)",
title=rf"Candidate search: $n={n},\ K=3$")
handles,labels=axs[0].get_legend_handles_labels()
fig.legend(handles,labels,loc="lower center",bbox_to_anchor=(.54,.105),ncol=3,fontsize=18)
fig.text(.54,.012,
"All candidates: floating-point screening; only selected witnesses independently certified.\n"
"Finite candidate search; no claim of an outer optimum.",
ha="center",va="bottom",fontsize=17,color="#4D4D4D",linespacing=1.2)
save(fig,out,"candidate_search_diagnostics")
print("Exported three PDF/PNG figure pairs.",flush=True)
if __name__=="__main__":
ap=argparse.ArgumentParser()
ap.add_argument("--run-dir",type=Path,required=True)
main(ap.parse_args().run_dir)
|