Datasets:
Download code/models.py from sleonca/sl-protostar-climate-ceviche: direct link, hf CLI and curl.
- Browser
- Download file 9.02 kB
-
https://huggingface.co/datasets/sleonca/sl-protostar-climate-ceviche/resolve/main/code/models.py
- Command line
-
hf download hf://datasets/sleonca/sl-protostar-climate-ceviche/code/models.py
-
curl -L -o models.py https://huggingface.co/datasets/sleonca/sl-protostar-climate-ceviche/resolve/main/code/models.py
9.02 kB
| """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 | |