File size: 6,420 Bytes
49f3de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""CDD delta method: shift-table from daily data + delta candidates.



For each city-year we precompute CDD under uniform temperature shifts

s in [-3, +6] F (0.25 steps): CDD(s) = sum_d max(0, (tmax+tmin)/2 + s - 65).

A forecast for year y replays historical years t, each warmed by

slope * (y - t), and aggregates (mean/median) the shifted CDDs.

Build:  python code/cdd_delta.py --build

"""
from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np
import pandas as pd

sys.path.insert(0, str(Path(__file__).parent))
from dataset import download
from panel import Panel

SHIFTS = np.round(np.arange(-3.0, 6.01, 0.25), 2)
YEAR0 = 1960


def build_shift_table(root: Path) -> Path:
    data_root = download(root / "data" / "_source")
    daily = pd.read_parquet(data_root / "daily" / "train-00000-of-00001.parquet")
    daily["Year"] = daily["Date"].astype(str).str.slice(0, 4).astype(int)
    daily = daily[daily["Year"] >= YEAR0]
    mean_temp = (daily["tmax"] + daily["tmin"]) / 2.0
    daily = daily.assign(mean_temp=mean_temp).dropna(subset=["mean_temp"])
    cities = sorted(daily["ID"].unique())
    years = np.arange(YEAR0, 2019)
    table = np.full((len(cities), len(years), len(SHIFTS)), np.nan, dtype=np.float32)
    city_idx = {c: i for i, c in enumerate(cities)}
    grouped = daily.groupby(["ID", "Year"])["mean_temp"]
    for (city, year), arr in grouped:
        v = arr.to_numpy(float)
        if len(v) < 300:  # too incomplete to replay
            continue
        excess = v[None, :] + SHIFTS[:, None] - 65.0
        table[city_idx[city], int(year) - YEAR0] = np.clip(excess, 0, None).sum(axis=1)
    out = root / "data" / "cdd_shift_table.npz"
    np.savez_compressed(out, table=table, cities=np.array(cities),
                        years=years, shifts=SHIFTS)
    print(f"wrote {out}: {table.shape}, finite city-years={np.isfinite(table[:, :, 18]).sum()}")
    return out


class CddDelta:
    def __init__(self, root: Path, panel: Panel):
        path = root / "data" / "cdd_shift_table.npz"
        if not path.exists():
            build_shift_table(root)
        z = np.load(path, allow_pickle=True)
        table, cities, years = z["table"], list(z["cities"]), z["years"]
        # Align to panel city order / year axis.
        self.panel = panel
        self.table = np.full((len(panel.cities), len(panel.years), len(SHIFTS)),
                             np.nan, dtype=np.float32)
        year_pos = {int(y): i for i, y in enumerate(years)}
        for ci, city in enumerate(cities):
            pi = panel.cities.index(city) if city in panel.cities else None
            if pi is None:
                continue
            for y, yi in year_pos.items():
                if y in panel.year_idx:
                    self.table[pi, panel.year_idx[y]] = table[ci, yi]

    def forecast(self, origin: int, history_years: int = 15,

                 aggregate: str = "median", trend: str = "nat",

                 slope_mult: float = 1.0) -> np.ndarray:
        panel = self.panel
        temp = panel.stats("annual_avg_temp", origin, years_back=40)
        if trend == "nat":
            slope = np.full(len(panel.cities), temp["pooled_slope"])
        elif trend == "reg":
            slope = panel.regional_slope("annual_avg_temp", origin, years_back=40)
        else:
            raise ValueError(trend)
        hist_years = list(range(origin - history_years + 1, origin + 1))
        hist_idx = [panel.year_idx[y] for y in hist_years]
        # Valid historical years: official CDD valid in panel.
        valid_hist = np.isfinite(panel.values["cdd"][:, hist_idx]) & \
            np.isfinite(self.table[:, hist_idx, 18])
        out = np.full((len(panel.cities), 7), np.nan)
        for h, target in enumerate(range(origin + 1, origin + 8)):
            s = slope_mult * slope[:, None] * (target - np.array(hist_years, dtype=float)[None, :])
            s_clip = np.clip(s, SHIFTS[0], SHIFTS[-1])
            pos = (s_clip - SHIFTS[0]) / 0.25
            lo = np.floor(pos).astype(int)
            frac = pos - lo
            hi = np.minimum(lo + 1, len(SHIFTS) - 1)
            cdd_lo = np.take_along_axis(self.table[:, hist_idx, :],
                                        lo[:, :, None], axis=2)[:, :, 0]
            cdd_hi = np.take_along_axis(self.table[:, hist_idx, :],
                                        hi[:, :, None], axis=2)[:, :, 0]
            shifted = cdd_lo * (1 - frac) + cdd_hi * frac
            shifted = np.where(valid_hist, shifted, np.nan)
            with np.errstate(invalid="ignore"):
                out[:, h] = (np.nanmedian(shifted, axis=1) if aggregate == "median"
                             else np.nanmean(shifted, axis=1))
        # Fallback: linear L15 candidate handled by caller blend; here use
        # city all-history median CDD for any remaining NaN.
        fallback = np.nanmedian(panel.values["cdd"][:, :panel.year_idx[origin] + 1], axis=1)
        bad = ~np.isfinite(out)
        if bad.any():
            out[bad] = np.take(fallback[:, None], np.where(bad)[0], axis=0).ravel() \
                if False else np.broadcast_to(fallback[:, None], out.shape)[bad]
        return np.maximum(out, 0.0)


def validate_shift0(root: Path, panel: Panel) -> pd.DataFrame:
    """CDD(shift=0) from daily vs official annual cdd, on valid years."""
    delta = CddDelta(root, panel)
    rows = []
    zi = list(SHIFTS).index(0.0)
    official = panel.values["cdd"]
    mine = delta.table[:, :, zi]
    diff = np.abs(mine - official)
    mask = np.isfinite(diff)
    print(f"shift-0 validation: n={mask.sum()}, mean|diff|={np.nanmean(diff):.3f} "
          f"F-days, max|diff|={np.nanmax(diff):.2f}, "
          f"share exact(<0.6)={np.mean(diff[mask] < 0.6):.3f}")
    return pd.DataFrame({"mean_abs_diff": [float(np.nanmean(diff))],
                         "max_abs_diff": [float(np.nanmax(diff))], "n": [int(mask.sum())]})


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--build", action="store_true")
    args = ap.parse_args()
    root = Path(__file__).resolve().parent.parent
    if args.build:
        build_shift_table(root)
    panel = Panel(root)
    validate_shift0(root, panel)


if __name__ == "__main__":
    main()