File size: 5,907 Bytes
b5e8582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Placeholder_v9-S: the submitted forecast. 2019-2025 for 210 cities x 4 metrics, made as of 2018-12-31.

    python code/prepare_warm_days.py        # once: data/daily_warm_days.csv from the daily subset (tracked; optional)
    python code/make_submission.py          # writes submission.csv (under a minute)
    python code/check_submission.py         # same checks as the challenge Space

The model (code/placeholder_v9s.py, plan v9 docs/plans/plan-v9-lineup.md, chosen on the rolling-origin bench 1990-2011
plus the late window 2012-2017 under plan v8 section 2; comparison docs/plans/v9-analysis/v9_compare.txt) is
Placeholder_v3.8 with one change, in CDD:

    annual_avg_temp   the city's mean of its last 15 years, carried forward at 1.75 x the warming rate shared by all
                      cities (median of the cities' 50-year least-squares slopes). Unchanged from v3.8.
    cdd               v3.8's CDD (combined model v4 plus half of any shortfall against a warming trend, plus the extra
                      temperature warming converted to CDD), with a new CDD-per-degree response in both terms:
                      r = 0.75 k + 0.25 d, where d is the city's average number of days a year with a daily mean above
                      65 F (1989-2018, valid CDD years; a uniform +1 F adds 1 F-day on each such day) and k is v3.8's
                      CDD-on-temperature regression pooled over the 15 cities nearest in distance AND in d. The 0.25
                      was picked on origins <= 2004, leads 4-7. Cities without 10 valid years keep v3.8's response.
    total_precip_in   the city's 30-year average plus Placeholder_v1.4's neighbour-graph term; unchanged
    hottest_day_temp

Input: data/annual_indices_train_to_2018.parquet (the challenge's annual_indices subset, checked by SHA-256 against the
pinned revision; downloaded at that revision if missing), loaded with the official 10-day validity rule, and
data/city_info.csv (latitude and longitude), and data/daily_warm_days.csv (days with both Tmax and Tmin, and days
with a mean above 65 F, per city and year, from the challenge daily subset by code/prepare_warm_days.py). DataRuleViolation is raised on any row after 2018. No 2019-2025 data and no
leaderboard score is used, and no value is edited by hand. Deterministic output (seed 42, no parallel sums).
Previous submissions: Placeholder_v3.8 (code/make_submission_v3_8.py), Placeholder_v3.6 (code/make_submission_v3_6.py), combined model v4 (code/make_submission_v4.py).
"""
from __future__ import annotations

import argparse
import io
import os
import sys
from pathlib import Path

CODE = Path(__file__).resolve().parent
ROOT = CODE.parent
sys.path.insert(0, str(CODE))

import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402

from common import CUTOFF_YEAR, METRICS, assert_no_post_cutoff  # noqa: E402
from evaluation.core import PINNED_ANNUAL_SHA256, digest, load_annual, pinned_annual  # noqa: E402

MODEL = "Placeholder_v9-S"
WARM_DAYS = ROOT / "data/daily_warm_days.csv"
ANNUAL = ROOT / "data/annual_indices_train_to_2018.parquet"
CITY_INFO = ROOT / "data/city_info.csv"
ORIGIN = CUTOFF_YEAR
YEARS = list(range(ORIGIN + 1, ORIGIN + 8))   # 2019-2025
KEY = ["city_id", "year", "metric"]


def _round_trip(frame: pd.DataFrame, dtypes: dict) -> pd.DataFrame:
    """The evaluation harness hands the model CSV-read tables; do the same so the numbers match the bench exactly."""
    buf = io.StringIO()
    frame.to_csv(buf, index=False, lineterminator="\n")
    buf.seek(0)
    return pd.read_csv(buf, dtype=dtypes)


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--output", type=Path, default=ROOT / "submission.csv")
    args = parser.parse_args(argv)

    source = ANNUAL if ANNUAL.is_file() else pinned_annual()
    if digest(source) != PINNED_ANNUAL_SHA256:
        raise SystemExit(f"{source} is not the pinned annual_indices file ({PINNED_ANNUAL_SHA256[:12]}...)")
    annual = load_annual(source)
    assert_no_post_cutoff(annual, "year", f"{MODEL} training history")
    cities = sorted(pd.read_csv(CITY_INFO, dtype={"city_id": str}).city_id.unique())

    train = _round_trip(annual[(annual.year <= ORIGIN) & annual.city_id.isin(cities)], {"city_id": str})
    targets = pd.MultiIndex.from_product([cities, YEARS, list(METRICS)], names=KEY).to_frame(index=False)
    targets = _round_trip(targets, {"city_id": str, "metric": str})
    assert_no_post_cutoff(train, "year", f"{MODEL} training history")

    os.environ["PROTOSTAR_ASSET_ROOT"] = str(ROOT)          # the model reads data/city_info.csv (lat, lon) from here
    os.environ.pop("PROTOSTAR_ARTIFACT_DIR", None)
    os.environ["PROTOSTAR_FOLD_CUTOFF"] = str(ORIGIN)
    if not WARM_DAYS.is_file():
        raise SystemExit(f"{WARM_DAYS} is missing: run python code/prepare_warm_days.py first")
    os.environ["PROTOSTAR_WARM_DAYS"] = str(WARM_DAYS.relative_to(ROOT).as_posix())   # read under PROTOSTAR_ASSET_ROOT
    import placeholder_v9s
    res = placeholder_v9s.forecast(train, targets, ORIGIN, seed=42)

    out = targets.merge(res[KEY + ["predicted_value"]], on=KEY, how="left", validate="one_to_one")
    order = {m: i for i, m in enumerate(METRICS)}
    out = out[KEY + ["predicted_value"]].sort_values(KEY, key=lambda s: s.map(order) if s.name == "metric" else s)
    out["predicted_value"] = out["predicted_value"].astype(float).round(3)
    if len(out) != len(cities) * len(YEARS) * len(METRICS) or not np.isfinite(out.predicted_value).all():
        raise SystemExit("incomplete or non-finite forecast grid")
    args.output.parent.mkdir(parents=True, exist_ok=True)
    out.to_csv(args.output, index=False, lineterminator="\n")
    print(f"Wrote {len(out):,} {MODEL} forecasts (origin {ORIGIN}) to {args.output}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())