heat-seekers-protostar / code /backtest_v3.py
tchaudha's picture
Heat Seekers v4: detrended-trimmed temp level, v2b CDD, hottest-day blend
89379eb verified
Raw History Blame Contribute Delete
4.99 kB
"""Run the pre-registered v3 ablations (research/V3_PROTOCOL.md) and apply its selection rule."""
import json, hashlib, sys, time
import numpy as np, pandas as pd
sys.path.insert(0, str(__import__('pathlib').Path(__file__).resolve().parent))
from v3lib import *
D = list(range(1985, 2005)); LATE = list(range(2005, 2012)); RES = ROOT / 'results'
REF = {'annual_avg_temp': 'v2', 'cdd': 'v2b', 'total_precip_in': 'clim30', 'hottest_day_temp': 'clim30'}
def protocol_check():
h = hashlib.sha256((ROOT / 'research/V3_PROTOCOL.md').read_bytes()).hexdigest()
assert h == (RES / 'v3_protocol_hash.txt').read_text().split()[0], 'V3 protocol changed after freezing'
return h
def run(P, fn):
rows = []
for o in D + LATE: rows.append(score_origin(P, fn(o), o))
return skill_table(pd.concat(rows, ignore_index=True))
def summarise(sk):
s = sk[sk.split != 'all'].copy(); s['set'] = np.where(s.origin <= 2004, 'dev', 'late')
t = s.groupby(['metric', 'method', 'set', 'split']).skill.mean().unstack(['set', 'split'])
t.columns = [f'{a}_{b}' for a, b in t.columns]; return t.reset_index()
def passes(t, m, c):
r = t[(t.metric == m) & (t.method == REF[m])].iloc[0]; x = t[(t.metric == m) & (t.method == c)].iloc[0]
return bool(x.dev_final_like > r.dev_final_like and x.late_final_like >= r.late_final_like)
def dev(t, m, c): return t[(t.metric == m) & (t.method == c)].dev_final_like.iloc[0]
def main():
ph = protocol_check(); t0 = time.time(); P = attach(Panel())
sk1 = run(P, lambda o: v3_block(P, o)); t1 = summarise(sk1)
notes = {}
meth = lambda m: sorted(set(t1[t1.metric == m].method) - {REF[m], 'clim30', 'exp10'})
def best(m, cands):
ok = [c for c in cands if passes(t1, m, c)]
return (max(ok, key=lambda c: dev(t1, m, c)) if ok else None), ok
T = 'annual_avg_temp'; C = 'cdd'
bs, okS = best(T, [c for c in meth(T) if c.startswith('slope_')]); bl, okL = best(T, [c for c in meth(T) if c.startswith('level_')])
notes[T] = dict(passing_slopes=okS, passing_levels=okL, homog_passes=passes(t1, T, 'homog'))
combos = []
if bs and bl: combos.append((bs.replace('slope_', ''), bl.replace('level_', '')))
if bs: combos.append((bs.replace('slope_', ''), 'v2')) # also yields C-tslope candidate
okC = [c for c in meth(C) if passes(t1, C, c)]; notes[C] = dict(passing_singles=okC)
def cdd_combo(o):
W = idw(P, o); s_v2 = temp_slope(P, o, 'v2'); L = 20 if 'L20' in okC else 15; sw, sc = s_v2, None
seas = [c for c in okC if c.startswith('season')]
if seas:
b = max(seas, key=lambda c: dev(t1, C, c)); ss = season_slope(P, o, W, b.split('_')[1]); sw, sc = ss['warm'], ss['cool']
L = max(L, int(b[-2:]))
norms = [c for c in okC if c.startswith('norm')]; norm = max(norms, key=lambda c: dev(t1, C, c)).split('_')[1] if norms else None
jacs = [c for c in okC if c.startswith('jac')]; js = None
if jacs: js = season_slope(P, o, W, 'nat')['warm'] if max(jacs, key=lambda c: dev(t1, C, c)) == 'jacw' else s_v2
return cdd_shift(P, o, L, sw, sc, norm=norm, jac=0.35 if jacs else 0.0, jac_slope=js)
def stage2(o):
f = v3_block(P, o, extra_temp_slopes=combos)
f = f[f.method.str.startswith('combo_') | f.method.str.startswith('tslope_') | (f.method == 'clim30')]
if len(okC) >= 2:
mat = cdd_combo(o)
f = pd.concat([f, pd.DataFrame({'city_id': np.repeat(P.ids, 7), 'year': np.tile(o + np.arange(1, 8), len(P.ids)), 'metric': 'cdd',
'method': 'cdd_combo', 'predicted_value': mat.ravel()})], ignore_index=True)
return f
sk2 = run(P, stage2); sk2 = sk2[sk2.method != 'clim30']; t2 = summarise(sk2)
t = pd.concat([t1, t2], ignore_index=True); t.to_csv(RES / 'v3_candidate_summary.csv', index=False)
pd.concat([sk1, sk2], ignore_index=True).to_csv(RES / 'v3_skills_by_origin.csv', index=False)
sel = {}
for m in METRICS:
cands = [c for c in t[t.metric == m].method.unique() if c not in (REF[m], 'clim30', 'exp10')]
if m == 'hottest_day_temp':
cands = [c for c in cands if not c.startswith('huber30+') or (passes(t, m, 'huber30') and passes(t, m, c.split('+')[1]))]
ok = [c for c in cands if passes(t, m, c)]
single = [c for c in ok if not (c.startswith('combo_') or c == 'cdd_combo')]
bsd = max([dev(t, m, c) for c in single], default=-9)
ok = single + [c for c in ok if (c.startswith('combo_') or c == 'cdd_combo') and dev(t, m, c) > bsd]
sel[m] = max(ok, key=lambda c: dev(t, m, c)) if ok else REF[m]
notes.setdefault(m, {})['all_passing'] = ok
out = dict(protocol_sha256=ph, selection=sel, reference=REF, notes=notes, temp_combos=combos, seconds=round(time.time() - t0, 1))
(RES / 'v3_selection.json').write_text(json.dumps(out, indent=2, default=str)); print(json.dumps(out, indent=2, default=str))
if __name__ == '__main__': main()