File size: 4,549 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
101
102
"""Pre-registered gate for the EO branch.



Question: does the static OlmoEarth-2018 city embedding add information --

beyond lat/lon (+elevation-free geography) -- about (a) city climate normals

1989-2018 and (b) city trend slopes, in leave-cities-out CV?



Gate (fixed): EO ships only if, for annual_avg_temp or cdd slopes, the

lat/lon+EO model beats lat/lon-only MAE by >=3% in 5-fold city CV.

Otherwise the EO branch is dropped and reported as a negative result.

"""
from __future__ import annotations

import json
import sys
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.linear_model import Ridge
from sklearn.model_selection import KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

sys.path.insert(0, str(Path(__file__).parent))
from dataset import (METRIC_COLUMNS, add_validity, download, load_annual,
                     load_coverage, long_valid)
from models import _ols_slope


def city_stats(long_df: pd.DataFrame) -> pd.DataFrame:
    rows = []
    for (city, metric), g in long_df.groupby(["city_id", "metric"]):
        w = g[(g["Year"] >= 1989) & (g["Year"] <= 2018)]
        if len(w) < 10:
            continue
        rows.append({"city_id": city, "metric": metric,
                     "normal": float(w["value"].mean()),
                     "slope": _ols_slope(w["Year"].to_numpy(float),
                                         w["value"].to_numpy(float)),
                     "Lat": float(g["Lat"].iloc[0]), "Lon": float(g["Lon"].iloc[0])})
    wide = pd.DataFrame(rows).pivot(index="city_id", columns="metric",
                                    values=["normal", "slope"])
    wide.columns = [f"{a}_{b}" for a, b in wide.columns]
    geo = pd.DataFrame(rows).drop_duplicates("city_id").set_index("city_id")[["Lat", "Lon"]]
    return wide.join(geo).reset_index()


def cv_mae(X: np.ndarray, y: np.ndarray, seed: int = 0) -> float:
    kf = KFold(5, shuffle=True, random_state=seed)
    errs = []
    for tr, te in kf.split(X):
        m = make_pipeline(StandardScaler(), Ridge(alpha=10.0))
        m.fit(X[tr], y[tr])
        errs.append(np.abs(m.predict(X[te]) - y[te]).mean())
    return float(np.mean(errs))


def main() -> None:
    root = Path(__file__).resolve().parent.parent
    emb_path = root / "outputs" / "eo" / "city_embeddings.csv"
    if not emb_path.exists():
        raise SystemExit("run eo_model.py first")
    emb = pd.read_csv(emb_path, dtype={"city_id": str})
    data_root = download(root / "data" / "_source")
    annual = add_validity(load_annual(data_root), load_coverage(data_root))
    stats = city_stats(long_valid(annual))
    df = stats.merge(emb, on="city_id", how="inner")
    print(f"gate sample: {len(df)} cities with embeddings + stats")
    emb_cols = [c for c in emb.columns if c.startswith("emb_")]

    # PCA to 8 dims on all cities (descriptor compression; target-free).
    pca = PCA(n_components=min(8, len(emb_cols)))
    pcs = pca.fit_transform(StandardScaler().fit_transform(df[emb_cols]))
    for i in range(pcs.shape[1]):
        df[f"pc{i}"] = pcs[:, i]

    targets = [f"normal_{m}" for m in METRIC_COLUMNS] + \
              [f"slope_{m}" for m in METRIC_COLUMNS]
    results = {}
    for t in targets:
        sub = df.dropna(subset=[t])
        geo = sub[["Lat", "Lon"]].to_numpy()
        geo_poly = np.column_stack([geo, geo ** 2, geo[:, :1] * geo[:, 1:]])
        both = np.column_stack([geo_poly, sub[[f"pc{i}" for i in range(pcs.shape[1])]].to_numpy()])
        mae_geo, mae_both = cv_mae(geo_poly, sub[t].to_numpy()), cv_mae(both, sub[t].to_numpy())
        results[t] = {"mae_latlon": mae_geo, "mae_latlon_plus_eo": mae_both,
                      "improvement_pct": 100 * (mae_geo - mae_both) / mae_geo, "n": len(sub)}
        print(f"{t:28s} lat/lon MAE {mae_geo:9.3f}  +EO {mae_both:9.3f}  "
              f"({results[t]['improvement_pct']:+.1f}%)")

    gate_targets = ["slope_annual_avg_temp", "slope_cdd"]
    passed = any(results[t]["improvement_pct"] >= 3.0 for t in gate_targets)
    decision = {"gate_passed": bool(passed), "gate": ">=3% MAE improvement on temp or cdd slope",
                "results": results}
    (root / "outputs" / "eo" / "gate_decision.json").write_text(json.dumps(decision, indent=2))
    print("\nEO GATE:", "PASS" if passed else "FAIL (EO dropped; negative result)")


if __name__ == "__main__":
    main()