File size: 15,131 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"""Step 8 of the ARIMA experiments: rolling-origin backtest on pre-2019 data only.

Origins 1990, 1994, 1998, 2002, 2006, 2011 with a 7-year horizon (backtest.ORIGINS / backtest.H).
No random K-fold: every model sees only data up to its origin.

* Each model's predictions for every (metric, origin) are computed once and cached in
  results/arima_backtest/preds/<model>.parquet (delete the folder, or pass --force, to recompute).
* The official MAE and skill S_m come from backtest.run() (unchanged), fed the cached predictions.
* On the same rows (valid years, cities with a 30-year baseline) we add RMSE, MAPE, mean bias
  (forecast - actual) and MAE by horizon (1-7 years).
* Composite Score per origin = 100 x max(0, mean of the four S_m), averaged over origins,
  as in 02_backtest.py; computed for models that cover all four metrics.
* Reference models: last year repeated, 30-year average, 30-year linear trend, and our current
  model (final_model.forecast).

Outputs: results/arima_backtest/{metrics_by_origin.csv, summary.csv, score_by_origin.csv,
mae_by_horizon.csv, fallbacks.csv, *.png} and results/arima_orders.csv.
Run: python code/arima_backtest.py [--force] [--only name1,name2]
"""
import argparse
import time
import warnings

warnings.filterwarnings("ignore")
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

import backtest
import final_model
import models
import models_arima as ma
from arima_prep import EDA_CITIES
from backtest import COORDS, H, LV, ORIGINS
from common import METRICS, ROOT, baseline30

OUT = ROOT / "results" / "arima_backtest"
PREDS = OUT / "preds"
ALL = list(METRICS)


def last_year(lv, o, yrs, coords, metric):  # identical to 02_backtest.last_year
    W = models.wide(lv, metric, o)
    last = W.ffill(axis=1).iloc[:, -1]
    return pd.concat([pd.DataFrame({"ID": W.index, "metric": metric, "Year": y, "pred": last.values}) for y in yrs])


def P(fn, metrics=ALL, **kw):
    return dict(fn=fn, kw=kw, metrics=metrics)


MODELS = {
    # reference models
    "last_year": P(last_year),
    "avg_30yr": P(models.baseline30_model),
    "linear_trend": P(models.linear30_model),
    "ours": P(final_model.forecast),
    # fixed orders proposed by ACF/PACF (Step 5), 50-year window
    "arima_000_ct": P(ma.arima_fixed, order=(0, 0, 0), trend="ct"),
    "arima_100_ct": P(ma.arima_fixed, order=(1, 0, 0), trend="ct"),
    "arima_101_ct": P(ma.arima_fixed, order=(1, 0, 1), trend="ct"),
    "arima_100_c": P(ma.arima_fixed, order=(1, 0, 0), trend="c"),
    "arima_010_drift": P(ma.arima_fixed, order=(0, 1, 0), trend="c"),
    "arima_011_drift": P(ma.arima_fixed, order=(0, 1, 1), trend="c"),
    "arima_111_drift": P(ma.arima_fixed, order=(1, 1, 1), trend="c"),
    # auto-ARIMA (pmdarima, stepwise AICc, p,q <= 3, d <= 1)
    "auto_kpss": P(ma.auto_arima_model, test="kpss", trend0="ct"),
    "auto_kpss_c": P(ma.auto_arima_model, test="kpss", trend0="c"),
    "auto_adf": P(ma.auto_arima_model, test="adf", trend0="ct"),
    "auto_d0_ct": P(ma.auto_arima_d0_trend, trend0="ct"),
    "auto_d0_c": P(ma.auto_arima_d0_trend, trend0="c"),
    # ARMA around the pooled (all-city, 50-yr) trend rate
    "pooled_auto": P(ma.pooled_trend_arima),
    "pooled_000": P(ma.pooled_trend_arima, order=(0, 0, 0)),
    # training-window length (named by the start year at origin 2018)
    "auto_kpss@1949": P(ma.auto_arima_model, test="kpss", trend0="ct", train_start=1949),
    "auto_kpss@1979": P(ma.auto_arima_model, test="kpss", trend0="ct", train_start=1979),
    "auto_d0_ct@1949": P(ma.auto_arima_d0_trend, trend0="ct", train_start=1949),
    "auto_d0_ct@1979": P(ma.auto_arima_d0_trend, trend0="ct", train_start=1979),
    "pooled_auto@1949": P(ma.pooled_trend_arima, train_start=1949),
    "pooled_auto@1979": P(ma.pooled_trend_arima, train_start=1979),
    # CDD from the ARIMA temperature forecast (pooled_auto) + shifted daily weather
    "cdd_hybrid_N10": P(ma.cdd_hybrid, metrics=["cdd"], N=10),
    "cdd_hybrid_N20": P(ma.cdd_hybrid, metrics=["cdd"], N=20),
}
REFERENCE = ["last_year", "avg_30yr", "linear_trend", "ours"]

