tchaudha's picture
Heat Seekers v4: detrended-trimmed temp level, v2b CDD, hottest-day blend
89379eb verified
Raw History Blame Contribute Delete
16.9 kB
"""Heat Seekers v3 ablations (SHEBE component ideas) on top of v2lib. Data <= 2018 only; every statistic for an
origin O reads only years <= O (tested by the poisoned-future test in test_v3.py)."""
import hashlib
import numpy as np, pandas as pd
from v2lib import *
from v2lib import _win
np.seterr(divide="ignore", invalid="ignore")
def daily_tables(P):
"""Per city-year daily-derived tables, cached. Seasonal CDD increments over DGRID, seasonal means,
JJA mean Tmax, active cooling days, top-3 independent (>=3 days apart) Tmax mean, calendar length."""
cache = ROOT / 'results/cache_v3_daily.npz'
src = DATA / 'daily/train-00000-of-00001.parquet'
tag = hashlib.sha256(src.read_bytes()).hexdigest()[:16] + f'_{len(DGRID)}_{Y0}_v3b'
if cache.exists():
z = np.load(cache)
if str(z['tag']) == tag: return {k: z[k] for k in z.files if k != 'tag'}
d = pd.read_parquet(src, columns=['ID', 'Date', 'tmax', 'tmin'])
dt = pd.to_datetime(d.Date); yr = dt.dt.year.to_numpy(); mo = dt.dt.month.to_numpy(); doy = dt.dt.dayofyear.to_numpy()
assert yr.max() <= 2018
keep = yr >= Y0; d = d[keep]; yr, mo, doy = yr[keep], mo[keep], doy[keep]
ci = np.searchsorted(P.ids, d.ID.to_numpy()); assert (P.ids[ci] == d.ID.to_numpy()).all()
n, T = len(P.ids), len(YEARS); size = n * T
key = ci * T + (yr - Y0)
tmax = d.tmax.to_numpy(); tmin = d.tmin.to_numpy()
pair = np.isfinite(tmax) & np.isfinite(tmin)
tav = (tmax + tmin) / 2
warm = (mo >= 5) & (mo <= 10)
out = {}
for name, sel in (('warm', pair & warm), ('cool', pair & ~warm)):
k = key[sel]; t = tav[sel]
base = np.bincount(k, np.maximum(t - 65, 0), minlength=size)
inc = np.empty((size, len(DGRID)), np.float32)
for j, dl in enumerate(DGRID):
inc[:, j] = np.bincount(k, np.maximum(t + dl - 65, 0), minlength=size) - base
out['inc_' + name] = inc.reshape(n, T, len(DGRID))
cnt = np.bincount(k, minlength=size)
out[name + '_mean'] = (np.bincount(k, t, minlength=size) / np.maximum(cnt, 1)).reshape(n, T)
out[name + '_n'] = cnt.reshape(n, T)
jja = np.isfinite(tmax) & (mo >= 6) & (mo <= 8)
c = np.bincount(key[jja], minlength=size)
out['jja_tmax'] = (np.bincount(key[jja], tmax[jja], minlength=size) / np.maximum(c, 1)).reshape(n, T)
out['jja_n'] = c.reshape(n, T)
out['active'] = np.bincount(key[pair], (tav[pair] > 65).astype(float), minlength=size).reshape(n, T)
# top-3 independent hot days
h3 = np.full(size, np.nan)
m = np.isfinite(tmax); kk = key[m]; tx = tmax[m]; dd = doy[m]
order = np.lexsort((-tx, kk)); kk, tx, dd = kk[order], tx[order], dd[order]
starts = np.flatnonzero(np.r_[True, kk[1:] != kk[:-1]]); ends = np.r_[starts[1:], len(kk)]
for s, e in zip(starts, ends):
picked = []; days = []
for v, dy in zip(tx[s:e], dd[s:e]):
if all(abs(dy - q) >= 3 for q in days):
picked.append(v); days.append(dy)
if len(picked) == 3: break
if len(picked) == 3: h3[kk[s]] = np.mean(picked)
out['h3'] = h3.reshape(n, T)
out['ndays'] = np.array([366 if (y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)) else 365 for y in YEARS])
np.savez(cache, tag=tag, **out)
return out
def attach(P):
P.d3 = daily_tables(P)
c = pd.read_parquet(DATA / 'coverage_and_stations/train-00000-of-00001.parquet')
m = np.zeros((len(P.ids), len(YEARS))); ci = np.searchsorted(P.ids, c.ID.to_numpy()); ti = c.Year.to_numpy() - Y0
k = ti >= 0; m[ci[k], ti[k]] = c['Days Both'].to_numpy()[k]; P.days_both = m
return P
def cut(P, origin, junk=999999.0):
"""Poisoned copy for leakage tests (all v2 + v3 arrays after origin set to junk)."""
Q = P.copy_cut(origin, junk); k = origin - Y0 + 1
for key, v in Q.d3.items():
if key == 'ndays': continue
v = v.copy(); v[:, k:] = junk; Q.d3[key] = v
Q.days_both = Q.days_both.copy(); Q.days_both[:, k:] = junk
return Q
# ---------------------------------------------------------------- slopes
def _city_slope(x, y, s, est):
xd = x.astype(float).copy(); yd = y.astype(float).copy()
for g in np.unique(s):
k = s == g; xd[k] -= x[k].mean(); yd[k] -= y[k].mean()
den = (xd ** 2).sum(); dof = len(x) - len(np.unique(s)) - 1
if den <= 0 or dof < 7: return np.nan, np.nan
b = (xd * yd).sum() / den
if est == 'huber':
for _ in range(20):
r = yd - b * xd; sc = np.median(np.abs(r - np.median(r))) * 1.4826 + 1e-9
u = np.abs(r) / sc; w = np.where(u <= 1.345, 1.0, 1.345 / u)
b = (w * xd * yd).sum() / (w * xd * xd).sum()
elif est == 'ts':
dx = x[None, :] - x[:, None]; dy = y[None, :] - y[:, None]; ok = (dx > 0) & (s[None, :] == s[:, None])
if ok.any(): b = float(np.median(dy[ok] / dx[ok]))
res = yd - b * xd
return b, (res ** 2).sum() / dof / den
def city_slopes(P, val, valid, origin, W, est='ols'):
a, bnd = _win(origin, W); yrs = YEARS[a:bnd]
b = np.full(len(P.ids), np.nan); s2 = np.full(len(P.ids), np.nan)
for i in range(len(P.ids)):
ok = valid[i, a:bnd]
if ok.sum() < 10: continue
b[i], s2[i] = _city_slope(yrs[ok], val[i, a:bnd][ok], P.seg[i, a:bnd][ok], est)
return b, s2
def idw(P, origin):
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 = 6371 * 2 * np.arcsin(np.sqrt(np.clip(h, 0, 1))); np.fill_diagonal(dist, np.inf)
W = np.zeros_like(dist); nn = np.argsort(dist, axis=1)[:, :12]
for i in range(len(dist)): W[i, nn[i]] = 1 / np.maximum(dist[i, nn[i]], 25) ** 2
return W
def wmean(W, v):
ok = np.isfinite(v); Wk = W * ok[None, :]; s = Wk.sum(1)
return np.where(s > 0, (Wk @ np.where(ok, v, 0)) / np.maximum(s, 1e-300), np.nan)
def eb(W, b, s2):
ok = np.isfinite(b); Wk = W * ok[None, :]; Wk = Wk / np.maximum(Wk.sum(1, keepdims=True), 1e-300)
bz = np.where(ok, b, 0); sz = np.where(ok, s2, 0)
r = Wk @ bz
tau2 = np.maximum((Wk * (bz[None, :] - r[:, None]) ** 2).sum(1) - Wk @ sz, 1e-6)
B = s2 / (s2 + tau2)
out = np.where(ok, B * r + (1 - B) * b, r)
return np.where(np.isfinite(out), out, np.nanmean(b))
def temp_slope(P, origin, kind, W=None):
T = 'annual_avg_temp'
if kind == 'v2':
b, _ = city_slopes(P, P.value[T], P.valid[T], origin, 30); return np.full(len(b), np.nanmean(b))
k, rest = kind.split('_', 1) if '_' in kind else (kind, '')
if kind.startswith('nat'):
b, _ = city_slopes(P, P.value[T], P.valid[T], origin, int(kind[3:])); return np.full(len(b), np.nanmean(b))
if kind.startswith('reg'):
b, _ = city_slopes(P, P.value[T], P.valid[T], origin, int(kind[3:]))
r = wmean(W, b); return np.where(np.isfinite(r), r, np.nanmean(b))
if kind.startswith('eb_'):
_, est, w = kind.split('_'); b, s2 = city_slopes(P, P.value[T], P.valid[T], origin, int(w), est)
return eb(W, b, s2)
raise ValueError(kind)
# ---------------------------------------------------------------- temperature
def anomaly_composite(P, m, origin, W):
"""A[i, t] for t in [O-29, O]: IDW mean of neighbours' anomaly vs their own [O-29,O] mean."""
a, b = _win(origin, 30); v = P.value[m][:, a:b]; ok = P.valid[m][:, a:b]
mu = np.where(ok.sum(1) > 0, np.nansum(np.where(ok, v, 0), 1) / np.maximum(ok.sum(1), 1), np.nan)
an = np.where(ok, v - mu[:, None], np.nan)
A = np.full(an.shape, np.nan)
for t in range(an.shape[1]): A[:, t] = wmean(W, an[:, t])
return A, a, b
def level_ra(P, origin, n, W, m='annual_avg_temp'):
A, a, b = anomaly_composite(P, m, origin, W)
yrs = YEARS[a:b]; lev = np.full(len(P.ids), np.nan); cen = np.full(len(P.ids), np.nan)
for i in range(len(P.ids)):
ok = P.valid[m][i, a:b] & np.isfinite(A[i])
if ok.sum() < 10: continue
idx = np.where(P.valid[m][i, :b])[0]; cur = P.seg[i, idx[-1]]
same = ok & (P.seg[i, a:b] == cur)
use = same if same.sum() >= 8 else ok
d = np.mean(P.value[m][i, a:b][use] - A[i][use])
rec = np.isfinite(A[i]) & (yrs > origin - n)
lev[i] = d + A[i][rec].mean(); cen[i] = yrs[rec].mean()
return lev, cen
def level_v2(P, origin, L=15, m='annual_avg_temp', value=None):
v = P.value[m] if value is None else value
lev = np.empty(len(P.ids)); cen = np.empty(len(P.ids))
for i in range(len(P.ids)):
ly = level_years(P, m, origin, i, L); lev[i] = v[i, ly].mean(); cen[i] = YEARS[ly].mean()
return lev, cen
def homogenised(P, origin, W, m='annual_avg_temp'):
"""Return value matrix with pre-move years shifted by detected steps (|jump|>0.35) inside [O-29,O]."""
A, a, b = anomaly_composite(P, m, origin, W)
v = P.value[m].copy(); yrs = YEARS[a:b]; njump = 0
for i in range(len(P.ids)):
seg = P.seg[i, a:b]; ok = P.valid[m][i, a:b] & np.isfinite(A[i])
diff = P.value[m][i, a:b] - A[i]
for j in range(len(yrs) - 1, 0, -1):
if seg[j] != seg[j - 1] and seg[j] >= 0 and seg[j - 1] >= 0:
pre = ok & (np.arange(len(yrs)) < j) & (np.arange(len(yrs)) >= j - 7)
post = ok & (np.arange(len(yrs)) >= j) & (np.arange(len(yrs)) < j + 7)
if pre.sum() >= 3 and post.sum() >= 3:
jump = np.median(diff[post]) - np.median(diff[pre])
if abs(jump) > 0.35:
v[i, :a + j] += jump; diff[:j] += jump; njump += 1
return v, njump
def temp_forecast(P, origin, slope, level, cen, H=7):
hs = np.arange(1, H + 1); return level[:, None] + slope[:, None] * (origin + hs[None] - cen[:, None])
# ---------------------------------------------------------------- CDD
def season_slope(P, origin, W, kind):
out = {}
valid = P.valid['annual_avg_temp']
for s in ('warm', 'cool'):
val = P.d3[s + '_mean']; vv = valid & (P.d3[s + '_n'] >= 150)
b, s2 = city_slopes(P, val, vv, origin, 30)
out[s] = np.full(len(b), np.nanmean(b)) if kind == 'nat' else eb(W, b, s2)
return out
def cdd_shift(P, origin, L, sw, sc=None, norm=None, H=7, jac=0.0, jac_slope=None):
"""Daily shift CDD. sw: slope for warm days (or all days if sc is None); sc: cool-season slope."""
hs = np.arange(1, H + 1); n = len(P.ids); out = np.empty((n, H)); m = 'cdd'
for i in range(n):
cy = level_years(P, m, origin, i, L); cyrs = YEARS[cy].astype(float); cv = P.value[m][i, cy]
dy = (origin + hs)[None, :] - cyrs[:, None]
vals = np.empty((len(cy), H))
for r, t in enumerate(cy):
if sc is None: inc = interp_inc(P.inc[i, t], sw[i] * dy[r])
else: inc = interp_inc(P.d3['inc_warm'][i, t], sw[i] * dy[r]) + interp_inc(P.d3['inc_cool'][i, t], sc[i] * dy[r])
v = cv[r] + inc
if norm == 'leap': v = v * np.array([P.d3['ndays'][min(origin + h - Y0, len(YEARS) - 1)] if origin + h <= Y1 else (366 if (origin + h) % 4 == 0 else 365) for h in hs]) / P.d3['ndays'][t]
elif norm == 'cov':
tgt = np.array([366 if (origin + h) % 4 == 0 else 365 for h in hs]); v = v * tgt / max(P.days_both[i, t], 1)
vals[r] = v
f = vals.mean(0)
if jac:
js = sw if jac_slope is None else jac_slope
act = P.d3['active'][i, cy].mean()
lin = cv.mean() + act * js[i] * (origin + hs - cyrs.mean())
f = (1 - jac) * f + jac * lin
out[i] = f
return np.maximum(out, 0)
# ---------------------------------------------------------------- precip / hottest
def huber_loc(y, c=1.345):
mu = np.median(y)
for _ in range(20):
sc = np.median(np.abs(y - np.median(y))) * 1.4826 + 1e-9; u = np.abs(y - mu) / sc
w = np.where(u <= c, 1.0, c / u); mu = (w * y).sum() / w.sum()
return mu
def window_stat(P, m, origin, N, f, minn=10):
a, b = _win(origin, N); out = np.empty(len(P.ids))
base, _ = clim30(P, m, origin)
for i in range(len(P.ids)):
ok = P.valid[m][i, a:b]
out[i] = f(P.value[m][i, a:b][ok]) if ok.sum() >= minn else base[i]
return out
def precip_ratio(P, origin, W):
m = 'total_precip_in'; m30 = window_stat(P, m, origin, 30, np.mean); m15 = window_stat(P, m, origin, 15, np.mean, 8)
r = np.where(m30 > 1, m15 / m30, np.nan); return np.clip(np.where(np.isfinite(wmean(W, r)), wmean(W, r), 1.0), 0.94, 1.06)
def hot_topk15(P, origin):
m = 'hottest_day_temp'; a, b = _win(origin, 30); a15, _ = _win(origin, 15)
base, _ = clim30(P, m, origin); out = base.copy(); h3 = P.d3['h3']
for i in range(len(P.ids)):
ok = P.valid[m][i, a:b] & np.isfinite(h3[i, a:b])
ok15 = P.valid[m][i, a15:b] & np.isfinite(h3[i, a15:b])
if ok.sum() >= 10 and ok15.sum() >= 5:
off = np.mean(P.value[m][i, a:b][ok] - h3[i, a:b][ok]); out[i] = h3[i, a15:b][ok15].mean() + off
return out
def jja_slope(P, origin):
vv = P.valid['hottest_day_temp'] & (P.d3['jja_n'] >= 80)
b, _ = city_slopes(P, P.d3['jja_tmax'], vv, origin, 30); return np.nanmean(b)
# ---------------------------------------------------------------- all candidates at one origin
def v3_block(P, origin, H=7, extra_temp_slopes=()):
ids = P.ids; hs = np.arange(1, H + 1); rows = []
def add(metric, method, mat):
mat = np.asarray(mat, float)
if mat.ndim == 1: mat = np.repeat(mat[:, None], H, 1)
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]}))
W = idw(P, origin); T = 'annual_avg_temp'
for m in METRICS: add(m, 'clim30', clim30(P, m, origin)[0])
add('cdd', 'exp10', exp10(P, 'cdd', origin))
# temperature
s_v2 = temp_slope(P, origin, 'v2'); lv, cv = level_v2(P, origin)
add(T, 'v2', temp_forecast(P, origin, s_v2, lv, cv, H))
kinds = [f'nat{w}' for w in (30, 40, 50)] + [f'reg{w}' for w in (30, 40, 50)] + [f'eb_{e}_{w}' for e in ('ols', 'huber', 'ts') for w in (30, 40, 50)]
slopes = {'v2': s_v2}
for k in kinds:
slopes[k] = temp_slope(P, origin, k, W); add(T, 'slope_' + k, temp_forecast(P, origin, slopes[k], lv, cv, H))
levels = {'v2': (lv, cv)}
for n in (12, 15):
l, c = level_ra(P, origin, n, W); fb = ~np.isfinite(l); l[fb] = lv[fb]; c[fb] = cv[fb]
levels[f'ra{n}'] = (l, c); add(T, f'level_ra{n}', temp_forecast(P, origin, s_v2, l, c, H))
hv, _ = homogenised(P, origin, W)
lh = np.empty(len(ids)); ch = np.empty(len(ids)); a, b = _win(origin, 30); bh = np.full(len(ids), np.nan)
for i in range(len(ids)):
idx = np.where(P.valid[T][i, :b])[0][-15:]; lh[i] = hv[i, idx].mean(); ch[i] = YEARS[idx].mean()
ok = P.valid[T][i, a:b]
if ok.sum() >= 10: bh[i] = np.polyfit(YEARS[a:b][ok] - origin, hv[i, a:b][ok], 1)[0]
add(T, 'homog', temp_forecast(P, origin, np.full(len(ids), np.nanmean(bh)), lh, ch, H))
for (sk, lk) in extra_temp_slopes:
l, c = levels[lk]; add(T, f'combo_{sk}+{lk}', temp_forecast(P, origin, slopes[sk], l, c, H))
# CDD
add('cdd', 'v2b', cdd_shift(P, origin, 15, s_v2))
add('cdd', 'L20', cdd_shift(P, origin, 20, s_v2))
ss = {k: season_slope(P, origin, W, k) for k in ('nat', 'eb')}
for k in ('nat', 'eb'):
for L in (15, 20): add('cdd', f'season_{k}_L{L}', cdd_shift(P, origin, L, ss[k]['warm'], ss[k]['cool']))
for nm in ('leap', 'cov'): add('cdd', f'norm_{nm}', cdd_shift(P, origin, 15, s_v2, norm=nm))
add('cdd', 'jac', cdd_shift(P, origin, 15, s_v2, jac=0.35))
add('cdd', 'jacw', cdd_shift(P, origin, 15, s_v2, jac=0.35, jac_slope=ss['nat']['warm']))
for sk, _ in extra_temp_slopes:
if sk != 'v2': add('cdd', f'tslope_{sk}', cdd_shift(P, origin, 15, slopes[sk]))
# precipitation
p = 'total_precip_in'
h30 = window_stat(P, p, origin, 30, huber_loc); h45 = window_stat(P, p, origin, 45, huber_loc)
m30 = clim30(P, p, origin)[0]; m45 = window_stat(P, p, origin, 45, np.mean); ratio = precip_ratio(P, origin, W)
add(p, 'huber30', h30); add(p, 'blend3045', 0.5 * m30 + 0.5 * m45); add(p, 'ratio', m30 * ratio)
add(p, 'shebe', 0.55 * h30 + 0.25 * h45 + 0.20 * m30 * ratio)
# hottest
q = 'hottest_day_temp'; hb = clim30(P, q, origin)[0]; hh = window_stat(P, q, origin, 30, huber_loc)
add(q, 'huber30', hh); add(q, 'topk15', hot_topk15(P, origin))
js = jja_slope(P, origin)
for beta in (0.25, 0.35, 0.5):
add(q, f'jja{beta:g}', hb[:, None] + beta * js * (hs[None] + 14.5))
add(q, f'huber30+jja{beta:g}', hh[:, None] + beta * js * (hs[None] + 14.5))
return pd.concat(rows, ignore_index=True)