protostar-climate-2026 / code /run_v3_amend.py
Tonic's picture
Protostar Climate submission: v2 forecast + v3/DCPP amendment audit (29 gated candidates)
49f3de8 verified
Raw History Blame Contribute Delete
5.73 kB
"""Amendment evaluation (organiser-approved items), selection era only.
Usage: .venv/Scripts/python.exe code/run_v3_amend.py [urban|eo|ml|dcpp|all]
Confirmation (2005-2011) is run only by a separate decision step if a gate passes.
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).parent))
from candidates_v3 import DailyCandidates, damped_temp, ew_slope_forecast, quantile_temp
from candidates_amend import (EoSimilarity, WalkForwardStacker,
eosim_forecast, load_impervious_proxy, urban_temp)
from harness_v3 import SELECTION_ORIGINS, evaluate_v3, gate, skill_table_v3
from leakage import assert_no_forbidden_artifacts
from panel import Panel
from run_v2_confirm import build_packages
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "outputs" / "v3"
class AmendContext:
def __init__(self):
self.panel, self.packages = build_packages()
self.v2 = {m: c["v2"] for m, c in self.packages.items()}
self._daily = None
self._eosim = None
self._proxy = None
@property
def daily(self) -> DailyCandidates:
if self._daily is None:
self._daily = DailyCandidates(ROOT, self.panel)
return self._daily
@property
def eosim(self) -> EoSimilarity:
if self._eosim is None:
self._eosim = EoSimilarity(ROOT, self.panel)
return self._eosim
@property
def proxy(self) -> np.ndarray:
if self._proxy is None:
self._proxy = load_impervious_proxy(ROOT, self.panel)
return self._proxy
def phase_candidates(ctx: AmendContext, phase: str) -> dict:
if phase == "urban":
return {"annual_avg_temp": {
"v2": ctx.v2["annual_avg_temp"],
"temp_urban_beta": lambda p, o: urban_temp(p, o, ctx.proxy),
}}
if phase == "eo":
return {
"annual_avg_temp": {
"v2": ctx.v2["annual_avg_temp"],
"temp_eosim_regW40": lambda p, o: eosim_forecast(p, o, "annual_avg_temp", ctx.eosim),
},
"cdd": {
"v2": ctx.v2["cdd"],
"cdd_eosim_regW40": lambda p, o: eosim_forecast(p, o, "cdd", ctx.eosim),
},
}
if phase == "ml":
temp_stack = WalkForwardStacker(ctx.panel, "annual_avg_temp", {
"v2": ctx.v2["annual_avg_temp"],
"damped85": lambda p, o: damped_temp(p, o, 0.85),
"quantile": quantile_temp,
"ew": lambda p, o: ew_slope_forecast(p, o, "annual_avg_temp"),
})
cdd_stack = WalkForwardStacker(ctx.panel, "cdd", {
"v2": ctx.v2["cdd"],
"delta": lambda p, o: ctx.daily.delta.forecast(o, 30, "median", "nat"),
"evanguo": lambda p, o: ctx.daily.evanguo_cdd(o),
})
return {
"annual_avg_temp": {"v2": ctx.v2["annual_avg_temp"],
"stack_temp_ridge": temp_stack.forecast},
"cdd": {"v2": ctx.v2["cdd"], "stack_cdd_ridge": cdd_stack.forecast},
}
if phase == "dcpp":
from dcpp import DcppCandidates # lazy: data pipeline is separate
dcpp = DcppCandidates(ROOT, ctx.panel)
return {
"annual_avg_temp": {
"v2": ctx.v2["annual_avg_temp"],
"dcpp_temp_pattern_w0.5": lambda p, o: dcpp.temp_pattern(o, ctx.v2["annual_avg_temp"], 0.5),
"dcpp_temp_pattern_w1.0": lambda p, o: dcpp.temp_pattern(o, ctx.v2["annual_avg_temp"], 1.0),
},
"total_precip_in": {
"v2": ctx.v2["total_precip_in"],
"dcpp_precip_pattern": lambda p, o: dcpp.precip_pattern(o, ctx.v2["total_precip_in"]),
},
}
raise ValueError(phase)
def main() -> None:
assert_no_forbidden_artifacts(Path(__file__).parent)
phase = sys.argv[1] if len(sys.argv) > 1 else "all"
phases = ["urban", "eo", "ml", "dcpp"] if phase == "all" else [phase]
ctx = AmendContext()
OUT.mkdir(parents=True, exist_ok=True)
results_path = OUT / "amendment_results.json"
results = json.loads(results_path.read_text()) if results_path.exists() else {}
for ph in phases:
registry = phase_candidates(ctx, ph)
for metric, cands in registry.items():
origin0 = SELECTION_ORIGINS[0]
_, scored = ctx.panel.truth(metric, origin0)
for n, f in cands.items():
fc = f(ctx.panel, origin0)
assert fc.shape == (len(ctx.panel.cities), 7), f"{n} bad shape"
assert np.isfinite(fc[scored]).all(), f"{n} non-finite on scored rows"
detail = evaluate_v3(ctx.panel, metric, cands, origins=SELECTION_ORIGINS)
detail.to_csv(OUT / f"detail_amend_{ph}_{metric}.csv", index=False)
tab = skill_table_v3(detail)
print(f"\n== amend {ph} {metric} (selection 1990-2004) ==")
print(tab[tab["era"] == "selection"].round(4).to_string(index=False))
for name in cands:
if name == "v2":
continue
g = gate(detail, name, "v2", metric)
results.setdefault(metric, {})[name] = g
print(f"gate {name}: diff {g['diff']:+.4f} vs SE {g['boot_se']:.4f} "
f"-> {'PASS' if g['passes'] else 'fail'}")
results_path.write_text(json.dumps(results, indent=2, default=float))
print(f"\nwrote {results_path}")
if __name__ == "__main__":
main()