# fixed colour per model (validated categorical palette, fixed order); 30-yr average = neutral grey
COLORS = {"ours": "#2a78d6", "arima_011_drift": "#eb6834", "arima_100_ct": "#1baf7a",
          "linear_trend": "#eda100", "auto_kpss": "#e87ba4", "auto_d0_ct": "#008300",
          "pooled_auto": "#6250d6", "cdd_hybrid_N10": "#e34948", "avg_30yr": "#77776f"}
PLOT_MODELS = list(COLORS)


def years_for(o):
    return list(range(o + 1, min(o + H, 2018) + 1))


def compute_preds(name, spec, force=False):
    f = PREDS / f"{name.replace('@', '_at_')}.parquet"
    if f.exists() and not force:
        return pd.read_parquet(f), None
    parts, logs = [], []
    for m in spec["metrics"]:
        for o in ORIGINS:
            p = spec["fn"](LV, o, years_for(o), COORDS, m, **spec["kw"])
            lg = p.attrs.get("log")
            if lg is not None and len(lg):
                logs.append(lg.assign(model=name, metric=m, origin=o))
            q = p[["ID", "metric", "Year", "pred"]].assign(origin=o)
            q.attrs = {}  # the log travels separately; pandas compares attrs on concat
            parts.append(q)
    df = pd.concat(parts, ignore_index=True)
    df.to_parquet(f)
    return df, (pd.concat(logs, ignore_index=True) if logs else None)


def official(name, preds, metric):
    """MAE and S_m through the unchanged backtest.run(), fed the cached predictions."""
    def cached(lv, o, yrs, coords, m):
        return preds[(preds.origin == o) & (preds.metric == m) & preds.Year.isin(yrs)][["ID", "metric", "Year", "pred"]]
    return backtest.run(cached, metric)


def detail(preds, metric):
    """Per-row errors on exactly the rows common.score() uses."""
    rows = []
    for o in ORIGINS:
        yrs = years_for(o)
        lvm = LV[LV.metric == metric]
        truth = lvm[lvm.Year.isin(yrs) & lvm.valid][["ID", "metric", "Year", "value"]]
        b = baseline30(lvm, o).rename("base").reset_index()
        df = truth.merge(b, on=["ID", "metric"]).dropna(subset=["base"])
        df = df.merge(preds[(preds.origin == o) & (preds.metric == metric)].drop(columns="origin"),
                      on=["ID", "metric", "Year"], how="left")
        rows.append(df.assign(origin=o, h=df.Year - o, e=df.pred - df.value, eb=df.base - df.value))
    return pd.concat(rows, ignore_index=True)


def stats(d):
    ae = d.e.abs()
    nz = d.value.abs() > 1e-9
    return pd.Series(dict(n=len(d), MAE=ae.mean(), RMSE=np.sqrt((d.e ** 2).mean()),
                          MAPE=100 * (ae[nz] / d.value.abs()[nz]).mean(), bias=d.e.mean(),
                          MAE_base=d.eb.abs().mean(), S=1 - ae.mean() / d.eb.abs().mean()))


# --------------------------------------------------------------------------- plots
def style(ax):
    ax.grid(axis="y", color="#e4e4e0", lw=0.8); ax.set_axisbelow(True)
    for s in ("top", "right"):
        ax.spines[s].set_visible(False)
    ax.spines["left"].set_color("#b8b8b0"); ax.spines["bottom"].set_color("#b8b8b0")
    ax.tick_params(colors="#55554f", labelsize=8)


