File size: 11,237 Bytes
ba0faed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#!/usr/bin/env python3
"""Render the three-panel MoS main-results figure from frozen evidence.

All three panels use the fixed-seed, five-domain R1 evaluation. Panel (a)
compares the matched-domain profiles of the Generalist and the two MoS
initializations; panels (b)--(c) show the corresponding MoS routing matrices.
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap, Normalize
from matplotlib.patches import Rectangle


REPO_ROOT = Path(__file__).resolve().parents[3]
DEFAULT_EVIDENCE = (
    REPO_ROOT
    / "paper"
    / "submission"
    / "evidence"
    / "r1_mainfig_seed20260719_20260721T0602Z_cells_summary.json"
)
DEFAULT_OUTPUT = (
    REPO_ROOT / "paper" / "submission" / "figures" / "fig_main_results.png"
)

DOMAINS = ["code", "math", "factual_qa", "creative_writing", "general"]
DOMAIN_LABELS = ["Code", "Math", "Factual QA", "Creative", "General"]

# Restrained, color-blind-safe palette. Shape and line style also distinguish
# methods, so the figure remains legible in grayscale.
INK = "#25313B"
MUTED = "#68747E"
GRID = "#E2E7EA"
GENERALIST = "#7F8790"
D0 = "#2F9E44"
WARM = "#9C36B5"
LIGHT_RULE = "#C8D0D5"


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--evidence", type=Path, default=DEFAULT_EVIDENCE)
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    return parser.parse_args()


def configure_style() -> None:
    mpl.rcParams.update(
        {
            "font.family": "sans-serif",
            "font.sans-serif": [
                "Arial",
                "Helvetica",
                "Liberation Sans",
                "DejaVu Sans",
            ],
            "font.size": 8.0,
            "axes.titlesize": 9.3,
            "axes.labelsize": 8.3,
            "xtick.labelsize": 7.4,
            "ytick.labelsize": 7.4,
            "legend.fontsize": 7.3,
            "pdf.fonttype": 42,
            "ps.fonttype": 42,
            "axes.linewidth": 0.65,
            "savefig.bbox": "tight",
            "savefig.pad_inches": 0.035,
        }
    )


def matrix_from_evidence(evidence: dict, key: str) -> np.ndarray:
    mapping = evidence[key]
    matrix = np.asarray(
        [[float(mapping[row][column]) for column in DOMAINS] for row in DOMAINS],
        dtype=float,
    )
    for column in range(len(DOMAINS)):
        if int(np.argmax(matrix[:, column])) != column:
            raise ValueError(f"{key}: matched MLP is not best in column {DOMAINS[column]}")
    return matrix


def generalist_from_evidence(evidence: dict) -> np.ndarray:
    mapping = evidence["panel_d_generalist"]
    return np.asarray([float(mapping[domain]) for domain in DOMAINS], dtype=float)


def panel_title(ax: plt.Axes, letter: str, title: str) -> None:
    # Use a point-based offset so the letter-to-title gap is physically
    # identical in the full-width trajectory and the half-width matrices.
    origin = (-0.055, 1.075)
    ax.text(
        *origin,
        letter,
        transform=ax.transAxes,
        ha="left",
        va="bottom",
        fontsize=9.8,
        fontweight="bold",
        color=INK,
    )
    ax.annotate(
        title,
        xy=origin,
        xycoords="axes fraction",
        xytext=(18, 0),
        textcoords="offset points",
        ha="left",
        va="bottom",
        fontsize=8.6,
        fontweight="bold",
        color=INK,
    )


def quiet_axes(ax: plt.Axes) -> None:
    ax.spines["top"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["left"].set_color(LIGHT_RULE)
    ax.spines["bottom"].set_color(LIGHT_RULE)
    ax.tick_params(color=LIGHT_RULE, labelcolor=INK, width=0.65, length=2.8)


def draw_profile_panel(
    ax: plt.Axes,
    generalist: np.ndarray,
    d0_diag: np.ndarray,
    warm_diag: np.ndarray,
) -> None:
    panel_title(ax, "A", "Matched-domain acceptance across five domains")
    quiet_axes(ax)
    ax.grid(axis="y", color=GRID, lw=0.6, alpha=0.9, zorder=0)
    x = np.arange(len(DOMAINS))
    ax.plot(
        x,
        generalist,
        color=GENERALIST,
        lw=1.65,
        ls="-",
        marker="o",
        ms=4.2,
        mfc="white",
        mec=GENERALIST,
        mew=1.0,
        alpha=0.90,
        label="Generalist",
        zorder=3,
    )
    ax.plot(
        x,
        d0_diag,
        color=D0,
        lw=1.75,
        marker="o",
        ms=4.3,
        mfc="white",
        mec=D0,
        mew=1.0,
        label="D0-init MoS",
        zorder=5,
    )
    ax.plot(
        x,
        warm_diag,
        color=WARM,
        lw=1.75,
        marker="s",
        ms=4.2,
        mfc="white",
        mec=WARM,
        mew=1.0,
        label="G-init MoS",
        zorder=6,
    )

    for index, value in enumerate(generalist):
        ax.annotate(
            f"{value:.3f}",
            xy=(x[index], value),
            xytext=(0, -7),
            textcoords="offset points",
            ha="center",
            va="top",
            fontsize=5.7,
            color=MUTED,
        )
    for index, value in enumerate(warm_diag):
        ax.annotate(
            f"{value:.3f}",
            xy=(x[index], value),
            xytext=(0, 6),
            textcoords="offset points",
            ha="center",
            va="bottom",
            fontsize=5.8,
            color=INK,
            fontweight="bold",
        )

    ax.set_xlim(-0.35, len(DOMAINS) - 0.65)
    ax.set_ylim(2.55, 5.78)
    ax.set_xticks(x, labels=DOMAIN_LABELS)
    ax.set_yticks([2.8, 3.4, 4.0, 4.6, 5.2, 5.8])
    ax.set_ylabel("Acceptance length")
    ax.legend(
        loc="upper right",
        bbox_to_anchor=(1.0, 1.02),
        frameon=False,
        ncol=3,
        handlelength=2.4,
        borderaxespad=0.1,
        columnspacing=1.15,
        handletextpad=0.4,
        labelspacing=0.25,
        fontsize=5.8,
    )


HEATMAP_D0_CMAP = LinearSegmentedColormap.from_list(
    "d0_matched_regret",
    ["#F7FAF7", "#DDEFE1", "#A7D7B1", "#68B97A", D0],
)
HEATMAP_WARM_CMAP = LinearSegmentedColormap.from_list(
    "warm_matched_regret",
    ["#FBF8FC", "#F0E0F4", "#D9B7E2", "#BC79CB", WARM],
)
HEATMAP_NORM = Normalize(vmin=-1.30, vmax=0.0)


def draw_matrix_panel(
    ax: plt.Axes,
    matrix: np.ndarray,
    letter: str,
    title: str,
    cmap: LinearSegmentedColormap,
    diagonal_edge: str,
) -> mpl.image.AxesImage:
    regret = matrix - np.diag(matrix)[None, :]
    image = ax.imshow(regret, cmap=cmap, norm=HEATMAP_NORM, aspect="equal")
    panel_title(ax, letter, title)
    ax.set_xticks(range(len(DOMAINS)), labels=DOMAIN_LABELS)
    ax.set_yticks(range(len(DOMAINS)), labels=DOMAIN_LABELS)
    ax.tick_params(axis="x", rotation=29, length=0, pad=2.2, labelsize=6.2)
    ax.tick_params(axis="y", length=0, pad=2.6, labelsize=6.5)
    ax.set_ylabel("Selected MLP", labelpad=2.5, fontsize=7.0)

    for row in range(len(DOMAINS)):
        for column in range(len(DOMAINS)):
            value = matrix[row, column]
            normalized = HEATMAP_NORM(regret[row, column])
            text_color = "white" if normalized > 0.68 else INK
            ax.text(
                column,
                row,
                f"{value:.3f}",
                ha="center",
                va="center",
                fontsize=6.0,
                color=text_color,
                fontweight="bold" if row == column else "normal",
            )
            if row == column:
                ax.add_patch(
                    Rectangle(
                        (column - 0.48, row - 0.48),
                        0.96,
                        0.96,
                        facecolor="none",
                        edgecolor=diagonal_edge,
                        linewidth=1.45,
                    )
                )

    ax.set_xticks(np.arange(-0.5, len(DOMAINS), 1), minor=True)
    ax.set_yticks(np.arange(-0.5, len(DOMAINS), 1), minor=True)
    ax.grid(which="minor", color="white", linestyle="-", linewidth=1.15)
    ax.tick_params(which="minor", bottom=False, left=False)
    for spine in ax.spines.values():
        spine.set_visible(False)
    return image


def main() -> None:
    args = parse_args()
    configure_style()
    evidence = json.loads(args.evidence.read_text())
    if not evidence.get("passed"):
        raise ValueError("R1 evidence is not marked passed")
    if evidence.get("cells_total") != 52 or evidence.get("cells_passed") != 52:
        raise ValueError("R1 evidence is not complete (expected 52/52 cells)")

    d0_matrix = matrix_from_evidence(evidence, "panel_b_matrix_dflash_init")
    warm_matrix = matrix_from_evidence(evidence, "panel_c_matrix_warm_start")
    generalist = generalist_from_evidence(evidence)

    if not np.all(np.diag(d0_matrix) > generalist):
        raise ValueError("DFlash-initialized MoS is not above Generalist in every domain")
    if not np.all(np.diag(warm_matrix) > generalist):
        raise ValueError("warm-started MoS is not above Generalist in every domain")

    # Match the intended AAAI double-column physical width. Raising DPI, rather
    # than drawing an oversized canvas and shrinking it in LaTeX, preserves the
    # configured 7--10 pt typography at publication size.
    fig = plt.figure(figsize=(7.15, 5.00), facecolor="white")
    outer = fig.add_gridspec(
        2,
        1,
        height_ratios=[0.82, 1.18],
        hspace=0.46,
        left=0.075,
        right=0.985,
        top=0.945,
        bottom=0.180,
    )
    ax_a = fig.add_subplot(outer[0, 0])
    matrices = outer[1, 0].subgridspec(1, 2, wspace=0.28)
    ax_b = fig.add_subplot(matrices[0, 0])
    ax_c = fig.add_subplot(matrices[0, 1])

    draw_profile_panel(
        ax_a,
        generalist,
        np.diag(d0_matrix),
        np.diag(warm_matrix),
    )
    d0_image = draw_matrix_panel(
        ax_b,
        d0_matrix,
        "B",
        "DFlash-initialized MoS",
        HEATMAP_D0_CMAP,
        "#226F32",
    )
    warm_image = draw_matrix_panel(
        ax_c,
        warm_matrix,
        "C",
        "Generalist-warm-started MoS",
        HEATMAP_WARM_CMAP,
        "#6F277D",
    )

    # Separate color strips preserve the original green/purple recipe identity
    # while keeping an identical quantitative scale in both matrices.
    for image, position in (
        (d0_image, [0.145, 0.065, 0.29, 0.010]),
        (warm_image, [0.575, 0.065, 0.29, 0.010]),
    ):
        cbar_ax = fig.add_axes(position)
        cbar = fig.colorbar(image, cax=cbar_ax, orientation="horizontal")
        cbar.set_ticks([-1.2, -0.6, 0.0])
        cbar.ax.tick_params(labelsize=5.7, length=1.8, color=LIGHT_RULE)
        cbar.outline.set_visible(False)
    fig.text(
        0.505,
        0.014,
        r"Shade: column-wise $\Delta$AL from the matched MLP",
        ha="center",
        va="bottom",
        fontsize=6.0,
        color=INK,
    )

    args.output.parent.mkdir(parents=True, exist_ok=True)
    fig.savefig(args.output, dpi=420, facecolor="white")
    plt.close(fig)
    print(f"saved {args.output}")


if __name__ == "__main__":
    main()