File size: 7,649 Bytes
8a83f19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Heat Seekers v6: ideas from higher-ranked teams' READMEs (research/V6_PROTOCOL.md). Data <= origin only."""
import hashlib
import numpy as np, pandas as pd
from v4lib import *
from v4lib import _win, cal_years

REF = {'annual_avg_temp': 't_dettrim_v2', 'cdd': 'v2b', 'total_precip_in': 'clim30', 'hottest_day_temp': 'h_blend15'}
CANDS = {'annual_avg_temp': ['t_regdep75', 't_regdep75_nat'], 'cdd': ['c_sens50'],
         'hottest_day_temp': ['h_nudge', 'h_blend15_nudge', 'h_os2'], 'total_precip_in': ['p_nudge', 'p_mm45']}

def top2_tables(P):
    cache = ROOT / 'results/cache_v6_top2.npz'; src = DATA / 'daily/train-00000-of-00001.parquet'
    tag = hashlib.sha256(src.read_bytes()).hexdigest()[:16] + f'_{Y0}_v6'
    if cache.exists():
        z = np.load(cache)
        if str(z['tag']) == tag: return z['top1'], z['top2']
    d = pd.read_parquet(src, columns=['ID', 'Date', 'tmax']); d = d[d.tmax.notna()]
    d['yr'] = pd.to_datetime(d.Date).dt.year; assert d.yr.max() <= 2018; d = d[d.yr >= Y0]
    g = d.sort_values('tmax', ascending=False).groupby(['ID', 'yr']).tmax
    t1 = g.nth(0); t2 = g.nth(1)
    a = d[['ID', 'yr']].drop_duplicates()
    top1 = np.full((len(P.ids), len(YEARS)), np.nan); top2 = top1.copy()
    s1 = d.loc[t1.index].set_index(['ID', 'yr']).tmax; s2 = d.loc[t2.index].set_index(['ID', 'yr']).tmax
    for s, out in ((s1, top1), (s2, top2)):
        ids = s.index.get_level_values(0).to_numpy(); yrs = s.index.get_level_values(1).to_numpy()
        ci = np.searchsorted(P.ids, ids); ok = (ci < len(P.ids)) & (P.ids[np.minimum(ci, len(P.ids) - 1)] == ids)
        out[ci[ok], yrs[ok] - Y0] = s.to_numpy()[ok]
    np.savez(cache, tag=tag, top1=top1, top2=top2); return top1, top2

def attach6(P):
    P = attach(P); P.top1, P.top2 = top2_tables(P); return P

def cut6(P, origin, junk=999999.0):
    Q = cut(P, origin, junk); k = origin - Y0 + 1
    Q.top1 = P.top1.copy(); Q.top2 = P.top2.copy(); Q.top1[:, k:] = junk; Q.top2[:, k:] = junk
    return Q

def neighbours(P, origin, k):
    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)
    return np.argsort(dist, axis=1, kind='stable')[:, :k]

def anomalies(P, m, origin, ratio=False):
    """a[c, t] over [T-29, T] (NaN if invalid or mu undefined), mu (NaN if <10 valid)."""
    a, b = _win(origin, 30); v = P.value[m][:, a:b]; ok = P.valid[m][:, a:b]; n = ok.sum(1)
    mu = np.where(n >= 10, np.nansum(np.where(ok, v, 0), 1) / np.maximum(n, 1), np.nan)
    if ratio: mu = np.where(mu > 0, mu, np.nan); an = np.where(ok, v / mu[:, None] - 1, np.nan)
    else: an = np.where(ok, v - mu[:, None], np.nan)
    return an, mu, a, b

def regional(an, nn, minc=10):
    vals = an[nn]  # c x k x t
    cnt = np.isfinite(vals).sum(1)
    return np.where(cnt >= minc, np.nanmean(np.where(np.isfinite(vals), vals, np.nan), axis=1), np.nan)

def nudge_D(P, m, origin, ratio):
    an, mu, a, b = anomalies(P, m, origin, ratio); R = regional(an, neighbours(P, origin, 31))
    d = an - R; yrs = YEARS[a:b]; last10 = yrs >= origin - 9; D = np.zeros(len(P.ids))
    for i in range(len(P.ids)):
        k = np.isfinite(d[i]) & last10
        if k.sum() >= 5: D[i] = d[i, k].mean()
    return D

def regdep_view(P, origin, H, nat_slope=None):
    m = 'annual_avg_temp'; an, mu, a, b = anomalies(P, m, origin); R = regional(an, neighbours(P, origin, 32))
    yrs = YEARS[a:b].astype(float); hs = np.arange(1, H + 1); out = np.full((len(P.ids), H), np.nan)
    for i in range(len(P.ids)):
        if not np.isfinite(mu[i]): continue
        k = np.isfinite(an[i]) & np.isfinite(R[i]) & (yrs >= origin - 14)
        idx = np.where(k)[0][-5:]
        if len(idx) < 3: continue
        dep = (an[i, idx] - R[i, idx]).mean(); f = np.isfinite(R[i])
        if nat_slope is None:
            s, c = np.polyfit(yrs[f], R[i, f], 1); rhat = c + s * (origin + hs)
        else:
            f15 = f & (yrs >= origin - 14); rhat = R[i, f15].mean() + nat_slope * (origin + hs - yrs[f15].mean())
        out[i] = mu[i] + rhat + dep
    return out