def plot_bars(summary):
    fig, axes = plt.subplots(1, 4, figsize=(18, 0.32 * summary.model.nunique() + 2), sharey=True)
    order = summary[summary.metric == "annual_avg_temp"].sort_values("S").model.tolist()
    order += [m for m in summary.model.unique() if m not in order]
    for ax, m in zip(axes, ALL):
        s = summary[summary.metric == m].set_index("model").reindex(order)
        col = [COLORS.get(k, "#9d9d95") for k in s.index]
        ax.barh(range(len(s)), s.S.values, color=col, height=0.7, edgecolor="white", linewidth=1)
        ax.axvline(0, color="#55554f", lw=0.8)
        ref = s.S.get("ours", np.nan)
        if np.isfinite(ref):
            ax.axvline(ref, color=COLORS["ours"], lw=1, ls="--")
        ax.set_yticks(range(len(s))); ax.set_yticklabels(s.index, fontsize=8)
        ax.set_title(f"{m}: mean S_m over 6 origins", fontsize=10); style(ax)
        ax.set_xlim(max(-0.4, np.nanmin(s.S.values) - 0.02), None)
        for i, v in enumerate(s.S.values):
            if np.isfinite(v):
                ax.text(v, i, f" {v:.3f}", va="center", fontsize=6.5, color="#2b2b28")
    fig.suptitle("Skill vs 30-year average (S_m = 1 - MAE/MAE_30yr); dashed = current model; "
                 "bars clipped at -0.4", fontsize=11)
    fig.tight_layout(); fig.savefig(OUT / "skill_by_model_metric.png", dpi=110); plt.close(fig)


def plot_score_lines(score):
    fig, ax = plt.subplots(figsize=(10, 5.5))
    for name in PLOT_MODELS:
        if name not in score.index:
            continue
        r = score.loc[name, ORIGINS]
        ax.plot(ORIGINS, r.values, marker="o", ms=5, lw=2 if name == "ours" else 1.5,
                color=COLORS[name], ls="--" if name == "avg_30yr" else "-", label=f"{name} (mean {score.loc[name, 'mean']:.1f})")
    ax.set_xticks(ORIGINS); ax.set_xlabel("forecast origin (forecasts origin+1 .. origin+7)")
    ax.set_ylabel("composite Score (0-100)"); style(ax)
    ax.legend(fontsize=8, frameon=False, loc="upper left")
    ax.set_title("Composite Score by origin", fontsize=11)
    fig.tight_layout(); fig.savefig(OUT / "score_by_origin.png", dpi=110); plt.close(fig)


def plot_horizon(hz):
    fig, axes = plt.subplots(1, 4, figsize=(18, 4.5))
    for ax, m in zip(axes, ALL):
        for name in PLOT_MODELS:
            s = hz[(hz.model == name) & (hz.metric == m)]
            if len(s):
                ax.plot(s.h, s.MAE, marker="o", ms=4, lw=1.5, color=COLORS[name],
                        ls="--" if name == "avg_30yr" else "-", label=name)
        ax.set_title(m, fontsize=10); ax.set_xlabel("horizon (years ahead)"); ax.set_xticks(range(1, 8)); style(ax)
    axes[0].set_ylabel("MAE (pooled over origins)")
    h, l = axes[3].get_legend_handles_labels()
    fig.legend(h, l, loc="lower center", ncol=len(l), fontsize=8, frameon=False)
    fig.tight_layout(rect=(0, 0.07, 1, 1)); fig.savefig(OUT / "mae_by_horizon.png", dpi=110); plt.close(fig)


def plot_cities(allpreds, cities=("USW00094823", "USW00023183", "USW00024233")):
    for cid in cities:
        fig, axes = plt.subplots(4, 1, figsize=(13, 13), sharex=True)
        for ax, m in zip(axes, ALL):
            t = LV[(LV.ID == cid) & (LV.metric == m) & (LV.Year >= 1970) & LV.valid]
            ax.plot(t.Year, t.value, color="#2b2b28", lw=1.2, marker=".", ms=4, label="actual")
            for name in PLOT_MODELS:
                p = allpreds.get(name)
                if p is None:
                    continue
                p = p[(p.ID == cid) & (p.metric == m)]
                for i, o in enumerate(ORIGINS):
                    q = p[p.origin == o].sort_values("Year")
                    ax.plot(q.Year, q.pred, color=COLORS[name], lw=1.5, ls="--" if name == "avg_30yr" else "-",
                            label=name if i == 0 else None)
            for o in ORIGINS:
                ax.axvline(o + 0.5, color="#d0d0c8", lw=0.8)
            ax.set_title(f"{EDA_CITIES[cid]} - {m}", fontsize=10); style(ax)
        h, l = axes[3].get_legend_handles_labels()
        fig.legend(h, l, loc="lower center", ncol=len(l), fontsize=8, frameon=False)
        fig.suptitle("Actual series and each model's 7-year forecasts from every backtest origin (grey lines = origins)", fontsize=11)
        fig.tight_layout(rect=(0, 0.03, 1, 0.98))
        fig.savefig(OUT / f"forecasts_{EDA_CITIES[cid].lower()}.png", dpi=100); plt.close(fig)


