File size: 8,350 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
"""Regenerate the number tables of README.md from the reports, so the write-up cannot drift.

Blocks between `<!-- BEGIN:name -->` and `<!-- END:name -->` in README.md are replaced:
    backtest        Score by model and fold; MAE and skill by metric (reports/backtest/table.csv)
    policy-numbers  the forecast numbers quoted in the Policy Idea (reports/forecast/forecast_summary.csv)
Also writes reports/forecast/POLICY_NUMBERS.md (all cities behind the policy numbers).

Run: PYTHONPATH=code python -m protostar.docs
"""

import json
import re

import pandas as pd

from .common import BASELINE_WINDOW, METRICS, REPORTS, ROOT, TRAIN_END, UNITS
from .data import load_coverage

SHORT = {"annual_avg_temp": "avg temp (°F)", "total_precip_in": "precip (in)",
         "hottest_day_temp": "hottest day (°F)", "cdd": "CDD (°F-days)"}
ROWS_B = ["30-year average", "Linear trend", "1 climatology: 10-year mean", "FINAL (selected per metric)"]
MIN_CDD_FOR_PCT = 500     # relative changes are only ranked for cities with a real cooling season
LEVER_PCT, LEVER_ABS = 10, 200   # Policy Idea lever (b): >= 10 % or >= 200 °F-days above the normal, cities with >= 500 CDD
MIN_YEARS_RANKED = 25     # city rankings: at least 25 valid years in 1989-2018 and no documented station change there


def backtest_block() -> str:
    t = pd.read_csv(REPORTS / "backtest" / "table.csv")
    folds = list(dict.fromkeys(t["fold"]))
    kind = dict(zip(t["fold"], t["fold_kind"]))
    head = "| Model | " + " | ".join(f"{f}<br>({kind[f]})" for f in folds) + " |"
    lines = ["**Score (0–100, the challenge's formula) by model and fold**", "", head,
             "|---|" + "---:|" * len(folds)]
    for model in dict.fromkeys(t["model"]):
        g = t[t["model"] == model].set_index("fold")
        name = f"**{model}**" if model.startswith("FINAL") else model
        lines.append(f"| {name} | " + " | ".join(f"{g.loc[f, 'score']:.2f}" for f in folds) + " |")
    lines += ["", "**MAE (skill vs the 30-year average) by metric**", "",
              "| Fold | Model | " + " | ".join(SHORT[m] for m in METRICS) + " |", "|---|---|" + "---:|" * len(METRICS)]
    for f in folds:
        for model in ROWS_B:
            r = t[(t["fold"] == f) & (t["model"] == model)].iloc[0]
            cells = []
            for m in METRICS:
                digits = 1 if m == "cdd" else 3
                cells.append(f"{r[f'mae_{m}']:.{digits}f} ({100 * r[f'skill_{m}']:+.1f} %)")
            name = "**FINAL**" if model.startswith("FINAL") else model.replace("1 climatology: ", "")
            lines.append(f"| {f} | {name} | " + " | ".join(cells) + " |")
    sel = json.loads((REPORTS / "backtest" / "selected.json").read_text())
    lines += ["", "Selected per metric: " + "; ".join(f"`{m}` → {sel['labels'][m]}" for m in METRICS) + "."]
    return "\n".join(lines)


def policy_frames():
    s = pd.read_csv(REPORTS / "forecast" / "forecast_summary.csv")
    s = s[s["n_valid_1989_2018"] >= 10]            # city-metrics with a baseline
    c = s[s["metric"] == "cdd"].copy()
    c["change"] = c["forecast_mean_2019_2025"] - c["mean_1989_2018"]
    c["change_pct"] = 100 * c["change"] / c["mean_1989_2018"]
    cov = load_coverage()
    moved = set(cov.loc[(cov["Station Changes"] > 0) & (cov["Year"] > TRAIN_END - BASELINE_WINDOW), "ID"])
    c["station_change_1989_2018"] = c["city_id"].isin(moved)
    c["ranked"] = (c["n_valid_1989_2018"] >= MIN_YEARS_RANKED) & ~c["station_change_1989_2018"]
    return s, c


def bias_row() -> str:
    """Signed CDD error (share of actual CDD) of the 30-year normal and of our model, per backtest fold."""
    t = pd.read_csv(REPORTS / "backtest" / "table.csv")
    cells = []
    for fold in dict.fromkeys(t["fold"]):
        normal = t[(t["fold"] == fold) & (t["model"] == "30-year average")]["bias_cdd"].iloc[0]
        ours = t[(t["fold"] == fold) & t["model"].str.startswith("FINAL")]["bias_cdd"].iloc[0]
        cells.append(f"{fold.split('-> ')[1].replace('-', '–')}: {100 * normal:+.1f} % → {100 * ours:+.1f} %")
    return "| CDD bias in backtests, 30-year normal → our model (forecast minus actual, share of actual) | " \
        + "; ".join(cells) + " |"


