File size: 5,570 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
"""Step 3 of the ARIMA experiments: exploratory analysis of 6 representative cities x 4 metrics.

Data: valid annual values up to 2018 only (window 1949-2018, invalid years left as gaps).
Outputs in results/arima_eda/:
  descriptive_stats.csv           mean, sd, min, max, missing years, per city x metric
  lines_<metric>.png              time series of the 6 cities
  box_decade_<metric>.png         box plots by decade (outliers, level shifts)
  acf_<metric>.png                ACF of the (interpolated) raw series; slow decay => trend
  decomp_<metric>.png             trend = centered 10-yr moving average, residual = series - trend
                                  (annual data has no seasonality, so STL's seasonal part is not used)
Run: python code/arima_eda.py
"""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import acf

from arima_prep import EDA_CITIES, prepare, wide_window
from common import CUTOFF_YEAR, METRICS, ROOT, load_annual, long_valid

START = 1949
OUT = ROOT / "results" / "arima_eda"
UNITS = {"annual_avg_temp": "°F", "total_precip_in": "in", "hottest_day_temp": "°F", "cdd": "°F-days"}


def grid(title):
    fig, axes = plt.subplots(2, 3, figsize=(15, 7.5), sharex=False)
    fig.suptitle(title, fontsize=13)
    return fig, axes.ravel()


def main():
    OUT.mkdir(parents=True, exist_ok=True)
    lv = long_valid(load_annual())
    stats, acf_rows, decomp_rows = [], [], []
    for m in METRICS:
        W = wide_window(lv, m, CUTOFF_YEAR, START).loc[list(EDA_CITIES)]
        S = prepare(lv, m, CUTOFF_YEAR, START)
        # descriptive statistics
        for cid, name in EDA_CITIES.items():
            r = W.loc[cid]
            stats.append(dict(city=name, ID=cid, metric=m, n_valid=int(r.notna().sum()),
                              n_missing=int(r.isna().sum()), mean=r.mean(), sd=r.std(),
                              min=r.min(), max=r.max(),
                              mean_1949_1978=r.loc[:1978].mean(), mean_1989_2018=r.loc[1989:].mean()))
        # line plots
        fig, ax = grid(f"{m} ({UNITS[m]}), valid years {START}-{CUTOFF_YEAR}")
        for a, (cid, name) in zip(ax, EDA_CITIES.items()):
            r = W.loc[cid]
            a.plot(r.index, r.values, marker=".", lw=1)
            a.set_title(name)
        fig.tight_layout(); fig.savefig(OUT / f"lines_{m}.png", dpi=110); plt.close(fig)
        # box plots by decade
        fig, ax = grid(f"{m} ({UNITS[m]}) by decade")
        for a, (cid, name) in zip(ax, EDA_CITIES.items()):
            r = W.loc[cid].dropna()
            dec = (r.index // 10) * 10
            groups = [r[dec == d].values for d in sorted(set(dec))]
            a.boxplot(groups, tick_labels=[f"{d}s" for d in sorted(set(dec))])
            a.set_title(name); a.tick_params(axis="x", labelsize=8)
        fig.tight_layout(); fig.savefig(OUT / f"box_decade_{m}.png", dpi=110); plt.close(fig)
        # ACF of the raw (interpolated) series
        fig, ax = grid(f"ACF of {m}, {START}-{CUTOFF_YEAR} (band = ±1.96/√N)")
        for a, (cid, name) in zip(ax, EDA_CITIES.items()):
            y = S[cid].y
            r = acf(y, nlags=20, fft=False)
            band = 1.96 / np.sqrt(len(y))
            a.bar(range(len(r)), r, width=0.3); a.axhline(band, ls="--", c="r"); a.axhline(-band, ls="--", c="r")
            a.axhline(0, c="k", lw=0.5); a.set_ylim(-0.6, 1.05); a.set_title(name)
            acf_rows.append(dict(city=name, metric=m, acf1=r[1], acf5=r[5], acf10=r[10],
                                 n_sig_lags_1_10=int((np.abs(r[1:11]) > band).sum())))
        fig.tight_layout(); fig.savefig(OUT / f"acf_{m}.png", dpi=110); plt.close(fig)
        # trend / residual decomposition with a centered 10-year moving average
        # one row per city: series + trend on the left, residual on its own axis on the right
        fig, ax = plt.subplots(6, 2, figsize=(13, 16), sharex=True, gridspec_kw=dict(width_ratios=[3, 2]))
        fig.suptitle(f"{m} ({UNITS[m]}): trend (10-yr centered MA) and residual", fontsize=13)
        for i, (cid, name) in enumerate(EDA_CITIES.items()):
            s = pd.Series(S[cid].y, index=S[cid].years)
            tr = s.rolling(10, center=True, min_periods=8).mean()
            res = s - tr
            ax[i, 0].plot(s.index, s.values, c="#9d9d95", lw=1, label="series")
            ax[i, 0].plot(tr.index, tr.values, c="#2a78d6", lw=2, label="trend")
            ax[i, 0].set_title(f"{name}: series and trend", fontsize=10)
            ax[i, 1].plot(res.index, res.values, c="#eb6834", lw=1)
            ax[i, 1].axhline(0, c="#55554f", lw=0.8)
            ax[i, 1].set_title(f"{name}: residual", fontsize=10)
            decomp_rows.append(dict(city=name, metric=m, trend_range=tr.max() - tr.min(),
                                    resid_sd=res.std(), ratio=(tr.max() - tr.min()) / res.std()))
        ax[0, 0].legend(fontsize=8, frameon=False)
        fig.tight_layout(); fig.savefig(OUT / f"decomp_{m}.png", dpi=100); plt.close(fig)

    st = pd.DataFrame(stats)
    st.to_csv(OUT / "descriptive_stats.csv", index=False)
    pd.DataFrame(acf_rows).to_csv(OUT / "acf_raw_summary.csv", index=False)
    pd.DataFrame(decomp_rows).to_csv(OUT / "decomp_summary.csv", index=False)
    pd.set_option("display.width", 200)
    print(st.round(2).to_string(index=False))
    print(pd.DataFrame(acf_rows).round(2).to_string(index=False))
    print(pd.DataFrame(decomp_rows).round(2).to_string(index=False))


if __name__ == "__main__":
    main()