File size: 9,053 Bytes
029e02e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""One-shot paper-artifact builder for the MacroLens NeurIPS 2026 D&B paper.

After every method has finished running and ``experiments/results/`` is
populated with ``RunRecord`` JSONs, this script bundles every downstream
artefact the paper consumes:

* **Aggregation** -- ``aggregate_results.aggregate(...)`` writes a long-form
  parquet to ``paper_artifacts/aggregate.parquet``.
* **Tables**      -- ``gen_tables.gen_tab_*`` writes 8 ``tab_<name>.tex``
  files into ``paper_artifacts/tables/``. Both the legacy nested-dict
  ``all_results[_quick].json`` (when present) and the new RunRecord glob are
  searched; whichever is available is used.
* **Figures**     -- ``gen_figures.render_all`` writes 5 ``fig_<name>.pdf``
  + ``fig_<name>.png`` pairs into ``paper_artifacts/figures/``.
* **Analysis**    -- ``analysis.run_all_analyses`` writes an
  ``analysis_results.json`` into the benchmark dir AND copies it to
  ``paper_artifacts/analysis/``.

CLI::

    python -m projects.agent_builder.scripts.whatif_bench.experiments.build_paper_artifacts \\
        --results-glob 'experiments/results/canon_*.json' \\
        --granularity   daily

Output tree (experiments/paper_artifacts/ -- experiment artifacts, NOT
under data_small_caps/, which is reserved for raw + derived data)::

    experiments/paper_artifacts/
        aggregate.parquet
        leaderboard.txt          (per-task primary-metric leaderboard)
        tables/   tab_*.tex
        figures/  fig_*.pdf, fig_*.png
        analysis/ analysis_results.json
