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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"inoculum_rank",
|
| 14 |
+
"organism",
|
| 15 |
+
"strain_id",
|
| 16 |
+
"antibiotic_name",
|
| 17 |
+
"antibiotic_class",
|
| 18 |
+
"exposure_index",
|
| 19 |
+
"mic_mg_L",
|
| 20 |
+
"cfu0_log10",
|
| 21 |
+
"cfu24_log10",
|
| 22 |
+
"kill_24_log10",
|
| 23 |
+
"media",
|
| 24 |
+
"assay_method",
|
| 25 |
+
"source_type",
|
| 26 |
+
"inoculum_effect_signal",
|
| 27 |
+
"earliest_inoculum_effect",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class Thresholds:
|
| 33 |
+
min_points: int = 3
|
| 34 |
+
|
| 35 |
+
# event trigger
|
| 36 |
+
inoculum_rise_min: float = 1.0 # log10 units vs baseline
|
| 37 |
+
kill_drop_min: float = 0.8 # drop in kill vs baseline
|
| 38 |
+
|
| 39 |
+
# gates to avoid confounds
|
| 40 |
+
exposure_fold_min: float = 0.90
|
| 41 |
+
mic_fold_max: float = 2.0
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _validate(df: pd.DataFrame) -> List[str]:
|
| 45 |
+
errs: List[str] = []
|
| 46 |
+
|
| 47 |
+
missing = [c for c in REQUIRED_COLS if c not in df.columns]
|
| 48 |
+
if missing:
|
| 49 |
+
errs.append(f"missing_columns: {missing}")
|
| 50 |
+
|
| 51 |
+
for c in ["inoculum_rank", "exposure_index", "mic_mg_L", "cfu0_log10", "cfu24_log10", "kill_24_log10"]:
|
| 52 |
+
if c in df.columns and df[c].isna().any():
|
| 53 |
+
errs.append(f"null_values_in: {c}")
|
| 54 |
+
|
| 55 |
+
for c in ["exposure_index", "mic_mg_L"]:
|
| 56 |
+
if c in df.columns:
|
| 57 |
+
bad = (df[c] <= 0).sum()
|
| 58 |
+
if bad:
|
| 59 |
+
errs.append(f"non_positive_values_in: {c} count={int(bad)}")
|
| 60 |
+
|
| 61 |
+
for c in ["inoculum_effect_signal", "earliest_inoculum_effect"]:
|
| 62 |
+
if c in df.columns:
|
| 63 |
+
bad = (~df[c].isin([0, 1])).sum()
|
| 64 |
+
if bad:
|
| 65 |
+
errs.append(f"non_binary_values_in: {c} count={int(bad)}")
|
| 66 |
+
|
| 67 |
+
counts = df.groupby("series_id")["earliest_inoculum_effect"].sum()
|
| 68 |
+
bad_series = counts[counts > 1].index.tolist()
|
| 69 |
+
if bad_series:
|
| 70 |
+
errs.append(f"multiple_earliest_inoculum_effect_in_series: {bad_series}")
|
| 71 |
+
|
| 72 |
+
return errs
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _f1(tp: int, fp: int, fn: int) -> float:
|
| 76 |
+
denom = 2 * tp + fp + fn
|
| 77 |
+
return 0.0 if denom == 0 else (2 * tp) / denom
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def score(path: str) -> Dict[str, object]:
|
| 81 |
+
df = pd.read_csv(path)
|
| 82 |
+
errors = _validate(df)
|
| 83 |
+
if errors:
|
| 84 |
+
return {"ok": False, "errors": errors}
|
| 85 |
+
|
| 86 |
+
t = Thresholds()
|
| 87 |
+
|
| 88 |
+
df = df.sort_values(["series_id", "inoculum_rank"]).reset_index(drop=True)
|
| 89 |
+
df["pred_earliest_inoculum_effect"] = 0
|
| 90 |
+
df["pred_inoculum_effect_signal"] = 0
|
| 91 |
+
df["flag_exposure_drop"] = 0
|
| 92 |
+
df["flag_mic_shift"] = 0
|
| 93 |
+
|
| 94 |
+
series_rows: List[Dict[str, object]] = []
|
| 95 |
+
|
| 96 |
+
for sid, g in df.groupby("series_id"):
|
| 97 |
+
g = g.sort_values("inoculum_rank").copy()
|
| 98 |
+
|
| 99 |
+
if len(g) < t.min_points:
|
| 100 |
+
series_rows.append(
|
| 101 |
+
{
|
| 102 |
+
"series_id": sid,
|
| 103 |
+
"y_effect": int(g["inoculum_effect_signal"].max()),
|
| 104 |
+
"p_effect": 0,
|
| 105 |
+
"true_transition_row_id": (str(g[g["earliest_inoculum_effect"] == 1].iloc[0]["row_id"]) if (g["earliest_inoculum_effect"] == 1).any() else None),
|
| 106 |
+
"pred_transition_row_id": None,
|
| 107 |
+
"flags": ["too_few_points"],
|
| 108 |
+
}
|
| 109 |
+
)
|
| 110 |
+
continue
|
| 111 |
+
|
| 112 |
+
base = g.iloc[0]
|
| 113 |
+
base_inoc = float(base["cfu0_log10"])
|
| 114 |
+
base_kill = float(base["kill_24_log10"])
|
| 115 |
+
base_exp = float(base["exposure_index"])
|
| 116 |
+
base_mic = float(base["mic_mg_L"])
|
| 117 |
+
|
| 118 |
+
hits = []
|
| 119 |
+
for idx, row in g.iterrows():
|
| 120 |
+
inoc = float(row["cfu0_log10"])
|
| 121 |
+
kill = float(row["kill_24_log10"])
|
| 122 |
+
exp = float(row["exposure_index"])
|
| 123 |
+
mic = float(row["mic_mg_L"])
|
| 124 |
+
|
| 125 |
+
exp_fold = exp / base_exp if base_exp > 0 else 0.0
|
| 126 |
+
mic_fold = mic / base_mic if base_mic > 0 else 99.0
|
| 127 |
+
|
| 128 |
+
if exp_fold < t.exposure_fold_min:
|
| 129 |
+
df.loc[idx, "flag_exposure_drop"] = 1
|
| 130 |
+
if mic_fold > t.mic_fold_max:
|
| 131 |
+
df.loc[idx, "flag_mic_shift"] = 1
|
| 132 |
+
|
| 133 |
+
if idx == g.index[0]:
|
| 134 |
+
continue
|
| 135 |
+
|
| 136 |
+
inoc_rise = inoc - base_inoc
|
| 137 |
+
kill_drop = base_kill - kill
|
| 138 |
+
|
| 139 |
+
candidate = (
|
| 140 |
+
inoc_rise >= t.inoculum_rise_min
|
| 141 |
+
and kill_drop >= t.kill_drop_min
|
| 142 |
+
and exp_fold >= t.exposure_fold_min
|
| 143 |
+
and mic_fold <= t.mic_fold_max
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
if candidate:
|
| 147 |
+
hits.append(idx)
|
| 148 |
+
|
| 149 |
+
if hits:
|
| 150 |
+
first = hits[0]
|
| 151 |
+
df.loc[first, "pred_earliest_inoculum_effect"] = 1
|
| 152 |
+
later = g[g.index >= first].index
|
| 153 |
+
df.loc[later, "pred_inoculum_effect_signal"] = 1
|
| 154 |
+
|
| 155 |
+
y = int(g["inoculum_effect_signal"].max())
|
| 156 |
+
p = int(df.loc[g.index, "pred_inoculum_effect_signal"].max())
|
| 157 |
+
|
| 158 |
+
true_tr = g[g["earliest_inoculum_effect"] == 1]
|
| 159 |
+
true_id = None
|
| 160 |
+
if len(true_tr) == 1:
|
| 161 |
+
true_id = str(true_tr.iloc[0]["row_id"])
|
| 162 |
+
|
| 163 |
+
pred_tr = None
|
| 164 |
+
pred_tr_rows = df.loc[g.index][df.loc[g.index, "pred_earliest_inoculum_effect"] == 1]
|
| 165 |
+
if len(pred_tr_rows) == 1:
|
| 166 |
+
pred_tr = str(pred_tr_rows.iloc[0]["row_id"])
|
| 167 |
+
|
| 168 |
+
series_rows.append(
|
| 169 |
+
{
|
| 170 |
+
"series_id": sid,
|
| 171 |
+
"y_effect": y,
|
| 172 |
+
"p_effect": p,
|
| 173 |
+
"true_transition_row_id": true_id,
|
| 174 |
+
"pred_transition_row_id": pred_tr,
|
| 175 |
+
"exposure_drop_flags": int(df.loc[g.index, "flag_exposure_drop"].sum()),
|
| 176 |
+
"mic_shift_flags": int(df.loc[g.index, "flag_mic_shift"].sum()),
|
| 177 |
+
}
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
sr = pd.DataFrame(series_rows)
|
| 181 |
+
|
| 182 |
+
tp = int(((sr["y_effect"] == 1) & (sr["p_effect"] == 1)).sum())
|
| 183 |
+
fp = int(((sr["y_effect"] == 0) & (sr["p_effect"] == 1)).sum())
|
| 184 |
+
fn = int(((sr["y_effect"] == 1) & (sr["p_effect"] == 0)).sum())
|
| 185 |
+
tn = int(((sr["y_effect"] == 0) & (sr["p_effect"] == 0)).sum())
|
| 186 |
+
|
| 187 |
+
transition_hit = int(
|
| 188 |
+
(
|
| 189 |
+
sr["true_transition_row_id"].notna()
|
| 190 |
+
& (sr["true_transition_row_id"] == sr["pred_transition_row_id"])
|
| 191 |
+
).sum()
|
| 192 |
+
)
|
| 193 |
+
transition_miss = int(
|
| 194 |
+
(
|
| 195 |
+
sr["true_transition_row_id"].notna()
|
| 196 |
+
& (sr["true_transition_row_id"] != sr["pred_transition_row_id"])
|
| 197 |
+
).sum()
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
return {
|
| 201 |
+
"ok": True,
|
| 202 |
+
"path": path,
|
| 203 |
+
"counts": {"tp": tp, "fp": fp, "fn": fn, "tn": tn},
|
| 204 |
+
"metrics": {
|
| 205 |
+
"f1_series": _f1(tp, fp, fn),
|
| 206 |
+
"transition_hit": transition_hit,
|
| 207 |
+
"transition_miss": transition_miss,
|
| 208 |
+
"n_series": int(len(sr)),
|
| 209 |
+
},
|
| 210 |
+
"series_table": series_rows,
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
if __name__ == "__main__":
|
| 215 |
+
import argparse
|
| 216 |
+
|
| 217 |
+
ap = argparse.ArgumentParser()
|
| 218 |
+
ap.add_argument("--path", required=True)
|
| 219 |
+
args = ap.parse_args()
|
| 220 |
+
|
| 221 |
+
result = score(args.path)
|
| 222 |
+
print(json.dumps(result, indent=2))
|