"""Pre-registered test: does a 50/50 blend of Placeholder_v9-S and combined model v3 beat both on past years? Rule (fixed before running): for forecast origins 1986, 1994, 2002 and 2010 (train on years <= origin, forecast the next 7 years, as in the real task), score each model with the leaderboard formula on the rows the challenge would score (valid year, and the city has a 30-year baseline). Submit the blend only if its mean Score over the four origins beats both v9-S and v3; otherwise keep v9-S. No 2019+ data is read. Run from the dataset root (final_submission/): python code/blend_test.py """ import os import sys import tempfile from pathlib import Path import numpy as np import pandas as pd HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) ROOT = HERE.parent import make_submission as ms # Meet's loader, constants and CSV round-trip (exactly as submitted) from common import METRICS, assert_no_post_cutoff ORIGINS = (1986, 1994, 2002, 2010) LEAD = 7 # the real task forecasts 7 years (2019-2025); v9-S requires exactly 7 KEY = ["city_id", "year", "metric"] def annual_table() -> pd.DataFrame: source = ms.ANNUAL if ms.ANNUAL.is_file() else ms.pinned_annual() annual = ms.load_annual(source) assert_no_post_cutoff(annual, "year", "blend test history") return annual def v9s_forecasts(annual, cities, origin, years, tmpdir) -> pd.DataFrame: warm = pd.read_csv(ROOT / "data" / "daily_warm_days.csv", dtype={"city_id": str}) warm_path = Path(tmpdir) / f"warm_{origin}.csv" warm[warm["year"] <= origin].to_csv(warm_path, index=False) os.environ["PROTOSTAR_ASSET_ROOT"] = str(ROOT) os.environ.pop("PROTOSTAR_ARTIFACT_DIR", None) os.environ["PROTOSTAR_FOLD_CUTOFF"] = str(origin) os.environ["PROTOSTAR_WARM_DAYS"] = str(warm_path) import importlib import placeholder_v9s importlib.reload(placeholder_v9s) # pick up this origin's warm-day file if hasattr(placeholder_v9s, "WARM_RELEASE"): placeholder_v9s.WARM_RELEASE = str(warm_path) train = ms._round_trip(annual[(annual.year <= origin) & annual.city_id.isin(cities)], {"city_id": str}) targets = pd.MultiIndex.from_product([cities, years, list(METRICS)], names=KEY).to_frame(index=False) targets = ms._round_trip(targets, {"city_id": str, "metric": str}) res = placeholder_v9s.forecast(train, targets, origin, seed=42) return res[KEY + ["predicted_value"]] def v3_forecasts(valid, cities, origin, years) -> pd.DataFrame: import combo_v3 as cm from common import wide parts = [] for metric in METRICS: table = wide(valid, metric).reindex(cities) pred = cm.forecast(table, metric, cm.METHOD[metric], origin, years) long = pred.stack().rename("predicted_value").reset_index() long.columns = ["city_id", "year", "predicted_value"] long["metric"] = metric parts.append(long) return pd.concat(parts)[KEY + ["predicted_value"]] def score(valid, pred: pd.DataFrame, origin, years) -> dict: from common import thirty_year_mean, wide import combo_v3 as cm out = {} for metric in METRICS: table = wide(valid, metric) history = table.loc[:, :origin] actual = table.reindex(columns=years).where(thirty_year_mean(history, origin).notna(), axis=0) ref = cm.average_forecast(history, origin, years).reindex(index=actual.index, columns=years) p = (pred[pred.metric == metric].pivot(index="city_id", columns="year", values="predicted_value") .reindex(index=actual.index, columns=years)) a, r, q = actual.stack(future_stack=True), ref.stack(future_stack=True), p.stack(future_stack=True) ok = a.notna() & r.notna() & q.notna() out[metric] = 1 - (q[ok] - a[ok]).abs().mean() / (r[ok] - a[ok]).abs().mean() out["Score"] = 100 * max(0.0, float(np.mean([out[m] for m in METRICS]))) return out def main() -> None: from common import load_valid_annual valid = load_valid_annual() # load before the per-origin cutoff is set (scoring needs years after origin) annual = annual_table() cities = sorted(pd.read_csv(ROOT / "data" / "city_info.csv", dtype={"city_id": str}).city_id.unique()) rows = [] with tempfile.TemporaryDirectory() as tmp: for origin in ORIGINS: years = list(range(origin + 1, origin + 1 + LEAD)) a = v9s_forecasts(annual, cities, origin, years, tmp) b = v3_forecasts(valid, cities, origin, years) m = a.merge(b, on=KEY, suffixes=("_v9s", "_v3")) blend = m[KEY].assign(predicted_value=0.5 * m.predicted_value_v9s + 0.5 * m.predicted_value_v3) for name, pred in [("v9-S", a), ("v3", b), ("blend 50/50", blend)]: s = score(valid, pred, origin, years) rows.append({"origin": origin, "model": name, **{k: round(v, 4) for k, v in s.items()}}) print(f"origin {origin} {name:12s} Score {s['Score']:5.2f} " + " ".join(f"{k} {s[k]:+.3f}" for k in METRICS), flush=True) os.environ.pop("PROTOSTAR_FOLD_CUTOFF", None) r = pd.DataFrame(rows) (ROOT / "reports").mkdir(exist_ok=True) r.to_csv(ROOT / "reports" / "blend_test.csv", index=False) means = r.groupby("model")["Score"].mean() print("\nMean Score over origins 1986/1994/2002/2010:") print(means.round(2).to_string()) win = means["blend 50/50"] > max(means["v9-S"], means["v3"]) print("\nRULE:", "blend beats both -> submit the blend" if win else "blend does not beat both -> keep v9-S") if __name__ == "__main__": main()