"""Run research/V6_PROTOCOL.md: leakage test, score v6 candidates vs v4 on dev/late origins, apply the 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 v6lib import * D = list(range(1985, 2005)); LATE = list(range(2005, 2012)); RES = ROOT / 'results' def main(): h = hashlib.sha256((ROOT / 'research/V6_PROTOCOL.md').read_bytes()).hexdigest() assert h == (RES / 'v6_protocol_hash.txt').read_text().split()[0], 'V6 protocol changed after freezing' t0 = time.time(); P = attach6(Panel()) for o in (1995, 2011): a, _ = v6_block(P, o); b, _ = v6_block(cut6(P, o), o) assert np.array_equal(a.predicted_value.to_numpy(), b.predicted_value.to_numpy()), f'leak at {o}' print('leakage test passed', flush=True) rows, infos = [], [] for o in D + LATE: f, info = v6_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 / 'v6_skills_by_origin.csv', index=False) pd.DataFrame(infos).to_csv(RES / 'v6_info_by_origin.csv', index=False) f = sk[sk.split != 'all'].copy(); f['set'] = np.where(f.origin <= 2004, 'dev', 'late') t = f.groupby(['metric', 'method', 'split', 'set']).skill.mean().unstack('set').reset_index() # sanity: v4 assembled ff = f[f.split == 'final_like'] v4 = pd.concat([ff[(ff.metric == m) & (ff.method == REF[m])] for m in METRICS]).groupby(['set', 'origin']).skill.mean().groupby('set').mean() * 100 print('v4 assembled h4-7 dev/late', v4.round(2).to_dict()); assert round(v4['dev'], 2) == 3.69 and round(v4['late'], 2) == 8.83 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) ff = ff.copy(); ff['block'] = pd.cut(ff.origin, [1984, 1993, 2002, 2011], labels=['b1_1985_93', 'b2_1994_02', 'b3_2003_11']) blk = ff.groupby(['metric', 'method', 'block'], observed=True).skill.mean().unstack('block').reset_index() wide = ff.pivot_table(index=['metric', 'origin'], columns='method', values='skill') wins = [] for m in METRICS: w = wide.loc[m] for c in CANDS[m]: wins.append(dict(metric=m, method=c, origins_beating_v4=int((w[c] > w[REF[m]]).sum()))) tf = t[t.split == 'final_like'].drop(columns='split').merge(pooled[['metric', 'method', 'pooled_ratio_skill_1985_2011']], on=['metric', 'method']).merge(blk, on=['metric', 'method']) t13 = t[t.split == 'live_like'].drop(columns='split').rename(columns={'dev': 'dev_h13', 'late': 'late_h13'}) tf = tf.merge(t13, on=['metric', 'method']).merge(pd.DataFrame(wins), on=['metric', 'method'], how='left') tf.to_csv(RES / 'v6_candidate_summary.csv', index=False) sel, notes = {}, {} for m in METRICS: R = tf[(tf.metric == m) & (tf.method == REF[m])].iloc[0]; c = tf[(tf.metric == m) & tf.method.isin(CANDS[m])] 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(), ref_dev=float(R.dev), ref_late=float(R.late)) asm = pd.concat([ff[(ff.metric == m) & (ff.method == sel[m])] for m in METRICS]).groupby(['set', 'origin']).skill.mean().groupby('set').mean() * 100 out = dict(protocol_sha256=h, selection=sel, reference=REF, notes=notes, adopted_any=sel != REF, assembled_h47_x100=asm.round(3).to_dict(), v4_h47_x100=v4.round(3).to_dict(), seconds=round(time.time() - t0, 1)) (RES / 'v6_selection.json').write_text(json.dumps(out, indent=2)); print(json.dumps(out, indent=2)) pd.set_option('display.width', 250); print(tf.round(4).to_string(index=False)) if __name__ == '__main__': main()