Datasets:
Download code/protostar/ghcnd.py from AlecAlameddine/protostar-climate: direct link, hf CLI and curl.
- Browser
- Download file 54.8 kB
-
https://huggingface.co/datasets/AlecAlameddine/protostar-climate/resolve/main/code/protostar/ghcnd.py
- Command line
-
hf download hf://datasets/AlecAlameddine/protostar-climate/code/protostar/ghcnd.py
-
curl -L -o ghcnd.py https://huggingface.co/datasets/AlecAlameddine/protostar-climate/resolve/main/code/protostar/ghcnd.py
54.8 kB
| """GHCN-Daily gap filling: an integration experiment (not part of the submission pipeline). | |
| Some cities of the challenge set have many invalid years (10-day rule) in 1989-2018 although | |
| NOAA GHCN-Daily holds data under the same station ID. This module | |
| 1. lists the cities with invalid years in 1989-2018 and picks those with >= MIN_INVALID, | |
| 2. downloads their daily TMAX/TMIN/PRCP for 1975-01-01..2018-12-31 from the NCEI Access | |
| Data Service (keyless), one request per station, and drops the values that carry a | |
| GHCN-D quality flag (they failed NOAA's checks; the service returns them all the same), | |
| 3. compares the two sources day by day and as annual metrics (same definitions), | |
| 4. fills city-years that are invalid in the challenge data but valid in NOAA, | |
| 5. measures what the filling does to the selected models in the backtest. | |
| THE DATA RULE: no observation dated after 2018-12-31 is downloaded, stored or used. | |
| - `_url()` refuses to build a request whose end date is after CAP (every request carries one); | |
| - `_parse()` checks the dates of every response before anything is written: a response with a | |
| later date is discarded and the run stops with LeakageError; | |
| - `load_ghcnd()` repeats the check (plus the sha256 of MANIFEST.csv) every time the files are read. | |
| Writes data/external/ghcnd/{<ID>.csv, MANIFEST.csv, QC_DROPPED.csv} and reports/ghcnd/*. | |
| Run: PYTHONPATH=code python -m protostar.ghcnd [--offline] [--refresh] | |
| (files already on disk are not requested again; --offline never touches the network) | |
| """ | |
| import hashlib | |
| import http.client | |
| import io | |
| import json | |
| import sys | |
| import time | |
| import urllib.error | |
| import urllib.parse | |
| import urllib.request | |
| from datetime import datetime, timezone | |
| import numpy as np | |
| import pandas as pd | |
| from .backtest import Fold, md_table | |
| from .common import (BASELINE_WINDOW, FORECAST_YEARS, CONFIRMATION_FOLDS, METRICS, MIN_VALID_YEARS, REPORTS, ROOT, | |
| SELECTION_FOLDS, TRAIN_END) | |
| from .data import LeakageError, assert_no_leak, cities, load_annual, load_daily, long_table, panels | |
| from .models import BASELINES, neighbor_order, predict | |
| from .scoring import challenge_score, skill | |
| EXT = ROOT / "data" / "external" / "ghcnd" | |
| OUT = REPORTS / "ghcnd" | |
| SERVICE = "https://www.ncei.noaa.gov/access/services/data/v1" | |
| CAP = "2018-12-31" # the data rule: no observation after this date | |
| START, END = "1975-01-01", CAP # requested period | |
| WINDOW = (TRAIN_END - BASELINE_WINDOW + 1, TRAIN_END) # 1989-2018: the final 30-year window | |
| MIN_INVALID = 3 # download cities with >= this many invalid years in WINDOW (either rule) | |
| MAX_STATIONS = 45 # ... raising the threshold until at most this many cities remain | |
| VARS = ("tmax", "tmin", "prcp") | |
| COLUMNS = ["station", "date", *VARS] | |
| MANIFEST = ["station", "url", "retrieved_utc", "rows", "first_date", "last_date", "sha256"] | |
| QC_FILE = "QC_DROPPED.csv" # the values dropped for a quality flag (same date cap, same guard) | |
| QC_COLUMNS = ["station", "date", "variable", "value", "quality_flag"] | |
| PAUSE, RETRIES, BACKOFF, TIMEOUT = 1.0, 4, 2.0, 120 # seconds between requests / attempts / base / timeout | |
| EQ_TOL = 1e-6 # "exactly equal" up to float representation | |
| ROUND_TOL = {"tmax": 0.5, "tmin": 0.5, "prcp": 0.0101} # a larger difference is another observation, not rounding | |
| MISMATCH_SHARE = 0.05 # a year "differs" if more than this share of its common days does | |
| REF = BASELINES["30-year average"] # {"type": "mean", "n": 30} | |
| TEMP_METRICS = [m for m, (_, miss) in METRICS.items() if "Miss Tmax" in miss] | |
| KEY = ["city_id", "year", "metric"] | |
| # ── The data rule ──────────────────────────────────────────────────────────── | |
| def assert_capped(dates, what: str) -> None: | |
| """Stop if any observation is dated after 2018-12-31 (or has no readable date).""" | |
| dates = pd.to_datetime(pd.Series(dates, dtype="object"), format="%Y-%m-%d") | |
| if dates.empty: | |
| return | |
| if dates.isna().any(): | |
| raise LeakageError(f"{what}: unreadable dates, cannot prove the data rule") | |
| if dates.max() > pd.Timestamp(CAP): | |
| raise LeakageError(f"{what}: latest date {dates.max().date()} is after {CAP} (data rule)") | |
| assert_no_leak(dates.dt.year, what) | |
| def _url(station: str, start: str, end: str) -> str: | |
| """The request for one station and period; refuses an end date after CAP.""" | |
| for day in (start, end): | |
| datetime.strptime(day, "%Y-%m-%d") # ISO dates: string order = date order | |
| if not start <= end <= CAP: | |
| raise LeakageError(f"request for {station} would end {end}, after {CAP} (data rule)") | |
| query = urllib.parse.urlencode( | |
| {"dataset": "daily-summaries", "stations": station, "startDate": start, "endDate": end, | |
| "dataTypes": "TMAX,TMIN,PRCP", "units": "standard", "format": "csv", | |
| "includeAttributes": "true"}, safe=",") | |
| return f"{SERVICE}?{query}" | |
| def _signature(url: str) -> dict: | |
| """A request without its dates: a file fetched with another signature is fetched again.""" | |
| query = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query) | |
| return {k: v for k, v in query.items() if k not in ("startDate", "endDate")} | |
| # ── Download ───────────────────────────────────────────────────────────────── | |
| class Denied(RuntimeError): | |
| """The proxy or the host answered 403/407: reported, never retried.""" | |
| def _get(url: str) -> bytes: | |
| """GET with retries and exponential backoff (TLS verified with the default CA bundle).""" | |
| error = "no attempt" | |
| for attempt in range(RETRIES): | |
| if attempt: | |
| time.sleep(BACKOFF * 2 ** attempt) | |
| try: | |
| request = urllib.request.Request(url, headers={"User-Agent": "python-urllib (daily-summaries client)"}) | |
| with urllib.request.urlopen(request, timeout=TIMEOUT) as response: | |
| return response.read() | |
| except urllib.error.HTTPError as e: | |
| if e.code in (403, 407): | |
| raise Denied(f"HTTP {e.code} for {url}: not retried") from e | |
| error = f"HTTP {e.code} {e.reason}: {e.read(300)!r}" | |
| if e.code in (400, 404, 413): # the same request will not succeed later | |
| break | |
| except (urllib.error.URLError, http.client.HTTPException, OSError) as e: | |
| if "403" in str(e) or "407" in str(e): # "Tunnel connection failed: 403 Forbidden" | |
| raise Denied(f"{e} for {url}: not retried") from e | |
| error = repr(e) | |
| raise RuntimeError(f"{url}: {error}") | |
| def _parse(body: bytes, station: str, start: str, end: str) -> tuple[pd.DataFrame, pd.DataFrame]: | |
| """Response -> ((station, date, tmax, tmin, prcp), the values dropped for a quality flag). | |
| The date cap is checked before anything else. `<TYPE>_ATTRIBUTES` is GHCN-D's | |
| "measurement,quality,source[,time]": a non-blank quality flag means the value failed one of | |
| NOAA's checks (e.g. a 122 °F day in Michigan, flag G), so it is treated as missing. | |
| """ | |
| text = body.decode("utf-8") | |
| if not text.strip(): | |
| return pd.DataFrame(columns=COLUMNS), pd.DataFrame(columns=QC_COLUMNS) | |
| raw = pd.read_csv(io.StringIO(text), dtype=str) | |
| if not {"STATION", "DATE"} <= set(raw.columns): | |
| raise ValueError(f"{station}: unexpected response {text[:200]!r}") | |
| assert_capped(raw["DATE"], f"NCEI response for {station}") # discard + stop on a later date | |
| assert (raw["STATION"] == station).all(), f"{station}: other stations in the response" | |
| assert raw["DATE"].between(start, end).all() and not raw["DATE"].duplicated().any() | |
| out, flagged = pd.DataFrame({"station": station, "date": raw["DATE"]}), [] | |
| for var in VARS: # a type the station never reported has no column | |
| col = var.upper() | |
| if col not in raw: | |
| out[var] = np.nan | |
| continue | |
| if f"{col}_ATTRIBUTES" not in raw: | |
| raise ValueError(f"{station}: no {col}_ATTRIBUTES in the response, quality flags unknown") | |
| value = pd.to_numeric(raw[col], errors="raise") | |
| quality = raw[f"{col}_ATTRIBUTES"].fillna("").str.split(",").str[1].fillna("") | |
| bad = (quality != "") & value.notna() | |
| if bad.any(): | |
| flagged.append(pd.DataFrame({"station": station, "date": raw["DATE"][bad], "variable": var, | |
| "value": value[bad], "quality_flag": quality[bad]})) | |
| out[var] = value.where(~bad) | |
| flagged = pd.concat(flagged, ignore_index=True) if flagged else pd.DataFrame(columns=QC_COLUMNS) | |
| return out.sort_values("date").reset_index(drop=True), flagged | |
| def fetch(station: str) -> tuple[pd.DataFrame, pd.DataFrame, str]: | |
| """One request for the whole period; split by decade only if that request fails. | |
| Returns (kept values, values dropped for a quality flag, request url(s)). | |
| """ | |
| try: | |
| spans = [(START, END)] | |
| parts = [_parse(_get(_url(station, a, b)), station, a, b) for a, b in spans] | |
| except Denied: | |
| raise | |
| except RuntimeError as whole: | |
| print(f" {station}: whole-period request failed ({whole}); splitting by decade", flush=True) | |
| first, last = int(START[:4]), int(END[:4]) | |
| spans = [(max(START, f"{y}-01-01"), min(END, f"{y + 9}-12-31")) for y in range(first, last + 1, 10)] | |
| parts = [] | |
| for a, b in spans: | |
| parts.append(_parse(_get(_url(station, a, b)), station, a, b)) | |
| time.sleep(PAUSE) | |
| frame = pd.concat([f for f, _ in parts], ignore_index=True) if len(parts) > 1 else parts[0][0] | |
| flagged = [q for _, q in parts if len(q)] | |
| flagged = pd.concat(flagged, ignore_index=True) if flagged else pd.DataFrame(columns=QC_COLUMNS) | |
| assert not frame["date"].duplicated().any() | |
| return frame, flagged, " ".join(_url(station, a, b) for a, b in spans) | |
| def _read_manifest() -> dict[str, dict]: | |
| path = EXT / "MANIFEST.csv" | |
| if not path.exists(): | |
| return {} | |
| rows = pd.read_csv(path, dtype=str, keep_default_na=False) | |
| assert list(rows.columns) == MANIFEST | |
| return {r["station"]: r for r in rows.to_dict("records")} | |
| def load_qc_dropped() -> pd.DataFrame: | |
| """The values dropped for a quality flag (station, date, variable, value, quality_flag); date cap asserted.""" | |
| path = EXT / QC_FILE | |
| if not path.exists(): | |
| return pd.DataFrame(columns=QC_COLUMNS) | |
| qc = pd.read_csv(path, dtype={"station": str, "date": str, "variable": str, "quality_flag": str}, | |
| keep_default_na=False) | |
| assert list(qc.columns) == QC_COLUMNS | |
| assert_capped(qc["date"], f"data/external/ghcnd/{QC_FILE}") | |
| return qc | |
| def download(stations, refresh: bool = False, offline: bool = False) -> tuple[pd.DataFrame, int]: | |
| """Fetch the stations not yet on disk, sequentially. Returns (manifest, number of requests).""" | |
| EXT.mkdir(parents=True, exist_ok=True) | |
| manifest, fetched = _read_manifest(), 0 | |
| for station in stations: | |
| path, row = EXT / f"{station}.csv", manifest.get(station) | |
| if (row and path.exists() and not refresh | |
| and all(_signature(u) == _signature(_url(station, START, END)) for u in row["url"].split()) | |
| and hashlib.sha256(path.read_bytes()).hexdigest() == row["sha256"]): | |
| continue | |
| if offline: | |
| raise FileNotFoundError(f"{path} is missing, changed or from another request, and --offline was given") | |
| if fetched: | |
| time.sleep(PAUSE) | |
| frame, flagged, url = fetch(station) | |
| assert_capped(frame["date"], f"{station} before writing") | |
| assert_capped(flagged["date"], f"{station} quality-flagged values before writing") | |
| others = load_qc_dropped() | |
| others = [q for q in (others[others["station"] != station], flagged) if len(q)] | |
| qc = pd.concat(others, ignore_index=True) if others else pd.DataFrame(columns=QC_COLUMNS) | |
| qc.sort_values(["station", "date", "variable"]).to_csv(EXT / QC_FILE, index=False, lineterminator="\n") | |
| data = frame.to_csv(index=False, lineterminator="\n").encode() | |
| part = path.with_name(path.name + ".part") | |
| part.write_bytes(data) | |
| part.replace(path) | |
| manifest[station] = { | |
| "station": station, "url": url, | |
| "retrieved_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), | |
| "rows": str(len(frame)), "first_date": frame["date"].min() if len(frame) else "", | |
| "last_date": frame["date"].max() if len(frame) else "", | |
| "sha256": hashlib.sha256(data).hexdigest()} | |
| pd.DataFrame([manifest[s] for s in sorted(manifest)], columns=MANIFEST).to_csv( | |
| EXT / "MANIFEST.csv", index=False, lineterminator="\n") | |
| fetched += 1 | |
| print(f" {station}: {len(frame)} rows, {manifest[station]['first_date']}..{manifest[station]['last_date']}, " | |
| f"{len(flagged)} values dropped for a quality flag", flush=True) | |
| return pd.DataFrame([manifest[s] for s in sorted(manifest)], columns=MANIFEST), fetched | |
| def load_ghcnd() -> pd.DataFrame: | |
| """Every saved station file as one table (ID, Date, tmax °F, tmin °F, prcp in). | |
| Checked on every read: each file's sha256 against MANIFEST.csv, that files and manifest | |
| list the same stations, and the data rule (no observation and no request after 2018-12-31, | |
| in the station files and in QC_DROPPED.csv). | |
| """ | |
| manifest = pd.read_csv(EXT / "MANIFEST.csv", dtype=str, keep_default_na=False) | |
| on_disk = {p.stem for p in EXT.glob("*.csv")} - {"MANIFEST", QC_FILE.removesuffix(".csv")} | |
| load_qc_dropped() | |
| assert on_disk == set(manifest["station"]), "station files and MANIFEST.csv differ" | |
| parts = [] | |
| for row in manifest.itertuples(): | |
| data = (EXT / f"{row.station}.csv").read_bytes() | |
| if hashlib.sha256(data).hexdigest() != row.sha256: | |
| raise ValueError(f"{row.station}.csv: sha256 does not match MANIFEST.csv") | |
| part = pd.read_csv(io.BytesIO(data), dtype={"station": str, "date": str}) | |
| assert list(part.columns) == COLUMNS and len(part) == int(row.rows) | |
| assert (part["station"] == row.station).all() and not part["date"].duplicated().any() | |
| assert_capped(part["date"], f"data/external/ghcnd/{row.station}.csv") | |
| for url in row.url.split(): | |
| end = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)["endDate"][0] | |
| if end > CAP: | |
| raise LeakageError(f"{row.station}: recorded request ends {end}, after {CAP}") | |
| parts.append(part) | |
| df = pd.concat(parts, ignore_index=True) | |
| assert_capped(df["date"], "data/external/ghcnd") | |
| df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d") | |
| for var in VARS: | |
| df[var] = df[var].astype(float) | |
| return df.rename(columns={"station": "ID", "date": "Date"}) | |
| # ── Scope ──────────────────────────────────────────────────────────────────── | |
| def scope(long: pd.DataFrame, annual: pd.DataFrame) -> tuple[pd.DataFrame, int]: | |
| """Cities with >= 1 invalid year in WINDOW by the temperature or the precipitation rule.""" | |
| w = long[long["year"].between(*WINDOW)] | |
| assert (w.groupby(["city_id", "metric"]).size() == BASELINE_WINDOW).all() | |
| invalid = (~w["valid"]).groupby([w["city_id"], w["metric"]]).sum().unstack("metric") | |
| out = pd.DataFrame({"invalid_temp": invalid[TEMP_METRICS].max(axis=1), | |
| "invalid_prcp": invalid["total_precip_in"]}) | |
| assert (invalid[TEMP_METRICS].nunique(axis=1) == 1).all() # one rule for the three metrics | |
| out["invalid_max"] = out.max(axis=1) | |
| out.insert(0, "name", annual.groupby("ID")["Name"].first().reindex(out.index)) | |
| out = out[out["invalid_max"] >= 1].rename_axis("city_id").reset_index() | |
| out = out.sort_values(["invalid_max", "city_id"], ascending=[False, True]).reset_index(drop=True) | |
| threshold = MIN_INVALID | |
| while (out["invalid_max"] >= threshold).sum() > MAX_STATIONS: | |
| threshold += 1 | |
| out["download"] = out["invalid_max"] >= threshold | |
| return out, threshold | |
| # ── Annual metrics with the challenge's definitions ────────────────────────── | |
| def annual_from_daily(d: pd.DataFrame) -> pd.DataFrame: | |
| """annual_indices columns from a complete daily calendar (one row per ID and day). | |
| Avg Temp = (mean Tmax + mean Tmin) / 2, each over the days with a value; ToT Prcp = sum; | |
| Max Tmax = max; cdd = sum of max(0, (tmax + tmin) / 2 - 65) over days with both; | |
| Miss X = days of the year without X. | |
| """ | |
| d = d.assign(Year=d["Date"].dt.year, cdd_day=((d["tmax"] + d["tmin"]) / 2 - 65).clip(lower=0)) | |
| g = d.groupby(["ID", "Year"]).agg( | |
| days=("Date", "size"), n_tmax=("tmax", "count"), n_tmin=("tmin", "count"), n_prcp=("prcp", "count"), | |
| n_both=("cdd_day", "count"), avg_tmax=("tmax", "mean"), avg_tmin=("tmin", "mean"), | |
| tot=("prcp", "sum"), max_tmax=("tmax", "max"), cdd_sum=("cdd_day", "sum")).reset_index() | |
| expected = np.where(pd.to_datetime(g["Year"].astype(str) + "-12-31").dt.day_of_year == 366, 366, 365) | |
| assert (g["days"] == expected).all(), "the daily calendar is not complete" | |
| return pd.DataFrame({ | |
| "ID": g["ID"], "Year": g["Year"], | |
| "Miss Tmax": g["days"] - g["n_tmax"], "Miss Tmin": g["days"] - g["n_tmin"], | |
| "Miss Prcp": g["days"] - g["n_prcp"], | |
| "Avg Temp": ((g["avg_tmax"].round(2) + g["avg_tmin"].round(2)) / 2).round(2), | |
| "ToT Prcp": g["tot"].round(2), "Max Tmax": g["max_tmax"], | |
| "cdd": g["cdd_sum"].where(g["n_both"] > 0)}) | |
| def both_sources(stations, noaa: pd.DataFrame) -> pd.DataFrame: | |
| """One row per station and day of START..END: challenge values (_c) and NOAA values (_n).""" | |
| days = pd.date_range(START, END, freq="D") | |
| cal = pd.DataFrame({"ID": np.repeat(np.asarray(stations), len(days)), "Date": np.tile(days, len(stations))}) | |
| ch = load_daily() | |
| ch = ch[ch["ID"].isin(stations) & (ch["Date"] >= START)][["ID", "Date", *VARS]] | |
| m = cal.merge(ch, on=["ID", "Date"], how="left", validate="1:1") | |
| m = m.merge(noaa[["ID", "Date", *VARS]], on=["ID", "Date"], how="left", suffixes=("_c", "_n"), validate="1:1") | |
| assert len(m) == len(cal) | |
| return m | |
| def side(m: pd.DataFrame, suffix: str) -> pd.DataFrame: | |
| return m[["ID", "Date"]].assign(**{v: m[f"{v}{suffix}"] for v in VARS}) | |
| # ── Agreement ──────────────────────────────────────────────────────────────── | |
| def daily_agreement(m: pd.DataFrame) -> pd.DataFrame: | |
| rows = [] | |
| for station, part in [("ALL", m)] + list(m.groupby("ID")): | |
| for var in VARS: | |
| c, n = part[f"{var}_c"], part[f"{var}_n"] | |
| both = c.notna() & n.notna() | |
| diff = (n - c)[both].abs() | |
| rows.append({"station": station, "variable": var, "days_both": int(both.sum()), | |
| "share_equal": float((diff <= EQ_TOL).mean()) if len(diff) else np.nan, | |
| "share_rounding": float(((diff > EQ_TOL) & (diff <= ROUND_TOL[var])).mean()) if len(diff) else np.nan, | |
| "share_other": float((diff > ROUND_TOL[var]).mean()) if len(diff) else np.nan, | |
| "mean_abs_diff": diff.mean(), "max_abs_diff": diff.max(), | |
| "days_challenge_only": int((c.notna() & n.isna()).sum()), | |
| "days_noaa_only": int((n.notna() & c.isna()).sum())}) | |
| return pd.DataFrame(rows) | |
| def mismatch(m: pd.DataFrame, names: pd.Series) -> tuple[pd.DataFrame, set]: | |
| """Per station: the years in which more than MISMATCH_SHARE of the common days differ by more | |
| than rounding in tmax or tmin, i.e. the challenge's record holds other observations than NOAA's | |
| file for the same ID. For those years: share of days on which NOAA's tmax equals the | |
| challenge's tmax of the same, the next and the previous day (a one-day shift shows here). | |
| Returns (one row per station, the set of differing (station, year)). | |
| """ | |
| dx, dn = (m["tmax_n"] - m["tmax_c"]).abs(), (m["tmin_n"] - m["tmin_c"]).abs() | |
| d = pd.DataFrame({"ID": m["ID"], "year": m["Date"].dt.year, | |
| "differs": (dx > ROUND_TOL["tmax"]) | (dn > ROUND_TOL["tmin"]), "same_day": dx <= ROUND_TOL["tmax"]}) | |
| for col, step in (("next_day", -1), ("previous_day", 1)): # rows are sorted by ID and Date | |
| other = m.groupby("ID")["tmax_c"].shift(step) | |
| d[col] = ((m["tmax_n"] - other).abs() <= ROUND_TOL["tmax"]).where(other.notna() & m["tmax_n"].notna()) | |
| d["same_day"] = d["same_day"].where(dx.notna()) | |
| d = d[dx.notna() | dn.notna()] | |
| rows, differing = [], set() | |
| for station, part in d.groupby("ID"): | |
| by_year = part.groupby("year")["differs"].mean() | |
| bad = by_year[by_year > MISMATCH_SHARE] | |
| differing.update((station, int(y)) for y in bad.index) | |
| sub = part[part["year"].isin(bad.index)] | |
| rows.append({"station": station, "name": names[station], "common_years": spans(by_year.index), | |
| "share_days_differing": float(part["differs"].mean()), "n_years_differing": len(bad), | |
| "years_differing": spans(bad.index), | |
| **{f"tmax_equal_challenge_{c}": float(sub[c].astype(float).mean()) if len(sub) else np.nan | |
| for c in ("same_day", "next_day", "previous_day")}}) | |
| return pd.DataFrame(rows), differing | |
| def annual_agreement(lc: pd.DataFrame, ln: pd.DataFrame, ac: pd.DataFrame, an: pd.DataFrame, | |
| differing: set) -> pd.DataFrame: | |
| """NOAA minus challenge. Metrics: city-years valid in both; missing-day counts: all city-years. | |
| `*_same_obs`: without the station-years in which the challenge holds other observations | |
| than NOAA's file (`differing`, from mismatch()). | |
| """ | |
| j = lc.merge(ln, on=KEY, suffixes=("_c", "_n"), validate="1:1") | |
| j["same_obs"] = [key not in differing for key in zip(j["city_id"], j["year"])] | |
| rows = [] | |
| for metric in METRICS: | |
| p = j[(j["metric"] == metric) & j["valid_c"] & j["valid_n"]] | |
| d = p["value_n"] - p["value_c"] | |
| same = d[p["same_obs"]].abs() | |
| rows.append({"quantity": metric, "city_years": "valid in both", "n": len(p), "bias": d.mean(), | |
| "mean_abs_diff": d.abs().mean(), "max_abs_diff": d.abs().max(), | |
| "share_equal": float((d.abs() <= EQ_TOL).mean()), "n_same_obs": len(same), | |
| "mean_abs_diff_same_obs": same.mean(), "max_abs_diff_same_obs": same.max()}) | |
| a = ac.merge(an, on=["ID", "Year"], suffixes=("_c", "_n"), validate="1:1") | |
| for col in ("Miss Tmax", "Miss Tmin", "Miss Prcp"): | |
| d = a[f"{col}_n"] - a[f"{col}_c"] | |
| rows.append({"quantity": col + " (days)", "city_years": "all", "n": len(a), "bias": d.mean(), | |
| "mean_abs_diff": d.abs().mean(), "max_abs_diff": d.abs().max(), | |
| "share_equal": float((d == 0).mean())}) | |
| return pd.DataFrame(rows) | |
| def spans(years) -> str: | |
| """[1975, 1976, 1977, 1990] -> '1975-1977, 1990'.""" | |
| years, out = sorted(int(y) for y in years), [] | |
| for y in years: | |
| if out and y == out[-1][1] + 1: | |
| out[-1][1] = y | |
| else: | |
| out.append([y, y]) | |
| return ", ".join(str(a) if a == b else f"{a}-{b}" for a, b in out) | |
| def coverage(ac: pd.DataFrame, an: pd.DataFrame, names: pd.Series) -> pd.DataFrame: | |
| """Per station and variable group: years one source has observations and the other has none.""" | |
| a = ac.merge(an, on=["ID", "Year"], suffixes=("_c", "_n"), validate="1:1") | |
| days = np.where(pd.to_datetime(a["Year"].astype(str) + "-12-31").dt.day_of_year == 366, 366, 365) | |
| rows = [] | |
| for group, cols in (("temperature", ("Miss Tmax", "Miss Tmin")), ("precipitation", ("Miss Prcp",))): | |
| has = {s: (a[[f"{c}{s}" for c in cols]].min(axis=1) < days) for s in ("_c", "_n")} | |
| for station, part in a.groupby("ID"): | |
| hc, hn = has["_c"][part.index], has["_n"][part.index] | |
| rows.append({"station": station, "name": names[station], "variables": group, | |
| "years_challenge": spans(part["Year"][hc]), "years_noaa": spans(part["Year"][hn]), | |
| "n_challenge_only": int((hc & ~hn).sum()), "n_noaa_only": int((hn & ~hc).sum()), | |
| "challenge_only": spans(part["Year"][hc & ~hn]), | |
| "noaa_only": spans(part["Year"][hn & ~hc])}) | |
| return pd.DataFrame(rows) | |
| # ── Gap filling ────────────────────────────────────────────────────────────── | |
| def fill(lc: pd.DataFrame, ln: pd.DataFrame) -> pd.DataFrame: | |
| """The challenge long table, with NOAA values where the challenge year is invalid and NOAA's is valid. | |
| Returns city_id, year, metric, value, valid, source ('challenge' or 'ghcnd'). | |
| """ | |
| out = lc.merge(ln.rename(columns={"value": "value_n", "valid": "valid_n"}), on=KEY, how="left", validate="1:1") | |
| take = ~out["valid"] & (out["valid_n"] == True) # noqa: E712 (NaN = not downloaded) | |
| out["value"] = out["value"].where(~take, out["value_n"]) | |
| out["valid"] = out["valid"] | take | |
| out["source"] = np.where(take, "ghcnd", "challenge") | |
| assert len(out) == len(lc) and (out[KEY].to_numpy() == lc[KEY].to_numpy()).all() | |
| return out[KEY + ["value", "valid", "source"]] | |
| def fill_counts(lc: pd.DataFrame, filled: pd.DataFrame, names: pd.Series) -> pd.DataFrame: | |
| """Per city and metric: valid years in WINDOW before and after, filled years in WINDOW and overall.""" | |
| f = filled.assign(valid_before=lc["valid"].to_numpy(), took=filled["source"] == "ghcnd", | |
| win=filled["year"].between(*WINDOW)) | |
| g = f.groupby(["city_id", "metric"], sort=False) | |
| out = pd.DataFrame({"valid_before": (f["valid_before"] & f["win"]).groupby([f["city_id"], f["metric"]]).sum(), | |
| "filled_window": (f["took"] & f["win"]).groupby([f["city_id"], f["metric"]]).sum(), | |
| "filled_all_years": g["took"].sum()}).reset_index() | |
| out["valid_after"] = out["valid_before"] + out["filled_window"] | |
| out.insert(1, "name", out["city_id"].map(names)) | |
| return out[["city_id", "name", "metric", "valid_before", "filled_window", "valid_after", "filled_all_years"]] | |
| # ── Backtest effect ────────────────────────────────────────────────────────── | |
| def backtest_effect(P0, P1, took: dict, order, selected: dict, names: pd.Series): | |
| """Selected model and 30-year average trained on original (a) vs gap-filled (b) panels. | |
| Truth, scored rows and the reference MAE always come from the ORIGINAL data, so only the | |
| training input changes. Affected cities: >= 1 filled year in the fold's 30-year window. | |
| Returns (fold x metric x cities table, per-city contributions to the all-city skill change). | |
| """ | |
| rows, per_city, years, ids = [], [], P0["cdd"].years, P0["cdd"].city_ids | |
| for kind, folds in (("selection", SELECTION_FOLDS), ("holdout", CONFIRMATION_FOLDS)): | |
| for origin, first, last in folds: | |
| fold = Fold(P0, origin, first, last) # truth + scored: original data | |
| train1 = {m: P1[m].upto(origin) for m in METRICS} # gap-filled training panels | |
| window = (years > origin - BASELINE_WINDOW) & (years <= origin) | |
| for metric in METRICS: | |
| truth, scored = fold.truth[metric], fold.scored[metric] | |
| affected = took[metric][:, window].any(axis=1) | |
| pred = {"ref_a": predict(REF, fold.train, metric, order, fold.years), | |
| "ref_b": predict(REF, train1, metric, order, fold.years), | |
| "sel_a": predict(selected[metric], fold.train, metric, order, fold.years), | |
| "sel_b": predict(selected[metric], train1, metric, order, fold.years)} | |
| for cities_, keep in (("all", np.ones(len(affected), bool)), ("affected", affected)): | |
| mask = scored & keep[:, None] | |
| n = int(mask.sum()) | |
| mae = {k: float(np.abs(p - truth)[mask].mean()) if n else np.nan for k, p in pred.items()} | |
| sk = {k: skill(v, mae["ref_a"]) if n else np.nan for k, v in mae.items()} | |
| if cities_ == "all": | |
| assert abs(sk["sel_a"] - fold.skill(selected[metric], metric, order)) < 1e-12 | |
| rows.append({"fold_kind": kind, "fold": fold.name, "metric": metric, "cities": cities_, | |
| "n_affected_cities": int(affected.sum()), | |
| "n_affected_scored_cities": int((scored.any(axis=1) & affected).sum()), | |
| "n_rows": n, "mae_30y_average_original": mae["ref_a"], | |
| "mae_selected_original": mae["sel_a"], "mae_selected_filled": mae["sel_b"], | |
| "mae_30y_average_filled": mae["ref_b"], | |
| "skill_selected_original": sk["sel_a"], "skill_selected_filled": sk["sel_b"], | |
| "skill_change_points": 100 * (sk["sel_b"] - sk["sel_a"]) if n else np.nan, | |
| "skill_30y_average_filled": sk["ref_b"]}) | |
| # who moves the all-city skill: summed |error| per city, relative to the reference's total | |
| err = {k: np.where(scored, np.abs(p - truth), 0.0).sum(axis=1) for k, p in pred.items()} | |
| points = -100 * (err["sel_b"] - err["sel_a"]) / err["ref_a"].sum() | |
| base = {"fold_kind": kind, "fold": fold.name, "metric": metric} | |
| for i in np.flatnonzero(affected & scored.any(axis=1)): | |
| k = scored[i].sum() | |
| per_city.append({**base, "city_id": ids[i], "name": names[ids[i]], | |
| "filled_years_in_window": int(took[metric][i, window].sum()), | |
| "scored_rows": int(k), "mae_selected_original": err["sel_a"][i] / k, | |
| "mae_selected_filled": err["sel_b"][i] / k, | |
| "skill_points_contributed": points[i]}) | |
| per_city.append({**base, "city_id": "", "name": "(all unaffected cities)", "filled_years_in_window": 0, | |
| "scored_rows": int(scored[~affected].sum()), | |
| "skill_points_contributed": points[~affected].sum()}) | |
| return pd.DataFrame(rows), pd.DataFrame(per_city) | |
| # ── Check of the submission's fallback ─────────────────────────────────────── | |
| def fallback_check(P0, P1, order, selected: dict, names: pd.Series) -> pd.DataFrame: | |
| """City-metrics without a baseline in the challenge data (not scored): the submission's | |
| fallback forecast, which uses the challenge data only, next to the selected model fitted on | |
| the NOAA-filled record where that record reaches MIN_VALID_YEARS valid years in 1989-2018.""" | |
| years, ids, rows = np.array(FORECAST_YEARS), P0["cdd"].city_ids, [] | |
| for metric in METRICS: | |
| n0 = np.isfinite(P0[metric].y[:, -BASELINE_WINDOW:]).sum(axis=1) | |
| n1 = np.isfinite(P1[metric].y[:, -BASELINE_WINDOW:]).sum(axis=1) | |
| ours = predict(selected[metric], P0, metric, order, years) # fallback rows filled | |
| noaa = predict(selected[metric], P1, metric, order, years, fill=False) # model on the filled record | |
| for i in np.flatnonzero(n0 < MIN_VALID_YEARS): | |
| fitted = bool(np.isfinite(noaa[i]).all()) | |
| window = P1[metric].y[i, -BASELINE_WINDOW:] | |
| rows.append({"city_id": ids[i], "name": names[ids[i]], "metric": metric, | |
| "valid_years_challenge": int(n0[i]), "valid_years_noaa_filled": int(n1[i]), | |
| "mean_1989_2018_noaa_filled": float(np.nanmean(window)) if n1[i] else np.nan, | |
| "fallback_forecast_mean": float(ours[i].mean()), | |
| "model_on_noaa_filled_mean": float(noaa[i].mean()) if fitted else np.nan, | |
| "fallback_minus_model": float(ours[i].mean() - noaa[i].mean()) if fitted else np.nan}) | |
| return pd.DataFrame(rows) | |
| def fallback_section(check: pd.DataFrame) -> str: | |
| fitted = check["model_on_noaa_filled_mean"].notna() | |
| shown = check.astype(object) | |
| for c in check.columns: | |
| if check[c].dtype == float: | |
| shown[c] = [f"{v:.2f}" if pd.notna(v) else "not repaired" for v in check[c]] | |
| return f""" | |
| ## 7 Check of the submission's fallback (forecasts 2019-2025, mean over the 7 years) | |
| The {len(check)} city-metrics below have no baseline in the challenge data, so the submission fills them with | |
| `models.fallback` (the city's last valid years plus the change its nearest fitted cities forecast), using the | |
| challenge data only. NOAA repairs {int(fitted.sum())} of them (>= {MIN_VALID_YEARS} valid years in 1989-2018), which lets the selected | |
| model run on the city's own record; that forecast is shown for comparison and is not submitted. | |
| {md_table(shown)} | |
| """ | |
| # ── Main ───────────────────────────────────────────────────────────────────── | |
| def main(argv=None): | |
| args = set(sys.argv[1:] if argv is None else argv) | |
| assert args <= {"--offline", "--refresh"}, f"unknown arguments: {args}" | |
| t0 = time.time() | |
| OUT.mkdir(parents=True, exist_ok=True) | |
| annual = load_annual() | |
| lc_all = long_table(annual) | |
| names = annual.groupby("ID")["Name"].first() | |
| # 1 scope | |
| sc, threshold = scope(lc_all, annual) | |
| stations = sorted(sc.loc[sc["download"], "city_id"]) | |
| sc.to_csv(OUT / "scope.csv", index=False) | |
| print(f"scope: {len(sc)} cities with >= 1 invalid year in {WINDOW[0]}-{WINDOW[1]}; " | |
| f"{len(stations)} with >= {threshold} are downloaded", flush=True) | |
| # 2 download (only what is not on disk) and guarded read | |
| manifest, n_requests = download(stations, refresh="--refresh" in args, offline="--offline" in args) | |
| t_download = time.time() - t0 | |
| noaa = load_ghcnd() | |
| noaa = noaa[noaa["ID"].isin(stations)] | |
| manifest = manifest[manifest["station"].isin(stations)] | |
| assert set(manifest["station"]) == set(stations) | |
| latest = noaa["Date"].max().date() | |
| qc = load_qc_dropped() | |
| qc = qc[qc["station"].isin(stations)] | |
| print(f"NOAA: {len(noaa)} rows, {noaa['ID'].nunique()} stations, {noaa['Date'].min().date()}..{latest}; " | |
| f"{len(qc)} values dropped for a quality flag", flush=True) | |
| # 3 agreement | |
| m = both_sources(stations, noaa) | |
| daily = daily_agreement(m) | |
| daily.insert(1, "name", daily["station"].map(names).fillna("all stations")) | |
| daily.to_csv(OUT / "agreement_daily.csv", index=False) | |
| mis, differing = mismatch(m, names) | |
| mis.to_csv(OUT / "station_mismatch.csv", index=False) | |
| # the values NOAA flags: does the challenge's daily table have them? (it mostly does not) | |
| theirs = (m.melt(id_vars=["ID", "Date"], value_vars=[f"{v}_c" for v in VARS], var_name="variable", | |
| value_name="challenge").assign(variable=lambda x: x["variable"].str[:-2])) | |
| flagged = qc.assign(Date=pd.to_datetime(qc["date"], format="%Y-%m-%d")).merge( | |
| theirs, left_on=["station", "Date", "variable"], right_on=["ID", "Date", "variable"], how="left", | |
| validate="1:1") | |
| qc_missing = float(flagged["challenge"].isna().mean()) if len(flagged) else np.nan | |
| # rounding: when do the two sources differ by a fraction of a degree, and is the challenge in whole °F? | |
| year = m["Date"].dt.year | |
| temps = pd.concat([pd.DataFrame({"year": year, "c": m[f"{v}_c"], "d": (m[f"{v}_n"] - m[f"{v}_c"]).abs()}) | |
| for v in ("tmax", "tmin")], ignore_index=True) | |
| small = temps[(temps["d"] > EQ_TOL) & (temps["d"] <= ROUND_TOL["tmax"])] | |
| have = temps[temps["c"].notna()] | |
| decimal = ((have["c"] % 1).abs() > 1e-9).groupby(have["year"] == TRAIN_END).mean() | |
| rounding = {"in_last_year": float((small["year"] == TRAIN_END).mean()), "max": float(small["d"].max()), | |
| "decimal_last_year": float(decimal.get(True, np.nan)), "decimal_before": float(decimal.get(False, np.nan))} | |
| an, own = annual_from_daily(side(m, "_n")), annual_from_daily(side(m, "_c")) | |
| ac = annual[annual["ID"].isin(stations) & (annual["Year"] >= int(START[:4]))] | |
| ac = ac[["ID", "Year", *[c for c in an.columns if c not in ("ID", "Year")]]].reset_index(drop=True) | |
| assert len(ac) == len(an) == len(own), "the challenge has no row for some station-year since 1975" | |
| # the definitions, applied to the challenge's own daily table, must reproduce annual_indices | |
| chk = long_table(ac).merge(long_table(own), on=KEY, suffixes=("_c", "_o"), validate="1:1") | |
| assert (chk["valid_c"] == chk["valid_o"]).all() | |
| selfcheck = (chk["value_c"] - chk["value_o"]).abs()[chk["valid_c"]].groupby(chk["metric"]).max() | |
| assert selfcheck.max() <= 0.0101, selfcheck | |
| lc, ln = long_table(ac), long_table(an) | |
| ann = annual_agreement(lc, ln, ac, an, differing) | |
| ann.to_csv(OUT / "agreement_annual.csv", index=False) | |
| cov = coverage(ac, an, names) | |
| cov.to_csv(OUT / "coverage.csv", index=False) | |
| # 4 gap filling | |
| filled = fill(lc_all, ln) | |
| filled[filled["source"] == "ghcnd"].to_csv(OUT / "filled_annual.csv", index=False) # the filled values only | |
| counts = fill_counts(lc_all, filled, names) | |
| counts = counts[counts["city_id"].isin(sc["city_id"])].reset_index(drop=True) | |
| counts.to_csv(OUT / "gapfill_counts.csv", index=False) | |
| j = lc.merge(ln, on=KEY, suffixes=("_c", "_n")) | |
| j["state"] = np.select([j["valid_c"] & j["valid_n"], j["valid_c"], j["valid_n"]], | |
| ["valid in both", "challenge only", "NOAA only (filled)"], "valid in neither") | |
| cross = (j[j["metric"].isin(["annual_avg_temp", "total_precip_in"])] | |
| .assign(rule=lambda x: np.where(x["metric"] == "annual_avg_temp", "temperature", "precipitation"), | |
| period=lambda x: np.where(x["year"] >= WINDOW[0], f"{WINDOW[0]}-{WINDOW[1]}", | |
| f"{START[:4]}-{WINDOW[0] - 1}")) | |
| .groupby(["rule", "period", "state"]).size().unstack("state", fill_value=0).reset_index()) | |
| cross.to_csv(OUT / "validity_crosstab.csv", index=False) | |
| # 5 backtest effect | |
| P0, P1 = panels(lc_all), panels(filled) | |
| geo = cities(annual) | |
| assert list(geo["city_id"]) == list(P0["cdd"].city_ids) == list(P1["cdd"].city_ids) | |
| order = neighbor_order(geo["lat"].to_numpy(), geo["lon"].to_numpy()) | |
| selected = json.loads((REPORTS / "backtest" / "selected.json").read_text())["selected"] | |
| took = {} | |
| for metric in METRICS: | |
| part = filled[(filled["metric"] == metric) & (filled["source"] == "ghcnd")] | |
| wide = part.assign(v=1.0).pivot(index="city_id", columns="year", values="v") | |
| took[metric] = wide.reindex(index=P0[metric].city_ids, columns=P0[metric].years).notna().to_numpy() | |
| changed = np.isfinite(P1[metric].y) & ~np.isfinite(P0[metric].y) | |
| assert (changed == took[metric]).all() and np.array_equal(P0[metric].y[~changed], P1[metric].y[~changed], | |
| equal_nan=True) | |
| effect, effect_cities = backtest_effect(P0, P1, took, order, selected, names) | |
| effect.to_csv(OUT / "backtest_effect.csv", index=False) | |
| effect_cities.to_csv(OUT / "backtest_effect_cities.csv", index=False) | |
| report(sc, threshold, manifest, noaa, qc, qc_missing, daily, mis, rounding, ann, selfcheck, cov, counts, cross, | |
| effect, effect_cities) | |
| check = fallback_check(P0, P1, order, selected, names) | |
| check.to_csv(OUT / "fallback_check.csv", index=False) | |
| with (OUT / "GHCND.md").open("a") as f: | |
| f.write(fallback_section(check)) | |
| pd.set_option("display.width", 250, "display.max_columns", 30, "display.max_rows", 200) | |
| print(daily[daily["station"] == "ALL"].round(4).to_string(index=False), "\n") | |
| print(ann.round(4).to_string(index=False), "\n") | |
| print(cross.to_string(index=False), "\n") | |
| show = effect[["fold", "metric", "cities", "n_affected_cities", "n_affected_scored_cities", "n_rows", | |
| "skill_selected_original", "skill_selected_filled", "skill_change_points", | |
| "skill_30y_average_filled"]] | |
| print(show.round(4).to_string(index=False)) | |
| print(f"\nlatest date in any saved file: {latest} (cap {CAP}); requests this run: {n_requests}; " | |
| f"download {t_download:.1f} s, total {time.time() - t0:.1f} s") | |
| def report(sc, threshold, manifest, noaa, qc, qc_missing, daily, mis, rounding, ann, selfcheck, cov, counts, cross, | |
| effect, effect_cities): | |
| w = f"{WINDOW[0]}-{WINDOW[1]}" | |
| pts = lambda v: f"{v:+.2f}" | |
| share = lambda v: "-" if pd.isna(v) else f"{v:.0%}" | |
| # 2 daily agreement | |
| overall = daily[daily["station"] == "ALL"].drop(columns=["station", "name"]) | |
| eq = overall.set_index("variable")["share_equal"] | |
| equal = daily[daily["station"] != "ALL"].pivot(index="station", columns="variable", values="share_equal") | |
| bad = mis[mis["n_years_differing"] > 0].sort_values("n_years_differing", ascending=False) | |
| worst = pd.DataFrame({ | |
| "station": bad["station"], "name": bad["name"], | |
| **{f"{v} equal": bad["station"].map(equal[v]) for v in VARS}, | |
| "years differing": bad["years_differing"], | |
| "there: NOAA tmax = challenge same / next / previous day": [ | |
| " / ".join(share(r[f"tmax_equal_challenge_{c}"]) for c in ("same_day", "next_day", "previous_day")) | |
| for _, r in bad.iterrows()]}).head(6) | |
| # 3 annual agreement and coverage | |
| ann = ann.rename(columns={"n_same_obs": "n (same obs.)", "mean_abs_diff_same_obs": "mean_abs_diff (same obs.)", | |
| "max_abs_diff_same_obs": "max_abs_diff (same obs.)"}) | |
| for col, f in {"bias": "{:+.4f}", "mean_abs_diff": "{:.4f}", "max_abs_diff": "{:.2f}", "share_equal": "{:.1%}", | |
| "n (same obs.)": "{:.0f}", "mean_abs_diff (same obs.)": "{:.4f}", | |
| "max_abs_diff (same obs.)": "{:.2f}"}.items(): | |
| ann[col] = [f.format(v) if pd.notna(v) else "-" for v in ann[col]] | |
| temp = cov[cov["variables"] == "temperature"] | |
| n_late = int((manifest["first_date"] > START).sum()) | |
| only_n = [] | |
| for _, part in cov[cov["n_noaa_only"] > 0].groupby("station", sort=False): | |
| s = dict(zip(part["variables"], part["noaa_only"])) | |
| same = len(s) == 2 and len(set(s.values())) == 1 | |
| only_n.append(f"{part['name'].iloc[0]} " + (part["noaa_only"].iloc[0] if same | |
| else ", ".join(f"{k[:4]}. {v}" for k, v in s.items()))) | |
| # 4 gap filling | |
| by_city = (counts.assign(rule=np.where(counts["metric"] == "total_precip_in", "prcp", "temp")) | |
| .drop_duplicates(["city_id", "rule"]).pivot(index=["city_id", "name"], columns="rule", | |
| values=["valid_before", "filled_window", "valid_after"])) | |
| top = pd.DataFrame({"temp: valid before": by_city[("valid_before", "temp")], | |
| "temp: filled": by_city[("filled_window", "temp")], | |
| "temp: valid after": by_city[("valid_after", "temp")], | |
| "prcp: valid before": by_city[("valid_before", "prcp")], | |
| "prcp: filled": by_city[("filled_window", "prcp")], | |
| "prcp: valid after": by_city[("valid_after", "prcp")]}).reset_index() | |
| top = top.assign(f=top["temp: filled"] + top["prcp: filled"]).sort_values("f", ascending=False) | |
| n_fill_cities = int((top["f"] > 0).sum()) | |
| top = top.head(6).drop(columns="f") | |
| tot = counts.groupby("metric")[["filled_window", "filled_all_years"]].sum() | |
| short = counts[counts["valid_before"] < MIN_VALID_YEARS] | |
| reach = short[short["valid_after"] >= MIN_VALID_YEARS] | |
| short_txt = "; ".join(f"{name} {', '.join(g['metric'])} {g['valid_before'].iloc[0]} -> {g['valid_after'].iloc[0]}" | |
| for (name, _, _), g in short.groupby(["name", "valid_before", "valid_after"], sort=False)) | |
| # 5 backtest effect | |
| e = effect.pivot(index=["fold_kind", "fold", "metric", "n_affected_cities", "n_affected_scored_cities"], | |
| columns="cities", values=["skill_selected_original", "skill_selected_filled", | |
| "skill_change_points", "skill_30y_average_filled"]) | |
| table = pd.DataFrame({"skill a (all)": e[("skill_selected_original", "all")], | |
| "skill b (all)": e[("skill_selected_filled", "all")], | |
| "b-a pts (all)": e[("skill_change_points", "all")], | |
| "skill a (aff.)": e[("skill_selected_original", "affected")], | |
| "skill b (aff.)": e[("skill_selected_filled", "affected")], | |
| "b-a pts (aff.)": e[("skill_change_points", "affected")], | |
| "30y b (all)": e[("skill_30y_average_filled", "all")], | |
| "30y b (aff.)": e[("skill_30y_average_filled", "affected")]}).reset_index() | |
| table = table.rename(columns={"n_affected_cities": "affected", "n_affected_scored_cities": "scored"}) | |
| order_ = {f"<={o} -> {a}-{b}": i for i, (o, a, b) in enumerate(SELECTION_FOLDS + CONFIRMATION_FOLDS)} | |
| table = (table.assign(k=table["fold"].map(order_), j=table["metric"].map(list(METRICS).index)) | |
| .sort_values(["k", "j"]).drop(columns=["k", "j", "fold_kind"])) | |
| alls = effect[effect["cities"] == "all"] | |
| sel, hold = alls[alls["fold_kind"] == "selection"], alls[alls["fold_kind"] == "holdout"] | |
| drivers = [] | |
| for _, r in sel[sel["skill_change_points"].abs() > 0.3].iterrows(): | |
| c = effect_cities[(effect_cities["fold"] == r["fold"]) & (effect_cities["metric"] == r["metric"])] | |
| named, rest = c[c["city_id"] != ""], c.loc[c["city_id"] == "", "skill_points_contributed"].sum() | |
| lead = named.loc[named["skill_points_contributed"].abs().idxmax()] | |
| others = named["skill_points_contributed"].sum() - lead["skill_points_contributed"] | |
| drivers.append(f"{r['metric']} {r['fold']}: {pts(r['skill_change_points'])} = {lead['name']} " | |
| f"{pts(lead['skill_points_contributed'])}, other affected cities {pts(others)}, " | |
| f"unaffected cities (pooled slopes) {pts(rest)}") | |
| change = {m: list(sel.loc[sel["metric"] == m, "skill_change_points"]) for m in METRICS} # selection-fold order | |
| moved = [m for m in METRICS if max(abs(v) for v in change[m]) > 0.3] | |
| listing = lambda ms: "; ".join(f"{m} {' / '.join(pts(v) for v in change[m])}" for m in ms) or "none" | |
| verdict = (f"**changes skill beyond ±0.3 points** for {listing(moved)}" if moved | |
| else "**does not change skill beyond ±0.3 points** for any metric") | |
| bigh = hold.loc[hold["skill_change_points"].abs().idxmax()] | |
| refmax = 100 * alls["skill_30y_average_filled"].abs().max() | |
| score = {} | |
| for fold, part in alls.groupby("fold", sort=False): | |
| s = part.set_index("metric") | |
| score[fold] = (challenge_score(s["skill_selected_original"].to_dict()), | |
| challenge_score(s["skill_selected_filled"].to_dict())) | |
| pct = {c: "{:+.2%}" for c in table.columns if c.startswith(("skill", "30y"))} | { | |
| "b-a pts (all)": "{:+.2f}", "b-a pts (aff.)": "{:+.1f}"} | |
| for col, f in pct.items(): # NaN (no scored row among the affected cities) -> "-" | |
| table[col] = [f.format(v) if pd.notna(v) else "-" for v in table[col]] | |
| folds_txt = " / ".join(f"<={o}" for o, _, _ in SELECTION_FOLDS) | |
| text = f"""# GHCN-Daily gap filling: integration experiment | |
| Generated by `python -m protostar.ghcnd` (do not edit). Do NOAA GHCN-Daily records under the same station ID repair the challenge set's invalid years, and does that change the backtest? | |
| ## 1 Download | |
| - Service: NCEI Access Data Service (`{SERVICE}`, `dataset=daily-summaries`, `dataTypes=TMAX,TMIN,PRCP`, `units=standard`, `includeAttributes=true`, csv), keyless, one request per station, sequential with a {PAUSE:g} s pause. | |
| - Scope: {len(sc)} cities have >= 1 invalid year in {w} by the temperature or the precipitation rule (`scope.csv`); the {int(sc['download'].sum())} with >= {threshold} were downloaded. | |
| - Period {START} to {END}: {len(manifest)} stations, {len(noaa):,} station-days in `data/external/ghcnd/<ID>.csv`; `MANIFEST.csv` records url, time, rows, first/last date and sha256. | |
| - Quality: the service also returns values that failed NOAA's checks; the {len(qc):,} values with a GHCN-D quality flag ({", ".join(f"{v} {int((qc['variable'] == v).sum())}" for v in VARS)}) are dropped and listed in `{QC_FILE}`; the challenge's `daily` has no value either for {qc_missing:.0%} of them. | |
| - End-date cap: every request carries `endDate={CAP}` (`_url` refuses a later one), each response's dates are checked before anything is written, and `load_ghcnd()` re-asserts the cap (and the sha256) on every read. Latest date in any file: **{noaa['Date'].max().date()}**. | |
| ## 2 Daily agreement on days present in both sources (NOAA vs the challenge's `daily`; per station: `agreement_daily.csv`) | |
| {md_table(overall, {"share_equal": "{:.2%}", "share_rounding": "{:.2%}", "share_other": "{:.2%}", "mean_abs_diff": "{:.4f}", "max_abs_diff": "{:.2f}"})} | |
| Units are °F and inches in both. `share_rounding` (temperature differences up to {rounding['max']:.1f} °F): {rounding['in_last_year']:.0%} of these days are in {TRAIN_END}, where {rounding['decimal_last_year']:.0%} of the challenge's temperatures carry a decimal (earlier years: {rounding['decimal_before']:.2%}) and NCEI returns whole °F. `share_other` clusters in years where the challenge's record holds other observations than NOAA's file for the same ID (> {MISMATCH_SHARE:.0%} of common days differ by > {ROUND_TOL['tmax']} °F): {len(bad)} of {len(mis)} stations have such years (`station_mismatch.csv`); the six with most: | |
| {md_table(worst, {f"{v} equal": "{:.1%}" for v in VARS})} | |
| ## 3 Annual metrics recomputed from NOAA daily vs `annual_indices` (NOAA - challenge, {START[:4]}-{END[:4]}, {len(manifest)} stations) | |
| {md_table(ann)} | |
| - `same obs.`: without the station-years of section 2 in which the challenge holds other observations. The same code on the challenge's own daily table reproduces `annual_indices` (max abs diff {selfcheck.max():.3f}, rounding of Avg Temp): the differences above are data, not definitions. | |
| - Challenge has observations, NOAA (same ID) has none: {int(temp['n_challenge_only'].sum())} station-years of temperature at {int((temp['n_challenge_only'] > 0).sum())} stations. NOAA's file starts after {START} at {n_late} of {len(manifest)} stations: it holds only the latest station of the challenge's threaded record (`coverage.csv`). | |
| - NOAA has observations, the challenge has none (whole years): {"; ".join(only_n) or "none"}. | |
| ## 4 Gap filling (challenge year invalid, NOAA year valid by the same 10-day rule) | |
| City-years of the downloaded stations in {w} by rule (`validity_crosstab.csv`; `filled_annual.csv` lists every filled city-year-metric): | |
| {md_table(cross[cross["period"] == w].drop(columns="period"))} | |
| Filled city-years in {w}: {", ".join(f"{m} {int(tot.loc[m, 'filled_window'])}" for m in METRICS)} (since {START[:4]}: {", ".join(str(int(tot.loc[m, 'filled_all_years'])) for m in METRICS)}) at {n_fill_cities} cities. City-metrics with < {MIN_VALID_YEARS} valid years in {w} ({len(short)}): {short_txt}; **{len(reach)} of {len(short)} reach >= {MIN_VALID_YEARS}**. Top cities (valid years of 30; `gapfill_counts.csv`): | |
| {md_table(top)} | |
| ## 5 Backtest effect (a = selected model trained on the original panels, b = on the gap-filled panels) | |
| Truth, scored rows and the reference MAE (30-year average) come from the original data in both cases. `affected` = cities with >= 1 filled year in the fold's 30-year window, `scored` = those among them with scored rows; `30y b` = skill of the 30-year average trained on filled data (0 = reference unchanged). First two folds: selection; last two: holdout. | |
| {md_table(table)} | |
| Who moves the all-city skill where it changes by more than 0.3 points on a selection fold (`backtest_effect_cities.csv`): {"; ".join(drivers) or "nobody"}. | |
| ## 6 Conclusion | |
| - Interoperability: on common days {eq['tmax']:.1%} / {eq['tmin']:.1%} / {eq['prcp']:.1%} of tmax / tmin / prcp values are equal; the rest is {TRAIN_END} rounding and {len(bad)} stations whose challenge record holds other observations than NOAA's file under the same ID in some years. | |
| - Gap filling adds {int(tot.loc['annual_avg_temp', 'filled_window'])} temperature and {int(tot.loc['total_precip_in', 'filled_window'])} precipitation city-years in {w} at {n_fill_cities} cities; {len(reach)} of the {len(short)} city-metrics with < {MIN_VALID_YEARS} valid years reach {MIN_VALID_YEARS}. | |
| - Selection folds, all cities, skill change b - a in points ({folds_txt} fold): gap filling {verdict}; within ±0.3: {listing([m for m in METRICS if m not in moved])}. | |
| - Holdout folds (their 30-year windows start before the {START[:4]} download start, so they are only partly filled): largest change {pts(bigh['skill_change_points'])} points ({bigh['metric']}, {bigh['fold']}). Score a -> b: {"; ".join(f"{f}: {a:.2f} -> {b:.2f}" for f, (a, b) in score.items())}. | |
| - The 30-year-average reference itself moves by at most {refmax:.2f} points when trained on filled data; affected cities without scored rows (no baseline or no valid truth in the original data) are outside this comparison. | |
| """ | |
| assert len(text.splitlines()) <= 90, len(text.splitlines()) | |
| (OUT / "GHCND.md").write_text(text) | |
| if __name__ == "__main__": | |
| main() | |