protostar-climate-2026 / code /run_v2_cdd.py
Tonic's picture
Protostar Climate submission: v2 forecast + v3/DCPP amendment audit (29 gated candidates)
49f3de8 verified
Raw History Blame Contribute Delete
4.19 kB
"""Phase 2/3: CDD delta candidates + homogenisation variants for temp/CDD."""
from __future__ import annotations
import sys
from pathlib import Path
import numpy as np
import pandas as pd
sys.path.insert(0, str(Path(__file__).parent))
from candidates import level_trend
from cdd_delta import CddDelta
from harness import evaluate, skill_table
from homogenise import segonly_panel, stepadj_panel
from panel import Panel
def show(metric: str, detail: pd.DataFrame, tag: str) -> None:
tab = skill_table(detail)
piv = tab.pivot_table(index="candidate", columns="era", values="skill")
g = detail.groupby("candidate").apply(
lambda s: 1 - (s.sum_err.sum() / s.n.sum()) / (s.sum_err_ref.sum() / s.n.sum()),
include_groups=False)
piv["all"] = g
print(f"\n== {metric} [{tag}] ==")
print(piv.sort_values("tune", ascending=False).round(4).to_string())
def main() -> None:
root = Path(__file__).resolve().parent.parent
panel = Panel(root)
delta = CddDelta(root, panel)
out = root / "outputs" / "v2"
linear15 = lambda p, o: level_trend(p, "cdd", o, 15, "mean", "nat", 40, clip_zero=True)
cands = {}
for hist in (15, 30):
for agg in ("median", "mean"):
for trend in ("nat", "reg"):
name = f"delta_h{hist}_{agg}_{trend}"
cands[name] = (lambda h, a, t: lambda p, o: delta.forecast(o, h, a, t))(hist, agg, trend)
# Blends with linear L15.
for hist, agg in ((15, "median"), (30, "median")):
name = f"blend50_delta_h{hist}_{agg}_nat"
cands[name] = (lambda h, a: lambda p, o: 0.5 * delta.forecast(o, h, a, "nat")
+ 0.5 * linear15(p, o))(hist, agg)
cands["linear_L15_natW40"] = linear15
detail = evaluate(panel, "cdd", cands)
detail.to_csv(out / "detail_cdd_delta.csv", index=False)
show("cdd", detail, "delta vs linear, raw panel")
# Homogenisation variants: forecasts from variant panels, scored on RAW truth.
seg = segonly_panel(root, panel)
adj = stepadj_panel(root, panel)
def evaluate_mixed(metric: str, variants: dict) -> pd.DataFrame:
from candidates import baseline_mean30
from harness import ORIGINS, TUNE_ORIGINS
rows = []
for origin in ORIGINS:
truth, mask = panel.truth(metric, origin)
ref = baseline_mean30(panel, metric, origin)
forecasts = {name: fn(vp, origin) for name, (vp, fn) in variants.items()}
for h in range(7):
m = mask[:, h]
if not m.any():
continue
t = truth[m, h]
for name, fc in forecasts.items():
if not np.isfinite(fc[m, h]).all():
raise ValueError(f"{name} non-finite at origin {origin}")
rows.append({"metric": metric, "origin": origin,
"target_year": origin + h + 1, "lead": h + 1,
"era": "tune" if origin in TUNE_ORIGINS else "check",
"n": int(m.sum()), "candidate": name,
"sum_err": float(np.abs(fc[m, h] - t).sum()),
"sum_err_ref": float(np.abs(ref[m, h] - t).sum())})
return pd.DataFrame(rows)
temp_fn = lambda p, o: level_trend(p, "annual_avg_temp", o, 15, "mean", "nat", 40)
detail_h = evaluate_mixed("annual_avg_temp", {
"L15_raw": (panel, temp_fn),
"L15_segonly": (seg, temp_fn),
"L15_stepadj": (adj, temp_fn),
})
detail_h.to_csv(out / "detail_temp_homog.csv", index=False)
show("annual_avg_temp", detail_h, "homogenisation, raw truth")
cdd_fn = lambda p, o: level_trend(p, "cdd", o, 15, "mean", "nat", 40, clip_zero=True)
detail_hc = evaluate_mixed("cdd", {
"L15_raw": (panel, cdd_fn),
"L15_segonly": (seg, cdd_fn),
})
detail_hc.to_csv(out / "detail_cdd_homog.csv", index=False)
show("cdd", detail_hc, "homogenisation, raw truth")
if __name__ == "__main__":
main()