"""

from __future__ import annotations

import argparse
import glob
import json
import logging
import shutil
from pathlib import Path
from typing import Any

from .. import config
from . import analysis as analysis_mod
from . import gen_figures
from . import gen_tables
from . import panel
from .aggregate_results import (
    _PRIMARY_METRIC_KEY,
    _PRIMARY_METRIC_LOWER_IS_BETTER,
    aggregate,
    print_summary,
)


logger = logging.getLogger(__name__)


def _legacy_results_dict(granularity: str) -> dict[str, Any]:
    """Return the legacy nested-dict ``all_results[_quick].json`` if present.

    These files used to live under ``data_small_caps/benchmark/<g>/`` but
    moved to ``experiments/results/legacy_per_family/`` once experiment
    outputs were separated from the benchmark tree. The granularity
    argument is kept for API compatibility with older callers; the
    legacy aggregates are not per-granularity (the file was overwritten
    by each granularity's runner).
    """
    del granularity  # legacy aggregates are not per-granularity on disk
    legacy_dir = Path(__file__).resolve().parent / "results" / "legacy_per_family"
    for cand in ("all_results.json", "all_results_quick.json"):
        p = legacy_dir / cand
        if p.exists():
            try:
                return json.loads(p.read_text())
            except (OSError, json.JSONDecodeError) as exc:
                logger.warning("could not read %s: %s", p, exc)
    return {}


def _write_leaderboard(per_task, output_path: Path) -> None:
    lines: list[str] = []
    lines.append("=== MacroLens leaderboard (per-task, primary-metric ranked) ===\n")
    for task in panel.ALL_TASKS:
        df = per_task.get(task)
        primary = _PRIMARY_METRIC_KEY.get(task, "?")
        if df is None or df.empty:
            lines.append(f"\n[{task}] (no records)\n")
            continue
        sub = df[df["metric_name"] == primary].dropna(subset=["value"]).copy()
        if sub.empty:
            lines.append(f"\n[{task}] primary metric '{primary}' missing.\n")
            continue
        agg = (sub.groupby(["method_id", "method_family"])["value"]
                  .mean().reset_index())
        ascending = _PRIMARY_METRIC_LOWER_IS_BETTER.get(task, True)
        agg = agg.sort_values("value", ascending=ascending).reset_index(drop=True)
        direction = "lower" if ascending else "higher"
        lines.append(f"\n[{task}] primary={primary} ({direction}=better):\n")
        for i, row in agg.iterrows():
            lines.append(f"  {i+1:2d}. {row['method_id']:30s} "
                         f"({row['method_family']:18s}) {row['value']:10.4f}\n")
    output_path.write_text("".join(lines))


def build(
    *,
    results_glob: str,
    granularity: str,
    output_dir: Path,
    quick: bool = False,
) -> dict[str, Any]:
    """Build every paper artefact under *output_dir*.

    Returns a manifest dict with the on-disk paths of the produced
    artefacts (handy for downstream LaTeX-build orchestration / CI).
    """
    output_dir = Path(output_dir)
    tables_dir = output_dir / "tables"
    figs_dir = output_dir / "figures"
    analysis_dir = output_dir / "analysis"
    for d in (output_dir, tables_dir, figs_dir, analysis_dir):
        d.mkdir(parents=True, exist_ok=True)

    manifest: dict[str, Any] = {
        "results_glob": results_glob,
        "granularity": granularity,
        "tables": {},
        "figures": {},
        "analysis": None,
        "leaderboard": None,
        "aggregate_parquet": None,
    }

    # 1. Aggregate RunRecord JSONs.
    parquet_path = output_dir / "aggregate.parquet"
    per_task = aggregate(input_glob=results_glob, output_path=parquet_path)
    manifest["aggregate_parquet"] = str(parquet_path) if parquet_path.exists() else None

    # 2. Per-task leaderboard.
    leaderboard_path = output_dir / "leaderboard.txt"
    _write_leaderboard(per_task, leaderboard_path)
    manifest["leaderboard"] = str(leaderboard_path)
    print_summary(per_task)

    # 3. LaTeX tables (use legacy nested-dict if available; tables degrade
    #    gracefully to "--" otherwise).
    legacy = _legacy_results_dict(granularity)
    table_calls: list[tuple[str, Any]] = [
        ("tsf",        gen_tables.gen_tab_tsf(legacy, granularity)),
        ("valuation",  gen_tables.gen_tab_valuation(legacy)),
        ("generation", gen_tables.gen_tab_generation(legacy)),
        ("scenario",   gen_tables.gen_tab_scenario(legacy)),
        ("re",         gen_tables.gen_tab_re(legacy)),
        ("zs_vs_ft",   gen_tables.gen_tab_zs_vs_ft(legacy, granularity)),
        ("ablation",   gen_tables.gen_tab_ablation(legacy)),
        ("panel",      gen_tables.gen_tab_panel_summary()),
    ]
    for name, body in table_calls:
        path = tables_dir / f"tab_{name}.tex"
        path.write_text(body)
        manifest["tables"][name] = str(path)

    # 4. Figures.
    long_df = None
    try:
        # Reuse the long-form DataFrame already produced by aggregate(); we
        # have to re-build it because aggregate() returns per-task split.
        from .aggregate_results import _load_records, _records_to_long_df
        paths = [Path(p) for p in sorted(glob.glob(results_glob))]
        recs, _, _ = _load_records(paths)
        long_df = _records_to_long_df(recs)
    except Exception as exc:  # pragma: no cover -- defensive
        logger.warning("could not build long-form DF for figures: %s", exc)
    if long_df is None:
        import pandas as pd
        long_df = pd.DataFrame()
    fig_outputs = gen_figures.render_all(
        long_df, figs_dir, granularity=granularity, quick=quick,
    )
    manifest["figures"] = {
        n: {"pdf": str(pdf), "png": str(png)} for n, (pdf, png) in fig_outputs.items()
    }

    # 5. Stratified analysis.
    try:
        analysis_results = analysis_mod.run_all_analyses(granularity)
        analysis_out = analysis_dir / "analysis_results.json"
        analysis_out.write_text(json.dumps(analysis_results, indent=2, default=str))
        manifest["analysis"] = str(analysis_out)
    except Exception as exc:
        logger.warning("analysis pipeline failed: %s", exc)
        manifest["analysis_error"] = str(exc)

    # 6. Manifest.
    manifest_path = output_dir / "manifest.json"
    manifest_path.write_text(json.dumps(manifest, indent=2, default=str))
    return manifest


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--results-glob", type=str,
        # Results live under experiments/results/, NOT data_small_caps/.
        default=str(Path(__file__).parent / "results" / "canon_*.json"),
    )
    parser.add_argument(
        "--granularity", default="daily",
        choices=["daily", "weekly", "monthly"],
    )
    parser.add_argument(
        "--output-dir", type=Path,
        default=Path(__file__).parent / "paper_artifacts",
    )
    parser.add_argument("--quick", action="store_true",
                        help="Downsample inputs to keep CI runs fast.")
    args = parser.parse_args(argv)

    logging.basicConfig(level=logging.INFO, format="%(levelname)s  %(message)s")
    manifest = build(
        results_glob=args.results_glob,
        granularity=args.granularity,
        output_dir=args.output_dir,
        quick=args.quick,
    )
    logger.info("paper artefacts manifest: %s", manifest.get("aggregate_parquet"))
    return 0


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