File size: 14,696 Bytes
89379eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Heat Seekers v2: trend-aware, origin-safe forecasts. Offline; uses only data <= 2018-12-31.

All functions take an `origin` and only read array columns for years <= origin (asserted by the
poisoned-future test in test_v2.py).
"""
from pathlib import Path
import hashlib, json
import numpy as np
import pandas as pd

ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / 'data'
TEMPLATE = ROOT / 'research/official/protostar-climate-submission-template/submission.csv'
METRICS = ['annual_avg_temp', 'total_precip_in', 'hottest_day_temp', 'cdd']
COLS = {'annual_avg_temp': 'Avg Temp', 'total_precip_in': 'ToT Prcp', 'hottest_day_temp': 'Max Tmax', 'cdd': 'cdd'}
KEY = ['city_id', 'year', 'metric']
Y0, Y1 = 1870, 2018
YEARS = np.arange(Y0, Y1 + 1)
DGRID = np.round(np.arange(-8.0, 12.0001, 0.1), 4)   # CDD shift grid, deg F

def check_inputs():
    for e in json.loads((DATA / 'manifest.json').read_text()):
        p = DATA / e['file']
        assert hashlib.sha256(p.read_bytes()).hexdigest() == e['sha256'], f'Input changed: {p}'

class Panel:
    """City x year arrays (years 1870..2018)."""
    def __init__(self, check=True, daily=True):
        if check: check_inputs()
        a = pd.read_parquet(DATA / 'annual_indices/train-00000-of-00001.parquet')
        c = pd.read_parquet(DATA / 'coverage_and_stations/train-00000-of-00001.parquet')
        assert a.Year.max() <= 2018 and c.Year.max() <= 2018
        a = a.merge(c.drop(columns='Name'), on=['ID', 'Year'], validate='one_to_one')
        a = a[a.Year >= Y0]
        self.ids = np.array(sorted(a.ID.unique()))
        n, T = len(self.ids), len(YEARS)
        ci = np.searchsorted(self.ids, a.ID.to_numpy()); ti = a.Year.to_numpy() - Y0
        def mat(col, fill=np.nan):
            m = np.full((n, T), fill, float); m[ci, ti] = a[col].to_numpy(float); return m
        self.value = {m: mat(COLS[m]) for m in METRICS}
        temp_ok = (mat('Miss Tmax', 999) <= 10) & (mat('Miss Tmin', 999) <= 10)
        prcp_ok = mat('Miss Prcp', 999) <= 10
        self.valid = {m: ((prcp_ok if m == 'total_precip_in' else temp_ok) & np.isfinite(self.value[m])) for m in METRICS}
        self.seg = mat('Station Segment', -1)
        self.lat = mat('Lat'); self.lon = mat('Lon')
        self.names = a.groupby('ID').Name.first().reindex(self.ids).to_numpy()
        self.inc = cdd_increment_table(self.ids) if daily else None

    def copy_cut(self, origin, junk=999999.0):
        """Return a copy where every year > origin is replaced by junk (for leakage tests)."""
        import copy
        p = copy.deepcopy(self); k = origin - Y0 + 1
        for m in METRICS:
            p.value[m][:, k:] = junk; p.valid[m][:, k:] = True
        p.seg[:, k:] = junk; p.lat[:, k:] = junk; p.lon[:, k:] = junk
        if p.inc is not None: p.inc[:, k:, :] = junk
        return p

def cdd_increment_table(ids):
    """inc[c, t, d] = CDD of year t with every day's (Tmax+Tmin)/2 shifted by DGRID[d], minus unshifted CDD.
    Only days with both temperatures count, matching the official CDD (paired days)."""
    cache = ROOT / 'results/cache_cdd_increment.npy'
    src = DATA / 'daily/train-00000-of-00001.parquet'
    tag = hashlib.sha256(src.read_bytes()).hexdigest()[:16] + f'_{len(DGRID)}_{Y0}'
    tagf = cache.with_suffix('.tag')
    if cache.exists() and tagf.exists() and tagf.read_text() == tag:
        return np.load(cache)
    d = pd.read_parquet(src, columns=['ID', 'Date', 'tmax', 'tmin'])
    d = d[d.tmax.notna() & d.tmin.notna()]
    yr = pd.to_datetime(d.Date).dt.year.to_numpy()
    assert yr.max() <= 2018
    keep = yr >= Y0; d = d[keep]; yr = yr[keep]
    ci = np.searchsorted(ids, d.ID.to_numpy()); assert (ids[ci] == d.ID.to_numpy()).all()
    key = ci * len(YEARS) + (yr - Y0)
    tav = ((d.tmax.to_numpy() + d.tmin.to_numpy()) / 2.0)
    size = len(ids) * len(YEARS)
    base = np.bincount(key, np.maximum(tav - 65, 0), minlength=size)
    out = np.empty((size, len(DGRID)))
    for j, dl in enumerate(DGRID):
        out[:, j] = np.bincount(key, np.maximum(tav + dl - 65, 0), minlength=size) - base
    out = out.reshape(len(ids), len(YEARS), len(DGRID))
    cache.parent.mkdir(exist_ok=True); np.save(cache, out); tagf.write_text(tag)
    return out

def interp_inc(inc_ct, shift):
    shift = np.clip(shift, DGRID[0], DGRID[-1])
    return np.interp(shift, DGRID, inc_ct)

# ---------------------------------------------------------------- per-origin statistics
def _win(origin, n):
    k1 = origin - Y0 + 1; return max(0, k1 - n), k1

def clim30(P, m, origin):
    """Official 30-year mean (>=10 valid years in [O-29,O]); fallback = last 30 valid years at any time."""
    a, b = _win(origin, 30)
    v = P.value[m][:, a:b]; ok = P.valid[m][:, a:b]
    n = ok.sum(1); mean = np.where(n > 0, np.nansum(np.where(ok, v, 0), 1) / np.maximum(n, 1), np.nan)
    eligible = n >= 10
    out = mean.copy()
    for i in np.where(~eligible)[0]:
        out[i] = last_valid(P, m, origin, i, 30).mean()
    return out, eligible

def last_valid(P, m, origin, i, L, years=False):
    k1 = origin - Y0 + 1
    idx = np.where(P.valid[m][i, :k1])[0][-L:]
    assert len(idx), f'no valid history {P.ids[i]} {m} {origin}'
    return (YEARS[idx] if years else P.value[m][i, idx])

def median30(P, m, origin):
    a, b = _win(origin, 30); out = np.empty(len(P.ids))
    for i in range(len(P.ids)):
        ok = P.valid[m][i, a:b]
        out[i] = np.median(P.value[m][i, a:b][ok]) if ok.sum() >= 10 else np.median(last_valid(P, m, origin, i, 30))
    return out

def meanN(P, m, origin, N):
    a, b = _win(origin, N); out = np.empty(len(P.ids))
    for i in range(len(P.ids)):
        ok = P.valid[m][i, a:b]
        out[i] = P.value[m][i, a:b][ok].mean() if ok.sum() >= 10 else last_valid(P, m, origin, i, 30).mean()
    return out

def exp10(P, m, origin):
    k1 = origin - Y0 + 1; out = np.empty(len(P.ids))
    w = 2.0 ** ((YEARS[:k1] - origin) / 10)
    for i in range(len(P.ids)):
        ok = P.valid[m][i, :k1]; out[i] = np.average(P.value[m][i, :k1][ok], weights=w[ok])
    return out

def lin30(P, m, origin):
    """Official linear trend: OLS through valid years in [O-29,O]; returns (level at origin, slope).
    Fallback (<10 valid): flat at clim30 fallback."""
    a, b = _win(origin, 30); yrs = YEARS[a:b]
    lev = np.empty(len(P.ids)); sl = np.zeros(len(P.ids))
    base, elig = clim30(P, m, origin)
    for i in range(len(P.ids)):
        ok = P.valid[m][i, a:b]
        if ok.sum() >= 10:
            x = yrs[ok] - origin; y = P.value[m][i, a:b][ok]
            s, c = np.polyfit(x, y, 1); lev[i] = c; sl[i] = s
        else:
            lev[i] = base[i]
    return lev, sl

def seg_slope(P, m, origin):
    """Own 30-year OLS slope with one intercept per station segment (common slope). NaN if <10 valid years."""
    a, b = _win(origin, 30); yrs = YEARS[a:b].astype(float); out = np.full(len(P.ids), np.nan)
    for i in range(len(P.ids)):
        ok = P.valid[m][i, a:b]
        if ok.sum() < 10: continue
        x = yrs[ok]; y = P.value[m][i, a:b][ok]; s = P.seg[i, a:b][ok]
        xd = x.copy(); yd = y.copy()
        for g in np.unique(s):
            k = s == g; xd[k] -= x[k].mean(); yd[k] -= y[k].mean()
        den = (xd ** 2).sum()
        if den > 0 and len(x) - len(np.unique(s)) >= 8: out[i] = (xd * yd).sum() / den
    return out

def coords(P, origin):
    k1 = origin - Y0 + 1; lat = np.empty(len(P.ids)); lon = np.empty(len(P.ids))
    for i in range(len(P.ids)):
        j = np.where(np.isfinite(P.lat[i, :k1]))[0][-1]; lat[i] = P.lat[i, j]; lon[i] = P.lon[i, j]
    return lat, lon

def regional(P, own, origin, kind):
    fin = np.isfinite(own)
    if kind == 'national':
        return np.full(len(own), own[fin].mean())
    lat, lon = coords(P, origin); la, lo = np.radians(lat), np.radians(lon)
    h = np.sin((la[:, None] - la[None]) / 2) ** 2 + np.cos(la[:, None]) * np.cos(la[None]) * np.sin((lo[:, None] - lo[None]) / 2) ** 2
    dist = 2 * np.arcsin(np.sqrt(np.clip(h, 0, 1)))
    np.fill_diagonal(dist, np.inf); dist[:, ~fin] = np.inf
    nn = np.argsort(dist, axis=1)[:, :10]
    return own[nn].mean(1)

def level_years(P, m, origin, i, L):
    """Last L valid years in the current station segment; if fewer than L/2 exist there, the last L valid years."""
    k1 = origin - Y0 + 1
    idx = np.where(P.valid[m][i, :k1])[0]
    assert len(idx), f'no valid history {P.ids[i]} {m} {origin}'
    cur = P.seg[i, idx[-1]]
    same = idx[P.seg[i, idx] == cur][-L:]
    return same if len(same) >= L / 2 else idx[-L:]

# ---------------------------------------------------------------- forecasts
def temp_configs():
    out = []
    for L in (10, 15, 20):
        for a in (0.0, 0.25, 0.5):
            for R in ('knn10', 'national'):
                out.append((L, a, R))
        out.append((L, 1.0, 'none'))
    return out

def cfg_name(L, a, R): return f'L{L}_a{a:g}_{R}'

def slopes(P, origin, cache=None):
    """Temperature slope components (CDD and hottest-day trend use the temperature slope)."""
    own = seg_slope(P, 'annual_avg_temp', origin)
    reg = {k: regional(P, own, origin, k) for k in ('knn10', 'national')}
    return own, reg

def combined_slope(own, reg, a, R):
    if R == 'none':
        r = reg['knn10']; s = np.where(np.isfinite(own), own, r)
    else:
        r = reg[R]; s = np.where(np.isfinite(own), a * own + (1 - a) * r, r)
    return s

def forecast_block(P, origin, which='all', configs=None, H=7):
    """Return long DataFrame: city_id, year, metric, method, predicted_value for horizons 1..H."""
    ids = P.ids; n = len(ids); hs = np.arange(1, H + 1)
    rows = []
    def add(metric, method, mat):  # mat: n x H
        mat = np.asarray(mat, float)
        if metric in ('cdd', 'total_precip_in'): mat = np.maximum(mat, 0)
        for j, h in enumerate(hs):
            rows.append(pd.DataFrame({'city_id': ids, 'year': origin + h, 'metric': metric, 'method': method, 'predicted_value': mat[:, j]}))
    flat = lambda v: np.repeat(np.asarray(v)[:, None], H, 1)
    configs = configs or temp_configs()
    own, reg = slopes(P, origin)
    for m in METRICS:
        base, _ = clim30(P, m, origin); add(m, 'clim30', flat(base))
        lev, sl = lin30(P, m, origin); add(m, 'lin30', lev[:, None] + sl[:, None] * hs[None])  # reference only
        if which == 'baselines' or m in ('annual_avg_temp', 'cdd'):
            add(m, 'exp10', flat(exp10(P, m, origin)))
    if which == 'baselines':
        return pd.concat(rows, ignore_index=True)
    # precipitation / hottest alternatives
    add('total_precip_in', 'median30', flat(median30(P, 'total_precip_in', origin)))
    add('total_precip_in', 'mean60', flat(meanN(P, 'total_precip_in', origin, 60)))
    add('hottest_day_temp', 'median30', flat(median30(P, 'hottest_day_temp', origin)))
    hb, _ = clim30(P, 'hottest_day_temp', origin)
    s_ref = combined_slope(own, reg, 0.25, 'knn10')
    for beta in (0.5, 1.0):
        add('hottest_day_temp', f'trend_beta{beta:g}', hb[:, None] + beta * s_ref[:, None] * (hs[None] + 14.5))
    # temperature level + trend, and CDD daily shift
    T = 'annual_avg_temp'
    for (L, a, R) in configs:
        s = combined_slope(own, reg, a, R)
        tmat = np.empty((n, H)); cmean = np.empty((n, H)); cmed = np.empty((n, H))
        for i in range(n):
            ly = level_years(P, T, origin, i, L)
            yrs = YEARS[ly].astype(float)
            tmat[i] = P.value[T][i, ly].mean() + s[i] * (origin + hs - yrs.mean())
            cy = level_years(P, 'cdd', origin, i, L)
            cyrs = YEARS[cy].astype(float); cv = P.value['cdd'][i, cy]
            shift = s[i] * ((origin + hs)[None, :] - cyrs[:, None])          # nyears x H
            vals = np.empty_like(shift)
            for r, t in enumerate(cy):
                vals[r] = cv[r] + interp_inc(P.inc[i, t], shift[r])
            cmean[i] = vals.mean(0); cmed[i] = np.median(vals, 0)
        name = cfg_name(L, a, R)
        add(T, 'LT_' + name, tmat)
        add('cdd', 'SHmean_' + name, cmean); add('cdd', 'SHmedian_' + name, cmed)
    return pd.concat(rows, ignore_index=True)

# ---------------------------------------------------------------- scoring
def truth_rows(P, origin, H=7):
    """Eligible scored rows for an origin (official rules), with clim30 eligibility from [O-29,O]."""
    out = []
    for m in METRICS:
        _, elig = clim30(P, m, origin)
        for h in range(1, H + 1):
            t = origin + h - Y0
            ok = P.valid[m][:, t] & elig
            out.append(pd.DataFrame({'city_id': P.ids[ok], 'year': origin + h, 'metric': m, 'value': P.value[m][ok, t]}))
    return pd.concat(out, ignore_index=True)

def score_origin(P, pred, origin, H=7):
    """Left-join truth to every method's forecast and assert full coverage; return per-row errors."""
    truth = truth_rows(P, origin, H)
    out = []
    for method, g in pred.groupby('method'):
        mets = g.metric.unique()
        t = truth[truth.metric.isin(mets)]
        r = t.merge(g[KEY + ['predicted_value']], on=KEY, how='left', validate='one_to_one')
        assert r.predicted_value.notna().all() and np.isfinite(r.predicted_value).all(), f'coverage gap {method} {origin}'
        assert len(r) == len(t)
        r['method'] = method; out.append(r)
    r = pd.concat(out, ignore_index=True)
    r['error'] = (r.predicted_value - r.value).abs(); r['origin'] = origin; r['horizon'] = r.year - origin
    r['split'] = np.where(r.horizon <= 3, 'live_like', 'final_like')
    return r

