File size: 4,994 Bytes
d79a78d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Loading, the valid-year rule, and the leakage guard.

Every loader checks the file's sha256 against the pinned Hub revision and asserts
that no row is dated after TRAIN_END (2018): the data rule is enforced in code.
"""

import hashlib
from dataclasses import dataclass

import numpy as np
import pandas as pd

from .common import (DATA_RAW, FILES, MAX_MISSING_DAYS, METRICS, N_CITIES, TRAIN_END)


class LeakageError(AssertionError):
    """A training input is dated after TRAIN_END."""


def assert_no_leak(years, what: str, limit: int = TRAIN_END) -> None:
    """Stop if any year in `years` is after `limit` (default: 2018)."""
    latest = int(np.max(np.asarray(years)))
    if latest > limit:
        raise LeakageError(f"{what}: latest year {latest} is after {limit} (data rule)")


def _path(name: str):
    path = DATA_RAW / name
    if not path.exists():
        raise FileNotFoundError(f"{path} is missing: run `python code/fetch_data.py`")
    digest = hashlib.sha256(path.read_bytes()).hexdigest()
    if digest != FILES[name][1]:
        raise ValueError(f"{name}: sha256 {digest} does not match the pinned revision")
    return path


def load_annual() -> pd.DataFrame:
    """annual_indices: one row per city and year, as published (+/-inf kept)."""
    df = pd.read_parquet(_path("annual_indices.parquet"))
    assert_no_leak(df["Year"], "annual_indices")
    assert df["ID"].nunique() == N_CITIES and not df.duplicated(["ID", "Year"]).any()
    return df


def load_city_info() -> pd.DataFrame:
    df = pd.read_parquet(_path("city_info.parquet"))
    for col in ("Stn.stDate", "Stn.edDate"):
        df[col] = pd.to_datetime(df[col].astype(str))
    assert_no_leak(df["Stn.edDate"].dt.year, "city_info")
    return df


def load_coverage() -> pd.DataFrame:
    df = pd.read_parquet(_path("coverage_and_stations.parquet"))
    assert_no_leak(df["Year"], "coverage_and_stations")
    return df


def load_daily() -> pd.DataFrame:
    import pyarrow.parquet as pq
    df = pq.read_table(_path("daily.parquet")).to_pandas(date_as_object=False)
    df["Date"] = pd.to_datetime(df["Date"])
    assert_no_leak(df["Date"].dt.year, "daily")
    return df


def cities(annual: pd.DataFrame) -> pd.DataFrame:
    """One row per city: city_id, name, lat, lon (location of the current station), sorted by id."""
    out = (annual.groupby("ID", as_index=False).agg(name=("Name", "first"), lat=("Lat", "first"),
                                                    lon=("Lon", "first"))
           .rename(columns={"ID": "city_id"}).sort_values("city_id").reset_index(drop=True))
    assert len(out) == N_CITIES and out[["lat", "lon"]].notna().all(axis=None)
    assert out["lat"].between(24, 50).all() and out["lon"].between(-125, -66).all()
    return out


def long_table(annual: pd.DataFrame) -> pd.DataFrame:
    """One row per city x year x metric: value and `valid` (the organizers' 10-day rule).

    valid = every variable the metric uses misses <= 10 days that year, and the value is a
    finite number (the source stores -inf as `Max Tmax` of a year with no observations).
    """
    parts = []
    for metric, (col, miss) in METRICS.items():
        part = annual[["ID", "Year"]].rename(columns={"ID": "city_id", "Year": "year"})
        value = annual[col].astype(float).where(np.isfinite(annual[col].astype(float)))
        part["metric"] = metric
        part["value"] = value
        part["valid"] = (annual[list(miss)] <= MAX_MISSING_DAYS).all(axis=1) & value.notna()
        parts.append(part)
    return pd.concat(parts, ignore_index=True)


@dataclass(frozen=True)
class Panel:
    """One metric as a city x year array; NaN = year missing or not valid (10-day rule)."""
    metric: str
    city_ids: np.ndarray   # sorted
    years: np.ndarray      # consecutive, ascending
    y: np.ndarray          # [n_city, n_year]

    @property
    def origin(self) -> int:
        return int(self.years[-1])

    def upto(self, origin: int) -> "Panel":
        """The panel as known at the end of `origin`: later years do not exist in the result."""
        keep = self.years <= origin
        return Panel(self.metric, self.city_ids, self.years[keep], self.y[:, keep])

    def between(self, first: int, last: int) -> "Panel":
        keep = (self.years >= first) & (self.years <= last)
        return Panel(self.metric, self.city_ids, self.years[keep], self.y[:, keep])


def panels(long: pd.DataFrame) -> dict[str, Panel]:
    """{metric: Panel}; all panels share the same city order and year axis."""
    assert_no_leak(long["year"], "long table")
    ids = np.array(sorted(long["city_id"].unique()))
    years = np.arange(long["year"].min(), long["year"].max() + 1)
    out = {}
    for metric in METRICS:
        part = long[(long["metric"] == metric) & long["valid"]]
        wide = part.pivot(index="city_id", columns="year", values="value").reindex(index=ids, columns=years)
        out[metric] = Panel(metric, ids, years, wide.to_numpy(dtype=float))
    return out