| from __future__ import annotations |
|
|
| import json |
| from dataclasses import dataclass |
| from typing import Dict, List |
|
|
| import pandas as pd |
|
|
|
|
| REQUIRED_COLS = [ |
| "row_id", |
| "series_id", |
| "timepoint_h", |
| "organism", |
| "strain_id", |
| "drug_name", |
| "target_gene", |
| "mutation_id", |
| "mutant_frac_target_mod", |
| "mic_drug_mg_L", |
| "resistant_mic_cutoff_mg_L", |
| "media", |
| "assay_method", |
| "source_type", |
| "penetration_signal", |
| "earliest_penetration", |
| ] |
|
|
|
|
| @dataclass |
| class Thresholds: |
| min_points: int = 3 |
|
|
| frac_threshold: float = 0.20 |
| mic_fold_max_at_penetration: float = 2.0 |
|
|
| confirm_requires_resistant: bool = True |
|
|
| spike_frac_min: float = 0.80 |
| snapback_frac_max: float = 0.05 |
|
|
|
|
| def _validate(df: pd.DataFrame) -> List[str]: |
| errs: List[str] = [] |
| missing = [c for c in REQUIRED_COLS if c not in df.columns] |
| if missing: |
| errs.append(f"missing_columns: {missing}") |
|
|
| for c in ["timepoint_h", "mutant_frac_target_mod", "mic_drug_mg_L", "resistant_mic_cutoff_mg_L"]: |
| if c in df.columns and df[c].isna().any(): |
| errs.append(f"null_values_in: {c}") |
|
|
| if "mutant_frac_target_mod" in df.columns: |
| bad = ((df["mutant_frac_target_mod"] < 0) | (df["mutant_frac_target_mod"] > 1)).sum() |
| if bad: |
| errs.append(f"mutant_frac_out_of_range count={int(bad)}") |
|
|
| for c in ["mic_drug_mg_L", "resistant_mic_cutoff_mg_L"]: |
| if c in df.columns: |
| bad = (df[c] <= 0).sum() |
| if bad: |
| errs.append(f"non_positive_values_in: {c} count={int(bad)}") |
|
|
| for c in ["penetration_signal", "earliest_penetration"]: |
| if c in df.columns: |
| bad = (~df[c].isin([0, 1])).sum() |
| if bad: |
| errs.append(f"non_binary_values_in: {c} count={int(bad)}") |
|
|
| counts = df.groupby("series_id")["earliest_penetration"].sum() |
| bad_series = counts[counts > 1].index.tolist() |
| if bad_series: |
| errs.append(f"multiple_earliest_penetration_in_series: {bad_series}") |
|
|
| return errs |
|
|
|
|
| def _flag_spike_snap(g: pd.DataFrame, t: Thresholds) -> pd.Series: |
| flag = pd.Series([0] * len(g), index=g.index) |
| if len(g) < 3: |
| return flag |
|
|
| g = g.sort_values("timepoint_h").copy() |
| for i in range(1, len(g) - 1): |
| idx = g.index[i] |
| prev_idx = g.index[i - 1] |
| next_idx = g.index[i + 1] |
|
|
| prev_v = float(g.loc[prev_idx, "mutant_frac_target_mod"]) |
| v = float(g.loc[idx, "mutant_frac_target_mod"]) |
| next_v = float(g.loc[next_idx, "mutant_frac_target_mod"]) |
|
|
| spike = v >= t.spike_frac_min and prev_v <= t.snapback_frac_max and next_v <= t.snapback_frac_max |
| if spike: |
| flag.loc[idx] = 1 |
|
|
| return flag |
|
|
|
|
| def _f1(tp: int, fp: int, fn: int) -> float: |
| denom = 2 * tp + fp + fn |
| return 0.0 if denom == 0 else (2 * tp) / denom |
|
|
|
|
| def score(path: str) -> Dict[str, object]: |
| df = pd.read_csv(path) |
| errors = _validate(df) |
| if errors: |
| return {"ok": False, "errors": errors} |
|
|
| t = Thresholds() |
|
|
| df = df.sort_values(["series_id", "timepoint_h"]).reset_index(drop=True) |
| df["pred_earliest_penetration"] = 0 |
| df["pred_penetration_signal"] = 0 |
| df["flag_measurement_spike"] = 0 |
|
|
| series_rows: List[Dict[str, object]] = [] |
|
|
| for sid, g in df.groupby("series_id"): |
| g = g.sort_values("timepoint_h").copy() |
| df.loc[g.index, "flag_measurement_spike"] = _flag_spike_snap(g, t).astype(int) |
|
|
| if len(g) < t.min_points: |
| series_rows.append( |
| { |
| "series_id": sid, |
| "y_pen": int(g["penetration_signal"].max()), |
| "p_pen": 0, |
| "true_transition_row_id": (str(g[g["earliest_penetration"] == 1].iloc[0]["row_id"]) if (g["earliest_penetration"] == 1).any() else None), |
| "pred_transition_row_id": None, |
| "flags": ["too_few_points"], |
| } |
| ) |
| continue |
|
|
| base = g.iloc[0] |
| base_mic = float(base["mic_drug_mg_L"]) |
| cutoff = float(base["resistant_mic_cutoff_mg_L"]) |
|
|
| |
| if base_mic >= cutoff: |
| series_rows.append( |
| { |
| "series_id": sid, |
| "y_pen": int(g["penetration_signal"].max()), |
| "p_pen": 0, |
| "true_transition_row_id": (str(g[g["earliest_penetration"] == 1].iloc[0]["row_id"]) if (g["earliest_penetration"] == 1).any() else None), |
| "pred_transition_row_id": None, |
| "flags": ["baseline_resistant"], |
| } |
| ) |
| continue |
|
|
| hits = [] |
| for idx, row in g.iterrows(): |
| if idx == g.index[0]: |
| continue |
| if int(df.loc[idx, "flag_measurement_spike"]) == 1: |
| continue |
|
|
| frac = float(row["mutant_frac_target_mod"]) |
| mic = float(row["mic_drug_mg_L"]) |
|
|
| mic_fold = mic / base_mic if base_mic > 0 else 99.0 |
|
|
| candidate = ( |
| frac >= t.frac_threshold |
| and mic_fold <= t.mic_fold_max_at_penetration |
| and mic < cutoff |
| ) |
|
|
| if candidate: |
| hits.append(idx) |
|
|
| confirm = True |
| if t.confirm_requires_resistant and hits: |
| later = g[g.index > hits[0]] |
| confirm = bool((later["mic_drug_mg_L"] >= cutoff).any()) |
|
|
| if hits and confirm: |
| first = hits[0] |
| df.loc[first, "pred_earliest_penetration"] = 1 |
| df.loc[g[g.index >= first].index, "pred_penetration_signal"] = 1 |
|
|
| y = int(g["penetration_signal"].max()) |
| p = int(df.loc[g.index, "pred_penetration_signal"].max()) |
|
|
| true_tr = g[g["earliest_penetration"] == 1] |
| true_id = str(true_tr.iloc[0]["row_id"]) if len(true_tr) == 1 else None |
|
|
| pred_tr_rows = df.loc[g.index][df.loc[g.index, "pred_earliest_penetration"] == 1] |
| pred_id = str(pred_tr_rows.iloc[0]["row_id"]) if len(pred_tr_rows) == 1 else None |
|
|
| series_rows.append( |
| { |
| "series_id": sid, |
| "y_pen": y, |
| "p_pen": p, |
| "true_transition_row_id": true_id, |
| "pred_transition_row_id": pred_id, |
| "measurement_spike_flags": int(df.loc[g.index, "flag_measurement_spike"].sum()), |
| } |
| ) |
|
|
| sr = pd.DataFrame(series_rows) |
|
|
| tp = int(((sr["y_pen"] == 1) & (sr["p_pen"] == 1)).sum()) |
| fp = int(((sr["y_pen"] == 0) & (sr["p_pen"] == 1)).sum()) |
| fn = int(((sr["y_pen"] == 1) & (sr["p_pen"] == 0)).sum()) |
| tn = int(((sr["y_pen"] == 0) & (sr["p_pen"] == 0)).sum()) |
|
|
| transition_hit = int( |
| ( |
| sr["true_transition_row_id"].notna() |
| & (sr["true_transition_row_id"] == sr["pred_transition_row_id"]) |
| ).sum() |
| ) |
| transition_miss = int( |
| ( |
| sr["true_transition_row_id"].notna() |
| & (sr["true_transition_row_id"] != sr["pred_transition_row_id"]) |
| ).sum() |
| ) |
|
|
| return { |
| "ok": True, |
| "path": path, |
| "counts": {"tp": tp, "fp": fp, "fn": fn, "tn": tn}, |
| "metrics": { |
| "f1_series": _f1(tp, fp, fn), |
| "transition_hit": transition_hit, |
| "transition_miss": transition_miss, |
| "n_series": int(len(sr)), |
| }, |
| "series_table": series_rows, |
| } |
|
|
|
|
| if __name__ == "__main__": |
| import argparse |
|
|
| ap = argparse.ArgumentParser() |
| ap.add_argument("--path", required=True) |
| args = ap.parse_args() |
|
|
| result = score(args.path) |
| print(json.dumps(result, indent=2)) |
|
|