def cdd_sens_view(P, origin, s2, H):
    a, b = _win(origin, 30); T = 'annual_avg_temp'; C = 'cdd'; hs = np.arange(1, H + 1); n = len(P.ids)
    sens = np.full(n, np.nan)
    for i in range(n):
        ok = P.valid[T][i, a:b] & P.valid[C][i, a:b]
        if ok.sum() >= 10: sens[i] = np.polyfit(P.value[T][i, a:b][ok], P.value[C][i, a:b][ok], 1)[0]
    sens = np.where(np.isfinite(sens), sens, np.nanmean(sens)); sens = np.maximum(sens, 0)
    out = np.empty((n, H))
    for i in range(n):
        V = cal_years(P, C, origin, i); out[i] = P.value[C][i, V].mean() + sens[i] * s2 * (origin + hs - YEARS[V].mean())
    return out, sens

def h_os2(P, origin, base):
    m = 'hottest_day_temp'; a, b = _win(origin, 30); ok = P.valid[m][:, a:b] & np.isfinite(P.top2[:, a:b]) & np.isfinite(P.top1[:, a:b])
    t2 = P.top2[:, a:b]; g = P.top1[:, a:b] - t2; nn = neighbours(P, origin, 10); out = base.copy()
    for i in range(len(P.ids)):
        if ok[i].sum() < 10: continue
        grp = np.r_[i, nn[i]]; pool = g[grp][ok[grp]]
        out[i] = t2[i][ok[i]].mean() + np.median(pool)
    return out

def p_mm45(P, origin, H):
    p = 'total_precip_in'; med = median30(P, p, origin); m30 = clim30(P, p, origin)[0]
    a, b = _win(origin, 45); a30, _ = _win(origin, 30); m45 = m30.copy()
    for i in range(len(P.ids)):
        ok = P.valid[p][i, a:b]
        if ok.sum() >= 15 and P.valid[p][i, a30:b].sum() >= 10: m45[i] = P.value[p][i, a:b][ok].mean()
    hs = np.arange(1, H + 1)
    return np.where(hs[None] <= 3, (0.5 * med + 0.5 * m30)[:, None], (0.5 * med + 0.5 * m45)[:, None])

def v6_block(P, origin, H=7):
    f4, info = v4_block(P, origin, H)
    keep = set(REF.values()) | {'clim30'}
    f4 = f4[f4.method.isin(keep)]
    def mat(metric, method):
        g = f4[(f4.metric == metric) & (f4.method == method)].pivot(index='city_id', columns='year', values='predicted_value')
        return g.reindex(P.ids).to_numpy()
    rows = [f4]; ids = P.ids; hs = np.arange(1, H + 1)
    def add(metric, method, M):
        M = np.asarray(M, float)
        if M.ndim == 1: M = np.repeat(M[:, None], H, 1)
        if metric in ('cdd', 'total_precip_in'): M = np.maximum(M, 0)
        for j, h in enumerate(hs):
            rows.append(pd.DataFrame({'city_id': ids, 'year': origin + h, 'metric': metric, 'method': method, 'predicted_value': M[:, j]}))
    s2 = info['s_v2']
    # I1
    q = 'hottest_day_temp'; p = 'total_precip_in'
    hb = clim30(P, q, origin)[0]; Dh = nudge_D(P, q, origin, False)
    add(q, 'h_nudge', hb + 0.3 * Dh); add(q, 'h_blend15_nudge', mat(q, 'h_blend15') + 0.3 * Dh[:, None])
    pb = clim30(P, p, origin)[0]; Dp = nudge_D(P, p, origin, True); add(p, 'p_nudge', pb * (1 + 0.3 * Dp))
    # I2
    S, sens = cdd_sens_view(P, origin, s2, H); add('cdd', 'c_sens50', 0.5 * mat('cdd', 'v2b') + 0.5 * S)
    # I3
    t4 = mat('annual_avg_temp', 't_dettrim_v2')
    for nm, ns in (('t_regdep75', None), ('t_regdep75_nat', s2)):
        v = regdep_view(P, origin, H, ns); f = 0.75 * v + 0.25 * t4; add('annual_avg_temp', nm, np.where(np.isfinite(v), f, t4))
    # I4
    add(q, 'h_os2', h_os2(P, origin, hb)); add(p, 'p_mm45', p_mm45(P, origin, H))
    info.update(n_fallback_regdep=int((~np.isfinite(regdep_view(P, origin, H)[:, 0])).sum()), sens_mean=float(sens.mean()),
                mean_Dh=float(Dh.mean()), mean_Dp=float(Dp.mean()))
    return pd.concat(rows, ignore_index=True), info