File size: 4,390 Bytes
89379eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run the frozen v2 protocol (research/V2_PROTOCOL.md): rolling origins 1985-2011, all fixed candidates,
official-formula skills with full-coverage asserts, then apply the pre-declared selection rules."""
import json, hashlib, sys, time
import numpy as np, pandas as pd
sys.path.insert(0, str(__import__('pathlib').Path(__file__).resolve().parent))
from v2lib import *

D = list(range(1985, 2005)); L_SET = list(range(2005, 2012))
RES = ROOT / 'results'

def protocol_check():
    h = hashlib.sha256((ROOT / 'research/V2_PROTOCOL.md').read_bytes()).hexdigest()
    rec = (RES / 'v2_protocol_hash.txt').read_text().split()[0]
    assert h == rec, 'Protocol changed after freezing'
    return h

def J(df):  # 0.3 live_like + 0.7 final_like mean skill
    live = df[df.split == 'live_like'].skill.mean(); fin = df[df.split == 'final_like'].skill.mean()
    return 0.3 * live + 0.7 * fin

def main():
    ph = protocol_check(); t0 = time.time(); P = Panel()
    rows = []
    for o in D + L_SET:
        rows.append(score_origin(P, forecast_block(P, o), o)); print('origin', o, flush=True)
    rows = pd.concat(rows, ignore_index=True)
    sk = skill_table(rows); sk.to_csv(RES / 'v2_skills_by_origin.csv', index=False)
    rows.to_parquet(RES / 'v2_errors.parquet', index=False)
    dev = sk[sk.origin.isin(D) & (sk.split != 'all')]; late = sk[sk.origin.isin(L_SET) & (sk.split != 'all')]
    summ = []
    for (m, meth), g in dev.groupby(['metric', 'method']):
        gl = late[(late.metric == m) & (late.method == meth)]
        fin = g[g.split == 'final_like'].set_index('origin').skill
        summ.append(dict(metric=m, method=meth, J_dev=J(g), dev_live=g[g.split == 'live_like'].skill.mean(),
                         dev_final=fin.mean(), dev_final_wins_vs_clim30=int((fin > 0).sum()), J_late=J(gl),
                         late_live=gl[gl.split == 'live_like'].skill.mean(), late_final=gl[gl.split == 'final_like'].skill.mean()))
    summ = pd.DataFrame(summ).sort_values(['metric', 'J_dev'], ascending=[True, False])
    summ.to_csv(RES / 'v2_candidate_summary.csv', index=False)
    S = summ.set_index(['metric', 'method'])
    sel = {}; notes = {}
    for m, prefix in (('annual_avg_temp', 'LT_'), ('cdd', 'SH')):
        c = summ[(summ.metric == m) & summ.method.str.startswith(prefix)].copy()
        c['len'] = c.method.str.len()
        best = c.sort_values(['J_dev', 'len'], ascending=[False, True]).iloc[0]
        ok = best.J_dev > S.loc[(m, 'clim30')].J_dev and best.J_dev > S.loc[(m, 'exp10')].J_dev and best.dev_final_wins_vs_clim30 >= 12
        sel[m] = best.method if ok else 'exp10'
        notes[m] = dict(best=best.method, J_best=best.J_dev, J_clim30=S.loc[(m, 'clim30')].J_dev, J_exp10=S.loc[(m, 'exp10')].J_dev,
                        wins=int(best.dev_final_wins_vs_clim30), adopted=bool(ok))
    alts = {'hottest_day_temp': ['median30', 'trend_beta0.5', 'trend_beta1'], 'total_precip_in': ['median30', 'mean60']}
    for m, cands in alts.items():
        c = summ[(summ.metric == m) & summ.method.isin(cands)].sort_values('J_dev', ascending=False).iloc[0]
        ok = c.J_dev - S.loc[(m, 'clim30')].J_dev > 0.005 and c.dev_final_wins_vs_clim30 >= 12
        sel[m] = c.method if ok else 'clim30'
        notes[m] = dict(best=c.method, J_best=c.J_dev, J_clim30=S.loc[(m, 'clim30')].J_dev, wins=int(c.dev_final_wins_vs_clim30), adopted=bool(ok))
    # safety gate on late set: assembled v2 vs v1 incumbent and clim30 (mean over metrics of late J)
    v1 = {'annual_avg_temp': 'exp10', 'cdd': 'exp10', 'hottest_day_temp': 'clim30', 'total_precip_in': 'clim30'}
    def late_J(choice): return np.mean([S.loc[(m, choice[m])].J_late for m in METRICS])
    gate = dict(v2=late_J(sel), v1=late_J(v1), clim30=late_J({m: 'clim30' for m in METRICS}))
    gate['passed'] = bool(gate['v2'] >= gate['v1'] and gate['v2'] >= gate['clim30'])
    reverted = []
    if not gate['passed']:
        for m in METRICS:
            if S.loc[(m, sel[m])].J_late < S.loc[(m, v1[m])].J_late: sel[m] = v1[m]; reverted.append(m)
    out = dict(protocol_sha256=ph, selection=sel, notes=notes, late_gate=gate, reverted=reverted,
               dev_origins=D, late_origins=L_SET, seconds=round(time.time() - t0, 1))
    (RES / 'v2_selection.json').write_text(json.dumps(out, indent=2, default=float))
    print(json.dumps(out, indent=2, default=float))

if __name__ == '__main__': main()