def policy_block() -> str:
    s, c = policy_frames()
    t = s[s["metric"] == "annual_avg_temp"]
    h = s[s["metric"] == "hottest_day_temp"]
    big = c[c["mean_1989_2018"] >= MIN_CDD_FOR_PCT]
    top_abs = c[c["ranked"]].sort_values("change", ascending=False).head(8)
    top_pct = big[big["ranked"]].sort_values("change_pct", ascending=False).head(10)
    ratio = 100 * (c["forecast_mean_2019_2025"].mean() / c["mean_1989_2018"].mean() - 1)
    recent = 100 * (c["mean_last10_valid"].mean() / c["mean_1989_2018"].mean() - 1)
    lever = int(((big["change_pct"] >= LEVER_PCT) | (big["change"] >= LEVER_ABS)).sum())
    lines = [
        "| Quantity (our forecasts vs each city's 1989–2018 mean) | Value |", "|---|---|",
        f"| Cities with a baseline | {len(c)} of 210 |",
        f"| CDD, mean over cities: 1989–2018 → forecast 2019–2025 | {c['mean_1989_2018'].mean():,.0f} → "
        f"{c['forecast_mean_2019_2025'].mean():,.0f} °F-days ({ratio:+.1f} %) |",
        f"| CDD change, median city | {c['change_pct'].median():+.1f} % |",
        f"| CDD, last 10 valid years (observed, up to 2018) vs the 1989–2018 mean | {recent:+.1f} % |",
        f"| Cities with CDD ≥ +10 % / ≥ +15 % | {int((c['change_pct'] >= 10).sum())} / {int((c['change_pct'] >= 15).sum())} |",
        f"| Cities with ≥ {MIN_CDD_FOR_PCT} CDD and CDD ≥ +{LEVER_PCT} % or ≥ +{LEVER_ABS} °F-days (lever b) | {lever} |",
        bias_row(),
        f"| Average temperature change, mean over cities | {(t['forecast_mean_2019_2025'] - t['mean_1989_2018']).mean():+.2f} °F |",
        "| Hottest day of the year | no trend survived the backtests: forecast = the 1989–2018 mean "
        f"(largest difference {(h['forecast_mean_2019_2025'] - h['mean_1989_2018']).abs().max():.2f} °F, rounding) |",
        "| Largest CDD increases, °F-days* | " + ", ".join(
            f"{r['name']} {r['change']:+.0f}" for _, r in top_abs.iterrows()) + " |",
        f"| Largest relative CDD increases (cities with ≥ {MIN_CDD_FOR_PCT} CDD)* | " + ", ".join(
            f"{r['name']} {r['change_pct']:+.0f} %" for _, r in top_pct.iterrows()) + " |",
        "",
        f"\\* Rankings use cities with at least {MIN_YEARS_RANKED} valid years in 1989–2018 and no documented station "
        f"change in that window ({int(c['ranked'].sum())} of {len(c)}); all cities are in "
        "`reports/forecast/policy_cdd_by_city.csv`.",
    ]
    return "\n".join(lines)


def write_policy_report():
    _, c = policy_frames()
    cols = ["name", "city_id", "lat", "lon", "n_valid_1989_2018", "station_change_1989_2018", "mean_1989_2018",
            "mean_last10_valid", "forecast_2019", "forecast_2025", "forecast_mean_2019_2025", "change", "change_pct"]
    out = c.sort_values("change_pct", ascending=False)[cols].round(1)
    out.to_csv(REPORTS / "forecast" / "policy_cdd_by_city.csv", index=False)
    text = ["# Numbers behind the Policy Idea", "",
            "Generated by `python -m protostar.docs` from `reports/forecast/forecast_summary.csv` "
            "(our forecasts and the 1989–2018 valid years of the training data; no data after 2018).", "",
            policy_block(), "",
            "All cities, sorted by relative change: `reports/forecast/policy_cdd_by_city.csv` "
            f"(columns in {UNITS['cdd']}; `change` = forecast mean 2019–2025 minus the 1989–2018 mean).", ""]
    (REPORTS / "forecast" / "POLICY_NUMBERS.md").write_text("\n".join(text))


def replace_block(text: str, name: str, body: str) -> str:
    pattern = re.compile(rf"(<!-- BEGIN:{name} -->\n).*?(<!-- END:{name} -->)", re.S)
    if not pattern.search(text):
        raise SystemExit(f"README.md has no block named {name!r}")
    return pattern.sub(lambda m: m.group(1) + body + "\n" + m.group(2), text)


def main():
    write_policy_report()
    readme = ROOT / "README.md"
    text = readme.read_text()
    for name, body in (("backtest", backtest_block()), ("policy-numbers", policy_block())):
        text = replace_block(text, name, body)
    readme.write_text(text)
    print("README.md tables regenerated from reports/")


if __name__ == "__main__":
    main()