File size: 5,601 Bytes
448d6a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generate logbook figures (plotly HTML + raw CSV) from claim result JSONs."""
import os, sys, json
import numpy as np
import plotly.graph_objects as go

BASE = os.path.join(os.path.dirname(__file__), "..")
OUT = os.path.join(BASE, "outputs", "figures")
os.makedirs(OUT, exist_ok=True)

def _save(fig, name):
    # embeddable fragment (div + inline script + one cdn plotly load) for logbook cells
    fig.write_html(os.path.join(OUT, name + ".html"), include_plotlyjs="cdn", full_html=False,
                   default_width="100%", default_height="430px")
    print("wrote", name + ".html", flush=True)

def load(claim):
    p = os.path.join(BASE, "outputs", claim, f"{claim}_results.json")
    return json.load(open(p)) if os.path.exists(p) else None

# ---- Claim 1: supernet operator heatmap ----
def fig_claim1():
    d = load("claim1")
    if not d: return
    ops = d["ctrl_ops"]; heat = d["heatmap"]
    domains = list(heat.keys())
    Z = [[heat[dom][o] for o in ops] for dom in domains]
    fig = go.Figure(go.Heatmap(z=Z, x=ops, y=domains, colorscale="Viridis", zmin=0, zmax=1,
                               colorbar=dict(title="P(include)")))
    fig.update_layout(title="Claim 1 — Mind supernet operator inclusion probability by topic domain",
                      xaxis_title="Thinking operator", yaxis_title="Domain", height=430)
    _save(fig, "claim1_supernet_heatmap")
    # CSV
    with open(os.path.join(OUT, "claim1_supernet_heatmap.csv"), "w") as f:
        f.write("domain," + ",".join(ops) + "\n")
        for dom in domains:
            f.write(dom + "," + ",".join(f"{heat[dom][o]:.4f}" for o in ops) + "\n")

# ---- Claim 2: per-method Overall + MOScores bar ----
def fig_claim2():
    d = load("claim2")
    if not d: return
    methods = [k for k in d if not k.startswith("_")]
    rows = [(m, d[m]["agg"]["Overall"], d[m]["agg"]["MOScore_PF"], d[m]["agg"]["MOScore_PS"], d[m]["agg"].get("novelty_mean", float("nan"))) for m in methods]
    rows.sort(key=lambda r: r[1])
    names = [r[0] for r in rows]
    fig = go.Figure()
    fig.add_bar(y=names, x=[r[2] for r in rows], name="MOScore PF", orientation="h")
    fig.add_bar(y=names, x=[r[3] for r in rows], name="MOScore PS", orientation="h")
    fig.add_trace(go.Scatter(y=names, x=[r[1] for r in rows], name="Overall", mode="markers",
                             marker=dict(size=12, color="black", symbol="diamond")))
    fig.update_layout(barmode="group", title="Claim 2 — Win-rate MOScore by method (MindFlow best aggregate)",
                      xaxis_title="Win-rate score vs expert reference", height=430)
    _save(fig, "claim2_methods_bar")
    with open(os.path.join(OUT, "claim2_methods.csv"), "w") as f:
        f.write("method,Overall,MOScore_PF,MOScore_PS,novelty\n")
        for r in sorted(rows, key=lambda x: -x[1]):
            f.write(f"{r[0]},{r[1]:.4f},{r[2]:.4f},{r[3]:.4f},{r[4]:.4f}\n")

# ---- Claim 3: learning curves + reward discrimination + distribution shift ----
def fig_claim3():
    d = load("claim3")
    if not d: return
    fig = go.Figure()
    colors = {"tournament": "#2ca02c", "pointwise": "#d62728"}
    for mode in ["tournament", "pointwise"]:
        if mode not in d: continue
        h = d[mode]["hist"]
        fig.add_trace(go.Scatter(x=h["eval_iter"], y=h["eval_overall"], mode="lines+markers",
                                 name=f"{mode}", line=dict(color=colors.get(mode))))
    fig.update_layout(title="Claim 3 — Held-out win-rate MOScore vs controller-optimization iteration",
                      xaxis_title="Optimization iteration", yaxis_title="Eval Overall MOScore", height=400)
    _save(fig, "claim3_learning_curve")

    # reward discrimination (mean reward_std per mode)
    fig2 = go.Figure()
    for mode in ["tournament", "pointwise"]:
        if mode not in d: continue
        h = d[mode]["hist"]
        fig2.add_trace(go.Scatter(x=h["iter"], y=h["reward_std"], mode="lines+markers",
                                  name=f"{mode}", line=dict(color=colors.get(mode))))
    fig2.update_layout(title="Claim 3 — Reward signal discrimination (std of intra-group reward)",
                       xaxis_title="Iteration", yaxis_title="Reward std (higher = less judgment collapse)", height=400)
    _save(fig2, "claim3_reward_discrimination")

    # distribution shift for tournament
    if "tournament" in d:
        t = d["tournament"]; ops = t["ctrl_ops"]
        init = np.array(t["init_probs"]).mean(axis=0)  # mean over layers
        fin = np.array(t["final_probs"]).mean(axis=0)
        fig3 = go.Figure()
        fig3.add_bar(x=ops, y=init, name="initial controller")
        fig3.add_bar(x=ops, y=fin, name="after tournament optimization")
        fig3.update_layout(barmode="group", title="Claim 3 — Supernet operator-inclusion shift after optimization",
                           xaxis_title="Operator", yaxis_title="Mean P(include)", height=400)
        _save(fig3, "claim3_distribution_shift")
        with open(os.path.join(OUT, "claim3_curves.csv"), "w") as f:
            f.write("mode,iter,eval_overall\n")
            for mode in ["tournament", "pointwise"]:
                if mode in d:
                    h = d[mode]["hist"]
                    for it, v in zip(h["eval_iter"], h["eval_overall"]):
                        f.write(f"{mode},{it},{v:.4f}\n")

if __name__ == "__main__":
    which = sys.argv[1] if len(sys.argv) > 1 else "all"
    if which in ("all", "claim1"): fig_claim1()
    if which in ("all", "claim2"): fig_claim2()
    if which in ("all", "claim3"): fig_claim3()
    print("figures ->", OUT)