File size: 4,185 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
"""Phase 2/3: CDD delta candidates + homogenisation variants for temp/CDD."""
from __future__ import annotations

import sys
from pathlib import Path

import numpy as np
import pandas as pd

sys.path.insert(0, str(Path(__file__).parent))
from candidates import level_trend
from cdd_delta import CddDelta
from harness import evaluate, skill_table
from homogenise import segonly_panel, stepadj_panel
from panel import Panel


def show(metric: str, detail: pd.DataFrame, tag: str) -> None:
    tab = skill_table(detail)
    piv = tab.pivot_table(index="candidate", columns="era", values="skill")
    g = detail.groupby("candidate").apply(
        lambda s: 1 - (s.sum_err.sum() / s.n.sum()) / (s.sum_err_ref.sum() / s.n.sum()),
        include_groups=False)
    piv["all"] = g
    print(f"\n== {metric} [{tag}] ==")
    print(piv.sort_values("tune", ascending=False).round(4).to_string())


def main() -> None:
    root = Path(__file__).resolve().parent.parent
    panel = Panel(root)
    delta = CddDelta(root, panel)
    out = root / "outputs" / "v2"
    linear15 = lambda p, o: level_trend(p, "cdd", o, 15, "mean", "nat", 40, clip_zero=True)

    cands = {}
    for hist in (15, 30):
        for agg in ("median", "mean"):
            for trend in ("nat", "reg"):
                name = f"delta_h{hist}_{agg}_{trend}"
                cands[name] = (lambda h, a, t: lambda p, o: delta.forecast(o, h, a, t))(hist, agg, trend)
    # Blends with linear L15.
    for hist, agg in ((15, "median"), (30, "median")):
        name = f"blend50_delta_h{hist}_{agg}_nat"
        cands[name] = (lambda h, a: lambda p, o: 0.5 * delta.forecast(o, h, a, "nat")
                       + 0.5 * linear15(p, o))(hist, agg)
    cands["linear_L15_natW40"] = linear15
    detail = evaluate(panel, "cdd", cands)
    detail.to_csv(out / "detail_cdd_delta.csv", index=False)
    show("cdd", detail, "delta vs linear, raw panel")

    # Homogenisation variants: forecasts from variant panels, scored on RAW truth.
    seg = segonly_panel(root, panel)
    adj = stepadj_panel(root, panel)

    def evaluate_mixed(metric: str, variants: dict) -> pd.DataFrame:
        from candidates import baseline_mean30
        from harness import ORIGINS, TUNE_ORIGINS
        rows = []
        for origin in ORIGINS:
            truth, mask = panel.truth(metric, origin)
            ref = baseline_mean30(panel, metric, origin)
            forecasts = {name: fn(vp, origin) for name, (vp, fn) in variants.items()}
            for h in range(7):
                m = mask[:, h]
                if not m.any():
                    continue
                t = truth[m, h]
                for name, fc in forecasts.items():
                    if not np.isfinite(fc[m, h]).all():
                        raise ValueError(f"{name} non-finite at origin {origin}")
                    rows.append({"metric": metric, "origin": origin,
                                 "target_year": origin + h + 1, "lead": h + 1,
                                 "era": "tune" if origin in TUNE_ORIGINS else "check",
                                 "n": int(m.sum()), "candidate": name,
                                 "sum_err": float(np.abs(fc[m, h] - t).sum()),
                                 "sum_err_ref": float(np.abs(ref[m, h] - t).sum())})
        return pd.DataFrame(rows)

    temp_fn = lambda p, o: level_trend(p, "annual_avg_temp", o, 15, "mean", "nat", 40)
    detail_h = evaluate_mixed("annual_avg_temp", {
        "L15_raw": (panel, temp_fn),
        "L15_segonly": (seg, temp_fn),
        "L15_stepadj": (adj, temp_fn),
    })
    detail_h.to_csv(out / "detail_temp_homog.csv", index=False)
    show("annual_avg_temp", detail_h, "homogenisation, raw truth")

    cdd_fn = lambda p, o: level_trend(p, "cdd", o, 15, "mean", "nat", 40, clip_zero=True)
    detail_hc = evaluate_mixed("cdd", {
        "L15_raw": (panel, cdd_fn),
        "L15_segonly": (seg, cdd_fn),
    })
    detail_hc.to_csv(out / "detail_cdd_homog.csv", index=False)
    show("cdd", detail_hc, "homogenisation, raw truth")


if __name__ == "__main__":
    main()