File size: 22,717 Bytes
d79a78d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
"""Backtest harness and model selection.

Folds simulate the real task (train up to an origin, forecast the next 7 years):
    selection folds     <=2011 -> 2012-2018 and <=2004 -> 2005-2011  (candidates are ranked here)
    confirmation folds  <=1997 -> 1998-2004 and <=1990 -> 1991-1997  (veto only, never ranking)
    practice fold       <=2010 -> 2011-2018                          (organizers' published numbers)

Selection climbs a ladder per metric: climatology -> trend (pooled slope; for cdd also the
regression on forecast temperature, competing on the same rung) -> blend. The best candidate of a rung (mean skill over
the two selection folds) replaces the incumbent only if
  1. its gain is positive on BOTH selection folds (i.e. larger than one fold-to-fold
     standard error) and larger than 2 standard errors of a paired bootstrap over cities, and
  2. it does not lose to the 30-year average on the confirmation folds (mean skill >= 0).
Otherwise the simpler model stays ("stop adding complexity when gains < noise").

Writes reports/backtest/{candidates.csv, table.csv, selected.json, BACKTEST.md}.
Run: PYTHONPATH=code python -m protostar.backtest
"""

import json

import numpy as np
import pandas as pd

from .common import (BASELINE_WINDOW, CONFIRMATION_FOLDS, METRICS, MIN_VALID_YEARS, PRACTICE_FOLD,
                     REPORTS, SEED, SELECTION_FOLDS, UNITS)
from .data import Panel, cities, load_annual, long_table, panels
from .models import BASELINES, neighbor_order, predict, window_mean
from .scoring import challenge_score, skill

OUT = REPORTS / "backtest"
N_BOOT = 2000
SE_MULT = 2.0           # a rung must gain more than this many standard errors
K_GRID = (8, 16, 32)    # nearest cities pooled for the slope
LAM_GRID = (0.0, 0.25, 0.5, 0.75, 1.0)   # weight of the city's own slope
W_STEP = 0.1            # blend weights on a simplex grid


def key(spec: dict) -> str:
    return json.dumps(spec, sort_keys=True)


class Fold:
    """One origin: training panels, truth, scored rows, and cached per-city errors."""

    def __init__(self, P: dict[str, Panel], origin: int, first: int, last: int,
                 min_valid: int = MIN_VALID_YEARS):
        self.origin, self.first, self.last = origin, first, last
        self.name = f"<={origin} -> {first}-{last}"
        self.years = np.arange(first, last + 1)
        self.train = {m: p.upto(origin) for m, p in P.items()}
        truth = {m: p.between(first, last).y for m, p in P.items()}
        self.truth = truth
        # scored = valid test year of a city-metric that has a 30-year-average baseline
        self.scored = {m: (np.isfinite(window_mean(self.train[m], BASELINE_WINDOW, min_valid))[:, None]
                           & np.isfinite(truth[m])) for m in P}
        # the reference of the skill: the 30-year average under this fold's minimum of valid years
        self.ref = {"type": "mean", "n": BASELINE_WINDOW, "min_valid": min_valid}
        self._cache = {}

    def predict(self, spec: dict, metric: str, order: np.ndarray) -> np.ndarray:
        """Forecast of `spec` for the test years, from the training panels only."""
        return predict(spec, self.train, metric, order, self.years)

    def errors(self, spec: dict, metric: str, order: np.ndarray):
        """(sum of |error| per city, scored rows per city) of `spec` on this fold."""
        k = (metric, key(spec))
        if k not in self._cache:
            pred = self.predict(spec, metric, order)
            mask = self.scored[metric]
            err = np.abs(np.where(mask, pred - self.truth[metric], 0.0))
            assert np.isfinite(err).all(), f"non-finite prediction on a scored row: {spec}"
            self._cache[k] = (err.sum(axis=1), mask.sum(axis=1))
        return self._cache[k]

    def mae(self, spec, metric, order) -> float:
        s, n = self.errors(spec, metric, order)
        return float(s.sum() / n.sum())

    def skill(self, spec, metric, order) -> float:
        return skill(self.mae(spec, metric, order), self.mae(self.ref, metric, order))

    def bias(self, spec, metric, order) -> float:
        """Mean signed error (forecast - actual) over the scored rows, as a share of the mean actual."""
        mask = self.scored[metric]
        diff = np.where(mask, self.predict(spec, metric, order) - self.truth[metric], 0.0)
        return float(diff.sum() / np.where(mask, self.truth[metric], 0.0).sum())


