ClarusC64 commited on
Commit
1f5e033
·
verified ·
1 Parent(s): 4f03e06

Create scorer.py

Browse files
Files changed (1) hide show
  1. scorer.py +235 -0
scorer.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import json
3
+ import sys
4
+ from typing import Dict, List
5
+
6
+ K = 1.0
7
+ BOUNDARY_EPS = 0.02
8
+ HIGH_CONTENT_SCORE_THRESHOLD = 0.90
9
+
10
+ REQUIRED_PRED_COLUMNS = {"scenario_id", "prediction"}
11
+ REQUIRED_TRUTH_COLUMNS = {
12
+ "scenario_id",
13
+ "pressure",
14
+ "buffer",
15
+ "lag",
16
+ "coupling",
17
+ "content_score",
18
+ "label_stable",
19
+ }
20
+
21
+
22
+ def load_csv(path: str) -> List[Dict[str, str]]:
23
+ with open(path, newline="", encoding="utf-8") as f:
24
+ return list(csv.DictReader(f))
25
+
26
+
27
+ def validate_columns(rows: List[Dict[str, str]], required_cols: set, name: str) -> None:
28
+ if not rows:
29
+ raise ValueError(f"{name} file is empty")
30
+
31
+ cols = set(rows[0].keys())
32
+ missing = required_cols - cols
33
+ if missing:
34
+ raise ValueError(f"{name} missing required columns: {sorted(missing)}")
35
+
36
+
37
+ def index_by_id(rows: List[Dict[str, str]], id_col: str = "scenario_id") -> Dict[str, Dict[str, str]]:
38
+ index: Dict[str, Dict[str, str]] = {}
39
+
40
+ for row in rows:
41
+ sid = str(row.get(id_col, "")).strip()
42
+
43
+ if not sid:
44
+ raise ValueError("Blank or missing scenario_id detected")
45
+
46
+ if sid in index:
47
+ raise ValueError(f"Duplicate scenario_id detected: {sid}")
48
+
49
+ index[sid] = row
50
+
51
+ return index
52
+
53
+
54
+ def parse_binary(value: str, field_name: str, sid: str) -> int:
55
+ try:
56
+ parsed = int(value)
57
+ except ValueError as e:
58
+ raise ValueError(f"Invalid {field_name} for {sid}: {value}") from e
59
+
60
+ if parsed not in (0, 1):
61
+ raise ValueError(f"Invalid {field_name} for {sid}: {parsed}")
62
+
63
+ return parsed
64
+
65
+
66
+ def compute_surfaces(pressure: float, buffer: float, lag: float, coupling: float) -> Dict[str, float]:
67
+ s1 = buffer - (pressure * coupling) - (K * lag)
68
+ s2 = buffer - (pressure * (coupling ** 2)) - (K * lag)
69
+ s3 = buffer - (pressure * coupling) - (K * (lag ** 2))
70
+ return {
71
+ "baseline_surface": s1,
72
+ "coupling_surface": s2,
73
+ "lag_surface": s3,
74
+ }
75
+
76
+
77
+ def compute_manifold_margin(pressure: float, buffer: float, lag: float, coupling: float) -> float:
78
+ return min(compute_surfaces(pressure, buffer, lag, coupling).values())
79
+
80
+
81
+ def classify_region(manifold_margin: float) -> str:
82
+ if abs(manifold_margin) <= BOUNDARY_EPS:
83
+ return "near_boundary"
84
+ if manifold_margin < 0:
85
+ return "collapse_zone"
86
+ return "safe_margin"
87
+
88
+
89
+ def evaluate(pred_path: str, truth_path: str) -> Dict[str, object]:
90
+ preds = load_csv(pred_path)
91
+ truth = load_csv(truth_path)
92
+
93
+ validate_columns(preds, REQUIRED_PRED_COLUMNS, "prediction")
94
+ validate_columns(truth, REQUIRED_TRUTH_COLUMNS, "truth")
95
+
96
+ if len(preds) != len(truth):
97
+ raise ValueError("Prediction and truth row counts do not match")
98
+
99
+ pred_map = index_by_id(preds)
100
+ truth_map = index_by_id(truth)
101
+
102
+ if set(pred_map.keys()) != set(truth_map.keys()):
103
+ raise ValueError("scenario_id mismatch between prediction and truth files")
104
+
105
+ total = 0
106
+ correct = 0
107
+
108
+ false_rescue = 0
109
+ high_conf_predicted_rescue_total = 0
110
+
111
+ boundary_total = 0
112
+ boundary_errors = 0
113
+
114
+ surface_distance_sum = 0.0
115
+
116
+ collapse_zone = 0
117
+ near_boundary = 0
118
+ safe_margin = 0
119
+
120
+ tp = tn = fp = fn = 0
121
+
122
+ regime_counts = {
123
+ "baseline_surface_active": 0,
124
+ "coupling_surface_active": 0,
125
+ "lag_surface_active": 0,
126
+ }
127
+
128
+ for sid in sorted(truth_map):
129
+ truth_row = truth_map[sid]
130
+ pred_row = pred_map[sid]
131
+
132
+ pred = parse_binary(pred_row["prediction"], "prediction", sid)
133
+ label = parse_binary(truth_row["label_stable"], "label_stable", sid)
134
+
135
+ try:
136
+ pressure = float(truth_row["pressure"])
137
+ buffer = float(truth_row["buffer"])
138
+ lag = float(truth_row["lag"])
139
+ coupling = float(truth_row["coupling"])
140
+ content_score = float(truth_row["content_score"])
141
+ except ValueError as e:
142
+ raise ValueError(f"Invalid numeric field for {sid}: {e}") from e
143
+
144
+ surfaces = compute_surfaces(pressure, buffer, lag, coupling)
145
+ manifold_margin = min(surfaces.values())
146
+ active_surface = min(surfaces, key=surfaces.get)
147
+
148
+ regime_counts[f"{active_surface}_active"] += 1
149
+
150
+ total += 1
151
+ surface_distance_sum += abs(manifold_margin)
152
+
153
+ if pred == label:
154
+ correct += 1
155
+
156
+ if label == 1 and pred == 1:
157
+ tp += 1
158
+ elif label == 0 and pred == 0:
159
+ tn += 1
160
+ elif label == 0 and pred == 1:
161
+ fp += 1
162
+ elif label == 1 and pred == 0:
163
+ fn += 1
164
+
165
+ if content_score > HIGH_CONTENT_SCORE_THRESHOLD and pred == 1:
166
+ high_conf_predicted_rescue_total += 1
167
+ if manifold_margin < 0:
168
+ false_rescue += 1
169
+
170
+ if abs(manifold_margin) <= BOUNDARY_EPS:
171
+ boundary_total += 1
172
+ if pred != label:
173
+ boundary_errors += 1
174
+
175
+ region = classify_region(manifold_margin)
176
+ if region == "collapse_zone":
177
+ collapse_zone += 1
178
+ elif region == "near_boundary":
179
+ near_boundary += 1
180
+ else:
181
+ safe_margin += 1
182
+
183
+ accuracy = correct / total if total else 0.0
184
+ false_rescue_rate = (
185
+ false_rescue / high_conf_predicted_rescue_total
186
+ if high_conf_predicted_rescue_total
187
+ else 0.0
188
+ )
189
+ boundary_error_rate = (
190
+ boundary_errors / boundary_total
191
+ if boundary_total
192
+ else 0.0
193
+ )
194
+ surface_distance_mean = surface_distance_sum / total if total else 0.0
195
+
196
+ return {
197
+ "accuracy": accuracy,
198
+ "false_rescue_rate": false_rescue_rate,
199
+ "boundary_error_rate": boundary_error_rate,
200
+ "surface_distance_mean": surface_distance_mean,
201
+ "collapse_margin_distribution": {
202
+ "collapse_zone": collapse_zone,
203
+ "near_boundary": near_boundary,
204
+ "safe_margin": safe_margin,
205
+ },
206
+ "confusion_matrix": {
207
+ "true_stable_predicted_stable": tp,
208
+ "true_unstable_predicted_unstable": tn,
209
+ "false_rescue": fp,
210
+ "false_collapse": fn,
211
+ },
212
+ "active_surface_counts": regime_counts,
213
+ "diagnostics": {
214
+ "total_rows": total,
215
+ "high_conf_predicted_rescue_total": high_conf_predicted_rescue_total,
216
+ "boundary_cases": boundary_total,
217
+ },
218
+ "thresholds": {
219
+ "k": K,
220
+ "boundary_eps": BOUNDARY_EPS,
221
+ "high_content_score_threshold": HIGH_CONTENT_SCORE_THRESHOLD,
222
+ },
223
+ }
224
+
225
+
226
+ if __name__ == "__main__":
227
+ if len(sys.argv) != 3:
228
+ print("Usage: scorer.py predictions.csv truth.csv")
229
+ sys.exit(1)
230
+
231
+ pred_file = sys.argv[1]
232
+ truth_file = sys.argv[2]
233
+
234
+ result = evaluate(pred_file, truth_file)
235
+ print(json.dumps(result, indent=2))