"""Per-city-metric forecast candidates (all fitted only on data <= origin).""" from __future__ import annotations import numpy as np import pandas as pd CLIP_ZERO = {"total_precip_in", "cdd"} CANDIDATES = ["mean30", "mean10", "own_line", "shared_slope", "half_slope", "shrunk_slope"] # Simplicity order for near-ties (pre-registered, see backtest.py). SIMPLICITY = ["mean30", "mean10", "shared_slope", "half_slope", "shrunk_slope", "own_line"] def _ols_slope(years: np.ndarray, vals: np.ndarray) -> float: if len(years) < 3 or np.ptp(years) == 0: return 0.0 x = years - years.mean() denom = float((x * x).sum()) return float((x * (vals - vals.mean())).sum() / denom) if denom > 0 else 0.0 def _window(df: pd.DataFrame, origin: int, years_back: int) -> pd.DataFrame: return df[(df["Year"] > origin - years_back) & (df["Year"] <= origin)] def forecast_metric(train: pd.DataFrame, metric: str, origin: int, target_years: list[int], method: str) -> pd.DataFrame: """train: long valid obs for ONE metric, Year <= origin. Returns long forecasts.""" df = train[train["Year"] <= origin] cities = sorted(df["city_id"].unique()) global_mean = float(df["value"].mean()) if len(df) else 0.0 w30 = _window(df, origin, 30) # Shared (pooled within-city) slope over the 30y window. shared_slope = 0.0 if method in ("shared_slope", "shrunk_slope"): num = den = 0.0 for _, g in w30.groupby("city_id"): x = g["Year"].to_numpy(float) - g["Year"].mean() y = g["value"].to_numpy(float) - g["value"].mean() num += float((x * y).sum()); den += float((x * x).sum()) shared_slope = num / den if den > 0 else 0.0 rows = [] for city in cities: g_all = df[df["city_id"] == city] g30 = w30[w30["city_id"] == city] g10 = _window(df, origin, 10) g10 = g10[g10["city_id"] == city] base30 = float(g30["value"].mean()) if len(g30) else ( float(g_all["value"].mean()) if len(g_all) else global_mean) mean_year = float(g30["Year"].mean()) if len(g30) else float(origin - 15) own_slope = _ols_slope(g30["Year"].to_numpy(float), g30["value"].to_numpy(float)) \ if len(g30) >= 5 else shared_slope n30 = len(g30) for year in target_years: horizon_c = year - mean_year if method == "mean30": v = base30 elif method == "mean10": v = float(g10["value"].mean()) if len(g10) else base30 elif method == "own_line": v = base30 + own_slope * horizon_c elif method == "shared_slope": v = base30 + shared_slope * horizon_c elif method == "half_slope": v = base30 + 0.5 * own_slope * horizon_c elif method == "shrunk_slope": w = n30 / (n30 + 10.0) v = base30 + (w * own_slope + (1 - w) * shared_slope) * horizon_c else: raise ValueError(f"unknown method {method}") if metric in CLIP_ZERO: v = max(0.0, float(v)) rows.append({"city_id": city, "Year": int(year), "metric": metric, "value": float(v)}) return pd.DataFrame(rows) def forecast_all(train_long: pd.DataFrame, origin: int, target_years: list[int], method_by_metric: dict[str, str]) -> pd.DataFrame: parts = [] for metric, method in method_by_metric.items(): sub = train_long[train_long["metric"] == metric] parts.append(forecast_metric(sub, metric, origin, target_years, method)) return pd.concat(parts, ignore_index=True)