tchaudha's picture
v9: first-difference-correlation neighbour weights for temperature (pre-registered V9 protocol; idea from a Gemini brainstorm)
b3952f1 verified
Raw History Blame Contribute Delete
8.78 kB
"""Heat Seekers v8: climate-character temperature and simple shrinkage (research/V8_PROTOCOL.md). Data <= origin only."""
import hashlib, json
import numpy as np, pandas as pd
from v7lib import *
from v6lib import _win
REF8 = dict(REF7)
REF8['cdd'] = 'c_map' # v7 adopted CDD; v6_mats still returns v2b under REF7['cdd']
CANDS8 = {
'annual_avg_temp': ['t_c2nat', 't_c2nat50'],
'hottest_day_temp': ['h_clim30', 'h_shrink50', 'h_median30'],
'total_precip_in': ['p_clim30', 'p_shrink50', 'p_median30'],
'cdd': ['c_map_tchar'],
}
LAND_COLS = ['crop_share', 'pasture_share', 'water_share', 'developed_share', 'forest_share',
'impervious_pct', 'tree_canopy_pct', 'elev_m']
CLIMATE_COLS = ['dewpoint_f', 'wind_kt', 'visibility_mi', 'dewpoint_trend', 'dtr_mean', 'dtr_trend']
FEATURES = LAND_COLS + CLIMATE_COLS
LAMBDA_TREND = 10.0
GSOD_FIRST, MIN_DAYS, MIN_DEW_TREND = 1980, 300, 8
EXT8 = DATA / 'external_v8'
def check_ext8():
man = json.loads((EXT8 / 'manifest.json').read_text())['files']
for name, digest in man.items():
got = hashlib.sha256((EXT8 / name).read_bytes()).hexdigest()
assert got == digest, f'external_v8 file changed: {name}'
def _dtr_table():
"""Official-valid DTR from the pinned annual file; years 1870..2018, never after 2018."""
a = pd.read_parquet(DATA / 'annual_indices/train-00000-of-00001.parquet',
columns=['ID', 'Year', 'Avg Tmax', 'Avg Tmin', 'Miss Tmax', 'Miss Tmin'])
a = a[(a.Year >= Y0) & (a.Year <= Y1) & (a['Miss Tmax'] <= 10) & (a['Miss Tmin'] <= 10)
& a['Avg Tmax'].notna() & a['Avg Tmin'].notna()]
return pd.DataFrame({'city_id': a['ID'], 'year': a['Year'].astype(int),
'dtr': a['Avg Tmax'].to_numpy(float) - a['Avg Tmin'].to_numpy(float)})
class Ext8:
"""Land + GSOD + DTR. as_of(origin) uses years <= origin only."""
def __init__(self):
check_ext8()
self.land = pd.read_csv(EXT8 / 'land_features.csv').set_index('city_id')
g = pd.read_csv(EXT8 / 'gsod_yearly.csv')
assert g['year'].max() <= 2018
self.gsod = g[(g['days'] >= MIN_DAYS) & (g['year'] >= GSOD_FIRST)].copy()
self.dtr = _dtr_table()
assert self.dtr['year'].max() <= 2018
def cut(self, origin, junk=999999.0):
Q = Ext8.__new__(Ext8)
Q.land = self.land
Q.gsod = self.gsod.copy()
Q.dtr = self.dtr.copy()
Q.gsod.loc[Q.gsod['year'] > origin, ['dewpoint_f', 'wind_kt', 'visibility_mi', 'days']] = junk
Q.dtr.loc[Q.dtr['year'] > origin, 'dtr'] = junk
return Q
def as_of(self, origin, city_ids):
g = self.gsod[self.gsod['year'] <= origin]
means = g.groupby('city_id')[['dewpoint_f', 'wind_kt', 'visibility_mi']].mean()
trend = {}
for cid, gg in g.dropna(subset=['dewpoint_f']).groupby('city_id'):
if len(gg) >= MIN_DEW_TREND:
trend[cid] = np.polyfit(gg['year'], gg['dewpoint_f'], 1)[0]
d = self.dtr[self.dtr['year'] <= origin]
dtr_mean = d.sort_values('year').groupby('city_id').tail(15).groupby('city_id')['dtr'].mean()
dtr_trend = {cid: np.polyfit(gg['year'], gg['dtr'], 1)[0]
for cid, gg in d[d['year'] > origin - 30].groupby('city_id') if len(gg) >= 15}
f = pd.DataFrame(index=pd.Index(list(city_ids), name='city_id'))
f = f.join(self.land[LAND_COLS]).join(means)
f['dewpoint_trend'] = pd.Series(trend)
f['dtr_mean'] = dtr_mean
f['dtr_trend'] = pd.Series(dtr_trend)
return f[FEATURES].apply(lambda c: c.fillna(c.median()) if c.notna().any() else c.fillna(0.0))
def segment_slope(years, values, segments):
segs = np.unique(segments)
X = np.column_stack([(segments == s).astype(float) for s in segs] + [years - years.mean()])
coef, *_ = np.linalg.lstsq(X, values, rcond=None)
return float(coef[-1])
def city_slopes15(P, origin):
"""Segment-aware 30-year temperature slopes; cities with >=15 valid years."""
m = TM; 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() >= 15:
out[i] = segment_slope(yrs[ok], P.value[m][i, a:b][ok], P.seg[i, a:b][ok])
return out
def neighbor_mean_slopes(P, origin, slopes, k=10):
"""Mean slope of up to k nearest cities that have a slope; 0 if none. Ties by city id."""
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)))
ids = P.ids; have = np.isfinite(slopes); out = np.zeros(len(ids))
for i in range(len(ids)):
order = [j for j in range(len(ids)) if j != i]
order.sort(key=lambda j: (dist[i, j], ids[j]))
vals = [slopes[j] for j in order if have[j]][:k]
out[i] = float(np.mean(vals)) if vals else 0.0
return out
def ridge_predict(X, y, Xn, lam=LAMBDA_TREND):
mu, sd = X.mean(0), X.std(0); sd = np.where(sd == 0, 1.0, sd)
Z = (X - mu) / sd; ym = y.mean()
coef = np.linalg.solve(Z.T @ Z + lam * np.eye(Z.shape[1]), Z.T @ (y - ym))
return ym + ((Xn - mu) / sd) @ coef
def t_c2nat(P, origin, ext, v6t):
"""Parth C2 regional slope, 50% national pooling, 15-year (segment) level. Fallback: v7 temperature."""
slopes = city_slopes15(P, origin)
have = np.isfinite(slopes)
assert have.sum() >= 2, 'too few city slopes'
s_nat = float(slopes[have].mean())
nb = neighbor_mean_slopes(P, origin, slopes)
F = ext.as_of(origin, P.ids)
pred = ridge_predict(F.to_numpy(float)[have], slopes[have], F.to_numpy(float))
regional = 0.5 * nb + 0.5 * pred
s = 0.5 * regional + 0.5 * s_nat
hs = np.arange(1, H + 1); out = v6t.copy(); k1 = origin - Y0 + 1
n_level = 0
for i in range(len(P.ids)):
idx_win = np.where(P.valid[TM][i, max(0, origin - 14 - Y0):k1])[0] + max(0, origin - 14 - Y0)
segs_all = np.where(np.isfinite(P.seg[i, :k1]) & (P.seg[i, :k1] >= 0))[0]
cur = int(P.seg[i, segs_all[-1]]) if len(segs_all) else None
level_idx = idx_win
if cur is not None and (P.seg[i, idx_win] == cur).sum() >= 5:
level_idx = idx_win[P.seg[i, idx_win] == cur]
if len(level_idx) < 3:
level_idx = np.where(P.valid[TM][i, :k1])[0][-15:]
if not len(level_idx):
continue
n_level += 1
lev = P.value[TM][i, level_idx].mean(); cen = YEARS[level_idx].astype(float).mean()
out[i] = lev + s[i] * (origin + hs - cen)
return out, dict(s_nat=s_nat, n_slopes=int(have.sum()), n_level=n_level, mean_s=float(s.mean()))
def attach8(P):
return attach6(P)
def cut8(P, ext, origin, junk=999999.0):
return cut6(P, origin, junk), ext.cut(origin, junk)
def v7_ref_mats(P, origin):
"""v7 counting methods plus clim30, as matrices (n, H) and the v6_block frame."""
mats, info, f6 = v6_mats(P, origin)
mats['cdd'] = c_map(P, origin, mats[TM])
clim = {}
for m in METRICS:
g = f6[(f6.metric == m) & (f6.method == 'clim30')].pivot(index='city_id', columns='year', values='predicted_value')
clim[m] = g.reindex(P.ids).to_numpy()
return mats, clim, info, f6
def v8_block(P, origin, ext):
mats, clim, info, f6 = v7_ref_mats(P, origin)
# keep v7 refs + clim30; add c_map (not in v6_block)
keep = set(REF7.values()) | {'clim30'}
f6 = f6[f6.method.isin(keep)]
rows = [f6]; 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)
assert np.isfinite(M).all(), method
for j, h in enumerate(hs):
rows.append(pd.DataFrame({'city_id': ids, 'year': origin + h, 'metric': metric, 'method': method,
'predicted_value': M[:, j]}))
add('cdd', 'c_map', mats['cdd'])
t1, tinfo = t_c2nat(P, origin, ext, mats[TM])
add(TM, 't_c2nat', t1); add(TM, 't_c2nat50', 0.5 * t1 + 0.5 * mats[TM])
q = 'hottest_day_temp'; p = 'total_precip_in'
add(q, 'h_clim30', clim[q]); add(q, 'h_shrink50', 0.5 * mats[q] + 0.5 * clim[q])
add(q, 'h_median30', median30(P, q, origin))
add(p, 'p_clim30', clim[p]); add(p, 'p_shrink50', 0.5 * mats[p] + 0.5 * clim[p])
add(p, 'p_median30', median30(P, p, origin))
add('cdd', 'c_map_tchar', c_map(P, origin, t1))
info.update({f'c2_{k}': v for k, v in tinfo.items()})
return pd.concat(rows, ignore_index=True), info