Datasets:
Download code/test_v2.py from tchaudha/heat-seekers-protostar: direct link, hf CLI and curl.
- Browser
- Download file 4.53 kB
-
https://huggingface.co/datasets/tchaudha/heat-seekers-protostar/resolve/main/code/test_v2.py
- Command line
-
hf download hf://datasets/tchaudha/heat-seekers-protostar/code/test_v2.py
-
curl -L -o test_v2.py https://huggingface.co/datasets/tchaudha/heat-seekers-protostar/resolve/main/code/test_v2.py
4.53 kB
| """Offline tests for v2: leakage, official harness parity, coverage, validator, determinism.""" | |
| import ast, io, math, sys, unittest, hashlib, json | |
| import numpy as np, pandas as pd | |
| sys.path.insert(0, str(__import__('pathlib').Path(__file__).resolve().parent)) | |
| from v2lib import * | |
| import make_submission_v2 as ms | |
| P = Panel() | |
| OFF = ROOT / 'research/official/protostar-challenge-climate-risk-intelligence' | |
| class V2(unittest.TestCase): | |
| def test_poisoned_future_does_not_change_forecasts(self): | |
| for o in (1997, 2010): | |
| a = forecast_block(P, o, configs=[(15, 0.0, 'national'), (10, 0.25, 'knn10')]) | |
| b = forecast_block(P.copy_cut(o), o, configs=[(15, 0.0, 'national'), (10, 0.25, 'knn10')]) | |
| pd.testing.assert_frame_equal(a, b) | |
| def test_practice_run_replicates_organizer_numbers(self): | |
| # about.md: train to 2010, predict 2011-2018: CDD MAE 212 (30-yr average) and 175 (linear trend) | |
| f = forecast_block(P, 2010, which='baselines', H=8) | |
| r = score_origin(P, f[f.metric == 'cdd'], 2010, H=8) | |
| mae = r.groupby('method').error.mean() | |
| self.assertEqual(round(mae['clim30']), 212); self.assertEqual(round(mae['lin30']), 175) | |
| def test_63_unscored_rows_at_2018(self): | |
| n = sum((~clim30(P, m, 2018)[1]).sum() for m in METRICS) | |
| self.assertEqual(n, 9) | |
| def test_coverage_assert_fires(self): | |
| f = forecast_block(P, 2000, which='baselines') | |
| t = truth_rows(P, 2000).query("metric == 'cdd'").iloc[0] | |
| f = f.drop(f[(f.method == 'clim30') & (f.metric == 'cdd') & (f.city_id == t.city_id) & (f.year == t.year)].index) | |
| with self.assertRaises(AssertionError): score_origin(P, f, 2000) | |
| def test_official_score_parity(self): | |
| tree = ast.parse((OFF / 'scoring.py').read_text(encoding='utf-8')) | |
| pure = [n for n in tree.body if isinstance(n, (ast.FunctionDef, ast.ClassDef)) and n.name in ('score', 'ScoringError')] | |
| ns = dict(pd=pd, math=math, KEY=KEY, SPLITS=('live', 'final'), METRICS=tuple(METRICS)) | |
| exec(compile(ast.Module(body=pure, type_ignores=[]), 'scoring.py', 'exec'), ns) | |
| o = 2004; f = forecast_block(P, o, configs=[(15, 0.0, 'national')]) | |
| r = score_origin(P, f, o) | |
| sk = skill_table(r); sk = sk[(sk.split == 'final_like')] | |
| meth = {'annual_avg_temp': 'LT_L15_a0_national', 'cdd': 'SHmean_L15_a0_national', 'hottest_day_temp': 'clim30', 'total_precip_in': 'clim30'} | |
| truth = r[(r.method == 'clim30') & (r.split == 'final_like')][KEY + ['value']].rename(columns={'value': 'actual_value'}) | |
| truth['split'] = 'final'; truth['scored'] = True | |
| ref = r[(r.method == 'clim30') & (r.split == 'final_like')].groupby('metric').error.mean() | |
| refdf = pd.DataFrame([dict(split='final', **ref.to_dict())]) | |
| sub = pd.concat([f[(f.metric == m) & (f.method == meth[m])] for m in METRICS])[KEY + ['predicted_value']] | |
| res = ns['score'](sub, truth, refdf, 'final') | |
| mine = np.mean([sk[(sk.metric == m) & (sk.method == meth[m])].skill.iloc[0] for m in METRICS]) | |
| self.assertAlmostEqual(res['score'], 100 * max(0, mine), places=9) | |
| def test_submissions_valid_official_checker_and_deterministic(self): | |
| tree = ast.parse((OFF / 'utils.py').read_text(encoding='utf-8')) | |
| pure = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'check_forecasts'] | |
| ids = set((OFF / 'data/city_ids.txt').read_text().split()) | |
| ns = dict(pd=pd, io=io, CITY_IDS=ids, YEARS=set(range(2019, 2026)), METRICS=set(METRICS), COLUMNS=KEY + ['predicted_value']) | |
| exec(compile(ast.Module(body=pure, type_ignores=[]), 'utils.py', 'exec'), ns) | |
| for v in ('strict', 'v2b'): | |
| out, _, log = ms.build(P, v) | |
| buf = out.to_csv(index=False, float_format='%.6f').encode() | |
| self.assertIsNone(ns['check_forecasts'](buf)) | |
| self.assertEqual(len(log) * 7, 63) | |
| rec = json.loads((ROOT / f'results/submission_v2_{v}.json').read_text())['sha256'] | |
| self.assertEqual(hashlib.sha256(buf.replace(b'\r\n', b'\n')).hexdigest(), rec) | |
| def test_validate_rejects_bad(self): | |
| df = pd.read_csv(ROOT / 'results/submission_v2_strict.csv'); validate(df) | |
| bad = df.copy(); bad.loc[0, 'predicted_value'] = np.nan | |
| with self.assertRaises(AssertionError): validate(bad) | |
| with self.assertRaises(AssertionError): validate(df.iloc[::-1].reset_index(drop=True)) | |
| if __name__ == '__main__': unittest.main(verbosity=2) | |