Download code/harness_v3.py from Tonic/protostar-climate-2026: direct link, hf CLI and curl.
- Browser
- Download file 4.92 kB
-
https://huggingface.co/datasets/Tonic/protostar-climate-2026/resolve/main/code/harness_v3.py
- Command line
-
hf download hf://datasets/Tonic/protostar-climate-2026/code/harness_v3.py
-
curl -L -o harness_v3.py https://huggingface.co/datasets/Tonic/protostar-climate-2026/resolve/main/code/harness_v3.py
4.92 kB
| """V3 rolling-origin harness: selection era 1990-2004, confirmation 2005-2011. | |
| Separate from harness.py so v2 results stay byte-reproducible. Adds signed | |
| bias (forecast - truth) per lead so cold/warm bias is visible, and keeps the | |
| v2 finite-forecast assertion (a NaN forecast must never be silently skipped). | |
| """ | |
| from __future__ import annotations | |
| import numpy as np | |
| import pandas as pd | |
| from candidates import baseline_mean30 | |
| from panel import Panel | |
| SELECTION_ORIGINS = list(range(1990, 2005)) | |
| CONFIRMATION_ORIGINS = list(range(2005, 2012)) | |
| ALL_ORIGINS = SELECTION_ORIGINS + CONFIRMATION_ORIGINS | |
| def era_of(origin: int) -> str: | |
| return "selection" if origin in SELECTION_ORIGINS else "confirmation" | |
| def evaluate_v3(panel: Panel, metric: str, candidates: dict, | |
| origins=SELECTION_ORIGINS, truth_panel: Panel | None = None) -> pd.DataFrame: | |
| """Score candidates; truth/baseline always from `panel` unless truth_panel given.""" | |
| tp = truth_panel or panel | |
| rows = [] | |
| for origin in origins: | |
| truth, mask = tp.truth(metric, origin) | |
| ref = baseline_mean30(tp, metric, origin) | |
| forecasts = {name: fn(panel, origin) for name, fn in candidates.items()} | |
| for name, fc in forecasts.items(): | |
| if fc.shape != truth.shape: | |
| raise ValueError(f"{name}: shape {fc.shape} != truth {truth.shape}") | |
| for h in range(7): | |
| m = mask[:, h] | |
| if not m.any(): | |
| continue | |
| t = truth[m, h] | |
| base = {"metric": metric, "origin": origin, | |
| "target_year": origin + h + 1, "lead": h + 1, | |
| "era": era_of(origin), "n": int(m.sum()), | |
| "sum_err_ref": float(np.abs(ref[m, h] - t).sum())} | |
| for name, fc in forecasts.items(): | |
| if not np.isfinite(fc[m, h]).all(): | |
| raise ValueError(f"{name} produced non-finite forecasts " | |
| f"for scored rows at origin {origin}, lead {h + 1}") | |
| rows.append({**base, "candidate": name, | |
| "sum_err": float(np.abs(fc[m, h] - t).sum()), | |
| "sum_signed": float((fc[m, h] - t).sum())}) | |
| return pd.DataFrame(rows) | |
| def skill_table_v3(detail: pd.DataFrame) -> pd.DataFrame: | |
| rows = [] | |
| for (cand, metric, era), sub in detail.groupby(["candidate", "metric", "era"]): | |
| mae = sub["sum_err"].sum() / sub["n"].sum() | |
| mae_ref = sub["sum_err_ref"].sum() / sub["n"].sum() | |
| rows.append({"candidate": cand, "metric": metric, "era": era, | |
| "skill": 1 - mae / mae_ref, "mae": mae, | |
| "bias_per_row": sub["sum_signed"].sum() / sub["n"].sum(), | |
| "n": int(sub["n"].sum())}) | |
| return pd.DataFrame(rows) | |
| def bootstrap_skill_diff_v3(detail: pd.DataFrame, cand_a: str, cand_b: str, | |
| metric: str, era: str | None = None, | |
| n_boot: int = 500, seed: int = 0) -> dict: | |
| """Year-block bootstrap of skill(a) - skill(b); same method as v2.""" | |
| d = detail[detail["metric"] == metric] | |
| if era: | |
| d = d[d["era"] == era] | |
| a = d[d["candidate"] == cand_a].groupby("target_year")[["sum_err", "n", "sum_err_ref"]].sum() | |
| b = d[d["candidate"] == cand_b].groupby("target_year")[["sum_err", "n", "sum_err_ref"]].sum() | |
| j = a.join(b, lsuffix="_a", rsuffix="_b", how="inner") | |
| if len(j) < 5: | |
| raise ValueError(f"too few target years for bootstrap: {len(j)}") | |
| rng = np.random.default_rng(seed) | |
| years = j.index.to_numpy() | |
| diffs = [] | |
| for _ in range(n_boot): | |
| s = j.loc[rng.choice(years, size=len(years), replace=True)] | |
| diffs.append((1 - s["sum_err_a"].sum() / s["sum_err_ref_a"].sum()) | |
| - (1 - s["sum_err_b"].sum() / s["sum_err_ref_b"].sum())) | |
| diffs = np.array(diffs) | |
| return {"mean_diff": float(diffs.mean()), "se": float(diffs.std()), | |
| "p_diff_le_0": float((diffs <= 0).mean())} | |
| def gate(detail: pd.DataFrame, candidate: str, control: str, metric: str) -> dict: | |
| """Selection-era gate: candidate enters pool iff skill diff > 1 bootstrap SE.""" | |
| tab = skill_table_v3(detail) | |
| sel = tab[tab["era"] == "selection"].set_index("candidate") | |
| boot = bootstrap_skill_diff_v3(detail, candidate, control, metric, era="selection") | |
| diff = float(sel.loc[candidate, "skill"] - sel.loc[control, "skill"]) | |
| return {"candidate": candidate, "control": control, "metric": metric, | |
| "skill_selection_candidate": float(sel.loc[candidate, "skill"]), | |
| "skill_selection_control": float(sel.loc[control, "skill"]), | |
| "diff": diff, "boot_mean_diff": boot["mean_diff"], "boot_se": boot["se"], | |
| "passes": bool(diff > boot["se"])} | |