| import argparse |
| import json |
| import pandas as pd |
| from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score |
|
|
|
|
| ALLOWED_SPLITS = { |
| "train", |
| "in_domain_test", |
| "boundary_trap", |
| "distribution_shift", |
| "counterfactual_intervention" |
| } |
|
|
| ALLOWED_TRAPS = { |
| "false_stability", |
| "boundary_masking", |
| "trajectory_aliasing", |
| "temporal_alias", |
| "intervention_decoy" |
| } |
|
|
| ALLOWED_DIFFICULTY = { |
| "easy", |
| "medium", |
| "hard" |
| } |
|
|
| LOW_BOUNDARY_THRESHOLD = 0.10 |
| HIGH_DRIFT_THRESHOLD = 0.05 |
|
|
|
|
| def load_csv(path): |
| return pd.read_csv(path) |
|
|
|
|
| def validate_columns(preds, truth): |
|
|
| if "scenario_id" not in preds.columns or "prediction" not in preds.columns: |
| raise ValueError("Predictions must contain scenario_id and prediction columns") |
|
|
| required_truth = { |
| "scenario_id", |
| "split_type", |
| "pair_id", |
| "pair_role", |
| "difficulty_level", |
| "pressure_obs_t0", |
| "pressure_obs_t1", |
| "pressure_obs_t2", |
| "buffer_obs_t0", |
| "buffer_obs_t1", |
| "buffer_obs_t2", |
| "true_label", |
| "trap_type", |
| "trap_active", |
| "boundary_distance", |
| "drift_gradient", |
| "drift_acceleration", |
| "recovery_feasibility", |
| "regime_competition_ratio", |
| "intervention_action", |
| "intervention_magnitude", |
| "boundary_distance_before", |
| "boundary_distance_after", |
| "intervention_effect_direction" |
| } |
|
|
| missing = required_truth - set(truth.columns) |
|
|
| if missing: |
| raise ValueError(f"Truth missing required columns: {sorted(missing)}") |
|
|
|
|
| def validate_values(preds, truth): |
|
|
| bad_pred = set(preds["prediction"].dropna().unique()) - {0, 1} |
| if bad_pred: |
| raise ValueError("Predictions must contain only 0 or 1") |
|
|
| bad_label = set(truth["true_label"].dropna().unique()) - {0, 1} |
| if bad_label: |
| raise ValueError("true_label must contain only 0 or 1") |
|
|
| bad_trap = set(truth["trap_active"].dropna().unique()) - {0, 1} |
| if bad_trap: |
| raise ValueError("trap_active must contain only 0 or 1") |
|
|
| unknown_splits = set(truth["split_type"].dropna().unique()) - ALLOWED_SPLITS |
| if unknown_splits: |
| raise ValueError(f"Unknown split_type values: {sorted(unknown_splits)}") |
|
|
| trap_values = set(truth["trap_type"].dropna().unique()) |
| unknown_traps = trap_values - ALLOWED_TRAPS |
| if unknown_traps: |
| raise ValueError(f"Unknown trap_type values: {sorted(unknown_traps)}") |
|
|
| unknown_difficulty = set(truth["difficulty_level"].dropna().unique()) - ALLOWED_DIFFICULTY |
| if unknown_difficulty: |
| raise ValueError(f"Unknown difficulty_level values: {sorted(unknown_difficulty)}") |
|
|
| if "intervention_effect_direction" in preds.columns: |
| bad_dir = set(preds["intervention_effect_direction"].dropna().unique()) - {-1, 0, 1} |
| if bad_dir: |
| raise ValueError("Predicted intervention_effect_direction must be one of -1, 0, 1") |
|
|
| valid_pair_roles = {"safe_pair", "unstable_pair"} |
| pair_roles = set(truth["pair_role"].dropna().unique()) - valid_pair_roles |
| if pair_roles: |
| raise ValueError(f"Unknown pair_role values: {sorted(pair_roles)}") |
|
|
|
|
| def validate_ids(df, name): |
|
|
| if df["scenario_id"].isna().any(): |
| raise ValueError(f"{name} contains missing scenario_id values") |
|
|
| ids = df["scenario_id"].astype(str).str.strip() |
|
|
| if (ids == "").any(): |
| raise ValueError(f"{name} contains blank scenario_id values") |
|
|
| if ids.duplicated().any(): |
| dupes = ids[ids.duplicated()].unique().tolist() |
| raise ValueError(f"{name} duplicate scenario_id values: {dupes[:10]}") |
|
|
| df = df.copy() |
| df["scenario_id"] = ids |
|
|
| return df |
|
|
|
|
| def compute_basic_metrics(y_true, y_pred): |
|
|
| return { |
| "accuracy": float(accuracy_score(y_true, y_pred)), |
| "precision": float(precision_score(y_true, y_pred, zero_division=0)), |
| "recall": float(recall_score(y_true, y_pred, zero_division=0)), |
| "f1": float(f1_score(y_true, y_pred, zero_division=0)), |
| "rows_evaluated": int(len(y_true)) |
| } |
|
|
|
|
| def compute_split_accuracy(df, split_name): |
|
|
| subset = df[df["split_type"] == split_name] |
|
|
| if subset.empty: |
| return None |
|
|
| return float(accuracy_score(subset["true_label"], subset["prediction"])) |
|
|
|
|
| def compute_trap_accuracy(df, trap_type=None): |
|
|
| subset = df[df["trap_active"] == 1] |
|
|
| if trap_type: |
| subset = subset[subset["trap_type"] == trap_type] |
|
|
| if subset.empty: |
| return None |
|
|
| return float(accuracy_score(subset["true_label"], subset["prediction"])) |
|
|
|
|
| def compute_difficulty_accuracy(df, difficulty_level): |
|
|
| subset = df[df["difficulty_level"] == difficulty_level] |
|
|
| if subset.empty: |
| return None |
|
|
| return float(accuracy_score(subset["true_label"], subset["prediction"])) |
|
|
|
|
| def compute_geometry_diagnostics(df): |
|
|
| results = {} |
|
|
| low_boundary = df[ |
| (df["true_label"] == 1) & |
| (df["boundary_distance"] <= LOW_BOUNDARY_THRESHOLD) |
| ] |
|
|
| if low_boundary.empty: |
| results["low_boundary_distance_miss_rate"] = None |
| else: |
| misses = (low_boundary["prediction"] == 0).sum() |
| results["low_boundary_distance_miss_rate"] = float(misses / len(low_boundary)) |
|
|
| high_drift = df[ |
| (df["true_label"] == 1) & |
| (df["drift_gradient"] >= HIGH_DRIFT_THRESHOLD) |
| ] |
|
|
| if high_drift.empty: |
| results["high_drift_gradient_miss_rate"] = None |
| else: |
| misses = (high_drift["prediction"] == 0).sum() |
| results["high_drift_gradient_miss_rate"] = float(misses / len(high_drift)) |
|
|
| return results |
|
|
|
|
| def compute_counterfactual_metrics(df): |
|
|
| results = { |
| "counterfactual_intervention_accuracy": None, |
| "intervention_effect_direction_accuracy": None |
| } |
|
|
| subset = df[df["split_type"] == "counterfactual_intervention"] |
|
|
| if subset.empty: |
| return results |
|
|
| results["counterfactual_intervention_accuracy"] = float( |
| accuracy_score(subset["true_label"], subset["prediction"]) |
| ) |
|
|
| if "predicted_intervention_effect_direction" in subset.columns: |
| valid = subset.dropna(subset=["intervention_effect_direction", "predicted_intervention_effect_direction"]) |
|
|
| if not valid.empty: |
| results["intervention_effect_direction_accuracy"] = float( |
| accuracy_score( |
| valid["intervention_effect_direction"], |
| valid["predicted_intervention_effect_direction"] |
| ) |
| ) |
|
|
| return results |
|
|
|
|
| def compute_pair_discrimination_accuracy(df): |
|
|
| paired = df[df["pair_id"].notna()].copy() |
|
|
| if paired.empty: |
| return None |
|
|
| correct = 0 |
| total = 0 |
|
|
| for pair_id, group in paired.groupby("pair_id"): |
| if len(group) != 2: |
| continue |
|
|
| roles = set(group["pair_role"]) |
| if roles != {"safe_pair", "unstable_pair"}: |
| continue |
|
|
| unstable_row = group[group["pair_role"] == "unstable_pair"].iloc[0] |
| safe_row = group[group["pair_role"] == "safe_pair"].iloc[0] |
|
|
| ok = (unstable_row["prediction"] == 1) and (safe_row["prediction"] == 0) |
|
|
| correct += int(ok) |
| total += 1 |
|
|
| if total == 0: |
| return None |
|
|
| return float(correct / total) |
|
|
|
|
| def compute_support_counts(df): |
|
|
| return { |
| "train_support": int((df["split_type"] == "train").sum()), |
| "in_domain_test_support": int((df["split_type"] == "in_domain_test").sum()), |
| "boundary_trap_support": int((df["split_type"] == "boundary_trap").sum()), |
| "distribution_shift_support": int((df["split_type"] == "distribution_shift").sum()), |
| "counterfactual_intervention_support": int((df["split_type"] == "counterfactual_intervention").sum()), |
| "trap_support": int((df["trap_active"] == 1).sum()) |
| } |
|
|
|
|
| def compute_casses_score(results): |
|
|
| weights = { |
| "in_domain_test_accuracy": 0.18, |
| "boundary_trap_accuracy": 0.20, |
| "distribution_shift_accuracy": 0.17, |
| "trap_accuracy": 0.15, |
| "counterfactual_intervention_accuracy": 0.15, |
| "trajectory_pair_discrimination_accuracy": 0.15 |
| } |
|
|
| score = 0 |
| weight_sum = 0 |
|
|
| for metric, weight in weights.items(): |
| value = results.get(metric) |
| if value is not None: |
| score += value * weight |
| weight_sum += weight |
|
|
| if weight_sum == 0: |
| return None |
|
|
| return score / weight_sum |
|
|
|
|
| def score(predictions_path, truth_path): |
|
|
| preds = load_csv(predictions_path) |
| truth = load_csv(truth_path) |
|
|
| validate_columns(preds, truth) |
| validate_values(preds, truth) |
|
|
| preds = validate_ids(preds, "Predictions") |
| truth = validate_ids(truth, "Truth") |
|
|
| if "intervention_effect_direction" in preds.columns: |
| preds = preds.rename(columns={ |
| "intervention_effect_direction": "predicted_intervention_effect_direction" |
| }) |
|
|
| pred_ids = set(preds["scenario_id"]) |
| truth_ids = set(truth["scenario_id"]) |
|
|
| if pred_ids != truth_ids: |
| missing = sorted(list(truth_ids - pred_ids))[:10] |
| extra = sorted(list(pred_ids - truth_ids))[:10] |
| raise ValueError( |
| f"scenario_id mismatch. Missing in predictions: {missing}. Extra in predictions: {extra}" |
| ) |
|
|
| merged = truth.merge(preds, on="scenario_id", how="inner", validate="one_to_one") |
| merged = merged.sort_values("scenario_id").reset_index(drop=True) |
|
|
| y_true = merged["true_label"] |
| y_pred = merged["prediction"] |
|
|
| results = compute_basic_metrics(y_true, y_pred) |
|
|
| results["train_accuracy"] = compute_split_accuracy(merged, "train") |
| results["in_domain_test_accuracy"] = compute_split_accuracy(merged, "in_domain_test") |
| results["boundary_trap_accuracy"] = compute_split_accuracy(merged, "boundary_trap") |
| results["distribution_shift_accuracy"] = compute_split_accuracy(merged, "distribution_shift") |
|
|
| results["trap_accuracy"] = compute_trap_accuracy(merged) |
| results["false_stability_accuracy"] = compute_trap_accuracy(merged, "false_stability") |
| results["boundary_masking_accuracy"] = compute_trap_accuracy(merged, "boundary_masking") |
| results["trajectory_aliasing_accuracy"] = compute_trap_accuracy(merged, "trajectory_aliasing") |
| results["temporal_alias_accuracy"] = compute_trap_accuracy(merged, "temporal_alias") |
| results["intervention_decoy_accuracy"] = compute_trap_accuracy(merged, "intervention_decoy") |
|
|
| results["easy_accuracy"] = compute_difficulty_accuracy(merged, "easy") |
| results["medium_accuracy"] = compute_difficulty_accuracy(merged, "medium") |
| results["hard_accuracy"] = compute_difficulty_accuracy(merged, "hard") |
|
|
| indomain = results["in_domain_test_accuracy"] |
| shift = results["distribution_shift_accuracy"] |
|
|
| if indomain is not None and shift is not None: |
| results["manifold_generalization_gap"] = float(indomain - shift) |
| else: |
| results["manifold_generalization_gap"] = None |
|
|
| results.update(compute_geometry_diagnostics(merged)) |
| results.update(compute_counterfactual_metrics(merged)) |
| results["trajectory_pair_discrimination_accuracy"] = compute_pair_discrimination_accuracy(merged) |
| results.update(compute_support_counts(merged)) |
| results["casses_score"] = compute_casses_score(results) |
|
|
| return results |
|
|
|
|
| def main(): |
|
|
| parser = argparse.ArgumentParser() |
| parser.add_argument("--predictions", required=True) |
| parser.add_argument("--truth", required=True) |
|
|
| args = parser.parse_args() |
|
|
| results = score(args.predictions, args.truth) |
|
|
| print(json.dumps(results, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |