"""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