File size: 10,109 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
"""Additional forecasters (PROMPT_SIGUIENTE, Step A), with the repository signature

    fn(lv, origin, years, coords, metric, **kw) -> DataFrame[ID, metric, Year, pred]

All of them use only data up to `origin` (the challenge data ends 2018-12-31).

1. ETS (statsmodels ExponentialSmoothing), one model per city and metric on the regular series of
   arima_prep (50-year window by default, interior gaps interpolated, weak series -> 30-year average):
     ets_holt     Holt's linear trend
     ets_damped   Holt's damped trend
     ets_pooled   simple exponential smoothing of the series minus the pooled trend
                  (models.temp_slope of that metric), forecast = SES level + pooled trend
2. Hierarchical model (statsmodels MixedLM) on the last 50 years up to the origin:
     value ~ region + region:t + (1 + t | city),   t = (year - origin) / 10
   Regions = 9 k-means clusters of the city coordinates (random_state 0), a proxy for climate regions.
   Each city's slope is shrunk towards its region's slope; the forecast extends the city's fitted line.
   For CDD, the shrunk *temperature* slope is passed to the shifted-daily-weather CDD model
   (as models.cdd_shift, averaging N = 10 and 20 years).
3. Tmax / Tmin separately: level_trend on `Avg Tmax` and `Avg Tmin` (validity as for the average
   temperature), each with its own pooled slope; annual_avg_temp = their mean (the official
   definition is (mean Tmax + mean Tmin) / 2).
"""
import warnings

import numpy as np
import pandas as pd
from joblib import Parallel, delayed

import models
from arima_prep import prepare
from common import MAX_MISS, load_annual
from models_arima import _fallback, window_start

N_JOBS = -1


# --------------------------------------------------------------------------- per-series runner (ETS)
def _ets_forecast(cid, y, h, kind):
    from statsmodels.tsa.holtwinters import ExponentialSmoothing
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            if kind == "ses":
                m = ExponentialSmoothing(y, trend=None, initialization_method="estimated").fit()
            else:
                m = ExponentialSmoothing(y, trend="add", damped_trend=(kind == "damped"),
                                         initialization_method="estimated").fit()
            fc = np.asarray(m.forecast(h), float)
        if not np.all(np.isfinite(fc)):
            raise ValueError("non-finite")
        return cid, fc, "ok"
    except Exception as e:  # noqa: BLE001
        return cid, None, f"failed: {type(e).__name__}"


def _run_series(lv, origin, years, metric, kind, train_start=1969, offset=None):
    S = prepare(lv, metric, origin, window_start(origin, train_start))
    fb = _fallback(lv, origin, metric)
    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, max(years) - s.last_year, s.last_year))
    res = Parallel(n_jobs=N_JOBS)(delayed(_ets_forecast)(cid, y, h, kind) for cid, y, h, _ in tasks)
    last = {cid: ly for cid, _, _, ly in tasks}
    out = []
    for cid, fc, status in res:
        log.append(dict(ID=cid, status=status))
        for yr in years:
            p = fb.get(cid, np.nan) if fc is None else 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


def ets_holt(lv, origin, years, coords, metric, train_start=1969):
    return _run_series(lv, origin, years, metric, "holt", train_start)


def ets_damped(lv, origin, years, coords, metric, train_start=1969):
    return _run_series(lv, origin, years, metric, "damped", train_start)


def ets_pooled(lv, origin, years, coords, metric, L=50, slope_scale=1.0, train_start=1969):
    slope = models.temp_slope(lv, origin, coords, L=L, metric=metric) * slope_scale
    return _run_series(lv, origin, years, metric, "ses", train_start, offset=slope)


# --------------------------------------------------------------------------- hierarchical (MixedLM)
_REGIONS = {}


def regions(coords: pd.DataFrame, k: int = 9) -> pd.Series:
    if k not in _REGIONS:
        from sklearn.cluster import KMeans
        lab = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(coords[["Lat", "Lon"]].to_numpy())
        _REGIONS[k] = pd.Series(lab, index=coords.index, name="region")
    return _REGIONS[k]


