File size: 9,019 Bytes
49f3de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""V3 selection-era evaluation (origins 1990-2004 only).



Usage: .venv/Scripts/python.exe code/run_v3_eval.py [phase0|phase1|phase2|phase3|phase5|all]

Confirmation-era (2005-2011) numbers are produced ONLY by run_v3_confirm.py.

Every candidate in candidates_v3.yaml is run and reported, pass or fail.

"""
from __future__ import annotations

import json
import sys
import urllib.request
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 candidates_v3 import (DailyCandidates, SeasonalPrecip, ar_anomaly_temp,
                           build_filled_panel, damped_temp, ew_slope_forecast,
                           global_beta_temp, hot_delta, oni_year1_temp,
                           quantile_temp, volcano_clean)
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"


def fetch_oni() -> pd.Series | None:
    """ERSST ONI index (NOAA PSL), cached; annual means. None if offline."""
    cache = ROOT / "data" / "external" / "oni.data.txt"
    try:
        if not cache.exists():
            cache.parent.mkdir(parents=True, exist_ok=True)
            with urllib.request.urlopen(
                    "https://psl.noaa.gov/data/correlation/oni.data", timeout=20) as r:
                cache.write_bytes(r.read())
        rows = {}
        for line in cache.read_text(errors="replace").splitlines():
            parts = line.split()
            if len(parts) == 13 and parts[0].isdigit() and 1850 <= int(parts[0]) <= 2018:
                vals = [float(v) for v in parts[1:]]
                vals = [v for v in vals if v > -90]
                if len(vals) >= 10:
                    rows[int(parts[0])] = float(np.mean(vals))
        return pd.Series(rows).sort_index() if rows else None
    except Exception as exc:  # offline etc: candidate is skipped, not faked
        print(f"ONI unavailable ({exc}); temp_oni_year1_shr0.5 will be skipped")
        return None


class Context:
    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._seasonal = None
        self._filled = None
        self._oni = ...

    @property
    def daily(self) -> DailyCandidates:
        if self._daily is None:
            self._daily = DailyCandidates(ROOT, self.panel)
        return self._daily

    @property
    def seasonal(self) -> SeasonalPrecip:
        if self._seasonal is None:
            self._seasonal = SeasonalPrecip(ROOT, self.panel)
        return self._seasonal

    @property
    def filled(self) -> Panel:
        if self._filled is None:
            self._filled = build_filled_panel(ROOT, self.panel)
        return self._filled

    @property
    def oni(self):
        if self._oni is ...:
            self._oni = fetch_oni()
        return self._oni


def phase_candidates(ctx: Context, phase: str) -> dict:
    """{metric: {candidate_name: fn}} including the v2 control per metric."""
    p = ctx.panel
    if phase == "phase0":
        return {m: {"v2": ctx.v2[m]} for m in ctx.v2}
    if phase == "phase1":
        return {"annual_avg_temp": {
            "v2": ctx.v2["annual_avg_temp"],
            "damped_phi0.70_L15natW40": lambda pp, o: damped_temp(pp, o, 0.70),
            "damped_phi0.85_L15natW40": lambda pp, o: damped_temp(pp, o, 0.85),
            "v2temp_plus_AR_rho0.30": lambda pp, o: ar_anomaly_temp(pp, o, ctx.v2["annual_avg_temp"]),
            "quantile_L15med_regW40": quantile_temp,
        }}
    if phase == "phase2":
        d = ctx.daily
        return {
            "cdd": {
                "v2": ctx.v2["cdd"],
                "delta_bootmedian_h30_nat": lambda pp, o: d.boot_median_cdd(o),
                "delta_asym1.125_h30_nat": lambda pp, o: d.delta.forecast(o, 30, "median", "nat", slope_mult=1.125),
                "delta_asym1.25_h30_nat": lambda pp, o: d.delta.forecast(o, 30, "median", "nat", slope_mult=1.25),
                "evanguo_L10_sens_natW40": lambda pp, o: d.evanguo_cdd(o),
            },
            "hottest_day_temp": {
                "v2": ctx.v2["hottest_day_temp"],
                "hotdelta_h30_nat": lambda pp, o: hot_delta(pp, o, 30, "nat"),
                "hotdelta_h15_nat": lambda pp, o: hot_delta(pp, o, 15, "nat"),
                "hotdelta_h30_reg": lambda pp, o: hot_delta(pp, o, 30, "reg"),
                "blend50_hotdelta_h30_nat_mean30": lambda pp, o: 0.5 * hot_delta(pp, o, 30, "nat")
                    + 0.5 * ctx.v2["hottest_day_temp"](pp, o),
            },
            "total_precip_in": {
                "v2": ctx.v2["total_precip_in"],
                "precip_seasonal_med30": lambda pp, o: ctx.seasonal.forecast(pp, o),
            },
        }
    if phase == "phase3":
        out = {
            "annual_avg_temp": {
                "v2": ctx.v2["annual_avg_temp"],
                "temp_volcano_clean_natW40": lambda pp, o: volcano_clean(pp, o, "annual_avg_temp"),
                "temp_globalbeta_shr0.5": global_beta_temp,
            },
            "cdd": {
                "v2": ctx.v2["cdd"],
                "cdd_volcano_clean_natW40": lambda pp, o: volcano_clean(pp, o, "cdd"),
                "cdd_fill30_mean30": lambda pp, o: level_trend(ctx.filled, "cdd", o, 30, "mean", "none", clip_zero=True),
            },
            "hottest_day_temp": {
                "v2": ctx.v2["hottest_day_temp"],
                "hottest_fill30_mean30": lambda pp, o: level_trend(ctx.filled, "hottest_day_temp", o, 30, "mean", "none"),
            },
        }
        if ctx.oni is not None:
            out["annual_avg_temp"]["temp_oni_year1_shr0.5"] = \
                lambda pp, o: oni_year1_temp(pp, o, ctx.oni, ctx.v2["annual_avg_temp"])
        else:
            print("skipped: temp_oni_year1_shr0.5 (no ONI data)")
        return out
    if phase == "phase5":
        return {
            "annual_avg_temp": {
                "v2": ctx.v2["annual_avg_temp"],
                "temp_ewslope_hl20_shr": lambda pp, o: ew_slope_forecast(pp, o, "annual_avg_temp"),
            },
            "cdd": {
                "v2": ctx.v2["cdd"],
                "cdd_ewslope_hl20_shr": lambda pp, o: ew_slope_forecast(pp, o, "cdd"),
            },
        }
    raise ValueError(phase)


def run_phase(ctx: Context, phase: str, results: dict) -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    registry = phase_candidates(ctx, phase)
    for metric, cands in registry.items():
        # Sanity probe: right shape, and finite on scored rows (the harness
        # contract; unscored sparse cities may legitimately be NaN pre-2000).
        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 {fc.shape}"
            assert np.isfinite(fc[scored]).all(), f"{n} non-finite on scored rows at {origin0}"
        detail = evaluate_v3(ctx.panel, metric, cands, origins=SELECTION_ORIGINS)
        detail.to_csv(OUT / f"detail_{phase}_{metric}.csv", index=False)
        tab = skill_table_v3(detail)
        print(f"\n== {phase} {metric} (selection 1990-2004) ==")
        print(tab[tab["era"] == "selection"].round(4).to_string(index=False))
        for name in cands:
            if name == "v2":
                results.setdefault(metric, {})["v2_selection"] = \
                    float(tab.loc[tab["candidate"] == "v2", "skill"].iloc[0])
                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'}")


def main() -> None:
    assert_no_forbidden_artifacts(Path(__file__).parent)
    phase = sys.argv[1] if len(sys.argv) > 1 else "all"
    phases = ["phase0", "phase1", "phase2", "phase3", "phase5"] if phase == "all" else [phase]
    ctx = Context()
    results_path = OUT / "selection_results.json"
    results = json.loads(results_path.read_text()) if results_path.exists() else {}
    for ph in phases:
        run_phase(ctx, ph, results)
    OUT.mkdir(parents=True, exist_ok=True)
    results_path.write_text(json.dumps(results, indent=2, default=float))
    n_new = sum(1 for m in results.values() for k in m if k != "v2_selection")
    print(f"\nnew configs evaluated so far: {n_new} (budget <= 40)")
    print(f"wrote {results_path}")


if __name__ == "__main__":
    main()