"""Step 7 of the ARIMA experiments: residual diagnostics of the candidate models. Every candidate is fitted at origin 2018 on the 50-year window 1969-2018 to all 840 series (weak series skipped, as in the models). For each fit: * Ljung-Box test on the residuals at lags 5 and 10 (model_df = p + q when smaller than the lag; the first d residuals, which come from the diffuse start of a differenced model, are dropped); * AICc. AICc is only comparable between models fitted to the same data: the d=0 models on y, the d=1 models on the differenced series, the pooled-trend models on the de-trended series. Figures for the 6 EDA cities (residual line, histogram, ACF) for auto_kpss and pooled_auto. Outputs: results/arima_diagnostics.csv, results/arima_diagnostics_summary.csv, results/arima_diagnostics/resid__.png Run: python code/arima_diagnostics.py """ import warnings warnings.filterwarnings("ignore") import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import pandas as pd from joblib import Parallel, delayed from statsmodels.stats.diagnostic import acorr_ljungbox from statsmodels.tsa.stattools import acf import models from arima_prep import EDA_CITIES, prepare from common import CUTOFF_YEAR, METRICS, ROOT, load_annual, long_valid from models_arima import fit_series START = 1969 OUT = ROOT / "results" / "arima_diagnostics" CANDIDATES = { "arima_000_ct": (dict(kind="fixed", order=(0, 0, 0), trend="ct"), False), "arima_100_ct": (dict(kind="fixed", order=(1, 0, 0), trend="ct"), False), "arima_101_ct": (dict(kind="fixed", order=(1, 0, 1), trend="ct"), False), "arima_100_c": (dict(kind="fixed", order=(1, 0, 0), trend="c"), False), "arima_010_drift": (dict(kind="fixed", order=(0, 1, 0), trend="c"), False), "arima_011_drift": (dict(kind="fixed", order=(0, 1, 1), trend="c"), False), "arima_111_drift": (dict(kind="fixed", order=(1, 1, 1), trend="c"), False), "auto_kpss": (dict(kind="auto", test="kpss", trend0="ct"), False), "auto_adf": (dict(kind="auto", test="adf", trend0="ct"), False), "auto_d0_ct": (dict(kind="auto", d=0, trend0="ct"), False), "auto_d0_c": (dict(kind="auto", d=0, trend0="c"), False), "pooled_auto": (dict(kind="auto", d=0, trend0="c"), True), } DATA = {"arima_010_drift": "Δy", "arima_011_drift": "Δy", "arima_111_drift": "Δy", "pooled_auto": "y - pooled trend"} PLOT = ["auto_kpss", "pooled_auto"] def diag(name, cid, metric, y, spec, keep_resid=False): try: m = fit_series(y, spec) except Exception as e: # noqa: BLE001 return dict(model=name, ID=cid, metric=metric, status=f"failed: {type(e).__name__}") p, d, q = m.order r = np.asarray(m.resid())[d:] out = dict(model=name, ID=cid, metric=metric, status="ok", order=str(m.order), d=d, aicc=m.aicc(), data="Δy" if (d == 1 and spec["kind"] == "auto") else DATA.get(name, "y")) for lag in (5, 10): mdf = p + q if p + q < lag else 0 out[f"lb{lag}_p"] = acorr_ljungbox(r, lags=[lag], model_df=mdf)["lb_pvalue"].iloc[0] if keep_resid: out["resid"] = r return out def main(): OUT.mkdir(parents=True, exist_ok=True) lv = long_valid(load_annual()) A = load_annual() coords = A.groupby("ID")[["Lat", "Lon"]].first() tasks = [] for metric in METRICS: S = prepare(lv, metric, CUTOFF_YEAR, START) slope = models.temp_slope(lv, CUTOFF_YEAR, coords, L=50, metric=metric) for cid, s in S.items(): if s.weak or len(s.y) == 0: continue for name, (spec, pooled) in CANDIDATES.items(): y = s.y - slope[cid] * (s.years - CUTOFF_YEAR) if pooled else s.y tasks.append((name, cid, metric, y, spec, cid in EDA_CITIES and name in PLOT)) res = Parallel(n_jobs=-1, batch_size=8)(delayed(diag)(*t) for t in tasks) t = pd.DataFrame(res) t.drop(columns="resid").to_csv(ROOT / "results" / "arima_diagnostics.csv", index=False) ok = t[t.status == "ok"] g = ok.groupby(["model", "metric"]) summ = pd.DataFrame({ "fits": g.size(), "failed": t[t.status != "ok"].groupby(["model", "metric"]).size(), "% LB5 p<0.05": g.lb5_p.apply(lambda p: (p < 0.05).mean() * 100), "% LB10 p<0.05": g.lb10_p.apply(lambda p: (p < 0.05).mean() * 100), "median AICc": g.aicc.median(), "data": g.data.agg(lambda s: s.mode().iloc[0]), }).fillna({"failed": 0}) # AICc wins among d=0 models fitted on y itself (comparable likelihoods) d0 = ok[ok.model.isin(["arima_000_ct", "arima_100_ct", "arima_101_ct", "arima_100_c", "auto_d0_ct", "auto_d0_c"])] win = d0.loc[d0.groupby(["ID", "metric"]).aicc.idxmin()].groupby(["metric", "model"]).size() win = (win / win.groupby(level=0).transform("sum") * 100).rename("% lowest AICc among d=0 on y") summ = summ.join(win.swaplevel(), how="left") summ.to_csv(ROOT / "results" / "arima_diagnostics_summary.csv") pd.set_option("display.width", 250); pd.set_option("display.max_rows", 100) print(summ.round(1).to_string()) print("\nauto_kpss / auto_adf chosen orders (origin 2018):") for nm in ("auto_kpss", "auto_adf", "auto_d0_ct", "pooled_auto"): print(nm, ok[ok.model == nm].groupby("metric").order.agg(lambda s: s.value_counts().head(5).to_dict()).to_dict()) # residual figures for the 6 cities figs = t[t.get("resid").notna()] if "resid" in t else t.iloc[0:0] for cid, name in EDA_CITIES.items(): for mdl in PLOT: fig, ax = plt.subplots(4, 3, figsize=(14, 12)) for i, metric in enumerate(METRICS): r = figs[(figs.ID == cid) & (figs.model == mdl) & (figs.metric == metric)] if r.empty: continue r = r.iloc[0] e = r.resid ax[i, 0].plot(range(START + r.d, START + r.d + len(e)), e, color="#2a78d6", lw=1) ax[i, 0].axhline(0, color="#55554f", lw=0.8) ax[i, 0].set_title(f"{metric} {r.order}: residuals", fontsize=9) ax[i, 1].hist(e, bins=12, color="#2a78d6", edgecolor="white") ax[i, 1].set_title(f"histogram (LB10 p = {r.lb10_p:.2f})", fontsize=9) a = acf(e, nlags=10, fft=False)[1:] band = 1.96 / np.sqrt(len(e)) ax[i, 2].bar(range(1, 11), a, width=0.4, color=np.where(np.abs(a) > band, "#e34948", "#2a78d6")) ax[i, 2].axhline(band, ls="--", c="#55554f", lw=0.8); ax[i, 2].axhline(-band, ls="--", c="#55554f", lw=0.8) ax[i, 2].axhline(0, c="#55554f", lw=0.5); ax[i, 2].set_ylim(-0.6, 0.6) ax[i, 2].set_title("residual ACF (band ±1.96/√N; red = outside)", fontsize=9) for a_ in ax[i]: for s in ("top", "right"): a_.spines[s].set_visible(False) fig.suptitle(f"{name}: residual diagnostics of {mdl}, fitted on {START}-{CUTOFF_YEAR}", fontsize=11) fig.tight_layout(); fig.savefig(OUT / f"resid_{name.lower()}_{mdl}.png", dpi=95); plt.close(fig) if __name__ == "__main__": main()