Download code/dataset.py from Tonic/protostar-climate-2026: direct link, hf CLI and curl.
- Browser
- Download file 5.06 kB
-
https://huggingface.co/datasets/Tonic/protostar-climate-2026/resolve/main/code/dataset.py
- Command line
-
hf download hf://datasets/Tonic/protostar-climate-2026/code/dataset.py
-
curl -L -o dataset.py https://huggingface.co/datasets/Tonic/protostar-climate-2026/resolve/main/code/dataset.py
5.06 kB
| """Challenge data loading (pinned revision) + validity rules. | |
| Only annual_indices / city_info / coverage_and_stations are needed for the | |
| forecast core. All rows are <= 2018 by construction of the source dataset; | |
| we assert it anyway. | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from huggingface_hub import snapshot_download | |
| from leakage import assert_dates_le_cutoff | |
| REPO = "CMU-OSPO/protostar-climate-train-to-2018" | |
| # Pinned revision (dataset sha observed 2026-11-11). | |
| REVISION = "bbbdebdab2a18e00f97ef87bd3f35a71e222180b" | |
| METRIC_COLUMNS = { | |
| "annual_avg_temp": "Avg Temp", | |
| "total_precip_in": "ToT Prcp", | |
| "hottest_day_temp": "Max Tmax", | |
| "cdd": "cdd", | |
| } | |
| METRICS = list(METRIC_COLUMNS) | |
| MAX_MISSING_DAYS = 10 | |
| def download(cache_dir: Path) -> Path: | |
| path = snapshot_download( | |
| repo_id=REPO, | |
| repo_type="dataset", | |
| revision=REVISION, | |
| local_dir=str(cache_dir), | |
| allow_patterns=["annual_indices/*.parquet", "city_info/*.parquet", | |
| "coverage_and_stations/*.parquet", "README.md"], | |
| ) | |
| return Path(path) | |
| def _clean_numeric(s: pd.Series) -> pd.Series: | |
| return pd.to_numeric(s, errors="coerce").replace([np.inf, -np.inf], np.nan) | |
| def load_annual(root: Path) -> pd.DataFrame: | |
| df = pd.read_parquet(root / "annual_indices" / "train-00000-of-00001.parquet") | |
| df.columns = [c.strip() for c in df.columns] | |
| for col in ["Avg Temp", "ToT Prcp", "Max Tmax", "cdd", | |
| "Miss Tmax", "Miss Tmin", "Miss Prcp"]: | |
| if col in df: | |
| df[col] = _clean_numeric(df[col]) | |
| assert_dates_le_cutoff(pd.to_datetime(df["Year"], format="%Y"), "annual_indices.Year") | |
| return df | |
| def load_coverage(root: Path) -> pd.DataFrame: | |
| df = pd.read_parquet(root / "coverage_and_stations" / "train-00000-of-00001.parquet") | |
| df.columns = [c.strip() for c in df.columns] | |
| return df | |
| def load_cities(root: Path) -> pd.DataFrame: | |
| df = pd.read_parquet(root / "city_info" / "train-00000-of-00001.parquet") | |
| df.columns = [c.strip() for c in df.columns] | |
| return df | |
| def add_validity(annual: pd.DataFrame, coverage: pd.DataFrame | None) -> pd.DataFrame: | |
| """Per-metric validity: <=10 missing days of the values the metric uses. | |
| annual_avg_temp / cdd: Miss Tmax<=10 and Miss Tmin<=10 | |
| hottest_day_temp: Miss Tmax<=10 | |
| total_precip_in: Miss Prcp<=10 | |
| CDD additionally merges Days Both (days with both temps) when available: | |
| valid only if (days_in_year - Days Both) <= 10. | |
| """ | |
| df = annual.copy() | |
| mt, mn, mp = df["Miss Tmax"], df["Miss Tmin"], df["Miss Prcp"] | |
| df["valid_annual_avg_temp"] = (mt <= MAX_MISSING_DAYS) & (mn <= MAX_MISSING_DAYS) | |
| df["valid_hottest_day_temp"] = mt <= MAX_MISSING_DAYS | |
| df["valid_total_precip_in"] = mp <= MAX_MISSING_DAYS | |
| df["valid_cdd"] = (mt <= MAX_MISSING_DAYS) & (mn <= MAX_MISSING_DAYS) | |
| if coverage is not None: | |
| cov_cols = {c.lower(): c for c in coverage.columns} | |
| # Locate ID/Year and the 'both' column robustly. | |
| id_c = next((coverage[c] for c in coverage.columns if c.strip() == "ID"), None) | |
| yr_c = next((coverage[c] for c in coverage.columns if c.strip().lower() == "year"), None) | |
| both_c = next((c for c in coverage.columns if "both" in c.lower()), None) | |
| if id_c is not None and yr_c is not None and both_c is not None: | |
| cov = pd.DataFrame({ | |
| "ID": id_c.values, "Year": pd.to_numeric(yr_c, errors="coerce").values, | |
| "DaysBoth": pd.to_numeric(coverage[both_c], errors="coerce").values, | |
| }) | |
| df = df.merge(cov, on=["ID", "Year"], how="left") | |
| days_in_year = np.where( | |
| ((df["Year"] % 4 == 0) & ((df["Year"] % 100 != 0) | (df["Year"] % 400 == 0))), | |
| 366, 365) | |
| df["valid_cdd"] = df["valid_cdd"] & ((days_in_year - df["DaysBoth"]) <= MAX_MISSING_DAYS) | |
| # A stored value must also exist and be finite. | |
| for metric, col in METRIC_COLUMNS.items(): | |
| df[f"valid_{metric}"] = df[f"valid_{metric}"] & df[col].notna() | |
| # Fully-missing precip years are stored as 0.00 with Miss Prcp ~365 (already | |
| # invalid); also drop implausible zeros guarded by the missing-day rule. | |
| return df | |
| def long_valid(df: pd.DataFrame) -> pd.DataFrame: | |
| """Long table of valid observations: city_id, Name, Year, metric, value, Lat, Lon.""" | |
| frames = [] | |
| for metric, col in METRIC_COLUMNS.items(): | |
| sub = df.loc[df[f"valid_{metric}"], ["ID", "Name", "Year", "Lat", "Lon", col]].copy() | |
| sub = sub.rename(columns={"ID": "city_id", col: "value"}) | |
| sub["metric"] = metric | |
| frames.append(sub[["city_id", "Name", "Year", "metric", "value", "Lat", "Lon"]]) | |
| out = pd.concat(frames, ignore_index=True) | |
| return out.sort_values(["city_id", "metric", "Year"]).reset_index(drop=True) | |