class Harness:
    def __init__(self, P: dict[str, Panel], order: np.ndarray):
        self.P, self.order = P, order
        self.sel = [Fold(P, *f) for f in SELECTION_FOLDS]
        self.hold = [Fold(P, *f) for f in CONFIRMATION_FOLDS]
        rng = np.random.default_rng(SEED)
        n = len(order)
        self.boot = rng.multinomial(n, np.full(n, 1.0 / n), size=N_BOOT).astype(float)  # [B, C]

    # mean skill over the selection folds, and its per-fold values
    def skills(self, spec, metric, folds=None):
        return [f.skill(spec, metric, self.order) for f in (folds or self.sel)]

    def mean_skill(self, spec, metric) -> float:
        return float(np.mean(self.skills(spec, metric)))

    def paired(self, spec_a, spec_b, metric):
        """Gain of a over b in mean selection-fold skill: (gain, bootstrap SE, per-fold gains)."""
        per_fold, boot = [], np.zeros(N_BOOT)
        for f in self.sel:
            (sa, n), (sb, _), (sr, _) = (f.errors(s, metric, self.order) for s in (spec_a, spec_b, f.ref))
            per_fold.append(float((sb.sum() - sa.sum()) / sr.sum()))
            boot += (self.boot @ (sb - sa)) / (self.boot @ sr) / len(self.sel)
        return float(np.mean(per_fold)), float(boot.std(ddof=1)), per_fold

    def best(self, specs, metric):
        return max(specs, key=lambda s: self.mean_skill(s, metric))


# ── Candidate families ───────────────────────────────────────────────────────

RECENT = {"type": "recent", "n": 10}                 # 10-year mean (2009-2018 for complete records)
LONG = {"type": "mean", "n": BASELINE_WINDOW}        # 30-year mean (1989-2018)


def climatology_specs():
    return [LONG, RECENT]


