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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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
"""Paper figure generator.

Produces four PDF figures for the MacroLens NeurIPS 2026 D&B paper.
Source of truth: aggregated long-DataFrame from
:mod:`experiments.aggregate_results` (or load directly from a results JSON
glob via the CLI below).

Figures (all panel-driven; method ordering follows the registry's
``family -> name`` sort):

* ``fig_panel_overview``       - Figure 1 (page-1 schematic): grid of 7 tasks
  x 7 families with counts where the family covers the task. Plus the
  benchmark headline numbers (4,416 tickers, 131 features, 1,130 events).
* ``fig_primary_metric_per_task`` - One subplot per task; horizontal bar
  chart of method primary-metric values with bootstrap-CI error bars; methods
  ordered by primary metric (best at top).
* ``fig_per_family_box``       - One subplot per task; box-and-whisker of
  primary metric grouped by family (n=members in that family that cover the
  task). Shows family-level distribution.
* ``fig_zs_vs_ft``             - Bar chart: ZS vs FT for the LLM family
  (the 3 frontier models), only on T1.

(Single-horizon experiment design — no horizon-curve figure; horizon is
fixed to the longest configured value per granularity, e.g. 252 daily.)

CLI::

    python -m projects.agent_builder.scripts.whatif_bench.experiments.gen_figures \
        --results-glob 'experiments/results/canon_*.json' \
        --output-dir   'experiments/paper_artifacts/figures/' \
        --granularity  daily

Headless: matplotlib is forced to the ``Agg`` backend so the script runs on a
GPU box / CI without an X server. Each figure is saved as both ``.pdf``
(vector, for LaTeX) and ``.png`` (raster, for previews / quicklook).
"""

from __future__ import annotations

import argparse
import glob
import logging
from pathlib import Path
from typing import Iterable

import matplotlib

matplotlib.use("Agg")  # headless
import matplotlib.pyplot as plt  # noqa: E402
import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402

from .. import config  # noqa: E402
from . import panel  # noqa: E402
from .aggregate_results import (  # noqa: E402
    _PRIMARY_METRIC_KEY,
    _PRIMARY_METRIC_LOWER_IS_BETTER,
    _load_records,
    _records_to_long_df,
    aggregate,
)


logger = logging.getLogger(__name__)


# Friendly family display name + plot colour. Stable across all figures so
# the same family always reads as the same hue.
_FAMILY_ORDER: tuple[str, ...] = (
    "naive", "classical", "sequence",
    "tsfm",
    "llm_ts",
    "llm",
)
_FAMILY_DISPLAY: dict[str, str] = {
    "naive": "Naive",
    "classical": "Classical",
    "sequence": "Deep Seq",
    "tsfm": "TSFM",
    "llm_ts": "LLM-TS",
    "llm": "LLM",
}
_FAMILY_COLOR: dict[str, str] = {
    "naive": "tab:gray",
    "classical": "tab:olive",
    "sequence": "tab:blue",
    "tsfm": "tab:cyan",
    "llm_ts": "tab:purple",
    "llm": "tab:orange",
}

# Registry-family aliases used by the runner inside the long DataFrame's
# ``method_family`` column. Panel and registry now use the same canonical
# family names ("tsfm", "llm", "llm_ts"); the alias map is a no-op kept
# only so adding a new family later is a one-line change.
_FAMILY_ALIASES: dict[str, str] = {}


def _canonical_family(family: str) -> str:
    return _FAMILY_ALIASES.get(family, family)


def _save_fig(fig: plt.Figure, output_path: Path) -> tuple[Path, Path]:
    """Save *fig* as both ``output_path.pdf`` and ``output_path.png``."""
    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    pdf = output_path.with_suffix(".pdf")
    png = output_path.with_suffix(".png")
    fig.savefig(pdf, bbox_inches="tight", dpi=300)
    fig.savefig(png, bbox_inches="tight", dpi=200)
    plt.close(fig)
    return pdf, png


def _method_display(method_id: str) -> str:
    """Display name for *method_id* (panel-aware, registry-fallback)."""
    for m in panel.ALL_METHODS:
        if m.id == method_id:
            return m.name
    return method_id


def _primary_view(df: pd.DataFrame, task: str) -> pd.DataFrame:
    """Per-method mean-over-seeds view of the task's primary metric."""
    metric = _PRIMARY_METRIC_KEY.get(task)
    if metric is None or df.empty:
        return pd.DataFrame()
    sub = df[(df["task"] == task) & (df["metric_name"] == metric)].copy()
    if sub.empty:
        return sub
    grouped = (
        sub.groupby(["method_id", "method_family"], as_index=False)
           .agg(value=("value", "mean"),
                ci_lo=("ci_lo", "mean"),
                ci_hi=("ci_hi", "mean"),
                std=("std", "mean"))
    )
    grouped["family"] = grouped["method_family"].map(_canonical_family)
    grouped["display"] = grouped["method_id"].map(_method_display)
    grouped = grouped.dropna(subset=["value"])
    return grouped


