Datasets:
File size: 9,282 Bytes
b47743b | 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 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | """Step 6 of the ARIMA experiments: ARIMA / auto-ARIMA forecasters with the repository's model signature
fn(lv, origin, years, coords, metric, **kw) -> DataFrame[ID, metric, Year, pred]
One model is fitted per city and metric on the regular series from arima_prep (data <= origin only).
Training window: `train_start` names the window used for the final forecast at origin 2018
(1949 -> 70 years, 1969 -> 50 years, 1979 -> 40 years). At an earlier backtest origin the same
*length* is used, ending at that origin, so the backtest measures the configuration that is
actually used for 2019-2025.
Trend handling (pmdarima / statsmodels SARIMAX conventions, checked in Step 6):
d=0, trend='ct' ARMA around a deterministic linear trend
d=0, trend='c' ARMA around a constant mean
d=1, trend='c' ARIMA with drift (the constant of the differenced series)
In auto-ARIMA, d is chosen first by pmdarima.ndiffs(test=...) with max_d=1, which is exactly
what pmdarima.auto_arima does internally. Fixing d before the search lets the trend
depend on d ('ct' for d=0, drift for d=1).
Fallback: weak series (arima_prep) and fits that fail or produce non-finite forecasts use the
30-year average (common.baseline30). Every prediction frame carries `.attrs["log"]` with the chosen
order, AICc and status per series, which arima_backtest.py collects into results/arima_orders.csv.
"""
import warnings
import numpy as np
import pandas as pd
import pmdarima as pm
from joblib import Parallel, delayed
from pmdarima.arima import ndiffs
import models
from arima_prep import prepare
from common import CUTOFF_YEAR, baseline30
N_JOBS = -1
RANDOM_STATE = 0
AUTO_KW = dict(seasonal=False, max_p=3, max_q=3, max_d=1, start_p=0, start_q=0,
information_criterion="aicc", stepwise=True, suppress_warnings=True,
error_action="ignore", random_state=RANDOM_STATE)
# --------------------------------------------------------------------------- single-series core
def fit_series(y: np.ndarray, spec: dict):
"""Fit one series. spec: kind 'fixed' (order, trend) or 'auto' (d or test, trend0).
Returns the fitted pmdarima.ARIMA."""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
if spec["kind"] == "fixed":
return pm.ARIMA(order=spec["order"], trend=spec["trend"], suppress_warnings=True).fit(y)
d = spec.get("d")
if d is None:
d = ndiffs(y, alpha=0.05, test=spec.get("test", "kpss"), max_d=1)
trend = spec.get("trend0", "ct") if d == 0 else "c"
return pm.auto_arima(y, d=d, trend=trend, **AUTO_KW)
def _fit_forecast(cid, y, h, spec):
try:
m = fit_series(y, spec)
fc = np.asarray(m.predict(h), float)
if not np.all(np.isfinite(fc)):
raise ValueError("non-finite forecast")
return cid, fc, dict(order=str(m.order), d=m.order[1], trend=m.trend, aicc=m.aicc(), status="ok")
except Exception as e: # noqa: BLE001 - any failure falls back to the 30-year average
return cid, None, dict(order=None, d=None, trend=None, aicc=np.nan, status=f"failed: {type(e).__name__}")
def window_start(origin: int, train_start: int) -> int:
return origin - (CUTOFF_YEAR - train_start)
def _fallback(lv, origin, metric):
b = baseline30(lv[lv.metric == metric], origin).xs(metric, level="metric")
allmean = lv[(lv.metric == metric) & lv.valid & (lv.Year <= origin)].groupby("ID").value.mean()
return b.reindex(allmean.index).fillna(allmean)
def run_arima(lv, origin, years, coords, metric, spec, train_start=1969, offset=None):
"""Fit `spec` to every city's series and forecast `years`.
offset: optional Series of per-city slopes (units/yr); the model is fitted to
y - slope*(year - origin) and the slope term is added back to the forecast."""
S = prepare(lv, metric, origin, window_start(origin, train_start))
fb = _fallback(lv, origin, metric)
ymax = max(years)
tasks, log = [], []
for cid, s in S.items():
if s.weak or len(s.y) == 0:
log.append(dict(ID=cid, status="weak"))
continue
y = s.y if offset is None else s.y - offset[cid] * (s.years - origin)
tasks.append((cid, y, ymax - s.last_year, s.last_year))
res = Parallel(n_jobs=N_JOBS)(delayed(_fit_forecast)(cid, y, h, spec) for cid, y, h, _ in tasks)
last = {cid: ly for cid, _, _, ly in tasks}
out = []
for cid, fc, info in res:
log.append(dict(ID=cid, **info))
for yr in years:
if fc is None:
p = fb.get(cid, np.nan)
else:
p = fc[yr - last[cid] - 1] + (0 if offset is None else offset[cid] * (yr - origin))
out.append((cid, yr, p))
for r in log:
if r["status"] == "weak":
out += [(r["ID"], yr, fb.get(r["ID"], np.nan)) for yr in years]
df = pd.DataFrame(out, columns=["ID", "Year", "pred"]).assign(metric=metric)[["ID", "metric", "Year", "pred"]]
df.attrs["log"] = pd.DataFrame(log).assign(metric=metric, origin=origin)
return df
# --------------------------------------------------------------------------- candidate models
def arima_fixed(lv, origin, years, coords, metric, order=(1, 0, 0), trend="ct", train_start=1969):
"""Fixed order from the ACF/PACF step, e.g. (1,0,0)+'ct', (0,1,1) with drift ('c')."""
return run_arima(lv, origin, years, coords, metric, dict(kind="fixed", order=order, trend=trend), train_start)
def auto_arima_model(lv, origin, years, coords, metric, test="kpss", trend0="ct", train_start=1969):
"""pmdarima auto-ARIMA: d in {0,1} by `test`, then stepwise AICc search over p,q <= 3.
trend0 is the deterministic term used when d=0; with d=1 a drift is always allowed."""
return run_arima(lv, origin, years, coords, metric, dict(kind="auto", test=test, trend0=trend0), train_start)
def auto_arima_d0_trend(lv, origin, years, coords, metric, trend0="ct", train_start=1969):
"""auto-ARIMA forced to d=0 with a deterministic linear trend: ARMA around the city's own trend."""
return run_arima(lv, origin, years, coords, metric, dict(kind="auto", d=0, trend0=trend0), train_start)
def pooled_trend_arima(lv, origin, years, coords, metric, L=50, k_nn=None, slope_scale=1.0,
order=None, train_start=1969):
"""ARIMA with a pooled-trend regressor (the most promising variant).
The trend rate is models.temp_slope (mean of the cities' OLS slopes of this metric over the
last L years, all cities or the k_nn nearest), computed with data <= origin only. It is
removed from the series, a d=0 ARMA with constant is fitted to the remainder (auto-ARIMA, or
a fixed `order`), and the forecast is ARMA(remainder) + pooled trend."""
slope = models.temp_slope(lv, origin, coords, L=L, k_nn=k_nn, metric=metric) * slope_scale
spec = (dict(kind="auto", d=0, trend0="c") if order is None
else dict(kind="fixed", order=order, trend="c"))
return run_arima(lv, origin, years, coords, metric, spec, train_start, offset=slope)
def cdd_hybrid(lv, origin, years, coords, metric="cdd", N=10, temp_fn=pooled_trend_arima, temp_kw=None):
"""CDD from an ARIMA temperature forecast and shifted daily weather.
For target year y and each valid past year t in the last N years, the daily mean temperatures
of year t are shifted by (forecast annual mean temperature of y) - (observed annual mean of t),
and CDD is read from data/processed/shift_table.parquet (as in models.cdd_shift). The forecast
is the mean over those N years. This keeps CDD's nonlinear response to warming while the
temperature path comes from ARIMA."""
assert metric == "cdd"
tab, deltas = models.shift_table()
tp = temp_fn(lv, origin, years, coords, "annual_avg_temp", **(temp_kw or {}))
tlog = tp.attrs.pop("log", pd.DataFrame())
Tp = tp.pivot(index="ID", columns="Year", values="pred")
Tobs = models.wide(lv, "annual_avg_temp", origin)
W = models.wide(lv, "cdd", origin)
valid = W.notna().stack()
win = [ix for ix in valid[valid].index if ix[1] > origin - N and ix in tab.index]
T = tab.loc[win]
ids = T.index.get_level_values(0)
ty = T.index.get_level_values(1).to_numpy()
tobs = Tobs.stack().reindex(pd.MultiIndex.from_arrays([ids, ty])).to_numpy()
M = T.to_numpy()
r = np.arange(len(M))
out = []
for y in years:
dl = np.clip(Tp[y].reindex(ids).to_numpy() - tobs, deltas[0], deltas[-1])
pos = np.interp(dl, deltas, np.arange(len(deltas)))
lo = np.floor(pos).astype(int); hi = np.minimum(lo + 1, len(deltas) - 1); f = pos - lo
v = pd.Series(M[r, lo] * (1 - f) + M[r, hi] * f, index=ids)
agg = v.groupby(level=0).mean()
out.append(pd.DataFrame({"ID": agg.index, "metric": metric, "Year": y, "pred": agg.values}))
df = pd.concat(out, ignore_index=True).dropna(subset=["pred"])
miss = set(W.index) - set(df.ID)
if miss: # no valid recent year: fall back to the existing CDD model
fb = models.cdd_shift(lv, origin, years, coords, N=20, L=50)
df = pd.concat([df, fb[fb.ID.isin(miss)]], ignore_index=True)
df.attrs["log"] = tlog.assign(note="temperature model inside cdd_hybrid")
return df
|