| | from __future__ import annotations |
| |
|
| | import json |
| | from dataclasses import dataclass |
| | from typing import Dict, List, Optional |
| |
|
| | import pandas as pd |
| |
|
| |
|
| | REQUIRED_COLS = [ |
| | "row_id", |
| | "series_id", |
| | "timepoint_h", |
| | "organism", |
| | "strain_id", |
| | "drug_a", |
| | "drug_b", |
| | "stress_index", |
| | "baseline_mic_a_mg_L", |
| | "baseline_mic_b_mg_L", |
| | "mic_a_mg_L", |
| | "mic_b_mg_L", |
| | "a_resistant_cutoff_mg_L", |
| | "b_susceptible_floor_mg_L", |
| | "b_sensitivity_fold_change", |
| | "media", |
| | "assay_method", |
| | "source_type", |
| | "collateral_sensitivity_signal", |
| | "earliest_collateral_sensitivity", |
| | ] |
| |
|
| |
|
| | @dataclass |
| | class Thresholds: |
| | min_points: int = 2 |
| |
|
| | stress_min: float = 0.80 |
| |
|
| | b_fold_min: float = 2.0 |
| | require_same_or_next_timepoint: bool = True |
| |
|
| |
|
| | 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", |
| | "stress_index", |
| | "baseline_mic_a_mg_L", |
| | "baseline_mic_b_mg_L", |
| | "mic_a_mg_L", |
| | "mic_b_mg_L", |
| | "a_resistant_cutoff_mg_L", |
| | "b_susceptible_floor_mg_L", |
| | "b_sensitivity_fold_change", |
| | ]: |
| | if c in df.columns and df[c].isna().any(): |
| | errs.append(f"null_values_in: {c}") |
| |
|
| | if "stress_index" in df.columns: |
| | bad = ((df["stress_index"] < 0) | (df["stress_index"] > 1)).sum() |
| | if bad: |
| | errs.append(f"stress_index_out_of_range count={int(bad)}") |
| |
|
| | for c in ["baseline_mic_a_mg_L", "baseline_mic_b_mg_L", "mic_a_mg_L", "mic_b_mg_L", "a_resistant_cutoff_mg_L", "b_susceptible_floor_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)}") |
| |
|
| | if "b_sensitivity_fold_change" in df.columns: |
| | bad = (df["b_sensitivity_fold_change"] <= 0).sum() |
| | if bad: |
| | errs.append(f"non_positive_values_in: b_sensitivity_fold_change count={int(bad)}") |
| |
|
| | for c in ["collateral_sensitivity_signal", "earliest_collateral_sensitivity"]: |
| | 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_collateral_sensitivity"].sum() |
| | bad_series = counts[counts > 1].index.tolist() |
| | if bad_series: |
| | errs.append(f"multiple_earliest_collateral_sensitivity_in_series: {bad_series}") |
| |
|
| | return errs |
| |
|
| |
|
| | 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_collateral_sensitivity"] = 0 |
| | df["pred_collateral_sensitivity_signal"] = 0 |
| |
|
| | series_rows: List[Dict[str, object]] = [] |
| |
|
| | for sid, g in df.groupby("series_id"): |
| | g = g.sort_values("timepoint_h").copy() |
| |
|
| | if len(g) < t.min_points: |
| | series_rows.append( |
| | { |
| | "series_id": sid, |
| | "y_cs": int(g["collateral_sensitivity_signal"].max()), |
| | "p_cs": 0, |
| | "true_transition_row_id": (str(g[g["earliest_collateral_sensitivity"] == 1].iloc[0]["row_id"]) if (g["earliest_collateral_sensitivity"] == 1).any() else None), |
| | "pred_transition_row_id": None, |
| | "flags": ["too_few_points"], |
| | } |
| | ) |
| | continue |
| |
|
| | base_A = float(g.iloc[0]["baseline_mic_a_mg_L"]) |
| | base_B = float(g.iloc[0]["baseline_mic_b_mg_L"]) |
| | cut_A = float(g.iloc[0]["a_resistant_cutoff_mg_L"]) |
| |
|
| | if base_A >= cut_A: |
| | series_rows.append( |
| | { |
| | "series_id": sid, |
| | "y_cs": int(g["collateral_sensitivity_signal"].max()), |
| | "p_cs": 0, |
| | "true_transition_row_id": (str(g[g["earliest_collateral_sensitivity"] == 1].iloc[0]["row_id"]) if (g["earliest_collateral_sensitivity"] == 1).any() else None), |
| | "pred_transition_row_id": None, |
| | "flags": ["baseline_A_resistant"], |
| | } |
| | ) |
| | continue |
| |
|
| | |
| | a_cross_idx: Optional[int] = None |
| | for idx in g.index[1:]: |
| | if float(df.loc[idx, "stress_index"]) < t.stress_min: |
| | continue |
| | if float(df.loc[idx, "mic_a_mg_L"]) >= cut_A: |
| | a_cross_idx = idx |
| | break |
| |
|
| | if a_cross_idx is None: |
| | series_rows.append( |
| | { |
| | "series_id": sid, |
| | "y_cs": int(g["collateral_sensitivity_signal"].max()), |
| | "p_cs": 0, |
| | "true_transition_row_id": (str(g[g["earliest_collateral_sensitivity"] == 1].iloc[0]["row_id"]) if (g["earliest_collateral_sensitivity"] == 1).any() else None), |
| | "pred_transition_row_id": None, |
| | "flags": ["A_never_crosses"], |
| | } |
| | ) |
| | continue |
| |
|
| | |
| | candidate_indices = [a_cross_idx] |
| | if t.require_same_or_next_timepoint: |
| | pos = list(g.index).index(a_cross_idx) |
| | if pos + 1 < len(g.index): |
| | candidate_indices.append(list(g.index)[pos + 1]) |
| |
|
| | hit: Optional[int] = None |
| | for idx in candidate_indices: |
| | if float(df.loc[idx, "stress_index"]) < t.stress_min: |
| | continue |
| |
|
| | b_mic = float(df.loc[idx, "mic_b_mg_L"]) |
| | fold = (base_B / b_mic) if b_mic > 0 else 0.0 |
| | floor = float(df.loc[idx, "b_susceptible_floor_mg_L"]) |
| |
|
| | if fold >= t.b_fold_min and b_mic <= floor: |
| | hit = idx |
| | break |
| |
|
| | if hit is not None: |
| | df.loc[hit, "pred_earliest_collateral_sensitivity"] = 1 |
| | df.loc[g[g.index >= hit].index, "pred_collateral_sensitivity_signal"] = 1 |
| |
|
| | y = int(g["collateral_sensitivity_signal"].max()) |
| | p = int(df.loc[g.index, "pred_collateral_sensitivity_signal"].max()) |
| |
|
| | true_tr = g[g["earliest_collateral_sensitivity"] == 1] |
| | true_id: Optional[str] = None |
| | if len(true_tr) == 1: |
| | true_id = str(true_tr.iloc[0]["row_id"]) |
| |
|
| | pred_tr_rows = df.loc[g.index][df.loc[g.index, "pred_earliest_collateral_sensitivity"] == 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_cs": y, |
| | "p_cs": p, |
| | "true_transition_row_id": true_id, |
| | "pred_transition_row_id": pred_id, |
| | "a_cross_row_id": str(df.loc[a_cross_idx, "row_id"]), |
| | "a_cross_time_h": float(df.loc[a_cross_idx, "timepoint_h"]), |
| | } |
| | ) |
| |
|
| | sr = pd.DataFrame(series_rows) |
| |
|
| | tp = int(((sr["y_cs"] == 1) & (sr["p_cs"] == 1)).sum()) |
| | fp = int(((sr["y_cs"] == 0) & (sr["p_cs"] == 1)).sum()) |
| | fn = int(((sr["y_cs"] == 1) & (sr["p_cs"] == 0)).sum()) |
| | tn = int(((sr["y_cs"] == 0) & (sr["p_cs"] == 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)) |
| |
|