# ---------------------------------------------------------------------------
# Figure 1: panel overview (task x family coverage matrix)
# ---------------------------------------------------------------------------

def fig_panel_overview(df: pd.DataFrame, output_path: Path) -> tuple[Path, Path]:
    """Page-1 schematic: 7 tasks x 7 families coverage grid + headline numbers.

    *df* is unused for the static schematic; accepted to keep the figure-API
    uniform across the five generators.
    """
    tasks = list(panel.ALL_TASKS)
    families = list(_FAMILY_ORDER)

    # Build coverage matrix from panel.ALL_METHODS (canonical 18-method panel).
    coverage = np.zeros((len(families), len(tasks)), dtype=int)
    for m in panel.ALL_METHODS:
        if m.family not in _FAMILY_DISPLAY:
            continue  # unknown family – skip
        i = families.index(m.family)
        for t in m.tasks:
            if t in tasks:
                j = tasks.index(t)
                coverage[i, j] += 1

    fig, ax = plt.subplots(figsize=(8.5, 4.0))
    # Heatmap with a reversed grayscale palette so 0 = white, n>0 = darker.
    im = ax.imshow(coverage, aspect="auto", cmap="Blues",
                   vmin=0, vmax=max(1, int(coverage.max())))
    ax.set_xticks(range(len(tasks)))
    ax.set_xticklabels(tasks, fontsize=10)
    ax.set_yticks(range(len(families)))
    ax.set_yticklabels([_FAMILY_DISPLAY[f] for f in families], fontsize=10)
    for i in range(len(families)):
        for j in range(len(tasks)):
            n = coverage[i, j]
            if n > 0:
                ax.text(j, i, str(n), ha="center", va="center",
                        color="white" if n >= 2 else "black", fontsize=10)
    ax.set_title("MacroLens method-x-task coverage "
                 "(4,416 tickers; 131 features; 1,130 events)",
                 fontsize=11)
    fig.colorbar(im, ax=ax, label="# methods")
    fig.tight_layout()
    return _save_fig(fig, output_path)


# ---------------------------------------------------------------------------
# Figure 2: primary metric per task
# ---------------------------------------------------------------------------

def fig_primary_metric_per_task(df: pd.DataFrame, output_path: Path) -> tuple[Path, Path]:
    """One horizontal-bar subplot per task; bars sorted best-on-top."""
    tasks = list(panel.ALL_TASKS)
    n_tasks = len(tasks)
    ncols = 2
    nrows = (n_tasks + ncols - 1) // ncols
    fig, axes = plt.subplots(nrows, ncols, figsize=(11, 2.4 * nrows + 1.0),
                             squeeze=False)
    axes_flat = axes.flatten()

    any_data = False
    for k, t in enumerate(tasks):
        ax = axes_flat[k]
        view = _primary_view(df, t)
        primary = _PRIMARY_METRIC_KEY[t]
        ascending = _PRIMARY_METRIC_LOWER_IS_BETTER[t]

        if view.empty:
            ax.set_axis_off()
            ax.set_title(f"{t} — no records")
            continue
        any_data = True
        view = view.sort_values("value", ascending=ascending).reset_index(drop=True)
        # Reverse so best-on-top after barh paints bottom-up.
        view = view.iloc[::-1].reset_index(drop=True)

        y = np.arange(len(view))
        # Symmetric error length from CI; fall back to std if CI absent.
        lo = view["value"].to_numpy() - view["ci_lo"].to_numpy()
        hi = view["ci_hi"].to_numpy() - view["value"].to_numpy()
        lo = np.where(np.isnan(lo), view["std"].fillna(0).to_numpy(), lo)
        hi = np.where(np.isnan(hi), view["std"].fillna(0).to_numpy(), hi)
        lo = np.clip(lo, 0, None)
        hi = np.clip(hi, 0, None)
        colors = [_FAMILY_COLOR.get(f, "tab:gray") for f in view["family"]]
        ax.barh(y, view["value"], xerr=[lo, hi], color=colors,
                edgecolor="black", linewidth=0.4, capsize=2)
        ax.set_yticks(y)
        ax.set_yticklabels(view["display"], fontsize=8)
        ax.set_title(f"{t} ({primary})", fontsize=10)
        ax.tick_params(axis="x", labelsize=8)

    # Hide unused axes
    for k in range(len(tasks), len(axes_flat)):
        axes_flat[k].set_axis_off()

    # Family legend – only families that actually appear.
    seen_fams = sorted({_canonical_family(f) for f in df["method_family"].unique()
                        if isinstance(f, str)}) if not df.empty else []
    handles = [plt.Rectangle((0, 0), 1, 1, color=_FAMILY_COLOR[f])
               for f in seen_fams if f in _FAMILY_COLOR]
    labels = [_FAMILY_DISPLAY[f] for f in seen_fams if f in _FAMILY_COLOR]
    if handles:
        fig.legend(handles, labels, ncol=min(len(handles), 4),
                   loc="lower center", bbox_to_anchor=(0.5, -0.01),
                   fontsize=8, frameon=False)
    fig.suptitle(
        "Per-task primary-metric leaderboard (mean across seeds; "
        "error bars = bootstrap 95% CI)" if any_data
        else "Per-task primary-metric leaderboard (no data)",
        fontsize=11,
    )
    fig.tight_layout(rect=[0, 0.03, 1, 0.97])
    return _save_fig(fig, output_path)


