stgfn-repro-code / make_figures.py
Gonzalez
Upload folder using huggingface_hub
a76f68a verified
Raw
History Blame Contribute Delete
7.67 kB
"""Generate the reproduction's figures (Plotly HTML + CSV raw data)."""
from __future__ import annotations
import argparse
import glob
import json
import os
from collections import defaultdict
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Colour-blind-safe categorical palette; ST-GFN is the highlighted series.
C_OURS = "#D55E00"
C_BASE = ["#0072B2", "#009E73", "#CC79A7", "#56B4E9", "#E69F00",
"#7570B3", "#666666", "#8C6D31", "#1B9E77", "#A6761D"]
LABEL = {
"stgfn": "ST-GFN (Ours)", "tb": "TB", "fm": "FM", "subtb": "SubTB", "db": "DB",
"eflownet": "EFlowNet", "stochastic_gfn": "Stochastic-GFN", "tb_rnd": "TB+RND",
"tb_novelty": "TB+Novelty", "tb_icm": "TB+ICM", "tb_cv": "TB+ControlVar",
"stgfn_no_spectral": "ST-GFN w/o spectral", "stgfn_no_intrinsic": "ST-GFN w/o intrinsic",
}
ORDER = ["stgfn", "tb", "fm", "subtb", "db", "eflownet", "stochastic_gfn",
"tb_rnd", "tb_novelty", "tb_icm", "tb_cv"]
LAYOUT = dict(
template="plotly_white", font=dict(family="Inter, system-ui, sans-serif", size=13),
margin=dict(l=60, r=30, t=60, b=55), hovermode="x unified",
)
def load(out_dir):
data = defaultdict(lambda: defaultdict(list))
for path in glob.glob(os.path.join(out_dir, "*.json")):
with open(path) as f:
r = json.load(f)
data[r["env"]][r["method"]].append(r)
return data
def color(m, i):
return C_OURS if m.startswith("stgfn") else C_BASE[i % len(C_BASE)]
def curve_figure(data, env, metric, ylabel, title, out_html, out_csv):
fig = go.Figure()
rows = [("method", "iter", "mean", "lo", "hi")]
for i, m in enumerate([m for m in ORDER if m in data[env]]):
runs = data[env][m]
iters = [c["iter"] for c in runs[0]["curve"]]
vals = []
for r in runs:
v = [c.get(metric) for c in r["curve"]]
if all(x is not None for x in v) and len(v) == len(iters):
vals.append(v)
if not vals:
continue
arr = np.array(vals, float)
mu = arr.mean(0)
ci = 1.96 * arr.std(0, ddof=1) / np.sqrt(len(arr)) if len(arr) > 1 else np.zeros_like(mu)
col = color(m, i)
wide = m == "stgfn"
fig.add_trace(go.Scatter(
x=iters + iters[::-1], y=list(mu + ci) + list(mu - ci)[::-1],
fill="toself", fillcolor=col, opacity=0.15, line=dict(width=0),
hoverinfo="skip", showlegend=False))
fig.add_trace(go.Scatter(x=iters, y=mu, name=LABEL.get(m, m),
line=dict(color=col, width=3.5 if wide else 1.9)))
for k, it in enumerate(iters):
rows.append((m, it, mu[k], mu[k] - ci[k], mu[k] + ci[k]))
fig.update_layout(title=title, xaxis_title="training iteration",
yaxis_title=ylabel, **LAYOUT)
fig.write_html(out_html, include_plotlyjs="cdn", full_html=True)
with open(out_csv, "w") as f:
for r in rows:
f.write(",".join(str(x) for x in r) + "\n")
print("wrote", out_html)
def bar_figure(data, env, metric, ylabel, title, out_html, out_csv, higher_better=True):
means, cis, labels, cols = [], [], [], []
rows = [("method", "mean", "ci95", "n_seeds")]
for i, m in enumerate([m for m in ORDER if m in data[env]]):
vals = [r["final"].get(metric) for r in data[env][m]]
vals = [v for v in vals if v is not None]
if not vals:
continue
mu = float(np.mean(vals))
ci = float(1.96 * np.std(vals, ddof=1) / np.sqrt(len(vals))) if len(vals) > 1 else 0.0
means.append(mu); cis.append(ci); labels.append(LABEL.get(m, m)); cols.append(color(m, i))
rows.append((m, mu, ci, len(vals)))
order = np.argsort(means)[::-1] if higher_better else np.argsort(means)
fig = go.Figure(go.Bar(
x=[labels[i] for i in order], y=[means[i] for i in order],
error_y=dict(type="data", array=[cis[i] for i in order], thickness=1.4),
marker_color=[cols[i] for i in order],
))
fig.update_layout(title=title, yaxis_title=ylabel, xaxis_tickangle=-35, **LAYOUT)
fig.write_html(out_html, include_plotlyjs="cdn", full_html=True)
with open(out_csv, "w") as f:
for r in rows:
f.write(",".join(str(x) for x in r) + "\n")
print("wrote", out_html)
def spectral_diag_figure(diag_path, out_html, out_csv):
with open(diag_path) as f:
d = json.load(f)
names = list(d.keys())
fig = make_subplots(rows=1, cols=2, subplot_titles=(
"RFF feature norm ||z(s)||² (theory: exactly 1)",
"Spectral regularizer energy ||V̂(s,a)||²"))
fig.add_trace(go.Bar(x=names, y=[d[n]["mean_z_norm_sq"] for n in names],
error_y=dict(type="data", array=[d[n]["std_z_norm_sq"] for n in names]),
marker_color="#0072B2", name="||z||²"), row=1, col=1)
fig.add_trace(go.Bar(x=names, y=[d[n]["mean_energy"] for n in names],
error_y=dict(type="data", array=[d[n]["std_energy"] for n in names]),
marker_color=C_OURS, name="||V̂||²"), row=1, col=2)
fig.add_hline(y=1.0, line_dash="dash", line_color="#666", row=1, col=1)
fig.add_hline(y=1.0, line_dash="dash", line_color="#666", row=1, col=2)
fig.update_layout(title="Why the spectral regularizer is inert in deterministic environments",
showlegend=False, xaxis_tickangle=-25, xaxis2_tickangle=-25, **LAYOUT)
fig.write_html(out_html, include_plotlyjs="cdn", full_html=True)
with open(out_csv, "w") as f:
f.write("env,mean_z_norm_sq,std_z_norm_sq,mean_energy,std_energy,mean_action_spread\n")
for n in names:
r = d[n]
f.write(f"{n},{r['mean_z_norm_sq']},{r['std_z_norm_sq']},{r['mean_energy']},"
f"{r['std_energy']},{r['mean_across_action_spread']}\n")
print("wrote", out_html)
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="../outputs/main")
ap.add_argument("--fig", default="../figures")
args = ap.parse_args()
os.makedirs(args.fig, exist_ok=True)
data = load(args.out)
F = args.fig
specs = [
("hypergrid", "modes_found", "modes discovered (of 64)", "HyperGrid: mode discovery", True),
("bitsequence", "top100_reward", "normalised top-100 reward", "BitSequence: reward under 90% action failure", True),
("bitsequence", "l1_to_target", "L1 distance to P* ∝ R", "BitSequence: distributional error", False),
("tictactoe", "win_pct", "win rate (%)", "TicTacToe vs 90%-optimal minimax", True),
("tictactoe", "optimal_pct", "optimal moves (%)", "TicTacToe: move quality", True),
("singlecell_proxy", "target_corr", "correlation with true reward", "SingleCell proxy: combinatorial generalisation", True),
]
CURVE_OK = {"modes_found", "top100_reward", "mean_reward", "win_pct",
"l1_to_target", "coverage_pct", "diversity"}
for env, metric, ylab, title, hib in specs:
if env not in data:
continue
bar_figure(data, env, metric, ylab, title,
f"{F}/{env}_{metric}_bar.html", f"{F}/{env}_{metric}_bar.csv", hib)
if metric in CURVE_OK:
curve_figure(data, env, metric, ylab, title + " (training curves)",
f"{F}/{env}_{metric}_curve.html", f"{F}/{env}_{metric}_curve.csv")
diag = "../outputs/spectral_diagnostics.json"
if os.path.exists(diag):
spectral_diag_figure(diag, f"{F}/spectral_diagnostics.html", f"{F}/spectral_diagnostics.csv")