def skill_table(rows):
    """Per origin/method/metric/split MAE and unclipped skill vs clim30 of the same origin & split."""
    parts = []
    for split in ('live_like', 'final_like', 'all'):
        r = rows if split == 'all' else rows[rows.split == split]
        mae = r.groupby(['origin', 'metric', 'method']).error.mean().rename('mae').reset_index()
        ref = mae[mae.method == 'clim30'][['origin', 'metric', 'mae']].rename(columns={'mae': 'ref_mae'})
        mae = mae.merge(ref, on=['origin', 'metric'], how='left', validate='many_to_one')
        assert mae.ref_mae.notna().all()
        mae['skill'] = 1 - mae.mae / mae.ref_mae; mae['split'] = split; parts.append(mae)
    return pd.concat(parts, ignore_index=True)

# ---------------------------------------------------------------- submission
def validate(df):
    template = pd.read_csv(TEMPLATE)
    assert list(df.columns) == KEY + ['predicted_value']
    assert len(df) == 5880 and not df.duplicated(KEY).any()
    assert df[KEY].reset_index(drop=True).equals(template[KEY]), 'Template order/keys differ'
    assert np.isfinite(df.predicted_value).all()
    assert (df.loc[df.metric.isin(['cdd', 'total_precip_in']), 'predicted_value'] >= 0).all()