# ---------------------------------------------------------------------------
# Figure 3: T1 horizon curves
# ---------------------------------------------------------------------------

# ---------------------------------------------------------------------------
# Figure 4: per-family box plot
# ---------------------------------------------------------------------------

def fig_per_family_box(df: pd.DataFrame, output_path: Path) -> tuple[Path, Path]:
    """One box-plot subplot per task; primary metric grouped by family."""
    tasks = list(panel.ALL_TASKS)
    n_tasks = len(tasks)
    ncols = 2
    nrows = (n_tasks + ncols - 1) // ncols
    fig, axes = plt.subplots(nrows, ncols, figsize=(11, 2.4 * nrows + 1.0),
                             squeeze=False)
    axes_flat = axes.flatten()

    for k, t in enumerate(tasks):
        ax = axes_flat[k]
        view = _primary_view(df, t)
        primary = _PRIMARY_METRIC_KEY[t]
        if view.empty:
            ax.set_axis_off()
            ax.set_title(f"{t} — no records")
            continue
        # Group values by family, drop empties, preserve canonical order.
        groups: list[tuple[str, np.ndarray]] = []
        for fam in _FAMILY_ORDER:
            arr = view.loc[view["family"] == fam, "value"].to_numpy()
            arr = arr[~np.isnan(arr)]
            if arr.size:
                groups.append((fam, arr))
        if not groups:
            ax.set_axis_off()
            ax.set_title(f"{t} — no data")
            continue
        positions = np.arange(len(groups))
        bp = ax.boxplot([g[1] for g in groups], positions=positions, widths=0.55,
                        patch_artist=True)
        for box, (fam, _) in zip(bp["boxes"], groups):
            box.set_facecolor(_FAMILY_COLOR.get(fam, "tab:gray"))
            box.set_alpha(0.7)
        for med in bp["medians"]:
            med.set_color("black")
        ax.set_xticks(positions)
        ax.set_xticklabels([_FAMILY_DISPLAY[g[0]] for g in groups],
                           rotation=30, ha="right", fontsize=8)
        ax.set_title(f"{t} ({primary})", fontsize=10)
        ax.tick_params(axis="y", labelsize=8)

    for k in range(len(tasks), len(axes_flat)):
        axes_flat[k].set_axis_off()
    fig.suptitle("Per-family primary-metric distribution by task", fontsize=11)
    fig.tight_layout(rect=[0, 0.0, 1, 0.97])
    return _save_fig(fig, output_path)


# ---------------------------------------------------------------------------
# Figure 5: ZS vs FT (T1)
# ---------------------------------------------------------------------------

