Datasets:
Download scorer.py from ClarusC64/clinical-five-node-mof-cascade-boundary-v1.0: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/datasets/ClarusC64/clinical-five-node-mof-cascade-boundary-v1.0/resolve/main/scorer.py
- Command line
-
hf download hf://datasets/ClarusC64/clinical-five-node-mof-cascade-boundary-v1.0/scorer.py
-
curl -L -o scorer.py https://huggingface.co/datasets/ClarusC64/clinical-five-node-mof-cascade-boundary-v1.0/resolve/main/scorer.py
12.6 kB
| import csv | |
| import json | |
| import sys | |
| from typing import Any, Dict, List | |
| LABEL_COL = "label_mof_boundary" | |
| POSITIVE_LABEL = 1 | |
| PRIMARY_METRIC = "recall_correct_control_sequence_selection" | |
| SECONDARY_METRIC = "false_effective_control_rate" | |
| CONTROL_ALIGNMENT_THRESHOLD = 0.60 | |
| INTERVENTION_ALIGNMENT_THRESHOLD = 0.60 | |
| RECOVERY_CONSISTENCY_THRESHOLD = 0.60 | |
| HIGH_UNCERTAINTY_THRESHOLD = 0.25 | |
| NARROW_WINDOW_THRESHOLD = 0.30 | |
| OSCILLATION_THRESHOLD = 0.25 | |
| STABLE_MARGIN_THRESHOLD = 0.60 | |
| TRAJECTORY_SHIFT_THRESHOLD = -0.10 | |
| def _to_float(value: Any, default: float = 0.0) -> float: | |
| try: | |
| return float(value) | |
| except (TypeError, ValueError): | |
| return default | |
| def _to_int(value: Any, default: int = 0) -> int: | |
| try: | |
| return int(float(value)) | |
| except (TypeError, ValueError): | |
| return default | |
| def _safe_div(numerator: float, denominator: float) -> float: | |
| return numerator / denominator if denominator else 0.0 | |
| def _read_csv(path: str) -> List[Dict[str, str]]: | |
| with open(path, "r", encoding="utf-8", newline="") as f: | |
| return list(csv.DictReader(f)) | |
| def _normalize_string(value: Any) -> str: | |
| if value is None: | |
| return "" | |
| return str(value).strip().lower() | |
| def _normalize_label(row: Dict[str, str]) -> int: | |
| if LABEL_COL in row: | |
| return _to_int(row[LABEL_COL]) | |
| for key, value in row.items(): | |
| if key.startswith("label_"): | |
| return _to_int(value) | |
| raise ValueError( | |
| f"No label column found in row. Expected '{LABEL_COL}' or a column starting with 'label_'." | |
| ) | |
| def _confusion(y_true: List[int], y_pred: List[int]) -> Dict[str, int]: | |
| tp = fp = tn = fn = 0 | |
| for yt, yp in zip(y_true, y_pred): | |
| if yt == 1 and yp == 1: | |
| tp += 1 | |
| elif yt == 0 and yp == 1: | |
| fp += 1 | |
| elif yt == 0 and yp == 0: | |
| tn += 1 | |
| elif yt == 1 and yp == 0: | |
| fn += 1 | |
| return {"tp": tp, "fp": fp, "tn": tn, "fn": fn} | |
| def _accuracy(y_true: List[int], y_pred: List[int]) -> float: | |
| return _safe_div(sum(1 for a, b in zip(y_true, y_pred) if a == b), len(y_true)) | |
| def _precision(cm: Dict[str, int]) -> float: | |
| return _safe_div(cm["tp"], cm["tp"] + cm["fp"]) | |
| def _recall(cm: Dict[str, int]) -> float: | |
| return _safe_div(cm["tp"], cm["tp"] + cm["fn"]) | |
| def _f1(precision: float, recall: float) -> float: | |
| return _safe_div(2 * precision * recall, precision + recall) | |
| def _mean_abs_error(true_vals: List[float], pred_vals: List[float]) -> float: | |
| if not true_vals: | |
| return 0.0 | |
| return sum(abs(a - b) for a, b in zip(true_vals, pred_vals)) / len(true_vals) | |
| def _rate(mask: List[bool], condition: List[bool]) -> float: | |
| idx = [i for i, flag in enumerate(mask) if flag] | |
| if not idx: | |
| return 0.0 | |
| return sum(1 for i in idx if condition[i]) / len(idx) | |
| def _string_accuracy(true_vals: List[str], pred_vals: List[str]) -> float: | |
| if not true_vals: | |
| return 0.0 | |
| return _safe_div( | |
| sum( | |
| 1 for a, b in zip(true_vals, pred_vals) | |
| if _normalize_string(a) == _normalize_string(b) | |
| ), | |
| len(true_vals), | |
| ) | |
| def _threshold_accuracy( | |
| gold: List[Dict[str, str]], | |
| pred: List[Dict[str, str]], | |
| field: str, | |
| threshold: float, | |
| ) -> float: | |
| true_flags = [_to_float(row.get(field, 0.0)) >= threshold for row in gold] | |
| pred_flags = [_to_float(row.get(field, 0.0)) >= threshold for row in pred] | |
| return _safe_div( | |
| sum(1 for a, b in zip(true_flags, pred_flags) if a == b), | |
| len(true_flags), | |
| ) | |
| def _validate_inputs(gold: List[Dict[str, str]], pred: List[Dict[str, str]]) -> None: | |
| if len(gold) != len(pred): | |
| raise ValueError("Solution and submission row counts do not match.") | |
| if not gold: | |
| raise ValueError("Solution file is empty.") | |
| if not pred: | |
| raise ValueError("Submission file is empty.") | |
| gold_has_id = all("scenario_id" in row for row in gold) | |
| pred_has_id = all("scenario_id" in row for row in pred) | |
| if gold_has_id and pred_has_id: | |
| for i, (g_row, p_row) in enumerate(zip(gold, pred)): | |
| if _normalize_string(g_row.get("scenario_id")) != _normalize_string(p_row.get("scenario_id")): | |
| raise ValueError( | |
| f"Scenario mismatch at row {i + 1}: " | |
| f"{g_row.get('scenario_id')} != {p_row.get('scenario_id')}" | |
| ) | |
| def score(solution_file: str, submission_file: str) -> Dict[str, Any]: | |
| gold = _read_csv(solution_file) | |
| pred = _read_csv(submission_file) | |
| _validate_inputs(gold, pred) | |
| y_true = [_normalize_label(row) for row in gold] | |
| y_pred = [_normalize_label(row) for row in pred] | |
| cm = _confusion(y_true, y_pred) | |
| accuracy = _accuracy(y_true, y_pred) | |
| precision = _precision(cm) | |
| recall = _recall(cm) | |
| f1 = _f1(precision, recall) | |
| # Primary v1.0 success condition: | |
| # A row counts as a true control success only when the system truly stabilized, | |
| # the trajectory improved meaningfully, the intervention was aligned, | |
| # the control sequence itself was aligned, and recovery remained coherent. | |
| primary_true = [ | |
| _to_int(row.get("stabilization_success", 0)) == 1 | |
| and _to_float(row.get("trajectory_shift", 0.0)) < TRAJECTORY_SHIFT_THRESHOLD | |
| and _to_float(row.get("intervention_alignment_score", 0.0)) >= INTERVENTION_ALIGNMENT_THRESHOLD | |
| and _to_float(row.get("control_sequence_alignment_score", 0.0)) >= CONTROL_ALIGNMENT_THRESHOLD | |
| and _to_float(row.get("recovery_consistency_score", 0.0)) >= RECOVERY_CONSISTENCY_THRESHOLD | |
| for row in gold | |
| ] | |
| primary_pred = [pred_label == POSITIVE_LABEL for pred_label in y_pred] | |
| recall_correct_control_sequence_selection = _rate(primary_true, primary_pred) | |
| false_effective_control_rate = _rate( | |
| primary_pred, | |
| [not flag for flag in primary_true] | |
| ) | |
| primary_intervention_path_accuracy = _string_accuracy( | |
| [row.get("primary_intervention_path", "") for row in gold], | |
| [row.get("primary_intervention_path", "") for row in pred], | |
| ) | |
| secondary_intervention_path_accuracy = _string_accuracy( | |
| [row.get("secondary_intervention_path", "") for row in gold], | |
| [row.get("secondary_intervention_path", "") for row in pred], | |
| ) | |
| control_sequence_alignment_accuracy = _threshold_accuracy( | |
| gold, pred, "control_sequence_alignment_score", CONTROL_ALIGNMENT_THRESHOLD | |
| ) | |
| feedback_response_accuracy = _threshold_accuracy( | |
| gold, pred, "feedback_response_score", CONTROL_ALIGNMENT_THRESHOLD | |
| ) | |
| intervention_timing_accuracy = _threshold_accuracy( | |
| gold, pred, "intervention_timing_score", CONTROL_ALIGNMENT_THRESHOLD | |
| ) | |
| missed_rescues = [ | |
| primary_true[i] and not primary_pred[i] | |
| for i in range(len(primary_true)) | |
| ] | |
| # Miss-conditioned diagnostics resolve to 0.0 by design when there are zero missed rescues. | |
| # Of missed rescues, what fraction occurred under high intervention uncertainty. | |
| high_uncertainty_control_miss_rate = _rate( | |
| missed_rescues, | |
| [_to_float(row.get("intervention_uncertainty", 0.0)) >= HIGH_UNCERTAINTY_THRESHOLD for row in gold] | |
| ) | |
| # Of missed rescues, what fraction occurred in narrow rescue windows. | |
| narrow_window_control_miss_rate = _rate( | |
| missed_rescues, | |
| [_to_float(row.get("rescue_window_width", 0.0)) <= NARROW_WINDOW_THRESHOLD for row in gold] | |
| ) | |
| adaptation_latency_error = _mean_abs_error( | |
| [_to_float(row.get("adaptation_latency", 0.0)) for row in gold], | |
| [_to_float(row.get("adaptation_latency", 0.0)) for row in pred], | |
| ) | |
| control_stability_error = _mean_abs_error( | |
| [_to_float(row.get("control_stability_margin", 0.0)) for row in gold], | |
| [_to_float(row.get("control_stability_margin", 0.0)) for row in pred], | |
| ) | |
| recovery_consistency_error = _mean_abs_error( | |
| [_to_float(row.get("recovery_consistency_score", 0.0)) for row in gold], | |
| [_to_float(row.get("recovery_consistency_score", 0.0)) for row in pred], | |
| ) | |
| control_horizon_error = _mean_abs_error( | |
| [_to_float(row.get("control_horizon", 0.0)) for row in gold], | |
| [_to_float(row.get("control_horizon", 0.0)) for row in pred], | |
| ) | |
| recalibration_overuse_rate = _rate( | |
| [True] * len(gold), | |
| [ | |
| _to_int(pred[i].get("control_recalibration_count", 0)) > | |
| _to_int(gold[i].get("control_recalibration_count", 0)) | |
| and _to_float(gold[i].get("control_stability_margin", 0.0)) >= STABLE_MARGIN_THRESHOLD | |
| for i in range(len(gold)) | |
| ] | |
| ) | |
| controller_oscillation_misread_rate = _rate( | |
| [True] * len(gold), | |
| [ | |
| (_to_float(gold[i].get("controller_oscillation_score", 0.0)) >= OSCILLATION_THRESHOLD) | |
| != (_to_float(pred[i].get("controller_oscillation_score", 0.0)) >= OSCILLATION_THRESHOLD) | |
| for i in range(len(gold)) | |
| ] | |
| ) | |
| terminal_pathway_state_accuracy = _string_accuracy( | |
| [row.get("terminal_pathway_state", "") for row in gold], | |
| [row.get("terminal_pathway_state", "") for row in pred], | |
| ) | |
| positive_class_count = sum(y_true) | |
| negative_class_count = len(y_true) - positive_class_count | |
| primary_true_count = sum(primary_true) | |
| primary_pred_count = sum(primary_pred) | |
| missed_rescue_count = sum(missed_rescues) | |
| result = { | |
| "primary_metric": PRIMARY_METRIC, | |
| "secondary_metric": SECONDARY_METRIC, | |
| "binary_metrics": { | |
| "accuracy": round(accuracy, 6), | |
| "precision": round(precision, 6), | |
| "recall": round(recall, 6), | |
| "f1": round(f1, 6), | |
| "confusion_matrix": cm | |
| }, | |
| "diagnostics": { | |
| PRIMARY_METRIC: round(recall_correct_control_sequence_selection, 6), | |
| SECONDARY_METRIC: round(false_effective_control_rate, 6), | |
| "primary_intervention_path_accuracy": round(primary_intervention_path_accuracy, 6), | |
| "secondary_intervention_path_accuracy": round(secondary_intervention_path_accuracy, 6), | |
| "control_sequence_alignment_accuracy": round(control_sequence_alignment_accuracy, 6), | |
| "control_horizon_error": round(control_horizon_error, 6), | |
| "feedback_response_accuracy": round(feedback_response_accuracy, 6), | |
| "intervention_timing_accuracy": round(intervention_timing_accuracy, 6), | |
| "high_uncertainty_control_miss_rate": round(high_uncertainty_control_miss_rate, 6), | |
| "narrow_window_control_miss_rate": round(narrow_window_control_miss_rate, 6), | |
| "adaptation_latency_error": round(adaptation_latency_error, 6), | |
| "control_stability_error": round(control_stability_error, 6), | |
| "recovery_consistency_error": round(recovery_consistency_error, 6), | |
| "recalibration_overuse_rate": round(recalibration_overuse_rate, 6), | |
| "controller_oscillation_misread_rate": round(controller_oscillation_misread_rate, 6), | |
| "terminal_pathway_state_accuracy": round(terminal_pathway_state_accuracy, 6) | |
| }, | |
| "support": { | |
| "num_rows": len(gold), | |
| "primary_true_count": primary_true_count, | |
| "primary_pred_count": primary_pred_count, | |
| "missed_rescue_count": missed_rescue_count, | |
| "positive_class_count": positive_class_count, | |
| "negative_class_count": negative_class_count | |
| }, | |
| "class_balance": { | |
| "positive_rate": round(_safe_div(positive_class_count, len(y_true)), 6), | |
| "negative_rate": round(_safe_div(negative_class_count, len(y_true)), 6) | |
| }, | |
| "thresholds": { | |
| "control_alignment_threshold": CONTROL_ALIGNMENT_THRESHOLD, | |
| "intervention_alignment_threshold": INTERVENTION_ALIGNMENT_THRESHOLD, | |
| "recovery_consistency_threshold": RECOVERY_CONSISTENCY_THRESHOLD, | |
| "high_uncertainty_threshold": HIGH_UNCERTAINTY_THRESHOLD, | |
| "narrow_window_threshold": NARROW_WINDOW_THRESHOLD, | |
| "oscillation_threshold": OSCILLATION_THRESHOLD, | |
| "stable_margin_threshold": STABLE_MARGIN_THRESHOLD, | |
| "trajectory_shift_threshold": TRAJECTORY_SHIFT_THRESHOLD | |
| } | |
| } | |
| return result | |
| if __name__ == "__main__": | |
| if len(sys.argv) != 3: | |
| raise SystemExit("Usage: python scorer.py <solution_file> <submission_file>") | |
| scores = score(sys.argv[1], sys.argv[2]) | |
| print(json.dumps(scores, indent=2)) | |