File size: 3,736 Bytes
49f3de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""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)