File size: 9,021 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
"""Forecast models. Each takes the valid history up to `origin` and returns predictions
for `years` (origin+1 .. origin+7). Nothing here looks past `origin`.
"""
import numpy as np
import pandas as pd

from common import METRICS


def wide(lv: pd.DataFrame, metric: str, origin: int, seg_only_min: int = 0) -> pd.DataFrame:
    """cities x years matrix of valid values up to origin (NaN = invalid/missing).

    seg_only_min > 0: drop years recorded before the city's latest station change (as of
    origin) when the current station has at least that many valid years, so a relocation
    does not bias the city's level.
    """
    w = lv[(lv.metric == metric) & (lv.Year <= origin)]
    w = w.assign(value=w.value.where(w.valid))
    if seg_only_min:
        last = w.groupby("ID")["segment"].transform("max")
        cur = w.segment == last
        n_cur = (cur & w.value.notna()).groupby(w.ID).transform("sum")
        w = w.assign(value=w.value.where(cur | (n_cur < seg_only_min)))
    return w.pivot(index="ID", columns="Year", values="value")


def _ols_slope(M: np.ndarray, x: np.ndarray, min_n: int = 10) -> np.ndarray:
    """Per-row OLS slope of M against x, ignoring NaN."""
    ok = ~np.isnan(M)
    n = ok.sum(1)
    X = np.where(ok, x, np.nan)
    xm = np.nanmean(X, 1, keepdims=True)
    ym = np.nanmean(M, 1, keepdims=True)
    num = np.nansum((X - xm) * (M - ym), 1)
    den = np.nansum((X - xm) ** 2, 1)
    s = num / den
    s[n < min_n] = np.nan
    return s


def knn_mean(values: pd.Series, coords: pd.DataFrame, k: int) -> pd.Series:
    """Average of `values` over each city's k nearest cities (itself included), by great-circle distance."""
    c = coords.loc[values.index]
    lat, lon = np.radians(c.Lat.values), np.radians(c.Lon.values)
    d = np.arccos(np.clip(np.sin(lat[:, None]) * np.sin(lat) + np.cos(lat[:, None]) * np.cos(lat) * np.cos(lon[:, None] - lon), -1, 1))
    v = values.values
    d = np.where(np.isnan(v)[None, :], np.inf, d)
    idx = np.argsort(d, 1)[:, :k]
    return pd.Series(np.nanmean(v[idx], 1), index=values.index)


