File size: 4,700 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
"""Step 2 of the ARIMA experiments: turn the valid annual history into regular series for ARIMA.

ARIMA needs one value per year with no gaps. For each city x metric series, using only data
up to the forecast origin (never after 2018):
  * keep the window train_start..origin;
  * invalid years (official 10-day rule, from common.long_valid) are NaN;
  * the series runs from its first to its last valid year inside the window; interior gaps are
    filled by linear interpolation (course week 2). Nothing is extrapolated: if the last valid
    year is before `origin`, the series simply ends there and the model forecasts further ahead;
  * a series is "weak" when more than 20 % of its years are imputed (or it has fewer than
    MIN_OBS valid years). Weak series use the fallback model (30-year average) in models_arima.

Run as a script to print the imputation summary for the 1969-2018 window:
    python code/arima_prep.py
"""
from dataclasses import dataclass

import numpy as np
import pandas as pd

from common import CUTOFF_YEAR, METRICS, load_annual, long_valid

TRAIN_STARTS = (1949, 1969, 1979)
MAX_IMPUTED_FRAC = 0.20
MIN_OBS = 15

# The six cities used for EDA, ACF/PACF and residual diagnostics.
EDA_CITIES = {
    "USW00094823": "Pittsburgh",
    "USW00024233": "Seattle",
    "USW00023183": "Phoenix",
    "USW00012839": "Miami",
    "USW00014922": "Minneapolis",
    "USW00003017": "Denver",
}


@dataclass
class Series:
    """One regular annual series ready for ARIMA."""
    ID: str
    metric: str
    years: np.ndarray      # consecutive years, first..last valid year in the window
    y: np.ndarray          # values (interior gaps linearly interpolated)
    n_imputed: int
    weak: bool

    @property
    def last_year(self) -> int:
        return int(self.years[-1]) if len(self.years) else -1


def wide_window(lv: pd.DataFrame, metric: str, origin: int, train_start: int) -> pd.DataFrame:
    """cities x years (train_start..origin) matrix of valid values; NaN = invalid or missing."""
    if origin > CUTOFF_YEAR:
        raise RuntimeError(f"origin {origin} is after {CUTOFF_YEAR}: data rule violated")
    w = lv[(lv.metric == metric) & (lv.Year >= train_start) & (lv.Year <= origin)]
    w = w.assign(value=w.value.where(w.valid))
    W = w.pivot(index="ID", columns="Year", values="value")
    return W.reindex(columns=range(train_start, origin + 1))


def regularize(row: pd.Series) -> tuple[np.ndarray, np.ndarray, int]:
    """Trim to first..last valid year, linearly interpolate interior gaps (no extrapolation)."""
    ok = row.notna().to_numpy()
    if not ok.any():
        return np.array([], int), np.array([]), 0
    i0, i1 = np.argmax(ok), len(ok) - 1 - np.argmax(ok[::-1])
    r = row.iloc[i0:i1 + 1]
    n_imp = int(r.isna().sum())
    y = r.interpolate(method="linear", limit_area="inside").to_numpy(float)
    return r.index.to_numpy(int), y, n_imp


def prepare(lv: pd.DataFrame, metric: str, origin: int, train_start: int) -> dict[str, Series]:
    """All series of one metric, regularized for ARIMA, keyed by city ID."""
    W = wide_window(lv, metric, origin, train_start)
    out = {}
    for cid, row in W.iterrows():
        years, y, n_imp = regularize(row)
        n = len(y)
        weak = n - n_imp < MIN_OBS or (n > 0 and n_imp / n > MAX_IMPUTED_FRAC)
        out[cid] = Series(cid, metric, years, y, n_imp, bool(weak))
    return out


def imputation_table(lv: pd.DataFrame, origin: int, train_start: int) -> pd.DataFrame:
    rows = []
    for m in METRICS:
        for s in prepare(lv, m, origin, train_start).values():
            rows.append(dict(ID=s.ID, metric=m, first=s.years[0] if len(s.years) else None,
                             last=s.last_year, n_years=len(s.y), n_imputed=s.n_imputed,
                             frac_imputed=s.n_imputed / max(len(s.y), 1), weak=s.weak))
    return pd.DataFrame(rows)


if __name__ == "__main__":
    from common import ROOT
    lv = long_valid(load_annual())
    out = ROOT / "results"
    out.mkdir(exist_ok=True)
    tabs = []
    for ts in TRAIN_STARTS:
        t = imputation_table(lv, CUTOFF_YEAR, ts).assign(train_start=ts)
        tabs.append(t)
        print(f"\nWindow {ts}-{CUTOFF_YEAR}")
        print(t.groupby("metric").agg(series=("ID", "size"), imputed_years=("n_imputed", "sum"),
                                      with_any_gap=("n_imputed", lambda s: (s > 0).sum()),
                                      ends_before_2018=("last", lambda s: (s < CUTOFF_YEAR).sum()),
                                      weak=("weak", "sum")).to_string())
    pd.concat(tabs).to_csv(out / "arima_imputation.csv", index=False)
    print(f"\nwrote {out / 'arima_imputation.csv'}")