File size: 8,130 Bytes
d9b9e9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Presentation-only figures and derived tables; never selects or changes policies."""
from pathlib import Path
import argparse
import hashlib
import json
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

COLORS = {"learned_acquisition": "#b61446", "random_acquisition": "#07818b",
          "fixed_disagreement": "#7951a5", "initial_bfgs": "#787878",
          "tuned_bfgs": "#28704c", "static_portfolio": "#aa721e"}
LABELS = {"learned_acquisition": "Learned acquisition", "random_acquisition": "Random acquisition",
          "fixed_disagreement": "Fixed disagreement", "same_label_passive": "Same-label passive",
          "initial_bfgs": "Initial BFGS controller", "tuned_bfgs": "Tuned SciPy BFGS",
          "tuned_lbfgs": "Tuned L-BFGS-B", "tuned_spg": "Tuned spectral gradient",
          "tuned_trust_sr1": "Tuned trust-region SR1", "static_portfolio": "Static classical portfolio"}


def main():
    parser = argparse.ArgumentParser(); parser.add_argument("--output", type=Path, default=Path("results"))
    args = parser.parse_args(); root = args.output; out = root / "figures"; out.mkdir(exist_ok=True)
    plt.rcParams.update({"font.size": 14, "axes.labelsize": 14, "axes.titlesize": 14,
                         "legend.fontsize": 12.5, "xtick.labelsize": 12.5, "ytick.labelsize": 12.5,
                         "axes.spines.top": False, "axes.spines.right": False, "pdf.fonttype": 42,
                         "axes.grid": True, "grid.alpha": .15, "savefig.facecolor": "white"})
    summary = json.loads((root / "summary.json").read_text())
    freeze = json.loads((root / "freeze_manifest.json").read_text())
    seeds = sorted(map(int, freeze["selected_programs"]))
    methods = ["learned_acquisition", "random_acquisition", "fixed_disagreement"]
    figures = []
    fig, axes = plt.subplots(1, 2, figsize=(10.5, 5.5), gridspec_kw={"width_ratios": [1.1, 1.]})
    for method in methods:
        values = []
        for seed in seeds:
            rows = json.loads((root / "search" / f"{method}_{seed}" / "checkpoints.json").read_text())
            values.append([row["development"]["fitness"] for row in rows])
        values = np.asarray(values); x = np.arange(values.shape[1])
        axes[0].plot(x, values.mean(axis=0), color=COLORS[method], lw=2, label=LABELS[method])
        axes[0].fill_between(x, values.min(axis=0), values.max(axis=0), color=COLORS[method], alpha=.1)
    axes[0].set(xlabel="Generation (0 = BFGS)", ylabel="Development fitness", title="Successor controllers")
    chosen = ["static_portfolio", "tuned_bfgs", "learned_acquisition", "random_acquisition", "initial_bfgs"]
    lookup = {row["method"]: row for row in summary["methods"]}
    display = ["Classical portfolio", "SciPy BFGS", "Learned acquisition", "Random acquisition", "Initial controller"]
    y = np.arange(len(chosen))
    axes[1].barh(y, [lookup[m]["mean_log10_relative_objective"] for m in chosen], color=[COLORS[m] for m in chosen])
    axes[1].set_yticks(y, display); axes[1].invert_yaxis()
    axes[1].set(xlabel="Final mean log10 objective ratio", title="Untouched nonlinear families")
    axes[1].set_xlim(-12, 0)
    handles, labels = axes[0].get_legend_handles_labels()
    fig.legend(handles, labels, loc="lower center", ncol=3, frameon=False, bbox_to_anchor=(.5, -.015))
    fig.subplots_adjust(left=.09, right=.99, top=.88, bottom=.23, wspace=.8)
    for extension in ("pdf", "png"):
        fig.savefig(out / f"01_controller_evolution_and_transfer.{extension}", dpi=200, bbox_inches="tight")
    plt.close(fig); figures.append("01_controller_evolution_and_transfer")
    fig, axes = plt.subplots(1, 3, figsize=(10.5, 4.7), sharey=True)
    families = ["cauchy", "gaussian_saturation", "matrix_gram"]
    family_names = ["Cauchy regression", "Gaussian saturation", "Matrix-Gram factorization"]
    plotted = ["learned_acquisition", "random_acquisition", "initial_bfgs", "tuned_bfgs", "static_portfolio"]
    with np.load(root / "final_trajectories.npz", allow_pickle=False) as archive:
        for axis, family, family_name in zip(axes, families, family_names):
            for method in plotted:
                curves = [archive[key] for key in archive.files if any(key.startswith(f"s{seed}_{method}_{family}_") for seed in seeds)]
                curve = np.mean(np.log10(np.maximum(np.asarray(curves), 1e-12)), axis=0)
                axis.plot(np.arange(1, 129), curve, color=COLORS[method], lw=2, label=LABELS[method])
            axis.set(title=family_name, xlabel="Paired oracle queries", xlim=(1, 128), ylim=(-12.3, .2))
            axis.set_xticks([1, 64, 128]); axis.set_yticks([-12, -8, -4, 0])
    axes[0].set_ylabel("Mean log10 objective ratio")
    handles, labels = axes[0].get_legend_handles_labels()
    fig.legend(handles, labels, ncol=2, frameon=False, loc="lower center", bbox_to_anchor=(.5, -.05))
    fig.subplots_adjust(left=.08, right=.99, top=.86, bottom=.32, wspace=.16)
    for extension in ("pdf", "png"):
        fig.savefig(out / f"02_unseen_nonlinear_query_curves.{extension}", dpi=200, bbox_inches="tight")
    plt.close(fig); figures.append("02_unseen_nonlinear_query_curves")
    generation = pd.read_csv(root / "generation_final_results.csv")
    generation = generation[generation.query_budget == 128]
    final = pd.read_csv(root / "final_results.csv"); final = final[final.query_budget == 128]
    fig, axes = plt.subplots(1, 2, figsize=(10.5, 5.4))
    for method in methods:
        means = generation[generation.method == method].groupby(["generation", "meta_seed"])["log10_relative_objective"].mean().unstack()
        axes[0].plot(means.index, means.mean(axis=1), color=COLORS[method], lw=2, label=LABELS[method])
        axes[0].fill_between(means.index, means.min(axis=1), means.max(axis=1), color=COLORS[method], alpha=.1)
    reference = final[final.method == "initial_bfgs"].log10_relative_objective.mean()
    axes[0].axhline(reference, color=COLORS["initial_bfgs"], ls="--", lw=1.5, label="Initial controller")
    axes[0].set(xlabel="Frozen successor generation", ylabel="Final mean log10 objective ratio", title="All generations, no final selection")
    active = final[final.method == "learned_acquisition"]
    totals = np.asarray([json.loads(s) for s in active.action_counts]).sum(axis=0)
    names = ["BFGS line search", "BB trial", "Preconditioned trial", "Curvature probe", "Reset + BFGS"]
    axes[1].barh(np.arange(5), totals / totals.sum(), color="#b61446")
    axes[1].set_yticks(np.arange(5), names); axes[1].invert_yaxis()
    axes[1].set(xlabel="Fraction of attempted actions", title="Selected controllers on final tasks", xlim=(0, 1))
    handles, labels = axes[0].get_legend_handles_labels()
    fig.legend(handles, labels, ncol=2, frameon=False, loc="lower center", bbox_to_anchor=(.5, -.01))
    fig.subplots_adjust(left=.09, right=.99, top=.88, bottom=.25, wspace=.9)
    for extension in ("pdf", "png"):
        fig.savefig(out / f"03_successor_replay_and_actions.{extension}", dpi=200, bbox_inches="tight")
    plt.close(fig); figures.append("03_successor_replay_and_actions")
    generation.groupby(["method", "generation"]).agg(mean_log10_relative_objective=("log10_relative_objective", "mean"),
        success_fraction=("success_1e_minus_6", "mean"), mean_restricted_queries=("restricted_queries_to_1e_minus_6", "mean")).to_csv(root / "summary_by_generation.csv")
    provenance = {"presentation_only": True, "policies_or_results_selected_or_changed": False,
        "plot_source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        "source_data_sha256": {name: hashlib.sha256((root / name).read_bytes()).hexdigest() for name in ["summary.json", "final_results.csv", "generation_final_results.csv", "final_trajectories.npz"]},
        "figures": figures, "shading": "minimum to maximum over five meta-training seeds; not a confidence interval"}
    (root / "figure_provenance.json").write_text(json.dumps(provenance, indent=2) + "\n")
    print(json.dumps({"figures": figures}, indent=2))


if __name__ == "__main__": main()