ClarusC64 commited on
Commit
bc895d6
·
verified ·
1 Parent(s): 86a9733

Create scorer.py

Browse files
Files changed (1) hide show
  1. scorer.py +387 -0
scorer.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import pandas as pd
4
+ from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
5
+
6
+
7
+ ALLOWED_SPLITS = {
8
+ "train",
9
+ "in_domain_test",
10
+ "boundary_trap",
11
+ "distribution_shift",
12
+ "counterfactual_intervention"
13
+ }
14
+
15
+ ALLOWED_TRAPS = {
16
+ "false_stability",
17
+ "boundary_masking",
18
+ "trajectory_aliasing",
19
+ "temporal_alias",
20
+ "intervention_decoy"
21
+ }
22
+
23
+ ALLOWED_DIFFICULTY = {
24
+ "easy",
25
+ "medium",
26
+ "hard"
27
+ }
28
+
29
+ LOW_BOUNDARY_THRESHOLD = 0.10
30
+ HIGH_DRIFT_THRESHOLD = 0.05
31
+
32
+
33
+ def load_csv(path):
34
+ return pd.read_csv(path)
35
+
36
+
37
+ def validate_columns(preds, truth):
38
+
39
+ if "scenario_id" not in preds.columns or "prediction" not in preds.columns:
40
+ raise ValueError("Predictions must contain scenario_id and prediction columns")
41
+
42
+ required_truth = {
43
+ "scenario_id",
44
+ "split_type",
45
+ "pair_id",
46
+ "pair_role",
47
+ "difficulty_level",
48
+ "pressure_obs_t0",
49
+ "pressure_obs_t1",
50
+ "pressure_obs_t2",
51
+ "buffer_obs_t0",
52
+ "buffer_obs_t1",
53
+ "buffer_obs_t2",
54
+ "true_label",
55
+ "trap_type",
56
+ "trap_active",
57
+ "boundary_distance",
58
+ "drift_gradient",
59
+ "drift_acceleration",
60
+ "recovery_feasibility",
61
+ "regime_competition_ratio",
62
+ "intervention_action",
63
+ "intervention_magnitude",
64
+ "boundary_distance_before",
65
+ "boundary_distance_after",
66
+ "intervention_effect_direction"
67
+ }
68
+
69
+ missing = required_truth - set(truth.columns)
70
+
71
+ if missing:
72
+ raise ValueError(f"Truth missing required columns: {sorted(missing)}")
73
+
74
+
75
+ def validate_values(preds, truth):
76
+
77
+ bad_pred = set(preds["prediction"].dropna().unique()) - {0, 1}
78
+ if bad_pred:
79
+ raise ValueError("Predictions must contain only 0 or 1")
80
+
81
+ bad_label = set(truth["true_label"].dropna().unique()) - {0, 1}
82
+ if bad_label:
83
+ raise ValueError("true_label must contain only 0 or 1")
84
+
85
+ bad_trap = set(truth["trap_active"].dropna().unique()) - {0, 1}
86
+ if bad_trap:
87
+ raise ValueError("trap_active must contain only 0 or 1")
88
+
89
+ unknown_splits = set(truth["split_type"].dropna().unique()) - ALLOWED_SPLITS
90
+ if unknown_splits:
91
+ raise ValueError(f"Unknown split_type values: {sorted(unknown_splits)}")
92
+
93
+ trap_values = set(truth["trap_type"].dropna().unique())
94
+ unknown_traps = trap_values - ALLOWED_TRAPS
95
+ if unknown_traps:
96
+ raise ValueError(f"Unknown trap_type values: {sorted(unknown_traps)}")
97
+
98
+ unknown_difficulty = set(truth["difficulty_level"].dropna().unique()) - ALLOWED_DIFFICULTY
99
+ if unknown_difficulty:
100
+ raise ValueError(f"Unknown difficulty_level values: {sorted(unknown_difficulty)}")
101
+
102
+ if "intervention_effect_direction" in preds.columns:
103
+ bad_dir = set(preds["intervention_effect_direction"].dropna().unique()) - {-1, 0, 1}
104
+ if bad_dir:
105
+ raise ValueError("Predicted intervention_effect_direction must be one of -1, 0, 1")
106
+
107
+ valid_pair_roles = {"safe_pair", "unstable_pair"}
108
+ pair_roles = set(truth["pair_role"].dropna().unique()) - valid_pair_roles
109
+ if pair_roles:
110
+ raise ValueError(f"Unknown pair_role values: {sorted(pair_roles)}")
111
+
112
+
113
+ def validate_ids(df, name):
114
+
115
+ if df["scenario_id"].isna().any():
116
+ raise ValueError(f"{name} contains missing scenario_id values")
117
+
118
+ ids = df["scenario_id"].astype(str).str.strip()
119
+
120
+ if (ids == "").any():
121
+ raise ValueError(f"{name} contains blank scenario_id values")
122
+
123
+ if ids.duplicated().any():
124
+ dupes = ids[ids.duplicated()].unique().tolist()
125
+ raise ValueError(f"{name} duplicate scenario_id values: {dupes[:10]}")
126
+
127
+ df = df.copy()
128
+ df["scenario_id"] = ids
129
+
130
+ return df
131
+
132
+
133
+ def compute_basic_metrics(y_true, y_pred):
134
+
135
+ return {
136
+ "accuracy": float(accuracy_score(y_true, y_pred)),
137
+ "precision": float(precision_score(y_true, y_pred, zero_division=0)),
138
+ "recall": float(recall_score(y_true, y_pred, zero_division=0)),
139
+ "f1": float(f1_score(y_true, y_pred, zero_division=0)),
140
+ "rows_evaluated": int(len(y_true))
141
+ }
142
+
143
+
144
+ def compute_split_accuracy(df, split_name):
145
+
146
+ subset = df[df["split_type"] == split_name]
147
+
148
+ if subset.empty:
149
+ return None
150
+
151
+ return float(accuracy_score(subset["true_label"], subset["prediction"]))
152
+
153
+
154
+ def compute_trap_accuracy(df, trap_type=None):
155
+
156
+ subset = df[df["trap_active"] == 1]
157
+
158
+ if trap_type:
159
+ subset = subset[subset["trap_type"] == trap_type]
160
+
161
+ if subset.empty:
162
+ return None
163
+
164
+ return float(accuracy_score(subset["true_label"], subset["prediction"]))
165
+
166
+
167
+ def compute_difficulty_accuracy(df, difficulty_level):
168
+
169
+ subset = df[df["difficulty_level"] == difficulty_level]
170
+
171
+ if subset.empty:
172
+ return None
173
+
174
+ return float(accuracy_score(subset["true_label"], subset["prediction"]))
175
+
176
+
177
+ def compute_geometry_diagnostics(df):
178
+
179
+ results = {}
180
+
181
+ low_boundary = df[
182
+ (df["true_label"] == 1) &
183
+ (df["boundary_distance"] <= LOW_BOUNDARY_THRESHOLD)
184
+ ]
185
+
186
+ if low_boundary.empty:
187
+ results["low_boundary_distance_miss_rate"] = None
188
+ else:
189
+ misses = (low_boundary["prediction"] == 0).sum()
190
+ results["low_boundary_distance_miss_rate"] = float(misses / len(low_boundary))
191
+
192
+ high_drift = df[
193
+ (df["true_label"] == 1) &
194
+ (df["drift_gradient"] >= HIGH_DRIFT_THRESHOLD)
195
+ ]
196
+
197
+ if high_drift.empty:
198
+ results["high_drift_gradient_miss_rate"] = None
199
+ else:
200
+ misses = (high_drift["prediction"] == 0).sum()
201
+ results["high_drift_gradient_miss_rate"] = float(misses / len(high_drift))
202
+
203
+ return results
204
+
205
+
206
+ def compute_counterfactual_metrics(df):
207
+
208
+ results = {
209
+ "counterfactual_intervention_accuracy": None,
210
+ "intervention_effect_direction_accuracy": None
211
+ }
212
+
213
+ subset = df[df["split_type"] == "counterfactual_intervention"]
214
+
215
+ if subset.empty:
216
+ return results
217
+
218
+ results["counterfactual_intervention_accuracy"] = float(
219
+ accuracy_score(subset["true_label"], subset["prediction"])
220
+ )
221
+
222
+ if "predicted_intervention_effect_direction" in subset.columns:
223
+ valid = subset.dropna(subset=["intervention_effect_direction", "predicted_intervention_effect_direction"])
224
+
225
+ if not valid.empty:
226
+ results["intervention_effect_direction_accuracy"] = float(
227
+ accuracy_score(
228
+ valid["intervention_effect_direction"],
229
+ valid["predicted_intervention_effect_direction"]
230
+ )
231
+ )
232
+
233
+ return results
234
+
235
+
236
+ def compute_pair_discrimination_accuracy(df):
237
+
238
+ paired = df[df["pair_id"].notna()].copy()
239
+
240
+ if paired.empty:
241
+ return None
242
+
243
+ correct = 0
244
+ total = 0
245
+
246
+ for pair_id, group in paired.groupby("pair_id"):
247
+ if len(group) != 2:
248
+ continue
249
+
250
+ roles = set(group["pair_role"])
251
+ if roles != {"safe_pair", "unstable_pair"}:
252
+ continue
253
+
254
+ unstable_row = group[group["pair_role"] == "unstable_pair"].iloc[0]
255
+ safe_row = group[group["pair_role"] == "safe_pair"].iloc[0]
256
+
257
+ ok = (unstable_row["prediction"] == 1) and (safe_row["prediction"] == 0)
258
+
259
+ correct += int(ok)
260
+ total += 1
261
+
262
+ if total == 0:
263
+ return None
264
+
265
+ return float(correct / total)
266
+
267
+
268
+ def compute_support_counts(df):
269
+
270
+ return {
271
+ "train_support": int((df["split_type"] == "train").sum()),
272
+ "in_domain_test_support": int((df["split_type"] == "in_domain_test").sum()),
273
+ "boundary_trap_support": int((df["split_type"] == "boundary_trap").sum()),
274
+ "distribution_shift_support": int((df["split_type"] == "distribution_shift").sum()),
275
+ "counterfactual_intervention_support": int((df["split_type"] == "counterfactual_intervention").sum()),
276
+ "trap_support": int((df["trap_active"] == 1).sum())
277
+ }
278
+
279
+
280
+ def compute_casses_score(results):
281
+
282
+ weights = {
283
+ "in_domain_test_accuracy": 0.18,
284
+ "boundary_trap_accuracy": 0.20,
285
+ "distribution_shift_accuracy": 0.17,
286
+ "trap_accuracy": 0.15,
287
+ "counterfactual_intervention_accuracy": 0.15,
288
+ "trajectory_pair_discrimination_accuracy": 0.15
289
+ }
290
+
291
+ score = 0
292
+ weight_sum = 0
293
+
294
+ for metric, weight in weights.items():
295
+ value = results.get(metric)
296
+ if value is not None:
297
+ score += value * weight
298
+ weight_sum += weight
299
+
300
+ if weight_sum == 0:
301
+ return None
302
+
303
+ return score / weight_sum
304
+
305
+
306
+ def score(predictions_path, truth_path):
307
+
308
+ preds = load_csv(predictions_path)
309
+ truth = load_csv(truth_path)
310
+
311
+ validate_columns(preds, truth)
312
+ validate_values(preds, truth)
313
+
314
+ preds = validate_ids(preds, "Predictions")
315
+ truth = validate_ids(truth, "Truth")
316
+
317
+ if "intervention_effect_direction" in preds.columns:
318
+ preds = preds.rename(columns={
319
+ "intervention_effect_direction": "predicted_intervention_effect_direction"
320
+ })
321
+
322
+ pred_ids = set(preds["scenario_id"])
323
+ truth_ids = set(truth["scenario_id"])
324
+
325
+ if pred_ids != truth_ids:
326
+ missing = sorted(list(truth_ids - pred_ids))[:10]
327
+ extra = sorted(list(pred_ids - truth_ids))[:10]
328
+ raise ValueError(
329
+ f"scenario_id mismatch. Missing in predictions: {missing}. Extra in predictions: {extra}"
330
+ )
331
+
332
+ merged = truth.merge(preds, on="scenario_id", how="inner", validate="one_to_one")
333
+ merged = merged.sort_values("scenario_id").reset_index(drop=True)
334
+
335
+ y_true = merged["true_label"]
336
+ y_pred = merged["prediction"]
337
+
338
+ results = compute_basic_metrics(y_true, y_pred)
339
+
340
+ results["train_accuracy"] = compute_split_accuracy(merged, "train")
341
+ results["in_domain_test_accuracy"] = compute_split_accuracy(merged, "in_domain_test")
342
+ results["boundary_trap_accuracy"] = compute_split_accuracy(merged, "boundary_trap")
343
+ results["distribution_shift_accuracy"] = compute_split_accuracy(merged, "distribution_shift")
344
+
345
+ results["trap_accuracy"] = compute_trap_accuracy(merged)
346
+ results["false_stability_accuracy"] = compute_trap_accuracy(merged, "false_stability")
347
+ results["boundary_masking_accuracy"] = compute_trap_accuracy(merged, "boundary_masking")
348
+ results["trajectory_aliasing_accuracy"] = compute_trap_accuracy(merged, "trajectory_aliasing")
349
+ results["temporal_alias_accuracy"] = compute_trap_accuracy(merged, "temporal_alias")
350
+ results["intervention_decoy_accuracy"] = compute_trap_accuracy(merged, "intervention_decoy")
351
+
352
+ results["easy_accuracy"] = compute_difficulty_accuracy(merged, "easy")
353
+ results["medium_accuracy"] = compute_difficulty_accuracy(merged, "medium")
354
+ results["hard_accuracy"] = compute_difficulty_accuracy(merged, "hard")
355
+
356
+ indomain = results["in_domain_test_accuracy"]
357
+ shift = results["distribution_shift_accuracy"]
358
+
359
+ if indomain is not None and shift is not None:
360
+ results["manifold_generalization_gap"] = float(indomain - shift)
361
+ else:
362
+ results["manifold_generalization_gap"] = None
363
+
364
+ results.update(compute_geometry_diagnostics(merged))
365
+ results.update(compute_counterfactual_metrics(merged))
366
+ results["trajectory_pair_discrimination_accuracy"] = compute_pair_discrimination_accuracy(merged)
367
+ results.update(compute_support_counts(merged))
368
+ results["casses_score"] = compute_casses_score(results)
369
+
370
+ return results
371
+
372
+
373
+ def main():
374
+
375
+ parser = argparse.ArgumentParser()
376
+ parser.add_argument("--predictions", required=True)
377
+ parser.add_argument("--truth", required=True)
378
+
379
+ args = parser.parse_args()
380
+
381
+ results = score(args.predictions, args.truth)
382
+
383
+ print(json.dumps(results, indent=2))
384
+
385
+
386
+ if __name__ == "__main__":
387
+ main()