Datasets:
Download code/common.py from sleonca/sl-protostar-climate-ceviche: direct link, hf CLI and curl.
- Browser
- Download file 3.38 kB
-
https://huggingface.co/datasets/sleonca/sl-protostar-climate-ceviche/resolve/main/code/common.py
- Command line
-
hf download hf://datasets/sleonca/sl-protostar-climate-ceviche/code/common.py
-
curl -L -o common.py https://huggingface.co/datasets/sleonca/sl-protostar-climate-ceviche/resolve/main/code/common.py
3.38 kB
| """Shared helpers: load the challenge data, apply the official validity rules, score forecasts. | |
| Everything here reads only data/raw/ (challenge dataset, which ends 2018-12-31). | |
| """ | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| ROOT = Path(__file__).resolve().parents[1] | |
| RAW = ROOT / "data" / "raw" | |
| CUTOFF_YEAR = 2018 | |
| METRICS = { | |
| "annual_avg_temp": "Avg Temp", | |
| "total_precip_in": "ToT Prcp", | |
| "hottest_day_temp": "Max Tmax", | |
| "cdd": "cdd", | |
| } | |
| # Which missing-day counts make a year invalid for a metric (official 10-day rule). | |
| MISS_COLS = { | |
| "annual_avg_temp": ["Miss Tmax", "Miss Tmin"], | |
| "total_precip_in": ["Miss Prcp"], | |
| "hottest_day_temp": ["Miss Tmax", "Miss Tmin"], | |
| "cdd": ["Miss Tmax", "Miss Tmin"], | |
| } | |
| MAX_MISS = 10 | |
| def guard(df: pd.DataFrame, col: str = "Year") -> pd.DataFrame: | |
| """Data-rule check: stop if any weather input is dated after 2018.""" | |
| if col in df and pd.to_numeric(df[col]).max() > CUTOFF_YEAR: | |
| raise RuntimeError(f"Weather input contains data after {CUTOFF_YEAR}: data rule violated") | |
| return df | |
| def load_annual() -> pd.DataFrame: | |
| a = guard(pd.read_parquet(RAW / "annual_indices.parquet")) | |
| cov = guard(pd.read_parquet(RAW / "coverage_and_stations.parquet")) | |
| a = a.merge(cov[["ID", "Year", "Days Both", "Station Segment", "Station Changes"]], on=["ID", "Year"], how="left") | |
| return a.sort_values(["ID", "Year"]).reset_index(drop=True) | |
| def load_daily() -> pd.DataFrame: | |
| d = pd.read_parquet(RAW / "daily.parquet", columns=["ID", "Date", "tmax", "tmin", "prcp"]) | |
| d["Date"] = pd.to_datetime(d["Date"]) | |
| if d["Date"].max() > pd.Timestamp(f"{CUTOFF_YEAR}-12-31"): | |
| raise RuntimeError("Daily weather input contains data after 2018-12-31: data rule violated") | |
| d["Year"] = d["Date"].dt.year | |
| return d | |
| def long_valid(a: pd.DataFrame) -> pd.DataFrame: | |
| """Long table: ID, Year, metric, value, valid (official 10-day rule).""" | |
| out = [] | |
| for m, col in METRICS.items(): | |
| miss = a[MISS_COLS[m]].max(axis=1) | |
| out.append(pd.DataFrame({ | |
| "ID": a["ID"], "Year": a["Year"], "metric": m, "value": a[col], | |
| "valid": (miss <= MAX_MISS) & a[col].notna(), | |
| "segment": a["Station Segment"], | |
| })) | |
| return pd.concat(out, ignore_index=True) | |
| def baseline30(lv: pd.DataFrame, origin: int) -> pd.Series: | |
| """30-year average over valid years origin-29..origin; NaN if < 10 valid years.""" | |
| w = lv[(lv.Year > origin - 30) & (lv.Year <= origin) & lv.valid] | |
| g = w.groupby(["ID", "metric"])["value"] | |
| mean, n = g.mean(), g.size() | |
| return mean.where(n >= 10) | |
| def score(pred: pd.DataFrame, lv: pd.DataFrame, origin: int, years) -> pd.DataFrame: | |
| """pred: columns ID, metric, Year, pred. Returns per-metric MAE, baseline MAE and skill S_m.""" | |
| truth = lv[lv.Year.isin(years) & lv.valid][["ID", "metric", "Year", "value"]] | |
| b = baseline30(lv, origin).rename("base").reset_index() | |
| df = truth.merge(b, on=["ID", "metric"]).dropna(subset=["base"]).merge(pred, on=["ID", "metric", "Year"], how="left") | |
| if df["pred"].isna().any(): | |
| raise ValueError(f"{df['pred'].isna().sum()} scored rows missing predictions") | |
| res = df.assign(e=(df.pred - df.value).abs(), eb=(df.base - df.value).abs()).groupby("metric")[["e", "eb"]].mean() | |
| res["S"] = 1 - res.e / res.eb | |
| return res | |