def level_trend(lv, origin, years, coords, metric, k=15, L=40, w_city=0.0, k_nn=None,
                stat="mean", slope_scale=1.0, fallback=30, seg_only_min=0):
    """Level = mean (or median) of the last k valid years; extended to each target year with a slope.

    slope = w_city * city OLS slope over the last L years + (1 - w_city) * pooled slope
    (pooled over the k_nn nearest cities, or all cities if k_nn is None).
    """
    W = wide(lv, metric, origin)
    Wl = wide(lv, metric, origin, seg_only_min) if seg_only_min else W
    cols = [y for y in W.columns if y > origin - k]
    R = Wl[cols]
    level = (R.median(1) if stat == "median" else R.mean(1))
    center = R.notna().mul(np.array(cols), axis=1).sum(1) / R.notna().sum(1)
    # fall back to a longer window if too few recent valid years
    few = R.notna().sum(1) < max(3, k // 3)
    if few.any():
        R2 = Wl[[y for y in W.columns if y > origin - fallback]]
        level[few] = R2.mean(1)[few]
        center[few] = (R2.notna().mul(np.array(R2.columns), axis=1).sum(1) / R2.notna().sum(1))[few]
    S = W[[y for y in W.columns if y > origin - L]]
    city_slope = pd.Series(_ols_slope(S.values, np.array(S.columns, float)), index=W.index)
    pooled = knn_mean(city_slope, coords, k_nn) if k_nn else pd.Series(np.nanmean(city_slope), index=W.index)
    slope = (w_city * city_slope.fillna(pooled) + (1 - w_city) * pooled) * slope_scale
    out = []
    for y in years:
        out.append(pd.DataFrame({"ID": W.index, "metric": metric, "Year": y,
                                 "pred": (level + slope * (y - center)).values}))
    return pd.concat(out, ignore_index=True)


def baseline30_model(lv, origin, years, coords, metric):
    return level_trend(lv, origin, years, coords, metric, k=30, slope_scale=0.0)


def linear30_model(lv, origin, years, coords, metric):
    return level_trend(lv, origin, years, coords, metric, k=30, L=30, w_city=1.0)


def _knn_index(coords: pd.DataFrame, ids, k: int) -> np.ndarray:
    c = coords.loc[ids]
    lat, lon = np.radians(c.Lat.values), np.radians(c.Lon.values)
    d = np.arccos(np.clip(np.sin(lat[:, None]) * np.sin(lat) + np.cos(lat[:, None]) * np.cos(lat) * np.cos(lon[:, None] - lon), -1, 1))
    return np.argsort(d, 1)[:, :k]


def regional_anom(lv, origin, years, coords, metric, k_nn=15, L=50, k_off=30, ref=30,
                  slope_scale=1.0, w_nat=0.0, fit="ols"):
    """value = city reference mean + city offset vs. its region + regional anomaly trend.

    Regional anomaly: average over the k_nn nearest cities of (value - own `ref`-year mean),
    which cancels most of the year-to-year noise shared by neighbours. Its linear trend over
    the last L years (optionally shrunk toward the national trend with weight w_nat) is
    extrapolated to the target years. The city offset is the city's mean departure from its
    regional anomaly over the last k_off years.
    """
    W = wide(lv, metric, origin)
    yrs = np.array(W.columns, float)
    V = W.values
    refmask = yrs > origin - ref
    mref = np.nanmean(V[:, refmask], 1)
    A = V - mref[:, None]
    idx = _knn_index(coords, W.index, k_nn) if k_nn else np.tile(np.arange(len(W)), (len(W), 1))
    Rg = np.nanmean(A[idx], 1)  # cities x years
    Nat = np.nanmean(A, 0)
    win = yrs > origin - L
    x = yrs[win]
    def line(Y):  # rows: series; returns slope, intercept at x-mean
        s = _ols_slope(Y[:, win], x, min_n=10)
        xm = x.mean()
        b = np.nanmean(Y[:, win], 1) - s * (np.nanmean(np.where(~np.isnan(Y[:, win]), x, np.nan), 1) - xm)
        return s, b, xm
    s_r, b_r, xm = line(Rg)
    s_n, b_n, _ = line(Nat[None, :])
    s = ((1 - w_nat) * s_r + w_nat * s_n[0]) * slope_scale
    # anchor regional line at its own mean over the window
    offwin = yrs > origin - k_off
    off = np.nanmean((A - Rg)[:, offwin], 1)
    off = np.where(np.isnan(off), 0, off)
    out = []
    for y in years:
        p = mref + off + b_r + s * (y - xm)
        out.append(pd.DataFrame({"ID": W.index, "metric": metric, "Year": y, "pred": p}))
    return pd.concat(out, ignore_index=True)


_SHIFT = None


def shift_table():
    global _SHIFT
    if _SHIFT is None:
        from common import ROOT
        t = pd.read_parquet(ROOT / "data" / "processed" / "shift_table.parquet").set_index(["ID", "Year"])
        cols = [c for c in t.columns if c.startswith("cdd_")]
        _SHIFT = (t[cols], np.array([float(c[4:]) for c in cols]))
    return _SHIFT


def temp_slope(lv, origin, coords, L=50, k_nn=None, w_city=0.0, metric="annual_avg_temp"):
    """Warming rate (°F/yr) per city: pooled (all cities or k nearest) mean of city OLS slopes."""
    W = wide(lv, metric, origin)
    S = W[[y for y in W.columns if y > origin - L]]
    cs = pd.Series(_ols_slope(S.values, np.array(S.columns, float)), index=W.index)
    pooled = knn_mean(cs, coords, k_nn) if k_nn else pd.Series(np.nanmean(cs), index=W.index)
    return w_city * cs.fillna(pooled) + (1 - w_city) * pooled


def cdd_shift(lv, origin, years, coords, metric="cdd", N=20, L=50, k_nn=None, w_city=0.0,
              slope_scale=1.0, stat="mean", seg_only_min=0):
    """CDD forecast from shifted daily weather.

    For target year y, each valid past year t in the last N years has its daily mean
    temperatures shifted by slope * (y - t) (the warming expected between t and y), and its
    CDD recomputed from the shifted days. The forecast is the average over those years.
    This respects that CDD responds nonlinearly to warming (more days cross 65 °F).
    """
    tab, deltas = shift_table()
    s = temp_slope(lv, origin, coords, L=L, k_nn=k_nn, w_city=w_city) * slope_scale
    W = wide(lv, "cdd", origin, seg_only_min)
    valid = W.notna().stack()
    valid = valid[valid].index
    win = [ix for ix in valid if ix[1] > origin - N]
    T = tab.loc[win]
    ids = T.index.get_level_values(0)
    ty = T.index.get_level_values(1).to_numpy()
    M = T.to_numpy()
    out = []
    for y in years:
        dl = s.loc[ids].to_numpy() * (y - ty)
        dl = np.clip(dl, deltas[0], deltas[-1])
        # linear interpolation along delta grid, row by row
        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
        r = np.arange(len(M))
        v = M[r, lo] * (1 - f) + M[r, hi] * f
        ser = pd.Series(v, index=ids)
        agg = ser.groupby(level=0).median() if stat == "median" else ser.groupby(level=0).mean()
        out.append(pd.DataFrame({"ID": agg.index, "metric": metric, "Year": y, "pred": agg.values}))
    df = pd.concat(out, ignore_index=True)
    # cities with no valid years in the window: fall back to the pooled level+trend model
    miss = set(W.index) - set(df.ID)
    if miss:
        fb = level_trend(lv, origin, years, coords, metric, k=30, L=L)
        df = pd.concat([df, fb[fb.ID.isin(miss)]], ignore_index=True)
    return df