Download code/eo_gate.py from Tonic/protostar-climate-2026: direct link, hf CLI and curl.
- Browser
- Download file 4.55 kB
-
https://huggingface.co/datasets/Tonic/protostar-climate-2026/resolve/main/code/eo_gate.py
- Command line
-
hf download hf://datasets/Tonic/protostar-climate-2026/code/eo_gate.py
-
curl -L -o eo_gate.py https://huggingface.co/datasets/Tonic/protostar-climate-2026/resolve/main/code/eo_gate.py
4.55 kB
| """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() | |