import json import pandas as pd VALID_LEVELS = {"low": 0, "medium": 1, "high": 2} VALID_LABELS = {"coherent", "tradeoff", "collapse_risk"} LEVEL_COLS = [ "signal_detection_drift", "ae_coding_variance", "unblinding_risk", "dsmb_decision_delay", ] def _level(x) -> int: s = str(x).strip().lower() if s not in VALID_LEVELS: raise ValueError(f"Bad level value: {x}") return VALID_LEVELS[s] def _label(x) -> str: s = str(x).strip() if s not in VALID_LABELS: raise ValueError(f"Bad label value: {x}") return s def predict_label(row) -> str: sdd, aec, unb, dsmb = [_level(row[c]) for c in LEVEL_COLS] levels = [sdd, aec, unb, dsmb] high_count = sum(v == 2 for v in levels) low_count = sum(v == 0 for v in levels) total = sum(levels) if high_count == 4: return "collapse_risk" # coherent = no highs and minimal strain (allows one medium) if high_count == 0 and total <= 1: return "coherent" return "tradeoff" def risk_score(row) -> float: levels = [_level(row[c]) for c in LEVEL_COLS] # 0.0 to 1.0 return sum(levels) / 8.0 def run_scorer(csv_path: str, label_col: str = "label"): df = pd.read_csv(csv_path) missing = [c for c in (["trial_id"] + LEVEL_COLS + [label_col]) if c not in df.columns] if missing: raise ValueError(f"Missing columns: {missing}") # Validate inputs for c in LEVEL_COLS: df[c].apply(_level) df[label_col] = df[label_col].apply(_label) df["prediction"] = df.apply(predict_label, axis=1) df["risk_score"] = df.apply(risk_score, axis=1) df["correct"] = df["prediction"] == df[label_col] report = { "n": int(len(df)), "accuracy": float(df["correct"].mean()), "pred_counts": df["prediction"].value_counts().to_dict(), "gold_counts": df[label_col].value_counts().to_dict(), "avg_risk_score": float(df["risk_score"].mean()), "confusion": pd.crosstab( df[label_col], df["prediction"], rownames=["gold"], colnames=["pred"], dropna=False ).to_dict(), "errors": df.loc[~df["correct"], ["trial_id", label_col, "prediction", "risk_score"]] .to_dict(orient="records"), } return df, report if __name__ == "__main__": import argparse p = argparse.ArgumentParser() p.add_argument("--csv", required=True) p.add_argument("--label_col", default="label") args = p.parse_args() _, report = run_scorer(args.csv, label_col=args.label_col) print(json.dumps(report, indent=2))