def sensitivity_specs(metric):
    """Not used for selection: how much the choices of window, k and pooling matter."""
    out = [{"type": "mean", "n": n, "min_valid": min(MIN_VALID_YEARS, n // 2)} for n in (15, 20, 40, 50)]
    out += [{"type": "ptrend", "n": n, "k": k, "lam": lam}
            for n, k, lam in ((30, 64, 0.5), (30, 0, 0.5), (30, 0, 0.0), (40, 32, 0.5), (40, 0, 0.5), (50, 32, 0.5))]
    if metric == "cdd":
        out += [{"type": "blend", "parts": [[0.5, {"type": "ptrend", "n": 30, "k": 32, "lam": 0.5}],
                                            [0.5, {"type": "cdd_via_temp", "n": 30,
                                                   "temp": {"type": "ptrend", "n": 30, "k": 32, "lam": 0.5}}]]}]
    return out


def trend_specs(k_grid=K_GRID):
    return [{"type": "ptrend", "n": BASELINE_WINDOW, "k": k, "lam": lam}
            for k in k_grid for lam in LAM_GRID if not (lam == 1.0 and k != k_grid[0])]


def blend_specs(recent, long, trend):
    steps = int(round(1 / W_STEP))
    out = []
    for i in range(steps + 1):
        for j in range(steps + 1 - i):
            w = (i / steps, j / steps, (steps - i - j) / steps)
            parts = [[wi, s] for wi, s in zip(w, (recent, long, trend)) if wi > 0]
            if len(parts) > 1:
                out.append({"type": "blend", "parts": parts})
    return out


def label(spec: dict) -> str:
    t = spec["type"]
    if t == "mean":
        return f"{spec['n']}-year mean"
    if t == "recent":
        return f"mean of last {spec['n']} valid years"
    if t == "last":
        return "last year repeated"
    if t == "ols":
        return f"per-city OLS line ({spec['n']} y)"
    if t == "ptrend":
        k = "all" if spec["k"] == 0 else spec["k"]
        window = "" if spec["n"] == BASELINE_WINDOW else f"{spec['n']} y, "
        return f"pooled trend ({window}k={k}, own-slope weight {spec['lam']:g})"
    if t == "cdd_via_temp":
        window = "" if spec["n"] == BASELINE_WINDOW else f" ({spec['n']} y)"
        return f"cdd ~ temp regression{window} on [{label(spec['temp'])}]"
    if t == "blend":
        return "blend: " + " + ".join(f"{w:g} x [{label(s)}]" for w, s in spec["parts"])
    return t


# ── Selection ladder ─────────────────────────────────────────────────────────

def climb(h: Harness, metric: str, rungs: list[tuple[str, list[dict]]], log: list[dict]) -> dict:
    """Climb the ladder for one metric; returns the selected spec."""
    incumbent = BASELINES["30-year average"]
    for rung, specs in rungs:
        cand = h.best(specs, metric)
        gain, se, per_fold = h.paired(cand, incumbent, metric)
        confirm = float(np.mean(h.skills(cand, metric, h.hold)))
        consistent = bool(gain > SE_MULT * se and min(per_fold) > 0)
        accept = bool(consistent and confirm >= 0)
        log.append({"metric": metric, "rung": rung, "candidate": label(cand), "spec": key(cand),
                    "n_candidates": len(specs), "incumbent": label(incumbent),
                    "gain_mean_skill": gain, "se_gain": se,
                    **{f"gain_{f.name}": g for f, g in zip(h.sel, per_fold)},
                    "confirmation_mean_skill": confirm,
                    "verdict": "accepted" if accept else
                               ("vetoed: loses to the 30-year average on the confirmation folds" if consistent
                                else "rejected: worse than the incumbent" if gain <= 0
                                else "rejected: gain within noise"),
                    "accepted": accept})
        if accept:
            incumbent = cand
    return incumbent


def select(h: Harness):
    log, chosen, rung_best = [], {}, {}

    def ladder(metric, trend_like):
        rung_best[(metric, "climatology")] = RECENT
        rung_best[(metric, "trend")] = comp = h.best(trend_like, metric)
        blends = blend_specs(RECENT, LONG, comp)
        rung_best[(metric, "blend")] = h.best(blends, metric)
        rungs = [("1 climatology (10-year mean)", [RECENT]),
                 ("2-3 trend" if metric == "cdd" else "2 pooled trend", trend_like),
                 ("4 blend (recent, long, trend)", blends)]
        return climb(h, metric, rungs, log)

    chosen["annual_avg_temp"] = ladder("annual_avg_temp", trend_specs())
    # cdd: the direct pooled trend and the regression on forecast temperature compete on one rung
    temps = {key(s): s for s in (chosen["annual_avg_temp"], rung_best[("annual_avg_temp", "trend")])}
    via = [{"type": "cdd_via_temp", "n": BASELINE_WINDOW, "temp": t} for t in temps.values()]
    chosen["cdd"] = ladder("cdd", trend_specs() + via)
    chosen["total_precip_in"] = ladder("total_precip_in", trend_specs())
    chosen["hottest_day_temp"] = ladder("hottest_day_temp", trend_specs())
    return chosen, pd.DataFrame(log), rung_best


# ── Reporting ────────────────────────────────────────────────────────────────

def fold_row(f: Fold, name: str, system: dict[str, dict], order) -> dict:
    row = {"model": name, "fold": f.name}
    skills = {}
    for m in METRICS:
        row[f"mae_{m}"] = f.mae(system[m], m, order)
        skills[m] = f.skill(system[m], m, order)
        row[f"skill_{m}"] = skills[m]
        row[f"bias_{m}"] = f.bias(system[m], m, order)
    row["score"] = challenge_score(skills)
    row["n_rows"] = int(sum(f.scored[m].sum() for m in METRICS))
    return row


def systems(chosen: dict, rung_best: dict, h: Harness) -> dict[str, dict[str, dict]]:
    """Named full systems (one spec per metric) for the model x fold table."""
    same = lambda s: {m: s for m in METRICS}
    out = {name: same(spec) for name, spec in BASELINES.items()}
    out["1 climatology: 10-year mean"] = same(RECENT)
    for k in K_GRID:
        out[f"2 pooled trend k={k}, own-slope weight 0.5"] = same({"type": "ptrend", "n": 30, "k": k, "lam": 0.5})
    direct = {m: h.best(trend_specs(), m) for m in METRICS}
    out["2 pooled trend, best (k, weight) per metric"] = direct
    via = {"type": "cdd_via_temp", "n": BASELINE_WINDOW, "temp": chosen["annual_avg_temp"]}
    out["3 as 2, but cdd ~ temp regression on forecast temp"] = {**direct, "cdd": via}
    out["4 best blend (recent, long, trend) per metric"] = {m: rung_best[(m, "blend")] for m in METRICS}
    out["FINAL (selected per metric)"] = chosen
    return out


def practice_check(P, order) -> pd.DataFrame:
    """Reproduce the organizers' practice-run numbers (train <= 2010, test 2011-2018).

    official rule:  baselines need >= 10 valid years in 1981-2010 (About tab, Space discussion #3)
    notebook rule:  no minimum; the line needs 2 valid years. The notebook scores its 10-year mean
                    on every valid test row that has a forecast, 6 rows more than its reference.
    """
    rows = []
    for rule, mv, line_mv in (("official (>= 10 valid years in the window)", MIN_VALID_YEARS, MIN_VALID_YEARS),
                              ("example notebook (no minimum)", 1, 2)):
        f = Fold(P, *PRACTICE_FOLD, min_valid=mv)
        for name, spec in (("30-year average", f.ref),
                           ("Linear trend", {"type": "ols", "n": BASELINE_WINDOW, "min_valid": line_mv}),
                           ("10-year mean", RECENT)):
            rows.append({"rule": rule, "model": name, **{m: f.mae(spec, m, order) for m in METRICS}})
    f = Fold(P, *PRACTICE_FOLD, min_valid=1)
    own_rows = {}
    for m in METRICS:
        pred = predict(RECENT, f.train, m, order, f.years, fill=False)
        mask = np.isfinite(f.truth[m]) & np.isfinite(pred)
        own_rows[m] = float(np.abs(pred - f.truth[m])[mask].mean())
    rows.append({"rule": "example notebook, scored on the rows the model covers", "model": "10-year mean", **own_rows})
    return pd.DataFrame(rows)


def md_table(df: pd.DataFrame, fmt: dict | None = None) -> str:
    fmt = fmt or {}
    cols = list(df.columns)
    lines = ["| " + " | ".join(cols) + " |", "|" + "|".join("---" for _ in cols) + "|"]
    for _, r in df.iterrows():
        cells = []
        for c in cols:
            v = r[c]
            cells.append(fmt[c].format(v) if c in fmt and pd.notna(v) else str(v))
        lines.append("| " + " | ".join(cells) + " |")
    return "\n".join(lines)


def main():
    OUT.mkdir(parents=True, exist_ok=True)
    annual = load_annual()
    P = panels(long_table(annual))
    geo = cities(annual)
    assert list(geo["city_id"]) == list(P["cdd"].city_ids)
    order = neighbor_order(geo["lat"].to_numpy(), geo["lon"].to_numpy())
    h = Harness(P, order)

    practice = practice_check(P, order)
    chosen, log, rung_best = select(h)

    # every candidate on every fold (for the record)
    cands = []
    for m in METRICS:
        used = (climatology_specs() + trend_specs() + list(BASELINES.values()) + [chosen[m]]
                + [json.loads(r["spec"]) for _, r in log[log["metric"] == m].iterrows()]
                + blend_specs(RECENT, LONG, rung_best[(m, "trend")]))
        specs = {key(s): ("selection", s) for s in used}
        specs.update({key(s): ("sensitivity only", s) for s in sensitivity_specs(m) if key(s) not in specs})
        for role, s in specs.values():
            for kind, folds in (("selection", h.sel), ("confirmation", h.hold)):
                for f in folds:
                    cands.append({"metric": m, "model": label(s), "role": role, "fold": f.name, "fold_kind": kind,
                                  "n_rows": int(f.scored[m].sum()), "mae": f.mae(s, m, order),
                                  "mae_30y_average": f.mae(f.ref, m, order),
                                  "skill": f.skill(s, m, order), "spec": key(s)})
    cands = pd.DataFrame(cands)
    assert not cands.duplicated(["metric", "model", "fold"]).any(), "two specs share a label"
    cands.to_csv(OUT / "candidates.csv", index=False)

    table = pd.DataFrame([fold_row(f, name, system, order)
                          for name, system in systems(chosen, rung_best, h).items()
                          for f in h.sel + h.hold])
    table["fold_kind"] = np.where(table["fold"].isin([f.name for f in h.sel]), "selection", "confirmation")
    table.to_csv(OUT / "table.csv", index=False)
    log.to_csv(OUT / "ladder.csv", index=False)
    practice.to_csv(OUT / "practice_run.csv", index=False)

    # gate: the final system must beat both baselines' Score on both selection folds
    final = table[table["model"] == "FINAL (selected per metric)"].set_index("fold")
    gate = {}
    for f in h.sel:
        others = table[(table["fold"] == f.name) & table["model"].isin(["30-year average", "Linear trend"])]
        gate[f.name] = bool((final.loc[f.name, "score"] > others["score"]).all())
    (OUT / "selected.json").write_text(json.dumps(
        {"selected": chosen, "labels": {m: label(s) for m, s in chosen.items()},
         "gate_beats_both_baselines_on_both_selection_folds": gate}, indent=1) + "\n")
    if not all(gate.values()):
        raise SystemExit(f"GATE FAILED: the final system does not beat both baselines on both folds: {gate}")

    write_report(table, log, practice, chosen, gate, h, cands)
    pd.set_option("display.width", 250, "display.max_columns", 30, "display.max_colwidth", 70)
    print(practice.round(3).to_string(index=False), "\n")
    print(log.drop(columns=["spec", "incumbent"]).round(4).to_string(index=False), "\n")
    print(table.drop(columns=[c for c in table if c.startswith("mae_")]).round(4).to_string(index=False))
    print("\nselected:", json.dumps({m: label(s) for m, s in chosen.items()}, indent=1))
    print("gate:", gate)


def write_report(table, log, practice, chosen, gate, h, cands):
    sk = {f"skill_{m}": "{:+.1%}" for m in METRICS}
    mae = {"mae_annual_avg_temp": "{:.3f}", "mae_total_precip_in": "{:.3f}",
           "mae_hottest_day_temp": "{:.3f}", "mae_cdd": "{:.1f}"}
    t = table[["model", "fold_kind", "fold", "score", *sk, *mae, "n_rows"]]
    lad = log[["metric", "rung", "candidate", "n_candidates", "incumbent", "gain_mean_skill", "se_gain",
               *[f"gain_{f.name}" for f in h.sel], "confirmation_mean_skill", "verdict"]]
    sens = (cands.pivot(index=["metric", "role", "model"], columns="fold", values="skill")
            .reindex(pd.MultiIndex.from_frame(cands[["metric", "role", "model"]].drop_duplicates()))
            [[f.name for f in h.sel + h.hold]].reset_index())
    sens["mean selection"] = sens[[f.name for f in h.sel]].mean(axis=1)
    sens["mean confirmation"] = sens[[f.name for f in h.hold]].mean(axis=1)
    sens = sens[~sens["model"].str.startswith("blend: 0.")
                | sens["model"].isin([label(s) for s in chosen.values()])
                | (sens["role"] == "sensitivity only")]
    text = f"""# Backtest report

Generated by `python -m protostar.backtest` (do not edit). Scoring is the challenge's:
MAE per metric over valid years (10-day rule) of city-metrics with a baseline (>= {MIN_VALID_YEARS}
valid years in the 30-year window), skill `S = 1 - MAE / MAE(30-year average)`, and
`Score = 100 * max(0, mean of the four S)`. Every fold trains on years <= origin only.

## Harness check against the organizers' practice run (train <= 2010, test 2011-2018)

Published (temp / precip / hottest day / cdd):
- official rule, CDD only: 30-year average 212 and linear trend 175 (About tab); 211.7 and 174.6
  (organizer, Space discussion #3);
- example notebook: 30-year average 1.657 / 6.198 / 2.563 / 212.636 and its 10-year mean
  1.513 / 6.207 / 2.568 / 184.059. The notebook scores its model on every valid test row that has
  a forecast, 6 rows more than its reference (last table row); on the reference's rows the same
  model gives the "example notebook (no minimum) / 10-year mean" row.

Our linear trend is a per-city least-squares line on the valid years of the window (x = calendar
year), not floored at zero; the organizers' fit is not published beyond these numbers.

{md_table(practice, {m: "{:.3f}" for m in METRICS})}

## Model x fold x metric

`selection` folds rank the candidates; `confirmation` folds can only veto (see the ladder).
Rows 1-4 are the rungs of the plan applied to all four metrics; FINAL is the per-metric choice.

{md_table(t, {"score": "{:.2f}", **sk, **mae})}

## Selection ladder

The best candidate of a rung (mean skill over the two selection folds) replaces the incumbent only
if its gain is positive on both selection folds and larger than {SE_MULT:g} standard errors (paired
bootstrap over cities, {N_BOOT} resamples, seed {SEED}), and its mean skill on the confirmation
folds is not negative. Gains are in skill units (0.01 = 1 % of the 30-year-average MAE).

Caveats. (1) Cities are spatially correlated, so a bootstrap over cities gives a lower bound on
the standard error; that is why a gain must also hold on both folds. (2) The test is applied to
the best of `n_candidates` with no adjustment for that choice; the accepted rungs clear it by a
wide margin and the one marginal case was vetoed. (3) The veto compares with the 30-year average,
not with the incumbent: `confirmation_mean_skill` of an accepted rung can be below the
incumbent's (compare the rows of the table above). (4) Because the veto decided the hottest-day
model, the confirmation folds are a clean holdout only for the other three metrics.

{md_table(lad, {c: "{:+.4f}" for c in lad.columns if c.startswith("gain_")} | {"se_gain": "{:.4f}", "confirmation_mean_skill": "{:+.4f}"})}

## Selected

{chr(10).join(f"- `{m}` ({UNITS[m]}): {label(s)}" for m, s in chosen.items())}

Gate (final system beats both the 30-year average and the linear trend on the Score, on both
selection folds): {gate}

## Candidates, skill per fold (and choices we did not let the backtest make)

Every candidate is in `candidates.csv`; this table leaves out the 63 blends of each metric (the
best one of each is in the ladder above). `sensitivity only` rows were never candidates: they
show how much the window length (40 or 50 years), the number of pooled neighbors (k=64, all
cities) and other climatology windows would matter. Pooled-trend rows whose label names no
window use the 30-year window.

{md_table(sens, {c: "{:+.1%}" for c in sens.columns if c not in ("metric", "role", "model")})}
"""
    (OUT / "BACKTEST.md").write_text(text)


if __name__ == "__main__":
    main()