File size: 28,303 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
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
"""Generate LaTeX tables from MacroLens benchmark results.

Panel-driven: the method list comes from `experiments/panel.py` (the canonical
18-method registry: 4 naive + 2 classical + 3 sequence + 3 TSFM + 3 LLM
+ 2 LLM-TS-Multi + 1 LLM-FT), where the LLM-FT entry is a deferred-selection
slot resolved post-hoc (winner of the Family-6 ZS sweep) and rendered in
tab:zs_vs_ft / tab:ablation. Adding / removing methods updates the tables
without touching this file.

Tables produced (in dependency order, all driven by `panel.ALL_METHODS`):
  1. tab:tsf        - T1 results: methods covering T1 x horizons {5, 21, 63}
  2. tab:valuation  - T2 (Val-PT) + T5 (Priv-Val) side by side
  3. tab:generation - T3 (Stmt-Gen) + T6 (Gen-Eval) side by side
  4. tab:scenario   - T4 (Scen-Ret)
  5. tab:re         - T7 (RE-Val)
  6. tab:zs_vs_ft   - ZS vs FT for the deferred-FT cell (LLM-FT)
  7. tab:ablation   - 5 settings x 4 tasks for the deferred-selection model

Usage:
    uv run python -m projects.agent_builder.scripts.whatif_bench.experiments.gen_tables
    uv run python -m projects.agent_builder.scripts.whatif_bench.experiments.gen_tables --full
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any

import pandas as pd

from .. import config
from . import panel


# ----------------------------------------------------------------------------
# Result loading
# ----------------------------------------------------------------------------
# Canonical results live in ``experiments/paper_artifacts/aggregate.parquet``
# (one long-form row per (task, method_id, metric_name) with value + CIs).
# The legacy ``experiments/results/legacy_per_family/all_results.json``
# path is still consulted as a fallback (the file used to live under
# ``data_small_caps/benchmark/<g>/`` but moved to experiments/ once
# experiment outputs were separated from the benchmark tree); for new
# submissions the parquet is the single source of truth.


def _aggregate_path() -> Path:
    return Path(__file__).resolve().parent / "paper_artifacts" / "aggregate.parquet"


def _load_aggregate() -> pd.DataFrame | None:
    p = _aggregate_path()
    if not p.exists():
        return None
    try:
        return pd.read_parquet(p)
    except Exception as exc:  # pragma: no cover -- IO-level failure
        print(f"warning: could not read {p}: {exc}", file=sys.stderr)
        return None


def _load_results(granularity: str = "daily", quick: bool = True) -> dict[str, Any]:
    """Legacy nested-dict results loader.

    Retained so the ``--legacy-json`` path that pre-dates the canon
    aggregate keeps working. The primary table-generation path now
    consumes :func:`_load_aggregate` and only falls back to the legacy
    JSON when the parquet is missing. The legacy aggregates used to live
    under ``data_small_caps/benchmark/<g>/all_results*.json`` but moved
    to ``experiments/results/legacy_per_family/`` once experiment
    outputs were separated from the benchmark tree; ``granularity`` is
    kept for API compatibility (legacy aggregates are not per-granularity
    on disk).
    """
    del granularity  # legacy aggregates are not per-granularity on disk
    suffix = "_quick" if quick else ""
    legacy_dir = Path(__file__).resolve().parent / "results" / "legacy_per_family"
    path = legacy_dir / f"all_results{suffix}.json"
    if not path.exists():
        return {}
    return json.loads(path.read_text())


# ----------------------------------------------------------------------------
# Family routing: which family JSON does each method's results live under?
# ----------------------------------------------------------------------------
# Panel families and the orchestrator's per-family JSON keys are aligned
# 1:1 on the canonical names ("tsfm", "llm", "llm_ts"). The legacy panel
# ("tsfm_zs", "llm_zs", "llm_ts_multitask") was reconciled with the
# canon RunRecord families in experiments/panel.py; this map is now a
# trivial pass-through and is retained only so that adding a new family
# remains a one-line change.

_PANEL_FAMILY_TO_JSON_KEY: dict[str, str] = {
    "naive": "naive",
    "classical": "classical",
    "sequence": "sequence",
    "tsfm": "tsfm",
    "llm_ts": "llm_ts_reason",
    "llm": "llm",
}


# Each family's key-naming convention for the per-task result key. Kept here
# so the table generator never has to hardcode method-by-method.

def _result_key(method: panel.Method, task: panel.Task, horizon: int | None = None) -> list[str]:
    """Candidate result keys to try for (method, task) under that family's JSON.

    Returns a list because some families historically used multiple naming
    schemes; we try them in order and use the first that matches.
    """
    mid = method.id
    family = method.family
    keys: list[str] = []

    if task == "T1":
        if family in ("naive", "classical", "sequence", "tsfm"):
            keys.append(f"tsf_{mid}_h{horizon}")
        elif family in ("llm_ts", "llm"):
            keys.append(f"tsf_llm_{mid}_h{horizon}")
            keys.append(f"tsf_{mid}_h{horizon}")
            # llm_ts uses chattime_task_1 style:
            keys.append(f"{mid}_task_1_h{horizon}")
            keys.append(f"{mid}_task_1")
    elif task == "T2":
        keys.append(f"task_2_{mid}")
        if family == "llm":
            keys.append(f"task_2_llm_{mid}")
        if family == "llm_ts":
            keys.append(f"{mid}_task_2")
    elif task == "T3":
        keys.append(f"task_3_{mid}")
        if family == "llm":
            keys.append(f"task_3_llm_{mid}")
        if family == "llm_ts":
            keys.append(f"{mid}_task_3")
    elif task == "T4":
        keys.append(f"task_4_{mid}")
        if family == "naive":
            # historical_analogue lives under the alias "task_4_analogue"
            keys.append("task_4_analogue")
        if family == "llm":
            keys.append(f"task_4_llm_{mid}")
        if family == "llm_ts":
            keys.append(f"{mid}_task_4")
    elif task == "T5":
        keys.append(f"task_5_{mid}")
        if family == "llm":
            keys.append(f"task_5_llm_{mid}")
        if family == "llm_ts":
            keys.append(f"{mid}_task_5")
    elif task == "T6":
        keys.append(f"task_6_{mid}")
        if family == "llm":
            keys.append(f"task_6_llm_{mid}")
        if family == "llm_ts":
            keys.append(f"{mid}_task_6")
    elif task == "T7":
        keys.append(f"task_7_{mid}")
        if family == "llm":
            keys.append(f"task_7_llm_{mid}")
        if family == "llm_ts":
            keys.append(f"{mid}_task_7")

    return keys


def _get_family_data(data: dict, method: panel.Method) -> dict:
    """Navigate `data` to the family dict for `method`."""
    json_key = _PANEL_FAMILY_TO_JSON_KEY.get(method.family, method.family)
    fam = data.get(json_key, {})
    if not isinstance(fam, dict):
        return {}
    return fam


def _lookup(data: dict, method: panel.Method, task: panel.Task,
            horizon: int | None = None) -> dict:
    """Find the result dict for (method, task[, horizon]); empty dict if missing.

    When ``data`` is the long-form parquet DataFrame (preferred path), the
    return dict is a flat mapping ``metric_name -> value`` augmented with
    paired ``<metric>_ci_lo`` / ``<metric>_ci_hi`` keys so existing
    per-table functions keep their ``r.get("mse")`` shape but can opt
    into CI rendering with ``r.get("mse_ci_lo")`` / ``_ci_hi``.

    When ``data`` is the legacy nested dict, the lookup returns the cell
    as-is (no CIs available).
    """
    if isinstance(data, pd.DataFrame):
        df = data[(data["method_id"] == method.id) & (data["task"] == task)]
        # Main-table lookups exclude ablation cells (the A--E settings
        # live in tab:ablation, not the per-task headline tables).
        df = df[df["ablation_setting"].isna()]
        if df.empty:
            return {}
        # Most cells have a single granularity/seed; pick the latest
        # timestamp deterministically.
        df = df.sort_values("timestamp").groupby("metric_name").tail(1)
        out: dict[str, Any] = {}
        for _, row in df.iterrows():
            name = row["metric_name"]
            out[name] = row["value"]
            if pd.notna(row.get("ci_lo")):
                out[f"{name}_ci_lo"] = row["ci_lo"]
            if pd.notna(row.get("ci_hi")):
                out[f"{name}_ci_hi"] = row["ci_hi"]
            if pd.notna(row.get("n_boot")):
                out[f"{name}_n_boot"] = int(row["n_boot"])
        return out
    fam = _get_family_data(data, method)
    if not fam:
        return {}
    for key in _result_key(method, task, horizon):
        result = fam.get(key)
        if isinstance(result, dict) and "error" not in result:
            return result
    return {}


# ----------------------------------------------------------------------------
# Number formatting
# ----------------------------------------------------------------------------

def _f(v, fmt: str = ".2f", default: str = "--") -> str:
    if v is None:
        return default
    try:
        if isinstance(v, (int, float)) and v != v:  # NaN check
            return default
        return format(float(v), fmt)
    except (TypeError, ValueError):
        return default


def _f_ci(value, ci_lo, ci_hi, fmt: str = ".2f", default: str = "--") -> str:
    """Format ``value [lo, hi]`` if CI is present; fall back to ``value``."""
    point = _f(value, fmt, default)
    if point == default:
        return default
    if ci_lo is None or ci_hi is None:
        return point
    try:
        if (isinstance(ci_lo, float) and ci_lo != ci_lo) or (
            isinstance(ci_hi, float) and ci_hi != ci_hi
        ):
            return point
    except TypeError:
        return point
    return (
        rf"{point}\,{{\scriptsize [{_f(ci_lo, fmt, default)},"
        rf"\,{_f(ci_hi, fmt, default)}]}}"
    )


def _pct(v) -> str:
    """Format a fraction (0..1) as `xx.x` percent."""
    if v is None:
        return "--"
    try:
        return f"{float(v) * 100:.1f}"
    except (TypeError, ValueError):
        return "--"


# ----------------------------------------------------------------------------
# Tables
# ----------------------------------------------------------------------------

def gen_tab_tsf(data: dict, granularity: str = "daily") -> str:
    """T1 (TSF) results across panel methods x horizons."""
    horizons = config.get_horizons(granularity)
    methods_t1 = [m for m in panel.ALL_METHODS if "T1" in m.tasks]

    n_h = len(horizons)
    col_spec = "ll " + " ".join(["rr"] * n_h)

    lines: list[str] = []
    lines.append(r"\begin{table}[t]")
    lines.append(r"\centering")
    lines.append(
        r"\caption{Task 1 (TSF) results, "
        f"{granularity}, lookback={config.get_lookback_windows(granularity)[0]}. "
        r"Best per-column \textbf{bold}.}")
    lines.append(r"\label{tab:tsf}")
    lines.append(r"\resizebox{\textwidth}{!}{%")
    lines.append(r"\begin{tabular}{" + col_spec + "}")
    lines.append(r"\toprule")
    headers = " & ".join(
        rf"\multicolumn{{2}}{{c}}{{\textbf{{H={h}}}}}" for h in horizons
    )
    lines.append(rf"& & {headers} \\")
    cmidrules = " ".join(
        rf"\cmidrule(lr){{{3 + 2*i}-{4 + 2*i}}}" for i in range(n_h)
    )
    lines.append(cmidrules)
    metric_hdr = " & ".join(["MSE", r"DA\%"] * n_h)
    lines.append(rf"\textbf{{Family}} & \textbf{{Method}} & {metric_hdr} \\")
    lines.append(r"\midrule")

    last_family: str | None = None
    for m in methods_t1:
        # Group by family with a midrule between groups.
        if last_family is not None and m.family != last_family:
            lines.append(r"\midrule")
        fam_label = m.family.replace("_", " ") if m.family != last_family else ""
        last_family = m.family
        row = [fam_label, m.name]
        for h in horizons:
            r = _lookup(data, m, "T1", horizon=h)
            if "overall" in r and isinstance(r["overall"], dict):
                mse = r["overall"].get("mse")
                mse_lo = mse_hi = None
                da = r["overall"].get("directional_accuracy")
            else:
                mse = r.get("mse")
                mse_lo = r.get("mse_ci_lo")
                mse_hi = r.get("mse_ci_hi")
                da = r.get("directional_accuracy")
            row += [_f_ci(mse, mse_lo, mse_hi, ".1f"), _pct(da)]
        lines.append(" & ".join(row) + r" \\")

    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


def gen_tab_valuation(data: dict) -> str:
    """T2 (Val-PT) + T5 (Priv-Val) side by side. MedAPE% / Spearman."""
    methods = [m for m in panel.ALL_METHODS if "T2" in m.tasks or "T5" in m.tasks]
    lines: list[str] = []
    lines.append(r"\begin{table}[t]")
    lines.append(r"\centering")
    lines.append(
        r"\caption{Valuation: Task~2 (Val-PT) vs Task~5 (Priv-Val). "
        r"MedAPE\%$\downarrow$, Spearman~$\rho\uparrow$.}")
    lines.append(r"\label{tab:valuation}")
    lines.append(r"\resizebox{\textwidth}{!}{%")
    lines.append(r"\begin{tabular}{ll cc cc}")
    lines.append(r"\toprule")
    lines.append(
        r"& & \multicolumn{2}{c}{\textbf{T2 Val-PT}} & "
        r"\multicolumn{2}{c}{\textbf{T5 Priv-Val}} \\")
    lines.append(r"\cmidrule(lr){3-4} \cmidrule(lr){5-6}")
    lines.append(
        r"\textbf{Family} & \textbf{Method} & "
        r"MedAPE\%$\downarrow$ & $\rho\uparrow$ & "
        r"MedAPE\%$\downarrow$ & $\rho\uparrow$ \\")
    lines.append(r"\midrule")

    last_family: str | None = None
    for m in methods:
        if last_family is not None and m.family != last_family:
            lines.append(r"\midrule")
        fam_label = m.family.replace("_", " ") if m.family != last_family else ""
        last_family = m.family
        row = [fam_label, m.name]
        for task in ("T2", "T5"):
            if task in m.tasks:
                r = _lookup(data, m, task)
                row += [
                    _f_ci(r.get("median_ape"),
                          r.get("median_ape_ci_lo"),
                          r.get("median_ape_ci_hi"), ".1f"),
                    _f(r.get("rank_correlation"), ".3f"),
                ]
            else:
                row += ["--", "--"]
        lines.append(" & ".join(row) + r" \\")

    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


def gen_tab_generation(data: dict) -> str:
    """T3 (Stmt-Gen) + T6 (Gen-Eval) side by side. Per-field MAPE%, Bal-Eq%."""
    methods = [m for m in panel.ALL_METHODS if "T3" in m.tasks or "T6" in m.tasks]
    lines: list[str] = []
    lines.append(r"\begin{table}[t]")
    lines.append(r"\centering")
    lines.append(
        r"\caption{Generation: Task~3 (Stmt-Gen) vs Task~6 (Gen-Eval). "
        r"per-field MAPE\%$\downarrow$, balance-equation accuracy\%$\uparrow$.}")
    lines.append(r"\label{tab:generation}")
    lines.append(r"\resizebox{\textwidth}{!}{%")
    lines.append(r"\begin{tabular}{ll cc cc}")
    lines.append(r"\toprule")
    lines.append(
        r"& & \multicolumn{2}{c}{\textbf{T3 Stmt-Gen}} & "
        r"\multicolumn{2}{c}{\textbf{T6 Gen-Eval}} \\")
    lines.append(r"\cmidrule(lr){3-4} \cmidrule(lr){5-6}")
    lines.append(
        r"\textbf{Family} & \textbf{Method} & "
        r"MAPE\%$\downarrow$ & Bal-Eq\%$\uparrow$ & "
        r"MAPE\%$\downarrow$ & Bal-Eq\%$\uparrow$ \\")
    lines.append(r"\midrule")

    last_family: str | None = None
    for m in methods:
        if last_family is not None and m.family != last_family:
            lines.append(r"\midrule")
        fam_label = m.family.replace("_", " ") if m.family != last_family else ""
        last_family = m.family
        row = [fam_label, m.name]
        for task in ("T3", "T6"):
            if task in m.tasks:
                r = _lookup(data, m, task)
                row += [
                    _f_ci(r.get("overall_mape"),
                          r.get("overall_mape_ci_lo"),
                          r.get("overall_mape_ci_hi"), ".1f"),
                    _pct(r.get("balance_equation_accuracy")),
                ]
            else:
                row += ["--", "--"]
        lines.append(" & ".join(row) + r" \\")

    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


def gen_tab_scenario(data: dict) -> str:
    """T4 (Scen-Ret): MAE%, DA%, CI calibration."""
    methods = [m for m in panel.ALL_METHODS if "T4" in m.tasks]
    lines: list[str] = []
    lines.append(r"\begin{table}[t]")
    lines.append(r"\centering")
    lines.append(
        r"\caption{Task~4 (Scen-Ret). Predict post-event return. "
        r"Best per-column \textbf{bold}.}")
    lines.append(r"\label{tab:scenario}")
    lines.append(r"\resizebox{0.85\textwidth}{!}{%")
    lines.append(r"\begin{tabular}{ll ccc}")
    lines.append(r"\toprule")
    lines.append(
        r"\textbf{Family} & \textbf{Method} & "
        r"MAE\%$\downarrow$ & DA\%$\uparrow$ & CI Cal.\%$\uparrow$ \\")
    lines.append(r"\midrule")

    last_family: str | None = None
    for m in methods:
        if last_family is not None and m.family != last_family:
            lines.append(r"\midrule")
        fam_label = m.family.replace("_", " ") if m.family != last_family else ""
        last_family = m.family
        r = _lookup(data, m, "T4")
        row = [
            fam_label, m.name,
            _f_ci(r.get("return_mae_pct"),
                  r.get("return_mae_pct_ci_lo"),
                  r.get("return_mae_pct_ci_hi"), ".2f"),
            _pct(r.get("directional_accuracy")),
            _pct(r.get("ci_calibration_95")),
        ]
        lines.append(" & ".join(row) + r" \\")

    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


def gen_tab_re(data: dict) -> str:
    """T7 (RE-Val): Rent MAPE / Price MAPE."""
    methods = [m for m in panel.ALL_METHODS if "T7" in m.tasks]
    lines: list[str] = []
    lines.append(r"\begin{table}[t]")
    lines.append(r"\centering")
    lines.append(
        r"\caption{Task~7 (RE-Val). Rent and price prediction across 100 metros.}")
    lines.append(r"\label{tab:re}")
    lines.append(r"\resizebox{0.7\textwidth}{!}{%")
    lines.append(r"\begin{tabular}{ll cc}")
    lines.append(r"\toprule")
    lines.append(
        r"\textbf{Family} & \textbf{Method} & "
        r"Rent MAPE\%$\downarrow$ & Price MAPE\%$\downarrow$ \\")
    lines.append(r"\midrule")

    last_family: str | None = None
    for m in methods:
        if last_family is not None and m.family != last_family:
            lines.append(r"\midrule")
        fam_label = m.family.replace("_", " ") if m.family != last_family else ""
        last_family = m.family
        r = _lookup(data, m, "T7")
        row = [
            fam_label, m.name,
            _f_ci(r.get("rent_MAPE"),
                  r.get("rent_MAPE_ci_lo"),
                  r.get("rent_MAPE_ci_hi"), ".1f"),
            _f_ci(r.get("price_MAPE"),
                  r.get("price_MAPE_ci_lo"),
                  r.get("price_MAPE_ci_hi"), ".1f"),
        ]
        lines.append(" & ".join(row) + r" \\")

    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


def gen_tab_zs_vs_ft(data: dict, granularity: str = "daily") -> str:
    """ZS vs FT comparison for the deferred-FT cell.

    Empty stub when `panel.LLM_FT_PANEL_HF_IDS` is empty. Once the
    deferred-selection rule populates that tuple, the table will resolve
    to the chosen FT cell automatically.
    """
    horizons = config.get_horizons(granularity)
    lines: list[str] = []
    lines.append(r"\begin{table}[t]")
    lines.append(r"\centering")
    lines.append(
        r"\caption{Zero-shot vs fine-tuned comparison. "
        r"Deferred-selection: a single FT cell for the panel-best "
        r"Family-6 ZS LLM (see paper \S6 / panel.py).}")
    lines.append(r"\label{tab:zs_vs_ft}")

    if not panel.LLM_FT_PANEL_HF_IDS:
        lines.append(
            r"\textit{Deferred -- target not yet selected from the full ZS sweep. "
            r"Selection rule pre-registered in \texttt{experiments/panel.py}.}")
        lines.append(r"\end{table}")
        return "\n".join(lines)

    # Both deferred slots resolved -> full table. Currently unreached.
    lines.append(
        r"\resizebox{\textwidth}{!}{%"
        r"\begin{tabular}{l " + " ".join(["rrr"] * len(horizons)) + "}")
    lines.append(r"\toprule")
    h_hdr = " & ".join(
        rf"\multicolumn{{3}}{{c}}{{\textbf{{H={h}}}}}" for h in horizons
    )
    lines.append(rf"& {h_hdr} \\")
    cmid = " ".join(
        rf"\cmidrule(lr){{{2 + 3*i}-{4 + 3*i}}}" for i in range(len(horizons))
    )
    lines.append(cmid)
    metric_hdr = " & ".join([r"ZS & FT & $\Delta$\%"] * len(horizons))
    lines.append(rf"\textbf{{Model}} & {metric_hdr} \\")
    lines.append(r"\midrule")
    # Rows resolved post-hoc once the deferred panels populate; left empty.
    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


def gen_tab_ablation(data: dict) -> str:
    """Family-9 ablation: 5 settings x 4 tasks for the deferred-selection model."""
    lines: list[str] = []
    lines.append(r"\begin{table}[t]")
    lines.append(r"\centering")
    lines.append(
        r"\caption{Context ablation. 5 feature settings (A-E) "
        r"$\times$ 4 tasks for the deferred-FT target.}")
    lines.append(r"\label{tab:ablation}")

    if not panel.ABLATION_MODEL_IDS:
        lines.append(
            r"\textit{Deferred -- ablation model resolves to the same target as "
            r"\texttt{LLM\_FT\_PANEL\_HF\_IDS} (post-hoc Family-7 ZS winner). "
            r"Selection rule pre-registered in \texttt{experiments/panel.py}.}")
        lines.append(r"\end{table}")
        return "\n".join(lines)

    # Once ABLATION_MODEL_IDS populates, render the 2 modes x 5 settings x 4 tasks.
    abl = data.get("ablation", {}) if isinstance(data.get("ablation"), dict) else {}
    settings = ["A", "B", "C", "D", "E"]

    # 4 tasks x 2 modes (ZS, FT) = 8 columns.
    col_spec = "ll " + " ".join(["rr"] * len(panel.ABLATION_TASKS))
    lines.append(r"\resizebox{\textwidth}{!}{%")
    lines.append(r"\begin{tabular}{" + col_spec + "}")
    lines.append(r"\toprule")
    task_hdr = " & ".join(
        rf"\multicolumn{{2}}{{c}}{{\textbf{{{t}}}}}" for t in panel.ABLATION_TASKS
    )
    lines.append(rf"& & {task_hdr} \\")
    cmid = " ".join(
        rf"\cmidrule(lr){{{3 + 2*i}-{4 + 2*i}}}" for i in range(len(panel.ABLATION_TASKS))
    )
    lines.append(cmid)
    mode_hdr = " & ".join(["ZS & FT"] * len(panel.ABLATION_TASKS))
    lines.append(rf"\textbf{{Setting}} & \textbf{{\#Feat}} & {mode_hdr} \\")
    lines.append(r"\midrule")

    for s in settings:
        s_meta = panel.ABLATION_SETTINGS[s]
        row = [s, str(s_meta["n_features"])]
        for t in panel.ABLATION_TASKS:
            for mode in panel.ABLATION_MODES:
                cell = abl.get(f"setting_{s}_{mode}_{t}", {})
                # Use the task's primary metric defined in panel.TASK_METADATA
                primary = panel.TASK_METADATA[t]["primary_metric"]
                key_map = {
                    "MSE": "mse",
                    "MedAPE": "median_ape",
                    "Return MAE": "return_mae_pct",
                    "per-field MAPE": "overall_mape",
                    "Rent + Price MAPE": "rent_MAPE",
                }
                k = key_map.get(primary, "mse")
                v = cell.get(k) if isinstance(cell, dict) else None
                row.append(_f(v, ".1f"))
        lines.append(" & ".join(row) + r" \\")

    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


def gen_tab_panel_summary() -> str:
    """Static appendix table: the 18-method panel from panel.py (incl. 1 deferred FT cell)."""
    lines: list[str] = []
    lines.append(r"\begin{table}[t]")
    lines.append(r"\centering")
    lines.append(
        r"\caption{MacroLens baseline panel. 17 fixed methods + 1 deferred-selection LLM-FT cell (post-hoc Family-6 ZS winner) = 18 entries.}")
    lines.append(r"\label{tab:panel}")
    lines.append(r"\begin{tabular}{lll l l}")
    lines.append(r"\toprule")
    lines.append(
        r"\textbf{Family} & \textbf{Method} & \textbf{HF id / source} & "
        r"\textbf{Tasks} & \textbf{Notes} \\")
    lines.append(r"\midrule")

    last_family: str | None = None
    for m in panel.ALL_METHODS:
        if last_family is not None and m.family != last_family:
            lines.append(r"\midrule")
        fam_label = m.family.replace("_", " ") if m.family != last_family else ""
        last_family = m.family
        tasks_str = ",".join(sorted(m.tasks))
        hf = m.hf_id or "--"
        # Truncate notes for table layout.
        note = m.notes.replace("\n", " ").strip()
        if len(note) > 60:
            note = note[:57] + "..."
        # Escape underscores for LaTeX in HF ids.
        hf_tex = hf.replace("_", r"\_")
        lines.append(
            f"{fam_label} & {m.name} & \\texttt{{{hf_tex}}} & {tasks_str} & {note} \\\\"
        )

    lines.append(r"\midrule")
    lines.append(
        r"\multicolumn{5}{l}{"
        r"\textit{Deferred: 1 LLM-FT cell (post-hoc Family-6 ZS winner).}} \\")

    lines.append(r"\bottomrule")
    lines.append(r"\end{tabular}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


# ----------------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------------

def _emit_all(data, granularity: str, output_dir: Path | None) -> None:
    print("% === MacroLens Paper Tables (panel-driven) ===")
    print(f"% panel summary: {panel.summary()}\n")

    tables = [
        ("tsf",        gen_tab_tsf(data, granularity)),
        ("valuation",  gen_tab_valuation(data)),
        ("generation", gen_tab_generation(data)),
        ("scenario",   gen_tab_scenario(data)),
        ("re",         gen_tab_re(data)),
        ("zs_vs_ft",   gen_tab_zs_vs_ft(data, granularity)),
        ("ablation",   gen_tab_ablation(data)),
        ("panel",      gen_tab_panel_summary()),
    ]
    for name, body in tables:
        print(f"\n% --- tab:{name} ---")
        print(body)
        if output_dir is not None:
            (output_dir / f"tab_{name}.tex").write_text(body)


def main():
    parser = argparse.ArgumentParser(
        description="Emit LaTeX tables for the MacroLens paper from aggregated results.",
    )
    parser.add_argument("--granularity", default="daily",
                        choices=["daily", "weekly", "monthly"])
    parser.add_argument("--legacy-json", action="store_true",
                        help=("Read the legacy nested-dict all_results.json "
                              "instead of the canon-aggregate parquet."))
    parser.add_argument("--full", action="store_true",
                        help=("Read full-run all_results.json instead of the "
                              "_quick variant (only meaningful with "
                              "--legacy-json)."))
    parser.add_argument("--out-dir", type=Path, default=None,
                        help="If provided, write each table to <out>/tab_<name>.tex.")
    args = parser.parse_args()

    if args.legacy_json:
        data: Any = _load_results(args.granularity, quick=not args.full)
    else:
        df = _load_aggregate()
        if df is None:
            print(
                f"error: aggregate.parquet not found at {_aggregate_path()}; "
                "run experiments/build_paper_artifacts.py or pass --legacy-json.",
                file=sys.stderr,
            )
            sys.exit(2)
        data = df

    if args.out_dir is not None:
        args.out_dir.mkdir(parents=True, exist_ok=True)
    _emit_all(data, args.granularity, args.out_dir)


if __name__ == "__main__":
    main()