Datasets:
File size: 9,030 Bytes
d79a78d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | """Refit the selected models on all data up to 2018 and write submission.csv.
Reads reports/backtest/selected.json (written by the backtest: the model of each metric),
forecasts 2019-2025 for the 210 cities, validates the file with the Space's own checks,
and writes plausibility reports to reports/forecast/.
Run: PYTHONPATH=code python -m protostar.forecast
"""
import json
import numpy as np
import pandas as pd
from .common import FORECAST_YEARS, METRICS, N_CITIES, REPORTS, ROOT, TRAIN_END, UNITS
from .data import assert_no_leak, cities, load_annual, long_table, panels
from .common import BASELINE_WINDOW, MIN_VALID_YEARS
from .models import last_valid_mean, neighbor_order, predict, window_mean
OUT = REPORTS / "forecast"
COLUMNS = ["city_id", "year", "metric", "predicted_value"]
DECIMALS = {"annual_avg_temp": 2, "total_precip_in": 2, "hottest_day_temp": 2, "cdd": 1}
RANGE_FACTOR = 1.5 # flag forecasts outside the 1989-2018 [min, max] widened to 1.5x its width
def check_forecasts(df: pd.DataFrame, city_ids: set[str]) -> list[str]:
"""The checks of the challenge Space (utils.check_forecasts); [] if the file can be scored."""
if list(df.columns) != COLUMNS:
return [f"columns must be exactly {COLUMNS}"]
problems = []
year = pd.to_numeric(df["year"], errors="coerce")
value = pd.to_numeric(df["predicted_value"], errors="coerce")
for mask, what in ((~df["city_id"].isin(city_ids), "unknown city_id"),
(~year.isin(set(FORECAST_YEARS)), "year outside 2019-2025"),
(~df["metric"].isin(set(METRICS)), "unknown metric"),
(value.isna() | value.abs().eq(float("inf")), "missing or non-numeric predicted_value"),
(df.duplicated(["city_id", "year", "metric"]), "duplicate rows")):
if mask.any():
problems.append(f"{int(mask.sum())} rows: {what}")
expected = len(city_ids) * len(FORECAST_YEARS) * len(METRICS)
if not problems and len(df) != expected:
problems.append(f"{len(df)} rows; expected {expected}")
return problems
def main():
OUT.mkdir(parents=True, exist_ok=True)
annual = load_annual()
long = long_table(annual)
assert_no_leak(long["year"], "training table") # the data rule, enforced
P = panels(long)
assert all(p.origin == TRAIN_END for p in P.values())
geo = cities(annual)
ids = P["cdd"].city_ids
assert list(geo["city_id"]) == list(ids) and len(ids) == N_CITIES
order = neighbor_order(geo["lat"].to_numpy(), geo["lon"].to_numpy())
choice = json.loads((REPORTS / "backtest" / "selected.json").read_text())
assert all(choice["gate_beats_both_baselines_on_both_selection_folds"].values()), \
"the backtest gate failed: no forecast from an ungated selection"
selected = choice["selected"]
years = np.array(FORECAST_YEARS)
frames, summary, notes = [], [], []
for metric in METRICS:
pred = predict(selected[metric], P, metric, order, years)
unfitted = ~np.isfinite(predict(selected[metric], P, metric, order, years, fill=False)).all(axis=1)
no_baseline = ~np.isfinite(window_mean(P[metric], BASELINE_WINDOW, MIN_VALID_YEARS))
assert (unfitted == no_baseline).all(), "the fallback must only serve city-metrics without a baseline"
for i in np.flatnonzero(unfitted):
notes.append(f"{ids[i]} ({geo['name'].iloc[i]}) `{metric}`: no baseline (fewer than {MIN_VALID_YEARS} valid "
f"years in 1989-2018, not scored); neighbor-anomaly fallback, forecast "
f"{pred[i, 0]:.2f} .. {pred[i, -1]:.2f}")
missing = ~np.isfinite(pred).all(axis=1)
if missing.any(): # a city with no valid year at all for this metric: mean of its 8 nearest cities
for i in np.flatnonzero(missing):
near = [j for j in order[i] if not missing[j]][:8]
pred[i] = pred[near].mean(axis=0)
notes.append(f"{ids[i]} {metric}: no valid year in the record; mean of the 8 nearest cities")
pred = np.round(pred, DECIMALS[metric])
frames.append(pd.DataFrame({"city_id": np.repeat(ids, len(years)), "year": np.tile(years, len(ids)),
"metric": metric, "predicted_value": pred.ravel()}))
# plausibility against the city's own 1989-2018 valid years
hist = P[metric].y[:, -30:]
n_valid = np.isfinite(hist).sum(axis=1)
lo, hi = np.nanmin(np.where(np.isfinite(hist), hist, np.inf), axis=1), \
np.nanmax(np.where(np.isfinite(hist), hist, -np.inf), axis=1)
lo, hi = np.where(n_valid > 0, lo, np.nan), np.where(n_valid > 0, hi, np.nan)
mid, half = (lo + hi) / 2, (hi - lo) / 2
summary.append(pd.DataFrame({
"city_id": ids, "name": geo["name"].to_numpy(), "lat": geo["lat"].to_numpy(),
"lon": geo["lon"].to_numpy(), "metric": metric,
"n_valid_1989_2018": n_valid, "min_1989_2018": lo, "max_1989_2018": hi,
"mean_1989_2018": window_mean(P[metric], 30, 1), "mean_last10_valid": last_valid_mean(P[metric], 10),
"forecast_2019": pred[:, 0], "forecast_2025": pred[:, -1], "forecast_mean_2019_2025": pred.mean(axis=1),
"outside_hist_range": (pred.min(axis=1) < lo) | (pred.max(axis=1) > hi),
"outside_1p5x_range": np.abs(pred - mid[:, None]).max(axis=1) > RANGE_FACTOR * half,
}))
sub = pd.concat(frames, ignore_index=True)
sub["metric"] = pd.Categorical(sub["metric"], categories=list(METRICS), ordered=True)
sub = sub.sort_values(["city_id", "year", "metric"]).reset_index(drop=True)
sub["metric"] = sub["metric"].astype(str)
sub = sub[COLUMNS]
problems = check_forecasts(sub, set(ids))
assert not problems, problems
assert len(sub) == N_CITIES * len(FORECAST_YEARS) * len(METRICS) == 5880
assert np.isfinite(sub["predicted_value"]).all()
assert (sub.loc[sub["metric"].isin(["cdd", "total_precip_in"]), "predicted_value"] >= 0).all()
sub.to_csv(ROOT / "submission.csv", index=False)
s = pd.concat(summary, ignore_index=True)
s["change_vs_1989_2018"] = s["forecast_mean_2019_2025"] - s["mean_1989_2018"]
s["change_pct"] = 100 * s["change_vs_1989_2018"] / s["mean_1989_2018"].where(s["mean_1989_2018"].abs() > 1e-9)
s.to_csv(OUT / "forecast_summary.csv", index=False)
flagged = s[s["outside_1p5x_range"] | (s["n_valid_1989_2018"] < 10)]
lines = ["# Forecast validation", "",
"Generated by `python -m protostar.forecast` (do not edit).", "",
f"- Rows: {len(sub)} = {N_CITIES} cities x {len(FORECAST_YEARS)} years x {len(METRICS)} metrics; "
"no missing, non-finite or duplicate values; the Space's `check_forecasts` rules pass.",
f"- Training data: years <= {TRAIN_END} only (asserted in code).",
f"- Models: " + "; ".join(f"`{m}`: {json.dumps(selected[m])}" for m in METRICS), "",
"## Plausibility against each city's own 1989-2018 valid years", "",
"City-metrics with a baseline only (the 9 without one are listed below; they are not scored).", "",
"| metric | forecasts outside the historical [min, max] | outside that interval widened to 1.5x | "
"median change vs 1989-2018 mean | min change | max change |", "|---|---|---|---|---|---|"]
for metric in METRICS:
g = s[(s["metric"] == metric) & (s["n_valid_1989_2018"] >= MIN_VALID_YEARS)] # city-metrics with a baseline
ch = g["change_vs_1989_2018"]
lines.append(f"| `{metric}` ({UNITS[metric]}) | {int(g['outside_hist_range'].sum())} cities | "
f"{int(g['outside_1p5x_range'].sum())} cities | {ch.median():+.2f} | {ch.min():+.2f} | {ch.max():+.2f} |")
lines += ["", "## Flagged city-metrics (outside the 1.5x interval, or fewer than 10 valid years in 1989-2018)", ""]
if len(flagged):
cols = ["city_id", "name", "metric", "n_valid_1989_2018", "min_1989_2018", "max_1989_2018",
"mean_last10_valid", "forecast_2019", "forecast_2025", "outside_1p5x_range"]
lines += ["| " + " | ".join(cols) + " |", "|" + "---|" * len(cols)]
for _, r in flagged[cols].iterrows():
lines.append("| " + " | ".join(f"{v:.2f}" if isinstance(v, float) else str(v) for v in r) + " |")
else:
lines.append("None.")
lines += ["", "## Fallbacks used", "",
"City-metrics without a baseline cannot be fitted; `models.fallback` gives them the mean of their "
"last 10 valid years plus the change their 8 nearest fitted cities forecast relative to the same years.",
""] + ([f"- {n}" for n in notes] or ["None."])
(OUT / "VALIDATION.md").write_text("\n".join(lines) + "\n")
print("\n".join(lines[:22]))
print(f"\nwrote {ROOT / 'submission.csv'} ({len(sub)} rows); flagged city-metrics: {len(flagged)}")
if __name__ == "__main__":
main()
|