AlecAlameddine's picture
Upload 105 files
d79a78d verified
Raw History Blame Contribute Delete
12.8 kB
"""Checks that guard the submission: leakage, scoring, model invariants, the file itself.
Run: PYTHONPATH=code python -m protostar.tests (also part of `make all`)
"""
import json
import numpy as np
import pandas as pd
from .backtest import (LONG, RECENT, Fold, Harness, blend_specs, climatology_specs, practice_check, select,
trend_specs)
from .common import (BASELINE_WINDOW, CONFIRMATION_FOLDS, FORECAST_YEARS, METRICS, MIN_VALID_YEARS, N_CITIES,
PRACTICE_FOLD, REPORTS, ROOT, SEED, SELECTION_FOLDS, TRAIN_END)
from .data import (LeakageError, Panel, assert_no_leak, cities, load_annual, load_city_info, long_table,
panels)
from .models import BASELINES, neighbor_order, predict
from .scoring import challenge_score, score_frames, skill
def setup():
annual = load_annual()
long = long_table(annual)
geo = cities(annual)
order = neighbor_order(geo["lat"].to_numpy(), geo["lon"].to_numpy())
return annual, long, panels(long), order
def test_leak_guard(annual, long, P, order):
"""Data after 2018 cannot enter: the loaders, the panels and predict() all refuse it."""
assert annual["Year"].max() == TRAIN_END
for bad in (lambda: assert_no_leak([2018, 2019], "x"),
lambda: panels(pd.concat([long, long.tail(1).assign(year=2019)])),
lambda: predict(BASELINES["30-year average"],
{m: Panel(m, p.city_ids, p.years + 1, p.y) for m, p in P.items()},
"cdd", order, [2020])):
try:
bad()
except LeakageError:
continue
raise AssertionError("a leak was not caught")
def test_no_peeking(annual, long, P, order):
"""Backtest forecasts do not change when every raw value after the origin is corrupted."""
selected = json.loads((REPORTS / "backtest" / "selected.json").read_text())["selected"]
rng = np.random.default_rng(SEED)
measured = [c for c in annual.columns if c not in ("Name", "ID", "Lat", "Lon", "Year")]
def specs(metric): # everything the ladder can evaluate, and what ships
out = list(BASELINES.values()) + climatology_specs() + trend_specs() + [selected[metric]]
out += blend_specs(RECENT, LONG, trend_specs()[5])[::7]
if metric == "cdd":
out += [{"type": "cdd_via_temp", "n": BASELINE_WINDOW, "temp": t} for t in trend_specs()[:3]]
return out
for origin, first, last in (*SELECTION_FOLDS, *CONFIRMATION_FOLDS, PRACTICE_FOLD):
bad = annual.copy()
later = (bad["Year"] > origin).to_numpy()
for c in measured: # through the real path: raw table -> valid-year rule -> panels -> Fold
if c.startswith("Miss"):
bad.loc[later, c] = rng.integers(0, 12, size=later.sum()) # valid and invalid years
else:
bad.loc[later, c] = rng.normal(0, 1e6, size=later.sum())
clean, dirty = Fold(P, origin, first, last), Fold(panels(long_table(bad)), origin, first, last)
for m in METRICS:
assert np.array_equal(clean.train[m].y, dirty.train[m].y, equal_nan=True), (origin, m)
assert not np.array_equal(clean.truth[m], dirty.truth[m], equal_nan=True) # the corruption is real
for spec in specs(m):
assert np.array_equal(clean.predict(spec, m, order), dirty.predict(spec, m, order),
equal_nan=True), (origin, m, spec)
def test_neighbors_are_geography(annual, long, P, order):
"""The neighbor order comes from fixed station coordinates only (it cannot carry weather)."""
assert (annual.groupby("ID")[["Lat", "Lon"]].nunique() == 1).all(axis=None) # one location per city
info = load_city_info().groupby("ID")[["Lat", "Lon"]].first().reindex(P["cdd"].city_ids)
assert np.array_equal(order, neighbor_order(info["Lat"].to_numpy(), info["Lon"].to_numpy()))
n = len(order)
assert order.shape == (n, n - 1) and all(i not in order[i] and len(set(order[i])) == n - 1 for i in range(n))
def test_selection_reproduces(annual, long, P, order):
"""Re-running the ladder with the coordinate-only neighbor order gives exactly selected.json and ladder.csv."""
chosen, log, _ = select(Harness(P, order))
assert chosen == json.loads((REPORTS / "backtest" / "selected.json").read_text())["selected"]
saved = pd.read_csv(REPORTS / "backtest" / "ladder.csv") # written by backtest.main with its own order
assert list(log["spec"]) == list(saved["spec"])
for col in ("gain_mean_skill", "se_gain", "confirmation_mean_skill"):
assert np.allclose(log[col], saved[col], rtol=0, atol=1e-12), col
def test_scoring_matches_space(annual, long, P, order):
"""The array scorer of the backtest equals the Space's table scorer (scoring.score_frames)."""
origin, first, last = 2011, 2012, 2018
f = Fold(P, origin, first, last)
ids = P["cdd"].city_ids
years = np.arange(first, last + 1)
def frame(spec_by_metric, col):
parts = []
for m in METRICS:
pred = predict(spec_by_metric[m], f.train, m, order, years, fill=col == "predicted_value")
parts.append(pd.DataFrame({"city_id": np.repeat(ids, len(years)), "year": np.tile(years, len(ids)),
"metric": m, col: pred.ravel()}))
return pd.concat(parts, ignore_index=True)
selected = json.loads((REPORTS / "backtest" / "selected.json").read_text())["selected"]
sub = frame(selected, "predicted_value")
ref = frame({m: BASELINES["30-year average"] for m in METRICS}, "predicted_value")
# answer key built like the organizers': valid test years; scored if the city-metric has a baseline
truth = long[long["year"].between(first, last)].rename(columns={"value": "actual_value"})
win = long[long["year"].between(origin - BASELINE_WINDOW + 1, origin) & long["valid"]]
n_valid = win.groupby(["city_id", "metric"]).size().rename("n").reset_index()
truth = truth.merge(n_valid, on=["city_id", "metric"], how="left")
truth["scored"] = truth["valid"] & (truth["n"].fillna(0) >= MIN_VALID_YEARS)
res = score_frames(sub, truth, ref)
skills = {m: f.skill(selected[m], m, order) for m in METRICS}
for m in METRICS:
assert abs(res["mae"][m] - f.mae(selected[m], m, order)) < 1e-9, m
assert abs(res["skill"][m] - skills[m]) < 1e-9, m
assert abs(res["score"] - challenge_score(skills)) < 1e-9
assert res["n_rows"] == sum(int(f.scored[m].sum()) for m in METRICS)
def test_practice_run(annual, long, P, order):
"""The harness reproduces the organizers' published practice-run numbers (About tab, notebook, discussion #3)."""
t = practice_check(P, order).set_index(["rule", "model"])
notebook = {"30-year average": {"annual_avg_temp": 1.657, "total_precip_in": 6.198,
"hottest_day_temp": 2.563, "cdd": 212.636}}
for m, value in notebook["30-year average"].items():
assert abs(t.loc[("example notebook (no minimum)", "30-year average"), m] - value) < 6e-4, m
own_rows = {"annual_avg_temp": 1.513, "total_precip_in": 6.207, "hottest_day_temp": 2.568, "cdd": 184.059}
for m, value in own_rows.items(): # the notebook's model column, scored the notebook's way
assert abs(t.loc[("example notebook, scored on the rows the model covers", "10-year mean"), m] - value) < 6e-4, m
official = "official (>= 10 valid years in the window)"
assert abs(t.loc[(official, "30-year average"), "cdd"] - 211.7) < 0.05 # organizer: 211.7 / 174.6
assert abs(t.loc[(official, "Linear trend"), "cdd"] - 174.6) < 0.05
def test_model_invariants(annual, long, P, order):
"""Baselines equal independent computations (groupby mean, numpy.polyfit); lam=1 is plain OLS."""
train = {m: p.upto(2011) for m, p in P.items()}
years = np.arange(2012, 2019)
for m in METRICS:
# the 30-year average equals a plain groupby mean of the valid years
ref = (long[(long["metric"] == m) & long["valid"] & long["year"].between(1982, 2011)]
.groupby("city_id")["value"].agg(["mean", "size"]))
ref = ref["mean"].where(ref["size"] >= MIN_VALID_YEARS).reindex(P[m].city_ids).to_numpy()
got = predict(BASELINES["30-year average"], train, m, order, years, fill=False)[:, 0]
assert np.allclose(got, ref, equal_nan=True), m
# a pooled trend with full weight on the own slope is the per-city OLS line
own = predict({"type": "ptrend", "n": 30, "k": 8, "lam": 1.0}, train, m, order, years, fill=False)
line = predict(BASELINES["Linear trend"], train, m, order, years, fill=False)
n_valid = np.isfinite(train[m].y[:, -30:]).sum(axis=1)
full = n_valid >= 15
floored = np.maximum(line, 0.0) if m in ("cdd", "total_precip_in") else line # our models are floored at 0
assert np.allclose(own[full], floored[full], equal_nan=True), m
# the OLS line equals numpy.polyfit on every complete city, and the baseline line is never floored
for i in np.flatnonzero(n_valid == 30):
coef = np.polyfit(train[m].years[-30:], train[m].y[i, -30:], 1)
assert np.allclose(line[i], np.polyval(coef, years)), (m, i)
filled = predict(BASELINES["Linear trend"], train, m, order, years)
assert np.array_equal(filled[np.isfinite(line)], line[np.isfinite(line)]), m
assert skill(1.0, 2.0) == 0.5 and challenge_score({m: -1.0 for m in METRICS}) == 0.0
def test_submission_file(annual, long, P, order):
"""submission.csv is complete and is exactly what the selected models produce."""
sub = pd.read_csv(ROOT / "submission.csv", dtype={"city_id": str, "metric": str})
assert list(sub.columns) == ["city_id", "year", "metric", "predicted_value"]
assert len(sub) == N_CITIES * len(FORECAST_YEARS) * len(METRICS) == 5880
assert not sub.duplicated(["city_id", "year", "metric"]).any()
assert set(sub["city_id"]) == set(P["cdd"].city_ids) and set(sub["year"]) == set(FORECAST_YEARS)
assert set(sub["metric"]) == set(METRICS) and np.isfinite(sub["predicted_value"]).all()
selected = json.loads((REPORTS / "backtest" / "selected.json").read_text())["selected"]
ids = list(P["cdd"].city_ids)
for m in METRICS:
pred = predict(selected[m], P, m, order, np.array(FORECAST_YEARS))
got = (sub[sub["metric"] == m].pivot(index="city_id", columns="year", values="predicted_value")
.reindex(index=ids, columns=list(FORECAST_YEARS)).to_numpy())
assert np.abs(got - pred).max() < 0.0051 + 0.05 * (m == "cdd"), m # rounding only
def test_fallback_is_unscored(annual, long, P, order):
"""The fallback fills exactly the 9 city-metrics without a baseline, and never a scored backtest row."""
selected = json.loads((REPORTS / "backtest" / "selected.json").read_text())["selected"]
years = np.array(FORECAST_YEARS)
n = 0
for m in METRICS:
raw = predict(selected[m], P, m, order, years, fill=False)
filled = predict(selected[m], P, m, order, years)
unfitted = ~np.isfinite(raw).all(axis=1)
no_baseline = np.isfinite(P[m].y[:, -BASELINE_WINDOW:]).sum(axis=1) < MIN_VALID_YEARS
assert (unfitted == no_baseline).all(), m
assert np.array_equal(raw[~unfitted], filled[~unfitted]) and np.isfinite(filled).all(), m
n += int(unfitted.sum())
assert n == 9, n # the organizers' count (63 rows)
for origin, first, last in ((2011, 2012, 2018), (2004, 2005, 2011), (1997, 1998, 2004), (1990, 1991, 1997)):
f = Fold(P, origin, first, last)
for m in METRICS:
raw = predict(selected[m], f.train, m, order, f.years, fill=False)
assert np.isfinite(raw[f.scored[m]]).all(), (origin, m)
def test_external_data_capped(annual, long, P, order):
"""The NOAA extract (analysis only) holds nothing after 2018-12-31 and matches its manifest."""
from .ghcnd import EXT, load_ghcnd
if not (EXT / "MANIFEST.csv").exists():
return
noaa = load_ghcnd() # asserts sha256 per file and the 2018-12-31 cap
assert noaa["Date"].max() <= pd.Timestamp("2018-12-31")
def main():
ctx = setup()
tests = [test_leak_guard, test_no_peeking, test_neighbors_are_geography, test_selection_reproduces,
test_scoring_matches_space, test_practice_run, test_model_invariants, test_submission_file,
test_fallback_is_unscored, test_external_data_capped]
for t in tests:
t(*ctx)
print(f"ok {t.__name__}: {t.__doc__.strip().splitlines()[0]}")
print(f"{len(tests)} checks passed")
if __name__ == "__main__":
main()