ClarusC64 commited on
Commit
f5a69eb
·
verified ·
1 Parent(s): 7a99489

Create scorer.py

Browse files
Files changed (1) hide show
  1. scorer.py +248 -0
scorer.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import dataclass
5
+ from typing import Dict, List
6
+
7
+ import pandas as pd
8
+
9
+
10
+ REQUIRED_COLS = [
11
+ "row_id",
12
+ "series_id",
13
+ "timepoint_h",
14
+ "organism",
15
+ "strain_id",
16
+ "drug_name",
17
+ "target_gene",
18
+ "mutation_id",
19
+ "mutant_frac_target_mod",
20
+ "mic_drug_mg_L",
21
+ "resistant_mic_cutoff_mg_L",
22
+ "media",
23
+ "assay_method",
24
+ "source_type",
25
+ "penetration_signal",
26
+ "earliest_penetration",
27
+ ]
28
+
29
+
30
+ @dataclass
31
+ class Thresholds:
32
+ min_points: int = 3
33
+
34
+ frac_threshold: float = 0.20
35
+ mic_fold_max_at_penetration: float = 2.0 # relative to baseline
36
+
37
+ confirm_requires_resistant: bool = True
38
+
39
+ spike_frac_min: float = 0.80
40
+ snapback_frac_max: float = 0.05
41
+
42
+
43
+ def _validate(df: pd.DataFrame) -> List[str]:
44
+ errs: List[str] = []
45
+ missing = [c for c in REQUIRED_COLS if c not in df.columns]
46
+ if missing:
47
+ errs.append(f"missing_columns: {missing}")
48
+
49
+ for c in ["timepoint_h", "mutant_frac_target_mod", "mic_drug_mg_L", "resistant_mic_cutoff_mg_L"]:
50
+ if c in df.columns and df[c].isna().any():
51
+ errs.append(f"null_values_in: {c}")
52
+
53
+ if "mutant_frac_target_mod" in df.columns:
54
+ bad = ((df["mutant_frac_target_mod"] < 0) | (df["mutant_frac_target_mod"] > 1)).sum()
55
+ if bad:
56
+ errs.append(f"mutant_frac_out_of_range count={int(bad)}")
57
+
58
+ for c in ["mic_drug_mg_L", "resistant_mic_cutoff_mg_L"]:
59
+ if c in df.columns:
60
+ bad = (df[c] <= 0).sum()
61
+ if bad:
62
+ errs.append(f"non_positive_values_in: {c} count={int(bad)}")
63
+
64
+ for c in ["penetration_signal", "earliest_penetration"]:
65
+ if c in df.columns:
66
+ bad = (~df[c].isin([0, 1])).sum()
67
+ if bad:
68
+ errs.append(f"non_binary_values_in: {c} count={int(bad)}")
69
+
70
+ counts = df.groupby("series_id")["earliest_penetration"].sum()
71
+ bad_series = counts[counts > 1].index.tolist()
72
+ if bad_series:
73
+ errs.append(f"multiple_earliest_penetration_in_series: {bad_series}")
74
+
75
+ return errs
76
+
77
+
78
+ def _flag_spike_snap(g: pd.DataFrame, t: Thresholds) -> pd.Series:
79
+ flag = pd.Series([0] * len(g), index=g.index)
80
+ if len(g) < 3:
81
+ return flag
82
+
83
+ g = g.sort_values("timepoint_h").copy()
84
+ for i in range(1, len(g) - 1):
85
+ idx = g.index[i]
86
+ prev_idx = g.index[i - 1]
87
+ next_idx = g.index[i + 1]
88
+
89
+ prev_v = float(g.loc[prev_idx, "mutant_frac_target_mod"])
90
+ v = float(g.loc[idx, "mutant_frac_target_mod"])
91
+ next_v = float(g.loc[next_idx, "mutant_frac_target_mod"])
92
+
93
+ spike = v >= t.spike_frac_min and prev_v <= t.snapback_frac_max and next_v <= t.snapback_frac_max
94
+ if spike:
95
+ flag.loc[idx] = 1
96
+
97
+ return flag
98
+
99
+
100
+ def _f1(tp: int, fp: int, fn: int) -> float:
101
+ denom = 2 * tp + fp + fn
102
+ return 0.0 if denom == 0 else (2 * tp) / denom
103
+
104
+
105
+ def score(path: str) -> Dict[str, object]:
106
+ df = pd.read_csv(path)
107
+ errors = _validate(df)
108
+ if errors:
109
+ return {"ok": False, "errors": errors}
110
+
111
+ t = Thresholds()
112
+
113
+ df = df.sort_values(["series_id", "timepoint_h"]).reset_index(drop=True)
114
+ df["pred_earliest_penetration"] = 0
115
+ df["pred_penetration_signal"] = 0
116
+ df["flag_measurement_spike"] = 0
117
+
118
+ series_rows: List[Dict[str, object]] = []
119
+
120
+ for sid, g in df.groupby("series_id"):
121
+ g = g.sort_values("timepoint_h").copy()
122
+ df.loc[g.index, "flag_measurement_spike"] = _flag_spike_snap(g, t).astype(int)
123
+
124
+ if len(g) < t.min_points:
125
+ series_rows.append(
126
+ {
127
+ "series_id": sid,
128
+ "y_pen": int(g["penetration_signal"].max()),
129
+ "p_pen": 0,
130
+ "true_transition_row_id": (str(g[g["earliest_penetration"] == 1].iloc[0]["row_id"]) if (g["earliest_penetration"] == 1).any() else None),
131
+ "pred_transition_row_id": None,
132
+ "flags": ["too_few_points"],
133
+ }
134
+ )
135
+ continue
136
+
137
+ base = g.iloc[0]
138
+ base_mic = float(base["mic_drug_mg_L"])
139
+ cutoff = float(base["resistant_mic_cutoff_mg_L"])
140
+
141
+ # if baseline already resistant, not an early penetration case
142
+ if base_mic >= cutoff:
143
+ series_rows.append(
144
+ {
145
+ "series_id": sid,
146
+ "y_pen": int(g["penetration_signal"].max()),
147
+ "p_pen": 0,
148
+ "true_transition_row_id": (str(g[g["earliest_penetration"] == 1].iloc[0]["row_id"]) if (g["earliest_penetration"] == 1).any() else None),
149
+ "pred_transition_row_id": None,
150
+ "flags": ["baseline_resistant"],
151
+ }
152
+ )
153
+ continue
154
+
155
+ hits = []
156
+ for idx, row in g.iterrows():
157
+ if idx == g.index[0]:
158
+ continue
159
+ if int(df.loc[idx, "flag_measurement_spike"]) == 1:
160
+ continue
161
+
162
+ frac = float(row["mutant_frac_target_mod"])
163
+ mic = float(row["mic_drug_mg_L"])
164
+
165
+ mic_fold = mic / base_mic if base_mic > 0 else 99.0
166
+
167
+ candidate = (
168
+ frac >= t.frac_threshold
169
+ and mic_fold <= t.mic_fold_max_at_penetration
170
+ and mic < cutoff
171
+ )
172
+
173
+ if candidate:
174
+ hits.append(idx)
175
+
176
+ confirm = True
177
+ if t.confirm_requires_resistant and hits:
178
+ later = g[g.index > hits[0]]
179
+ confirm = bool((later["mic_drug_mg_L"] >= cutoff).any())
180
+
181
+ if hits and confirm:
182
+ first = hits[0]
183
+ df.loc[first, "pred_earliest_penetration"] = 1
184
+ df.loc[g[g.index >= first].index, "pred_penetration_signal"] = 1
185
+
186
+ y = int(g["penetration_signal"].max())
187
+ p = int(df.loc[g.index, "pred_penetration_signal"].max())
188
+
189
+ true_tr = g[g["earliest_penetration"] == 1]
190
+ true_id = str(true_tr.iloc[0]["row_id"]) if len(true_tr) == 1 else None
191
+
192
+ pred_tr_rows = df.loc[g.index][df.loc[g.index, "pred_earliest_penetration"] == 1]
193
+ pred_id = str(pred_tr_rows.iloc[0]["row_id"]) if len(pred_tr_rows) == 1 else None
194
+
195
+ series_rows.append(
196
+ {
197
+ "series_id": sid,
198
+ "y_pen": y,
199
+ "p_pen": p,
200
+ "true_transition_row_id": true_id,
201
+ "pred_transition_row_id": pred_id,
202
+ "measurement_spike_flags": int(df.loc[g.index, "flag_measurement_spike"].sum()),
203
+ }
204
+ )
205
+
206
+ sr = pd.DataFrame(series_rows)
207
+
208
+ tp = int(((sr["y_pen"] == 1) & (sr["p_pen"] == 1)).sum())
209
+ fp = int(((sr["y_pen"] == 0) & (sr["p_pen"] == 1)).sum())
210
+ fn = int(((sr["y_pen"] == 1) & (sr["p_pen"] == 0)).sum())
211
+ tn = int(((sr["y_pen"] == 0) & (sr["p_pen"] == 0)).sum())
212
+
213
+ transition_hit = int(
214
+ (
215
+ sr["true_transition_row_id"].notna()
216
+ & (sr["true_transition_row_id"] == sr["pred_transition_row_id"])
217
+ ).sum()
218
+ )
219
+ transition_miss = int(
220
+ (
221
+ sr["true_transition_row_id"].notna()
222
+ & (sr["true_transition_row_id"] != sr["pred_transition_row_id"])
223
+ ).sum()
224
+ )
225
+
226
+ return {
227
+ "ok": True,
228
+ "path": path,
229
+ "counts": {"tp": tp, "fp": fp, "fn": fn, "tn": tn},
230
+ "metrics": {
231
+ "f1_series": _f1(tp, fp, fn),
232
+ "transition_hit": transition_hit,
233
+ "transition_miss": transition_miss,
234
+ "n_series": int(len(sr)),
235
+ },
236
+ "series_table": series_rows,
237
+ }
238
+
239
+
240
+ if __name__ == "__main__":
241
+ import argparse
242
+
243
+ ap = argparse.ArgumentParser()
244
+ ap.add_argument("--path", required=True)
245
+ args = ap.parse_args()
246
+
247
+ result = score(args.path)
248
+ print(json.dumps(result, indent=2))