Tonic's picture
Protostar Climate submission: v2 forecast + v3/DCPP amendment audit (29 gated candidates)
49f3de8 verified
Raw History Blame Contribute Delete
3.74 kB
"""DCPP decadal-prediction candidates (organiser-approved amendment).
Method frozen in candidates_v3_amendment.yaml: for origin T, only the
MPI-ESM1-2-HR dcppA-hindcast initialised at T (members r1+r2) is used, drift-
corrected by a lead-dependent climatology from r1 hindcast starts 1960..T.
The candidate adds only the *spatial pattern* (city anomaly minus national
mean anomaly) to the v2 forecast; the national trend stays with v2.
Data: data/external/dcpp_city_annual.csv built by dcpp_fetch.py.
"""
from __future__ import annotations
from pathlib import Path
import numpy as np
import pandas as pd
from panel import Panel
HORIZON = 7
class DcppCandidates:
def __init__(self, root: Path, panel: Panel):
path = root / "data" / "external" / "dcpp_city_annual.csv"
if not path.exists():
raise FileNotFoundError(f"{path} missing; run code/dcpp_fetch.py first")
df = pd.read_csv(path)
city_cols = [c for c in df.columns if c.startswith("city")]
assert len(city_cols) == len(panel.cities), "DCPP city columns misaligned with panel"
self.panel = panel
self.city_cols = city_cols
self.df = df
def _annual(self, variable: str, member: str, start: int) -> np.ndarray | None:
sub = self.df[(self.df["variable"] == variable)
& (self.df["member"] == member)
& (self.df["start"] == start)].sort_values("lead")
if len(sub) != HORIZON:
return None
return sub[self.city_cols].to_numpy(float).T # (210, 7) leads 1..7
def _climatology(self, variable: str, origin: int) -> np.ndarray:
"""Lead-dependent r1 climatology from starts 1960..origin: (210, 7)."""
sub = self.df[(self.df["variable"] == variable)
& (self.df["member"] == "r1i1p1f1")
& (self.df["start"] <= origin)
& (self.df["start"] >= 1960)]
if sub.empty:
raise ValueError(f"no DCPP climatology starts <= {origin}")
clim = sub.groupby("lead")[self.city_cols].mean().sort_index()
if len(clim) != HORIZON:
raise ValueError(f"incomplete DCPP climatology at origin {origin}")
return clim.to_numpy(float).T
def _ensemble(self, variable: str, origin: int, members: tuple[str, ...]) -> np.ndarray:
# Mean over whichever members the catalog actually holds for this
# start (MPI catalog lacks e.g. r1 s2002 / r2 s1998); >= 1 required.
mats = []
for m in members:
a = self._annual(variable, m, origin)
if a is not None:
mats.append(a)
if not mats:
raise ValueError(f"DCPP {variable} start {origin}: no members fetched")
return np.mean(mats, axis=0)
def temp_pattern(self, origin: int, v2_fn, weight: float) -> np.ndarray:
ens = self._ensemble("tas", origin, ("r1i1p1f1", "r2i1p1f1"))
clim = self._climatology("tas", origin)
anomaly = ens - clim # Kelvin == degC differences
pattern_k = anomaly.mean(axis=1) - anomaly.mean() # lead-avg, national removed
return v2_fn(self.panel, origin) + weight * 1.8 * pattern_k[:, None]
def precip_pattern(self, origin: int, v2_fn) -> np.ndarray:
ens = self._ensemble("pr", origin, ("r1i1p1f1",))
clim = self._climatology("pr", origin)
ratio_city = (ens.mean(axis=1) + 1e-12) / (clim.mean(axis=1) + 1e-12)
ratio_nat = float(np.mean(ratio_city))
factor = np.clip(ratio_city / ratio_nat, 0.8, 1.25)
return np.maximum(v2_fn(self.panel, origin) * factor[:, None], 0.0)