Download code/experiments/gen_tables.py from DeepAuto-AI/MacroLens: direct link, hf CLI and curl.
- Browser
- Download file 28.3 kB
-
https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/experiments/gen_tables.py
- Command line
-
hf download hf://datasets/DeepAuto-AI/MacroLens/code/experiments/gen_tables.py
-
curl -L -o gen_tables.py https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/experiments/gen_tables.py
28.3 kB
| """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() | |