heat-seekers-protostar / code /backtest_v4.py
tchaudha's picture
Heat Seekers v4: detrended-trimmed temp level, v2b CDD, hottest-day blend
89379eb verified
Raw History Blame Contribute Delete
2.77 kB
"""Run research/V4_PROTOCOL.md: score all v4 candidates, apply the V3 rule, report secondary pooled/block views."""
import json, hashlib, sys, time
import numpy as np, pandas as pd
sys.path.insert(0, str(__import__('pathlib').Path(__file__).resolve().parent))
from v4lib 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 main():
h = hashlib.sha256((ROOT / 'research/V4_PROTOCOL.md').read_bytes()).hexdigest()
assert h == (RES / 'v4_protocol_hash.txt').read_text().split()[0], 'V4 protocol changed after freezing'
t0 = time.time(); P = attach(Panel()); rows, infos = [], []
for o in D + LATE:
f, info = v4_block(P, o); rows.append(score_origin(P, f, o)); infos.append(info)
r = pd.concat(rows, ignore_index=True); sk = skill_table(r); sk.to_csv(RES / 'v4_skills_by_origin.csv', index=False)
pd.DataFrame(infos).to_csv(RES / 'v4_slopes_by_origin.csv', index=False)
f = sk[sk.split == 'final_like'].copy(); f['set'] = np.where(f.origin <= 2004, 'dev', 'late')
t = f.groupby(['metric', 'method', 'set']).skill.mean().unstack('set').reset_index()
# secondary (not used for selection)
fl = r[r.split == 'final_like']; mae = fl.groupby(['origin', 'metric', 'method']).error.mean().reset_index()
ref = mae[mae.method == 'clim30'].groupby('metric').error.sum()
pooled = mae.groupby(['metric', 'method']).error.sum().reset_index()
pooled['pooled_ratio_skill_1985_2011'] = 1 - pooled.error / pooled.metric.map(ref)
f['block'] = pd.cut(f.origin, [1984, 1993, 2002, 2011], labels=['b1_1985_93', 'b2_1994_02', 'b3_2003_11'])
blk = f.groupby(['metric', 'method', 'block'], observed=True).skill.mean().unstack('block').reset_index()
t = t.merge(pooled[['metric', 'method', 'pooled_ratio_skill_1985_2011']], on=['metric', 'method']).merge(blk, on=['metric', 'method'])
t.to_csv(RES / 'v4_candidate_summary.csv', index=False)
sel, notes = {}, {}
for m in METRICS:
R = t[(t.metric == m) & (t.method == REF[m])].iloc[0]
c = t[(t.metric == m) & ~t.method.isin([REF[m], 'clim30'])]
ok = c[(c.dev > R.dev) & (c.late >= R.late)]
sel[m] = ok.sort_values('dev', ascending=False).iloc[0].method if len(ok) else REF[m]
notes[m] = dict(passing=ok.method.tolist())
out = dict(protocol_sha256=h, selection=sel, reference=REF, notes=notes, adopted_any=sel != REF, seconds=round(time.time() - t0, 1))
(RES / 'v4_selection.json').write_text(json.dumps(out, indent=2)); print(json.dumps(out, indent=2))
pd.set_option('display.width', 250); print(t.round(4).to_string(index=False))
if __name__ == '__main__': main()