def hier_fit(lv, origin, coords, metric, L=50, k_regions=9):
    """Fitted MixedLM line per city: returns (intercept at origin, slope per year) Series indexed by ID."""
    import statsmodels.formula.api as smf
    w = lv[(lv.metric == metric) & lv.valid & (lv.Year > origin - L) & (lv.Year <= origin)].copy()
    w["t"] = (w.Year - origin) / 10.0
    w["region"] = regions(coords, k_regions).reindex(w.ID).to_numpy().astype(str)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        md = smf.mixedlm("value ~ 0 + C(region) + C(region):t", w, groups="ID", re_formula="~t")
        fit = None
        for method in (["lbfgs"], ["powell", "lbfgs"], ["nm", "lbfgs"]):
            try:
                fit = md.fit(method=method, reml=True)
                break
            except Exception:  # noqa: BLE001
                continue
    if fit is None:
        raise RuntimeError("MixedLM did not fit")
    ids = sorted(w.ID.unique())
    reg = regions(coords, k_regions).reindex(ids).astype(str)
    fe = fit.fe_params
    b0 = np.array([fe.get(f"C(region)[{r}]", 0.0) for r in reg])
    b1 = np.array([fe.get(f"C(region)[{r}]:t", 0.0) for r in reg])
    re = fit.random_effects
    u0 = np.array([re[i].iloc[0] for i in ids])
    u1 = np.array([re[i].iloc[1] for i in ids])
    return (pd.Series(b0 + u0, index=ids), pd.Series((b1 + u1) / 10.0, index=ids),
            dict(converged=bool(getattr(fit, "converged", True)), n=len(w)))


def _cdd_with_slope(lv, origin, years, slope: pd.Series, N: int):
    """models.cdd_shift with an externally supplied warming rate (°F/yr per city)."""
    tab, deltas = models.shift_table()
    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()
    M = T.to_numpy()
    r = np.arange(len(M))
    s = slope.reindex(ids).fillna(slope.mean()).to_numpy()
    out = []
    for y in years:
        dl = np.clip(s * (y - ty), 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
        agg = pd.Series(M[r, lo] * (1 - f) + M[r, hi] * f, index=ids).groupby(level=0).mean()
        out.append(pd.DataFrame({"ID": agg.index, "metric": "cdd", "Year": y, "pred": agg.values}))
    df = pd.concat(out, ignore_index=True)
    return df, set(W.index) - set(df.ID)  # caller fills cities with no recent valid year


def hierarchical(lv, origin, years, coords, metric, L=50, k_regions=9, cdd_N=(10, 20)):
    if metric == "cdd":
        _, slope, info = hier_fit(lv, origin, coords, "annual_avg_temp", L, k_regions)
        parts, miss = [], set()
        for N in cdd_N:
            d, m = _cdd_with_slope(lv, origin, years, slope, N)
            parts.append(d.set_index(["ID", "metric", "Year"]).pred)
            miss |= m
        df = (sum(parts) / len(parts)).rename("pred").reset_index().dropna(subset=["pred"])
        if miss or set(models.wide(lv, "cdd", origin).index) - set(df.ID):
            fb = models.cdd_shift(lv, origin, years, coords, N=20, L=50)
            df = pd.concat([df, fb[~fb.ID.isin(df.ID)]], ignore_index=True)
    else:
        a, b, info = hier_fit(lv, origin, coords, metric, L, k_regions)
        df = pd.concat([pd.DataFrame({"ID": a.index, "metric": metric, "Year": y, "pred": (a + b * (y - origin)).values})
                        for y in years], ignore_index=True)
        fb = _fallback(lv, origin, metric)
        miss = sorted(set(fb.index) - set(a.index))
        if miss:
            df = pd.concat([df] + [pd.DataFrame({"ID": miss, "metric": metric, "Year": y, "pred": fb.reindex(miss).values})
                                   for y in years], ignore_index=True)
    df.attrs["log"] = pd.DataFrame([dict(metric=metric, origin=origin, **info)])
    return df


# --------------------------------------------------------------------------- Tmax / Tmin separately
_TMM = None


def _tmaxmin_long():
    global _TMM
    if _TMM is None:
        a = load_annual()
        valid_t = a[["Miss Tmax", "Miss Tmin"]].max(axis=1) <= MAX_MISS
        _TMM = pd.concat([pd.DataFrame({"ID": a.ID, "Year": a.Year, "metric": m, "value": a[c],
                                        "valid": valid_t & a[c].notna(), "segment": a["Station Segment"]})
                          for m, c in (("avg_tmax", "Avg Tmax"), ("avg_tmin", "Avg Tmin"))], ignore_index=True)
    return _TMM


def tmax_tmin(lv, origin, years, coords, metric="annual_avg_temp", k=15, L=50, slope_scale=1.25):
    """annual_avg_temp = mean of level_trend forecasts of Avg Tmax and Avg Tmin (pooled slope of each)."""
    assert metric == "annual_avg_temp", "tmax_tmin only forecasts annual_avg_temp"
    ext = _tmaxmin_long()
    ext = ext[ext.Year <= origin]
    parts = [models.level_trend(ext, origin, years, coords, m, k=k, L=L, slope_scale=slope_scale)
             .set_index(["ID", "Year"]).pred for m in ("avg_tmax", "avg_tmin")]
    p = ((parts[0] + parts[1]) / 2).rename("pred").reset_index()
    return p.assign(metric=metric)[["ID", "metric", "Year", "pred"]]