def fig_zs_vs_ft(df: pd.DataFrame, output_path: Path) -> tuple[Path, Path]:
    """Single-panel bar chart comparing ZS vs FT on T1 for the LLM family."""
    fig, ax = plt.subplots(1, 1, figsize=(6.5, 4.0))

    if df.empty:
        ax.text(0.5, 0.5, "no records", ha="center", va="center",
                transform=ax.transAxes); ax.set_axis_off()
        return _save_fig(fig, output_path)

    sub = df[(df["task"] == "T1") & (df["metric_name"] == "mse")].copy()
    sub["family"] = sub["method_family"].map(_canonical_family)
    sub["display"] = sub["method_id"].map(_method_display)
    sub["base_id"] = sub["method_id"].str.replace(r"_(zs|ft)$", "", regex=True)

    # ZS-vs-FT pair: zero-shot LLMs ("llm") vs fine-tuned LLMs ("llm_ft").
    # The current panel reports zero-shot only, so the FT side stays empty
    # and the deferred-placeholder branch below handles the no-data case.
    title, fam_pair = "LLM", ["llm", "llm_ft"]
    zs = sub[sub["family"] == fam_pair[0]]
    ft = sub[sub["family"] == fam_pair[1]]
    if zs.empty and ft.empty:
        ax.text(0.5, 0.5, f"{title}: no data", ha="center", va="center",
                transform=ax.transAxes); ax.set_axis_off()
        fig.suptitle("Zero-shot vs fine-tuned, T1 only", fontsize=11)
        fig.tight_layout(rect=[0, 0, 1, 0.97])
        return _save_fig(fig, output_path)

    zs_avg = (zs.groupby("base_id", as_index=False)["value"].mean()
                .rename(columns={"value": "zs"}))
    ft_avg = (ft.groupby("base_id", as_index=False)["value"].mean()
                .rename(columns={"value": "ft"}))
    merged = zs_avg.merge(ft_avg, on="base_id", how="outer")
    if merged.empty:
        ax.text(0.5, 0.5, f"{title}: no data", ha="center", va="center",
                transform=ax.transAxes); ax.set_axis_off()
        fig.suptitle("Zero-shot vs fine-tuned, T1 only", fontsize=11)
        fig.tight_layout(rect=[0, 0, 1, 0.97])
        return _save_fig(fig, output_path)

    merged = merged.sort_values("base_id").reset_index(drop=True)
    x = np.arange(len(merged))
    w = 0.36
    ax.bar(x - w/2, merged["zs"].fillna(np.nan), width=w,
           color=_FAMILY_COLOR[fam_pair[0]], label="ZS",
           edgecolor="black", linewidth=0.4)
    ax.bar(x + w/2, merged["ft"].fillna(np.nan), width=w,
           color=_FAMILY_COLOR[fam_pair[1]], label="FT",
           edgecolor="black", linewidth=0.4)
    ax.set_xticks(x)
    ax.set_xticklabels(merged["base_id"], rotation=30, ha="right", fontsize=8)
    ax.set_title(f"{title} family — T1 MSE (lower = better)", fontsize=10)
    ax.set_ylabel("MSE", fontsize=9)
    ax.legend(fontsize=8, frameon=False)

    fig.suptitle("Zero-shot vs fine-tuned, T1 only", fontsize=11)
    fig.tight_layout(rect=[0, 0, 1, 0.97])
    return _save_fig(fig, output_path)


# ---------------------------------------------------------------------------
# Driver
# ---------------------------------------------------------------------------

ALL_FIGURES: tuple[str, ...] = (
    "panel_overview",
    "primary_metric_per_task",
    "per_family_box",
    "zs_vs_ft",
)


def render_all(
    df: pd.DataFrame,
    output_dir: Path,
    *,
    granularity: str = "daily",
    quick: bool = False,
) -> dict[str, tuple[Path, Path]]:
    """Render every paper figure from the long-form aggregator output.

    *quick* downsamples the long-form input to the first 32 rows of each
    (task, method) group to keep CI runs fast.
    """
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    out: dict[str, tuple[Path, Path]] = {}

    if quick and not df.empty:
        df = (
            df.groupby(["task", "method_id"], as_index=False, group_keys=False)
              .head(32)
        )

    out["panel_overview"] = fig_panel_overview(df, output_dir / "fig_panel_overview")
    out["primary_metric_per_task"] = fig_primary_metric_per_task(
        df, output_dir / "fig_primary_metric_per_task")
    out["per_family_box"] = fig_per_family_box(df, output_dir / "fig_per_family_box")
    out["zs_vs_ft"] = fig_zs_vs_ft(df, output_dir / "fig_zs_vs_ft")
    return out


def _df_from_glob(input_glob: str) -> pd.DataFrame:
    paths = [Path(p) for p in sorted(glob.glob(input_glob))]
    records, n_skip, n_mig = _load_records(paths)
    logger.info("loaded %d records (%d non-ok, %d migrated v1->v2)",
                len(records), n_skip, n_mig)
    return _records_to_long_df(records)


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--results-glob", type=str,
        default=str(Path(__file__).resolve().parent / "results" / "canon_*.json"),
        help="Glob pointing to RunRecord JSON files.",
    )
    parser.add_argument(
        "--output-dir", type=Path,
        default=Path(__file__).resolve().parent / "paper_artifacts" / "figures",
        help="Directory to write fig_*.pdf / fig_*.png pairs.",
    )
    parser.add_argument(
        "--granularity", default="daily",
        choices=["daily", "weekly", "monthly"],
    )
    parser.add_argument(
        "--quick", action="store_true",
        help="Downsample long-form input for faster CI runs.",
    )
    args = parser.parse_args(argv)

    logging.basicConfig(level=logging.INFO, format="%(levelname)s  %(message)s")
    df = _df_from_glob(args.results_glob)
    out = render_all(df, args.output_dir, granularity=args.granularity, quick=args.quick)
    for name, (pdf, png) in out.items():
        logger.info("wrote %s -> %s", name, pdf)
    return 0


if __name__ == "__main__":  # pragma: no cover
    import sys
    sys.exit(main())