# --------------------------------------------------------------------------- main
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--force", action="store_true")
    ap.add_argument("--only", default="")
    args = ap.parse_args()
    PREDS.mkdir(parents=True, exist_ok=True)
    names = [n for n in MODELS if not args.only or n in args.only.split(",")]

    orders_f = ROOT / "results" / "arima_orders.csv"
    old_orders = pd.read_csv(orders_f) if orders_f.exists() else pd.DataFrame(columns=["model"])
    allpreds, new_logs, rows, dets = {}, [], [], []
    for name in names:
        t0 = time.time()
        preds, lg = compute_preds(name, MODELS[name], args.force)
        allpreds[name] = preds
        if lg is not None:
            new_logs.append(lg)
        for m in MODELS[name]["metrics"]:
            off = official(name, preds, m)
            d = detail(preds, m)
            for o in ORIGINS:
                s = stats(d[d.origin == o])
                r = off[off.origin == o].iloc[0]
                assert abs(s.MAE - r.mae) < 1e-9 and abs(s.S - r.S) < 1e-9, (name, m, o)
                rows.append(dict(model=name, metric=m, origin=o, **s))
            dets.append(d.assign(model=name)[["model", "metric", "origin", "h", "e", "eb"]])
        print(f"{name:18s} {time.time() - t0:6.1f}s", flush=True)

    if new_logs:
        nl = pd.concat(new_logs, ignore_index=True)
        old_orders = old_orders[~old_orders.model.isin(nl.model.unique())]
        pd.concat([old_orders, nl], ignore_index=True).to_csv(orders_f, index=False)
    orders = pd.read_csv(orders_f) if orders_f.exists() else None

    mo = pd.DataFrame(rows)
    mo.to_csv(OUT / "metrics_by_origin.csv", index=False)
    summary = mo.groupby(["model", "metric"], sort=False)[["MAE", "RMSE", "MAPE", "bias", "S"]].mean().reset_index()
    s2011 = mo[mo.origin == 2011].set_index(["model", "metric"]).S.rename("S_2011")
    summary = summary.join(s2011, on=["model", "metric"])
    summary.to_csv(OUT / "summary.csv", index=False)

    full = [n for n in names if set(MODELS[n]["metrics"]) == set(ALL)]
    score = (mo[mo.model.isin(full)].groupby(["model", "origin"]).S.mean().clip(lower=0).mul(100).unstack())
    score["mean"] = score[ORIGINS].mean(1)
    score = score.sort_values("mean", ascending=False)
    score.to_csv(OUT / "score_by_origin.csv")

    det = pd.concat(dets, ignore_index=True)
    hz = det.groupby(["model", "metric", "h"]).apply(lambda d: d.e.abs().mean(), include_groups=False).rename("MAE").reset_index()
    hz.to_csv(OUT / "mae_by_horizon.csv", index=False)

    if orders is not None and len(orders):
        fb = (orders.assign(fallback=orders.status != "ok")
              .groupby(["model", "metric"]).agg(series=("ID", "size"), fallback=("fallback", "sum"),
                                                weak=("status", lambda s: (s == "weak").sum()),
                                                failed=("status", lambda s: s.str.startswith("failed").sum())))
        fb.to_csv(OUT / "fallbacks.csv")

    pd.set_option("display.width", 250); pd.set_option("display.max_rows", 200)
    print("\nComposite Score by origin:\n", score.round(1).to_string())
    print("\nMean S_m by metric (and origin 2011):")
    print(summary.pivot(index="model", columns="metric", values="S")[ALL].round(3).to_string())
    print(summary.pivot(index="model", columns="metric", values="S_2011")[ALL].round(3).to_string())

    if len(names) == len(MODELS):
        plot_bars(summary); plot_score_lines(score); plot_horizon(hz); plot_cities(allpreds)


if __name__ == "__main__":
    main()