File size: 4,931 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
"""Vectorised city x year panel for fast rolling-origin evaluation.



values[metric]: (n_cities, n_years) float array, NaN where the year is not

valid under the official <=10-missing-day rule. All statistics are computed

from slices ending at the origin, so no post-origin data can leak.

"""
from __future__ import annotations

from pathlib import Path

import numpy as np
import pandas as pd

from dataset import (METRICS, add_validity, download, load_annual, load_cities,
                     load_coverage, long_valid)

YEAR_MIN = 1930


class Panel:
    def __init__(self, root: Path):
        data_root = download(root / "data" / "_source")
        annual = add_validity(load_annual(data_root), load_coverage(data_root))
        cities_df = load_cities(data_root)
        long_df = long_valid(annual)
        self.cities = sorted(long_df["city_id"].unique())
        self.years = np.arange(YEAR_MIN, 2019)
        self.year_idx = {int(y): i for i, y in enumerate(self.years)}
        geo = (long_df.drop_duplicates("city_id").set_index("city_id")
               .loc[self.cities])
        self.lat = geo["Lat"].to_numpy(float)
        self.lon = geo["Lon"].to_numpy(float)
        self.values: dict[str, np.ndarray] = {}
        for metric in METRICS:
            sub = long_df[long_df["metric"] == metric]
            piv = sub.pivot(index="city_id", columns="Year", values="value")
            piv = piv.reindex(index=self.cities, columns=self.years)
            self.values[metric] = piv.to_numpy(float)
        self._neighbours()
        self._cache: dict = {}

    def _neighbours(self, k: int = 32):
        lat, lon = np.radians(self.lat), np.radians(self.lon)
        dlat = lat[:, None] - lat[None, :]
        dlon = lon[:, None] - lon[None, :]
        a = np.sin(dlat / 2) ** 2 + np.cos(lat[:, None]) * np.cos(lat[None, :]) * np.sin(dlon / 2) ** 2
        dist = 6371 * 2 * np.arcsin(np.sqrt(np.clip(a, 0, 1)))
        np.fill_diagonal(dist, np.inf)
        self.nn_idx = np.argsort(dist, axis=1)[:, :k]  # (210, k) nearest others

    def window(self, metric: str, origin: int, start: int):
        i0, i1 = self.year_idx[start], self.year_idx[origin]
        return self.values[metric][:, i0:i1 + 1], self.years[i0:i1 + 1]

    def stats(self, metric: str, origin: int, years_back: int | None = None,

              start: int | None = None) -> dict:
        """Per-city window stats + pooled slope. Cached per (metric, origin, window)."""
        if start is None:
            start = origin - years_back + 1
        key = (metric, origin, int(start))
        if key in self._cache:
            return self._cache[key]
        vals, yrs = self.window(metric, origin, int(start))
        valid = np.isfinite(vals)
        n = valid.sum(axis=1)
        x = np.where(valid, yrs[None, :], 0.0)
        y = np.where(valid, vals, 0.0)
        sx, sy = x.sum(1), y.sum(1)
        sxx, sxy = (x * x).sum(1), (x * y).sum(1)
        with np.errstate(invalid="ignore", divide="ignore"):
            mean = np.where(n > 0, sy / np.maximum(n, 1), np.nan)
            mean_year = np.where(n > 0, sx / np.maximum(n, 1), np.nan)
            denom = sxx - sx * sx / np.maximum(n, 1)
            slope = np.where((n >= 5) & (denom > 0),
                             (sxy - sx * sy / np.maximum(n, 1)) / np.where(denom > 0, denom, 1),
                             np.nan)
            median = np.nanmedian(vals, axis=1)
        pooled_num = np.nansum(sxy - sx * sy / np.maximum(n, 1))
        pooled_den = np.nansum(denom)
        out = {"n": n, "mean": mean, "median": median, "mean_year": mean_year,
               "slope": slope,
               "pooled_slope": float(pooled_num / pooled_den) if pooled_den > 0 else 0.0,
               "start": int(start)}
        self._cache[key] = out
        return out

    def regional_slope(self, metric: str, origin: int, years_back: int | None = None,

                       start: int | None = None, k: int = 32) -> np.ndarray:
        st = self.stats(metric, origin, years_back, start)
        slopes = st["slope"]
        nn = slopes[self.nn_idx[:, :k]]  # (210, k)
        with np.errstate(invalid="ignore"):
            reg = np.nanmedian(nn, axis=1)
        return np.where(np.isfinite(reg), reg, st["pooled_slope"])

    def truth(self, metric: str, origin: int, horizon: int = 7):
        """(values (210,7), scored_mask) for origin+1..origin+7.



        Scored: truth valid AND city-metric has >=10 valid years in the

        30-year window ending at origin (official baseline-eligibility rule).

        """
        cols = [self.year_idx[origin + h] for h in range(1, horizon + 1)]
        vals = self.values[metric][:, cols]
        st = self.stats(metric, origin, years_back=30)
        eligible = (st["n"] >= 10)[:, None]
        return vals, np.isfinite(vals) & eligible