summaryrefslogtreecommitdiff
path: root/scripts/plot_operator_overlap_grid.py
blob: e1e599fb2f14750e445026db1214ddb08cd602e2 (plain)
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env python3
"""Plot theory/empirical overlap panels for operator stress settings."""

from __future__ import annotations

import argparse
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd


SETTING_ORDER = [
    "d1_w64_T50_s20",
    "d2_w32_T50_s20",
    "d2_w64_T25_s10",
    "d2_w64_T50_s20_256traj",
    "d2_w64_T100_s40",
    "d2_w96_T50_s20",
    "d3_w64_T50_s20",
]


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--rows",
        type=Path,
        default=Path("outputs/operator_stress_grid_summary/stress_grid_rows.csv"),
    )
    parser.add_argument(
        "--metrics",
        type=Path,
        default=Path("outputs/operator_stress_grid_summary/stress_grid_metrics.csv"),
    )
    parser.add_argument(
        "--outdir",
        type=Path,
        default=Path("outputs/operator_stress_grid_summary"),
    )
    return parser.parse_args()


def summarize_by_margin(group: pd.DataFrame, column: str) -> pd.DataFrame:
    records = []
    for margin, by_margin in group.groupby("hard_fa_capacity_margin"):
        values = by_margin[column].to_numpy(dtype=np.float64)
        records.append(
            {
                "margin": float(margin),
                "mean": float(values.mean()),
                "q05": float(np.quantile(values, 0.05)),
                "q25": float(np.quantile(values, 0.25)),
                "q75": float(np.quantile(values, 0.75)),
                "q95": float(np.quantile(values, 0.95)),
            }
        )
    return pd.DataFrame(records).sort_values("margin")


def trajectory_id(frame: pd.DataFrame) -> pd.Series:
    return frame["init_seed"].astype(str) + ":" + frame["feedback_seed"].astype(str)


def pretty_setting(setting: str) -> str:
    if setting == "d2_w64_T50_s20_256traj":
        return "d2 w64 T50 s20 (256 traj)"
    return setting.replace("_", " ")


def panel_ylim(group: pd.DataFrame) -> tuple[float, float]:
    values = np.concatenate(
        [
            group["empirical_gap"].to_numpy(dtype=np.float64),
            group["linear_gap"].to_numpy(dtype=np.float64),
        ]
    )
    lo = float(values.min())
    hi = float(values.max())
    pad = max((hi - lo) * 0.12, 0.004)
    return max(0.0, lo - pad), hi + pad


def plot_panel(
    ax: plt.Axes,
    group: pd.DataFrame,
    metrics: pd.Series,
    show_legend: bool,
) -> None:
    group = group.sort_values(["hard_fa_capacity_margin", "init_seed", "feedback_seed"])
    theory = summarize_by_margin(group, "linear_gap")
    empirical = summarize_by_margin(group, "empirical_gap")
    group = group.assign(_trajectory_id=trajectory_id(group))

    for _tid, traj in group.groupby("_trajectory_id"):
        traj = traj.sort_values("hard_fa_capacity_margin")
        ax.plot(
            traj["hard_fa_capacity_margin"],
            traj["empirical_gap"],
            color="#c65f16",
            alpha=0.16 if len(group) > 80 else 0.26,
            linewidth=1.05,
        )

    ax.fill_between(
        theory["margin"],
        theory["q05"],
        theory["q95"],
        color="#1f5a9d",
        alpha=0.14,
        linewidth=0,
        label="theory 5-95%",
    )
    ax.fill_between(
        theory["margin"],
        theory["q25"],
        theory["q75"],
        color="#1f5a9d",
        alpha=0.26,
        linewidth=0,
        label="theory 25-75%",
    )
    ax.plot(
        theory["margin"],
        theory["mean"],
        color="#174f91",
        marker="o",
        markersize=3.3,
        linewidth=2.0,
        label="theory mean",
    )
    ax.plot(
        empirical["margin"],
        empirical["mean"],
        color="#a84708",
        marker="o",
        markersize=3.0,
        linewidth=1.8,
        label="empirical mean",
    )
    ax.axvline(0.0, color="black", linestyle="--", linewidth=0.9)
    ax.set_ylim(*panel_ylim(group))
    ax.grid(alpha=0.17)
    ax.set_title(
        f"{pretty_setting(str(metrics.name))}\n"
        f"MAE={metrics['linear_mae']:.4g}, "
        f"bias={metrics['linear_bias']:.4g}, "
        f"corr={metrics['linear_corr']:.4f}",
        fontsize=10,
    )
    if show_legend:
        ax.legend(loc="upper left", fontsize=8, frameon=True)


def main() -> None:
    args = parse_args()
    args.outdir.mkdir(parents=True, exist_ok=True)
    rows = pd.read_csv(args.rows)
    metrics = pd.read_csv(args.metrics).set_index("setting")
    settings = [setting for setting in SETTING_ORDER if setting in set(rows["setting"])]

    fig, axes = plt.subplots(4, 2, figsize=(15.5, 18.5), dpi=180)
    axes_flat = axes.ravel()
    for index, setting in enumerate(settings):
        group = rows[rows["setting"] == setting]
        plot_panel(
            axes_flat[index],
            group,
            metrics.loc[setting],
            show_legend=index == 0,
        )
        axes_flat[index].set_xlabel("hard FA capacity margin")
        axes_flat[index].set_ylabel("FA train MSE - BP train MSE")

    for index in range(len(settings), len(axes_flat)):
        axes_flat[index].axis("off")

    fig.suptitle(
        "Early-kernel velocity theory vs empirical trajectory distributions",
        fontsize=18,
        y=0.995,
    )
    fig.tight_layout(rect=(0, 0, 1, 0.985))
    outpath = args.outdir / "stress_grid_overlap_panels.png"
    fig.savefig(outpath)
    plt.close(fig)
    print(f"plot: {outpath}")


if __name__ == "__main__":
    main()