ClarusC64 commited on
Commit
8436bc9
·
verified ·
1 Parent(s): 9a116df

Create scorer.py

Browse files
Files changed (1) hide show
  1. scorer.py +161 -0
scorer.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import json
3
+ from collections import Counter
4
+
5
+ VALID_LABELS = {"0", "1", "2"}
6
+
7
+ POP_MAP = {"none": 0, "minor": 1, "major": 2}
8
+ DEV_MAP = {"low": 0, "medium": 1, "high": 2}
9
+ SITE_MAP = {"low": 0, "medium": 1, "high": 2}
10
+ FRAG_MAP = {"low": 0, "medium": 1, "high": 2}
11
+
12
+ REQUIRED_GOLD_COLS = [
13
+ "id",
14
+ "population_shift",
15
+ "protocol_deviation_rate",
16
+ "site_variance_level",
17
+ "endpoint_fragility",
18
+ "label",
19
+ ]
20
+
21
+ def _norm(x) -> str:
22
+ return str(x).strip().lower()
23
+
24
+ def _map_val(x, m, name: str) -> int:
25
+ s = _norm(x)
26
+ if s not in m:
27
+ raise ValueError(f"Bad {name} value: {x}")
28
+ return m[s]
29
+
30
+ def _validate_gold_row(r: dict):
31
+ for c in REQUIRED_GOLD_COLS:
32
+ if c not in r:
33
+ raise ValueError(f"Missing column: {c}")
34
+ lab = str(r["label"]).strip()
35
+ if lab not in VALID_LABELS:
36
+ raise ValueError(f"Bad label: {r['label']}")
37
+
38
+ _map_val(r["population_shift"], POP_MAP, "population_shift")
39
+ _map_val(r["protocol_deviation_rate"], DEV_MAP, "protocol_deviation_rate")
40
+ _map_val(r["site_variance_level"], SITE_MAP, "site_variance_level")
41
+ _map_val(r["endpoint_fragility"], FRAG_MAP, "endpoint_fragility")
42
+
43
+ def _extract_pred_label(pred_row: dict) -> str:
44
+ v = pred_row.get("label") or pred_row.get("prediction") or pred_row.get("output") or ""
45
+ s = str(v).strip()
46
+
47
+ if s in VALID_LABELS:
48
+ return s
49
+
50
+ # allow JSON {"label":"2"}
51
+ if s.startswith("{") and s.endswith("}"):
52
+ try:
53
+ obj = json.loads(s)
54
+ if isinstance(obj, dict) and "label" in obj:
55
+ lab = str(obj["label"]).strip()
56
+ if lab in VALID_LABELS:
57
+ return lab
58
+ except Exception:
59
+ pass
60
+
61
+ return "invalid"
62
+
63
+ def _rule_pred(g: dict) -> str:
64
+ pop = _map_val(g["population_shift"], POP_MAP, "population_shift")
65
+ dev = _map_val(g["protocol_deviation_rate"], DEV_MAP, "protocol_deviation_rate")
66
+ site = _map_val(g["site_variance_level"], SITE_MAP, "site_variance_level")
67
+ frag = _map_val(g["endpoint_fragility"], FRAG_MAP, "endpoint_fragility")
68
+
69
+ # collapse when fragility is high plus any other high strain
70
+ if frag == 2 and (pop == 2 or dev == 2 or site == 2):
71
+ return "2"
72
+
73
+ # also collapse when three nodes are high/major/medium-high combined
74
+ highish = sum([
75
+ 1 if pop >= 1 else 0,
76
+ 1 if dev >= 1 else 0,
77
+ 1 if site >= 1 else 0,
78
+ 1 if frag >= 1 else 0,
79
+ ])
80
+ if highish >= 4 and (dev == 2 or site == 2):
81
+ return "2"
82
+
83
+ # coherent only when all nodes low/none
84
+ if pop == 0 and dev == 0 and site == 0 and frag == 0:
85
+ return "0"
86
+
87
+ return "1"
88
+
89
+ def _risk_score(g: dict) -> float:
90
+ pop = _map_val(g["population_shift"], POP_MAP, "population_shift")
91
+ dev = _map_val(g["protocol_deviation_rate"], DEV_MAP, "protocol_deviation_rate")
92
+ site = _map_val(g["site_variance_level"], SITE_MAP, "site_variance_level")
93
+ frag = _map_val(g["endpoint_fragility"], FRAG_MAP, "endpoint_fragility")
94
+
95
+ # fragility weighs double
96
+ raw = pop + dev + site + (2 * frag)
97
+ # max raw = 2+2+2+4 = 10
98
+ return raw / 10.0
99
+
100
+ def run_scorer(preds_csv_path: str, gold_csv_path: str):
101
+ with open(gold_csv_path, newline="", encoding="utf-8") as gf:
102
+ gold_rows = list(csv.DictReader(gf))
103
+
104
+ for r in gold_rows:
105
+ _validate_gold_row(r)
106
+
107
+ with open(preds_csv_path, newline="", encoding="utf-8") as pf:
108
+ pred_rows = list(csv.DictReader(pf))
109
+
110
+ pred_by_id = {str(r.get("id")).strip(): r for r in pred_rows if r.get("id") is not None}
111
+
112
+ total = 0
113
+ correct = 0
114
+ confusion = Counter()
115
+ errors = []
116
+ missing_ids = []
117
+
118
+ for g in gold_rows:
119
+ gid = str(g["id"]).strip()
120
+ gold = str(g["label"]).strip()
121
+
122
+ pr = pred_by_id.get(gid)
123
+ if pr is None:
124
+ pred = "missing"
125
+ missing_ids.append(gid)
126
+ else:
127
+ pred = _extract_pred_label(pr)
128
+
129
+ confusion[(gold, pred)] += 1
130
+
131
+ if pred == gold:
132
+ correct += 1
133
+ else:
134
+ errors.append({
135
+ "id": gid,
136
+ "gold": gold,
137
+ "pred": pred,
138
+ "rule_pred": _rule_pred(g),
139
+ "risk_score": round(_risk_score(g), 4),
140
+ })
141
+
142
+ total += 1
143
+
144
+ report = {
145
+ "n": total,
146
+ "accuracy": (correct / total) if total else 0.0,
147
+ "confusion": {f"{k[0]}->{k[1]}": v for k, v in confusion.items()},
148
+ "avg_risk_score": round(sum(_risk_score(r) for r in gold_rows) / max(1, len(gold_rows)), 4),
149
+ "errors_sample": errors[:25],
150
+ "missing_ids": missing_ids[:50],
151
+ }
152
+ return report
153
+
154
+ if __name__ == "__main__":
155
+ import argparse
156
+ p = argparse.ArgumentParser()
157
+ p.add_argument("--preds_csv", required=True)
158
+ p.add_argument("--gold_csv", required=True)
159
+ args = p.parse_args()
160
+
161
+ print(json.dumps(run_scorer(args.preds_csv, args.gold_csv), indent=2))