"""Forecast models. Each is a pure function of training panels that end at the origin. A model is described by a small dict (a "spec") so the backtest and the final refit run exactly the same code: {"type": "mean", "n": 30} 30-year average (organizers' baseline) {"type": "ols", "n": 30} per-city straight line (organizers' baseline; never floored: it stays a straight line) {"type": "last"} last valid year repeated (organizers' baseline) {"type": "recent", "n": 10} mean of the last n valid years {"type": "ptrend", "n": 30, "k": 16, "lam": .5} line through the n-year centroid whose slope is lam * own OLS slope + (1 - lam) * mean slope of the k nearest cities (k = 0: all other cities) {"type": "cdd_via_temp", "n": 30, "temp": spec} per-city regression cdd ~ annual_avg_temp on the last n years, applied to the temperature forecast {"type": "blend", "parts": [[w, spec], ...]} convex combination (weights shared by all cities) `predict()` never sees a year after the panels' last year, so leakage is impossible by construction; it also asserts that last year is <= 2018. City-metrics a model cannot fit (fewer than 10 valid years in the window: no baseline, not scored by the organizers) are filled by `fallback()`. """ import numpy as np from .common import BASELINE_WINDOW, MIN_VALID_YEARS, TRAIN_END from .data import Panel, assert_no_leak EARTH_RADIUS_KM = 6371.0088 OWN_SLOPE_MIN_YEARS = 15 # a city's own slope needs this many valid years in the window FALLBACK_YEARS = 10 # fallback level: the city's last 10 valid years, reaching back over gaps FALLBACK_NEIGHBORS = 8 # ... moved by what its 8 nearest fitted cities forecast relative to those years # ── Geography ──────────────────────────────────────────────────────────────── def distance_km(lat, lon) -> np.ndarray: """Great-circle (haversine) distance matrix between all cities, in km.""" la, lo = np.radians(np.asarray(lat, float)), np.radians(np.asarray(lon, float)) dla, dlo = la[:, None] - la[None, :], lo[:, None] - lo[None, :] h = np.sin(dla / 2) ** 2 + np.cos(la)[:, None] * np.cos(la)[None, :] * np.sin(dlo / 2) ** 2 return 2 * EARTH_RADIUS_KM * np.arcsin(np.sqrt(np.clip(h, 0, 1))) def neighbor_order(lat, lon) -> np.ndarray: """[n_city, n_city - 1]: for each city, the other cities from nearest to farthest.""" d = distance_km(lat, lon) np.fill_diagonal(d, np.inf) return np.argsort(d, axis=1, kind="stable")[:, :-1] # ── Building blocks (p is a training panel; its last year is the origin) ───── def window_mean(p: Panel, n: int, min_valid: int = 1) -> np.ndarray: """Mean of the valid years among the last n calendar years; NaN below min_valid.""" y = p.y[:, -n:] count = np.isfinite(y).sum(axis=1) total = np.where(np.isfinite(y), y, 0.0).sum(axis=1) return np.where(count >= max(min_valid, 1), total / np.maximum(count, 1), np.nan) def last_valid_mean(p: Panel, n: int) -> np.ndarray: """Mean of each city's last n valid years, reaching back over gaps; NaN if none.""" out = np.full(len(p.city_ids), np.nan) for i, row in enumerate(p.y): valid = row[np.isfinite(row)] if valid.size: out[i] = valid[-n:].mean() return out def ols(p: Panel, n: int): """Per-city least squares on the valid years of the last n calendar years. Returns (count, mean year, mean value, slope); slope is NaN with < 2 valid years. """ years = p.years[-n:].astype(float) y = p.y[:, -n:] ok = np.isfinite(y) count = ok.sum(axis=1) safe = np.maximum(count, 1) tbar = (ok * years).sum(axis=1) / safe ybar = np.where(ok, y, 0.0).sum(axis=1) / safe dt = (years[None, :] - tbar[:, None]) * ok sxx = (dt ** 2).sum(axis=1) sxy = (dt * np.where(ok, y, 0.0)).sum(axis=1) slope = np.where(sxx > 0, sxy / np.where(sxx > 0, sxx, 1.0), np.nan) none = count == 0 return count, np.where(none, np.nan, tbar), np.where(none, np.nan, ybar), slope def pooled_slope(slope: np.ndarray, order: np.ndarray, k: int, lam: float) -> np.ndarray: """lam * own slope + (1 - lam) * mean slope of the k nearest cities with a slope. k = 0 pools all other cities. A city without its own slope takes the neighbors' mean. """ neighbor = np.full(len(slope), np.nan) for i in range(len(slope)): s = slope[order[i]] s = s[np.isfinite(s)] if k: s = s[:k] if s.size: neighbor[i] = s.mean() own = np.where(np.isfinite(slope), slope, neighbor) return lam * own + (1.0 - lam) * np.where(np.isfinite(neighbor), neighbor, own) # ── Models ─────────────────────────────────────────────────────────────────── def _flat(value: np.ndarray, target_years) -> np.ndarray: return np.repeat(value[:, None], len(target_years), axis=1) def _predict(spec: dict, panels: dict[str, Panel], metric: str, order: np.ndarray, target_years: np.ndarray) -> np.ndarray: p = panels[metric] kind = spec["type"] if kind == "mean": # baseline rule: needs MIN_VALID_YEARS valid years in the window return _flat(window_mean(p, spec["n"], spec.get("min_valid", MIN_VALID_YEARS)), target_years) if kind == "recent": return _flat(last_valid_mean(p, spec["n"]), target_years) if kind == "last": return _flat(last_valid_mean(p, 1), target_years) if kind == "ols": # organizers' linear trend: a line through the valid years of the window count, tbar, ybar, slope = ols(p, spec["n"]) line = ybar[:, None] + slope[:, None] * (target_years[None, :] - tbar[:, None]) return np.where((count >= spec.get("min_valid", MIN_VALID_YEARS))[:, None], line, np.nan) if kind == "ptrend": count, tbar, ybar, slope = ols(p, spec["n"]) own = np.where(count >= OWN_SLOPE_MIN_YEARS, slope, np.nan) b = pooled_slope(own, order, spec["k"], spec["lam"]) line = ybar[:, None] + b[:, None] * (target_years[None, :] - tbar[:, None]) return np.where((count >= MIN_VALID_YEARS)[:, None], line, np.nan) if kind == "cdd_via_temp": assert metric == "cdd" temp = panels["annual_avg_temp"] n = spec["n"] x, y = temp.y[:, -n:], p.y[:, -n:] ok = np.isfinite(x) & np.isfinite(y) count = ok.sum(axis=1) safe = np.maximum(count, 1) xbar = np.where(ok, x, 0.0).sum(axis=1) / safe ybar = np.where(ok, y, 0.0).sum(axis=1) / safe dx = (x - xbar[:, None]) * ok sxx = (np.where(ok, dx, 0.0) ** 2).sum(axis=1) sxy = (np.where(ok, dx, 0.0) * np.where(ok, y, 0.0)).sum(axis=1) beta = np.where(sxx > 0, sxy / np.where(sxx > 0, sxx, 1.0), np.nan) t_hat = predict(spec["temp"], panels, "annual_avg_temp", order, target_years) out = ybar[:, None] + beta[:, None] * (t_hat - xbar[:, None]) return np.where((count >= MIN_VALID_YEARS)[:, None], out, np.nan) if kind == "blend": weights = np.array([w for w, _ in spec["parts"]], float) assert (weights >= -1e-12).all() and abs(weights.sum() - 1.0) < 1e-9, "blend must be convex" parts = [_predict(s, panels, metric, order, target_years) for _, s in spec["parts"]] return sum(w * part for w, part in zip(weights, parts)) raise ValueError(f"unknown model type {kind!r}") def fallback(p: Panel, raw: np.ndarray, order: np.ndarray) -> np.ndarray: """Fill the rows of `raw` ([n_city, n_year] forecasts) that the model could not fit. Such a city-metric has fewer than 10 valid years in the window, so its recent level is unknown. Its level is the mean of its last FALLBACK_YEARS valid years (reaching back over gaps, possibly decades); the forecast is that level plus the regional change since those years: the mean, over the FALLBACK_NEIGHBORS nearest fitted cities, of (their forecast minus their own mean over the same years). Without usable neighbors the level itself is used; a city-metric with no valid year at all stays NaN. Only training data enters. """ out = raw.copy() fitted = np.isfinite(raw).all(axis=1) for i in np.flatnonzero(~fitted): idx = np.flatnonzero(np.isfinite(p.y[i]))[-FALLBACK_YEARS:] if idx.size == 0: continue level = p.y[i, idx].mean() deltas = [] for j in order[i]: if not fitted[j]: continue same_years = p.y[j, idx] ok = np.isfinite(same_years) if ok.sum() >= max(3, (idx.size + 1) // 2): deltas.append(raw[j] - same_years[ok].mean()) if len(deltas) == FALLBACK_NEIGHBORS: break out[i] = level + (np.mean(deltas, axis=0) if deltas else 0.0) return out def predict(spec: dict, panels: dict[str, Panel], metric: str, order: np.ndarray, target_years, fill: bool = True) -> np.ndarray: """Forecast `metric` for `target_years` -> [n_city, n_year]. panels: training panels of every metric, all ending at the origin (<= 2018). fill: fill what the model could not fit with `fallback` (those city-metrics have no baseline and are not scored). """ target_years = np.asarray(target_years, dtype=float) for q in panels.values(): assert_no_leak(q.years, f"training panel {q.metric}", TRAIN_END) assert q.origin == panels[metric].origin, "panels must end at the same origin" assert target_years.min() > panels[metric].origin, "targets must be after the origin" out = _predict(spec, panels, metric, order, target_years) if fill: out = fallback(panels[metric], out, order) if metric in ("cdd", "total_precip_in") and spec["type"] != "ols": out = np.where(np.isfinite(out), np.maximum(out, 0.0), out) # physical floor (our models only) return out BASELINES = { "30-year average": {"type": "mean", "n": BASELINE_WINDOW}, "Linear trend": {"type": "ols", "n": BASELINE_WINDOW}, "Last year repeated": {"type": "last"}, }