| """eval_formula.py — the shared evaluation core. |
| |
| Runs ONE formula module over the test set and returns raw metrics, both |
| per-cluster and pooled. This is the common engine called by evaluate.py |
| (on each reference baseline and on a submitted formula.py). |
| |
| A formula module must expose the v2 contract: |
| USED_INPUTS, LAW_CONSTANTS, OTHER_CONSTANTS, LOCAL_FITTABLE, |
| predict(X, **params) and (Type II) fit(X_fit, y_fit, **law_constants). |
| |
| `run_formula` performs NO score normalisation and NO judging — it only |
| executes the formula and measures error. The reference-relative score |
| and the judge channels live in evaluate.py. |
| """ |
| from __future__ import annotations |
|
|
| import csv |
| import random |
| import signal |
| import time |
| from pathlib import Path |
|
|
| import numpy as np |
|
|
|
|
| |
| |
| |
|
|
| def load_csv(path: Path) -> tuple[list[str], list[list[str]]]: |
| with path.open("r", newline="") as fh: |
| reader = csv.reader(fh) |
| header = next(reader) |
| rows = [list(r) for r in reader] |
| return header, rows |
|
|
|
|
| def group_by_cluster(header: list[str], rows: list[list[str]]) -> dict[int, list[list[str]]]: |
| gid = header.index("group_id") |
| out: dict[int, list[list[str]]] = {} |
| for r in rows: |
| out.setdefault(int(float(r[gid])), []).append(r) |
| return out |
|
|
|
|
| def load_clusters(task_root: Path) -> dict: |
| """Type II loader. Load test_fit.csv + test_test.csv, grouped by cluster. |
| |
| Returns a dict with: fit_header, test_header, fit_by_cluster, |
| test_by_cluster, cluster_ids (sorted, present in both). |
| """ |
| fit_header, fit_rows = load_csv(task_root / "data" / "test_fit.csv") |
| test_header, test_rows = load_csv(task_root / "data" / "test_test.csv") |
| fit_by_cluster = group_by_cluster(fit_header, fit_rows) |
| test_by_cluster = group_by_cluster(test_header, test_rows) |
| cluster_ids = sorted(set(fit_by_cluster) & set(test_by_cluster)) |
| return { |
| "fit_header": fit_header, "test_header": test_header, |
| "fit_by_cluster": fit_by_cluster, "test_by_cluster": test_by_cluster, |
| "cluster_ids": cluster_ids, |
| } |
|
|
|
|
| def load_flat(task_root: Path) -> dict: |
| """Type I loader. Load train.csv + test.csv as flat tables (no clusters). |
| |
| The reference / submission formulas predict directly on test.csv. |
| train.csv is carried for completeness (the SR system trains on it) but |
| the v2 score does not use it — there is no naive baseline. |
| """ |
| train_header, train_rows = load_csv(task_root / "data" / "train.csv") |
| test_header, test_rows = load_csv(task_root / "data" / "test.csv") |
| return { |
| "train_header": train_header, "train_rows": train_rows, |
| "test_header": test_header, "test_rows": test_rows, |
| } |
|
|
|
|
| |
| |
| |
|
|
| def _to_array(rows: list[list[str]], header: list[str], cols: list[str]) -> np.ndarray: |
| idx = [header.index(c) for c in cols] |
| return np.array([[float(row[i]) for i in idx] for row in rows], dtype=float) |
|
|
|
|
| def _col(rows: list[list[str]], header: list[str], name: str) -> np.ndarray: |
| i = header.index(name) |
| return np.array([float(r[i]) for r in rows], dtype=float) |
|
|
|
|
| def metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict: |
| """Full metric menu so any task-declared `metric` can be selected later.""" |
| y_true = np.asarray(y_true, dtype=float) |
| y_pred = np.asarray(y_pred, dtype=float) |
| mask = np.isfinite(y_pred) & np.isfinite(y_true) |
| n = int(mask.sum()) |
| if n == 0: |
| return {"rmse": None, "mae": None, "mse": None, "r2": None, "smape": None, "n_finite": 0} |
| yt, yp = y_true[mask], y_pred[mask] |
| err = yp - yt |
| mse = float(np.mean(err ** 2)) |
| rmse = float(np.sqrt(mse)) |
| mae = float(np.mean(np.abs(err))) |
| ss_tot = float(np.sum((yt - yt.mean()) ** 2)) |
| r2 = float(1.0 - float(np.sum(err ** 2)) / ss_tot) if ss_tot > 0 else None |
| denom = (np.abs(yt) + np.abs(yp)) / 2.0 |
| safe = denom > 0 |
| smape = (float(np.mean(np.where(safe, np.abs(err) / np.where(safe, denom, 1.0), 0.0))) |
| if safe.any() else None) |
| return {"rmse": rmse, "mae": mae, "mse": mse, "r2": r2, "smape": smape, "n_finite": n} |
|
|
|
|
| class _Timeout(Exception): |
| pass |
|
|
|
|
| def _timeout_handler(signum, frame): |
| raise _Timeout() |
|
|
|
|
| |
| |
| |
|
|
| def run_formula(mod, clusters: dict, target_name: str, |
| fit_timeout_seconds: int | None = None, |
| seed: int | None = None) -> dict: |
| """Execute one formula module over every test cluster. |
| |
| `seed`, if given, fixes the global NumPy / Python RNG before the run so |
| a stochastic submission `fit()` is reproducible. evaluate.py runs each |
| Type II submission under several seeds and reports mean / std. |
| |
| Returns: |
| { |
| "per_cluster": {cid: {"metrics": {...}, "failed": bool, "error": str|None}}, |
| "pooled": {...metrics over all clusters' test rows...}, |
| "n_clusters_fitted": int, |
| "n_clusters_failed": int, |
| "max_fit_seconds": float, # slowest per-cluster fit() wall-time |
| } |
| |
| A cluster is `failed` if fit() raises / times out, or predict() returns |
| non-finite. Failed clusters are excluded from the pooled metric here; |
| the reference-relative score for failed clusters is evaluate.py's job. |
| `max_fit_seconds` lets evaluate.py derive the fit_timeout cap from the |
| reference bank's measured fit cost. |
| """ |
| fit_header = clusters["fit_header"] |
| test_header = clusters["test_header"] |
| fit_by_cluster = clusters["fit_by_cluster"] |
| test_by_cluster = clusters["test_by_cluster"] |
| cluster_ids = clusters["cluster_ids"] |
|
|
| if seed is not None: |
| np.random.seed(seed) |
| random.seed(seed) |
|
|
| used = list(mod.USED_INPUTS) |
| LAW = dict(mod.LAW_CONSTANTS) |
| is_type_ii = bool(mod.LOCAL_FITTABLE) |
|
|
| per_cluster: dict[int, dict] = {} |
| pooled_pred, pooled_true = [], [] |
| n_failed = 0 |
| max_fit_seconds = 0.0 |
|
|
| for cid in cluster_ids: |
| fr = fit_by_cluster[cid] |
| tr = test_by_cluster[cid] |
| try: |
| if used: |
| X_fit = _to_array(fr, fit_header, used) |
| X_test = _to_array(tr, test_header, used) |
| else: |
| X_fit = np.zeros((len(fr), 0), dtype=float) |
| X_test = np.zeros((len(tr), 0), dtype=float) |
| y_fit = _col(fr, fit_header, target_name) |
| y_test = _col(tr, test_header, target_name) |
|
|
| if is_type_ii: |
| if fit_timeout_seconds: |
| signal.signal(signal.SIGALRM, _timeout_handler) |
| signal.alarm(int(fit_timeout_seconds)) |
| t0 = time.perf_counter() |
| try: |
| local = mod.fit(X_fit, y_fit, **LAW) |
| finally: |
| if fit_timeout_seconds: |
| signal.alarm(0) |
| max_fit_seconds = max(max_fit_seconds, time.perf_counter() - t0) |
| else: |
| local = {} |
|
|
| y_pred = np.asarray(mod.predict(X_test, **LAW, **local), dtype=float) |
| if not np.all(np.isfinite(y_pred)): |
| raise RuntimeError("predict returned non-finite values") |
|
|
| m = metrics(y_test, y_pred) |
| per_cluster[cid] = {"metrics": m, "failed": False, "error": None} |
| pooled_pred.append(y_pred) |
| pooled_true.append(y_test) |
| except _Timeout: |
| n_failed += 1 |
| per_cluster[cid] = {"metrics": None, "failed": True, |
| "error": f"fit() exceeded {fit_timeout_seconds}s"} |
| except Exception as exc: |
| n_failed += 1 |
| per_cluster[cid] = {"metrics": None, "failed": True, |
| "error": f"{type(exc).__name__}: {exc}"} |
|
|
| pooled = (metrics(np.concatenate(pooled_true), np.concatenate(pooled_pred)) |
| if pooled_pred else None) |
|
|
| return { |
| "per_cluster": per_cluster, |
| "pooled": pooled, |
| "n_clusters_fitted": len(cluster_ids) - n_failed, |
| "n_clusters_failed": n_failed, |
| "max_fit_seconds": max_fit_seconds, |
| } |
|
|
|
|
| |
| |
| |
|
|
| def run_formula_flat(mod, flat: dict, target_name: str) -> dict: |
| """Execute one Type I formula on the flat test set. |
| |
| Type I: LOCAL_FITTABLE is empty, there is no fit() — predict() is called |
| once on the whole test set with only LAW_CONSTANTS. |
| |
| Returns: |
| {"pooled": {...metrics...} | None, "failed": bool, "error": str|None} |
| """ |
| test_header = flat["test_header"] |
| test_rows = flat["test_rows"] |
| used = list(mod.USED_INPUTS) |
| LAW = dict(mod.LAW_CONSTANTS) |
|
|
| try: |
| X_test = (_to_array(test_rows, test_header, used) if used |
| else np.zeros((len(test_rows), 0), dtype=float)) |
| y_test = _col(test_rows, test_header, target_name) |
| y_pred = np.asarray(mod.predict(X_test, **LAW), dtype=float) |
| if not np.all(np.isfinite(y_pred)): |
| raise RuntimeError("predict returned non-finite values") |
| return {"pooled": metrics(y_test, y_pred), "failed": False, "error": None} |
| except Exception as exc: |
| return {"pooled": None, "failed": True, |
| "error": f"{type(exc).__name__}: {exc}"} |
|
|