""" Clarus v0.8 reference scorer. Usage: python scorer.py \ --ground_truth data/train.csv \ --predictions predictions.csv Returns classification metrics and regime-transition diagnostics. """ import csv import json from collections import Counter TRANSITION_SCORE_THRESHOLD = 0.50 HIGH_TRANSITION_UNCERTAINTY_THRESHOLD = 0.25 BOUNDARY_COMPETITION_NEAR_THRESHOLD = 1.15 def _normalize_label(value): if value is None: return None text = str(value).strip().lower() if text in {"1", "true", "yes", "y", "positive"}: return 1 if text in {"0", "false", "no", "n", "negative"}: return 0 try: return int(float(text)) except ValueError as exc: raise ValueError(f"Unable to normalize label value: {value}") from exc def _safe_float(value): if value is None: return None text = str(value).strip() if text == "": return None try: return float(text) except ValueError: return None def _safe_str(value): if value is None: return None text = str(value).strip() return text if text else None def _read_csv(path): with open(path, "r", encoding="utf-8") as f: return list(csv.DictReader(f)) def _find_label_column(fieldnames): matches = [name for name in fieldnames if name.startswith("label_")] if not matches: raise KeyError("No label column found. Expected a column starting with 'label_'.") if len(matches) > 1: raise KeyError(f"Multiple label columns found: {matches}") return matches[0] def _extract_labels(rows, label_column): if not rows: raise ValueError("CSV has no rows.") if label_column not in rows[0]: raise KeyError(f"Expected label column '{label_column}' not found.") return [_normalize_label(row[label_column]) for row in rows] def _accuracy(y_true, y_pred): correct = sum(1 for a, b in zip(y_true, y_pred) if a == b) return correct / len(y_true) if y_true else 0.0 def _confusion_matrix(y_true, y_pred): tp = sum(1 for a, b in zip(y_true, y_pred) if a == 1 and b == 1) tn = sum(1 for a, b in zip(y_true, y_pred) if a == 0 and b == 0) fp = sum(1 for a, b in zip(y_true, y_pred) if a == 0 and b == 1) fn = sum(1 for a, b in zip(y_true, y_pred) if a == 1 and b == 0) return {"tp": tp, "tn": tn, "fp": fp, "fn": fn} def _precision(tp, fp): denom = tp + fp return tp / denom if denom else 0.0 def _recall(tp, fn): denom = tp + fn return tp / denom if denom else 0.0 def _f1(precision, recall): denom = precision + recall return 2 * precision * recall / denom if denom else 0.0 def _mean(values): values = [v for v in values if v is not None] return sum(values) / len(values) if values else None def _ratio(num, denom): return num / denom if denom else 0.0 def _truth_transition_flag(row): score = _safe_float(row.get("regime_transition_score")) if score is None: return None return 1 if score >= TRANSITION_SCORE_THRESHOLD else 0 def _pred_transition_flag(row): score = _safe_float(row.get("regime_transition_score")) if score is None: return None return 1 if score >= TRANSITION_SCORE_THRESHOLD else 0 def _direction_match(truth_row, pred_row): truth_dir = _safe_str(truth_row.get("transition_direction")) pred_dir = _safe_str(pred_row.get("transition_direction")) if truth_dir is None or pred_dir is None: return None return 1 if truth_dir == pred_dir else 0 def _regime_transition_diagnostics(truth_rows, pred_rows): true_transition_count = 0 detected_transition_count = 0 predicted_stable_count = 0 false_stable_count = 0 predicted_transition_count = 0 false_transition_count = 0 transition_eval_count = 0 transition_correct_count = 0 direction_eval_count = 0 direction_correct_count = 0 missed_transition_count = 0 high_uncertainty_missed_transition_count = 0 competition_error_values = [] primary_regime_eval_count = 0 misidentified_primary_regime_count = 0 for truth_row, pred_row in zip(truth_rows, pred_rows): truth_transition = _truth_transition_flag(truth_row) pred_transition = _pred_transition_flag(pred_row) if truth_transition is not None and pred_transition is not None: transition_eval_count += 1 if truth_transition == pred_transition: transition_correct_count += 1 if pred_transition == 1: predicted_transition_count += 1 if truth_transition == 0: false_transition_count += 1 if truth_transition is not None: if truth_transition == 1: true_transition_count += 1 if pred_transition == 1: detected_transition_count += 1 else: missed_transition_count += 1 truth_unc = _safe_float(truth_row.get("transition_uncertainty")) if ( truth_unc is not None and truth_unc >= HIGH_TRANSITION_UNCERTAINTY_THRESHOLD ): high_uncertainty_missed_transition_count += 1 if pred_transition == 0: predicted_stable_count += 1 if truth_transition == 1: false_stable_count += 1 if truth_transition == 1 and pred_transition == 1: match = _direction_match(truth_row, pred_row) if match is not None: direction_eval_count += 1 direction_correct_count += match truth_ratio = _safe_float(truth_row.get("boundary_competition_ratio")) pred_ratio = _safe_float(pred_row.get("boundary_competition_ratio")) if truth_ratio is not None and pred_ratio is not None: competition_error_values.append(abs(truth_ratio - pred_ratio)) truth_bd = _safe_float(truth_row.get("boundary_distance")) truth_sbd = _safe_float(truth_row.get("secondary_boundary_distance")) pred_bd = _safe_float(pred_row.get("boundary_distance")) pred_sbd = _safe_float(pred_row.get("secondary_boundary_distance")) if None not in (truth_bd, truth_sbd, pred_bd, pred_sbd): primary_regime_eval_count += 1 truth_primary = "primary" if truth_bd <= truth_sbd else "secondary" pred_primary = "primary" if pred_bd <= pred_sbd else "secondary" if truth_primary != pred_primary: misidentified_primary_regime_count += 1 return { "recall_regime_transition_detection": round( _ratio(detected_transition_count, true_transition_count), 6 ), "false_stable_regime_rate": round( _ratio(false_stable_count, predicted_stable_count), 6 ), "transition_direction_accuracy": round( _ratio(direction_correct_count, direction_eval_count), 6 ), "high_uncertainty_transition_miss_rate": round( _ratio(high_uncertainty_missed_transition_count, missed_transition_count), 6 ), "transition_detection_accuracy": round( _ratio(transition_correct_count, transition_eval_count), 6 ), "false_transition_rate": round( _ratio(false_transition_count, predicted_transition_count), 6 ), "missed_transition_rate": round( _ratio(missed_transition_count, true_transition_count), 6 ), "boundary_competition_error": round( _mean(competition_error_values) or 0.0, 6 ), "misidentified_primary_regime_rate": round( _ratio(misidentified_primary_regime_count, primary_regime_eval_count), 6 ), "support": { "true_transition_count": true_transition_count, "predicted_transition_count": predicted_transition_count, "predicted_stable_count": predicted_stable_count, "transition_eval_count": transition_eval_count, "direction_eval_count": direction_eval_count, "missed_transition_count": missed_transition_count, "primary_regime_eval_count": primary_regime_eval_count, }, } def score(ground_truth_path, predictions_path): truth_rows = _read_csv(ground_truth_path) pred_rows = _read_csv(predictions_path) if len(truth_rows) != len(pred_rows): raise ValueError( f"Row count mismatch: ground truth has {len(truth_rows)} rows, " f"predictions has {len(pred_rows)} rows." ) if not truth_rows: raise ValueError("Ground truth CSV has no rows.") if not pred_rows: raise ValueError("Predictions CSV has no rows.") label_column = _find_label_column(truth_rows[0].keys()) y_true = _extract_labels(truth_rows, label_column) y_pred = _extract_labels(pred_rows, label_column) cm = _confusion_matrix(y_true, y_pred) precision = _precision(cm["tp"], cm["fp"]) recall = _recall(cm["tp"], cm["fn"]) f1 = _f1(precision, recall) accuracy = _accuracy(y_true, y_pred) regime_diag = _regime_transition_diagnostics(truth_rows, pred_rows) return { "label_column": label_column, "num_rows": len(y_true), "class_balance": dict(Counter(y_true)), "primary_metric": "recall_regime_transition_detection", "secondary_metric": "false_stable_regime_rate", "thresholds": { "transition_score_threshold": TRANSITION_SCORE_THRESHOLD, "high_transition_uncertainty_threshold": HIGH_TRANSITION_UNCERTAINTY_THRESHOLD, "boundary_competition_near_threshold": BOUNDARY_COMPETITION_NEAR_THRESHOLD, }, "classification_metrics": { "accuracy": round(accuracy, 6), "precision": round(precision, 6), "recall": round(recall, 6), "f1": round(f1, 6), "confusion_matrix": cm, }, "regime_transition_diagnostics": regime_diag, } if __name__ == "__main__": import argparse parser = argparse.ArgumentParser( description="Canonical scorer for Clarus v0.8 regime transition geometry datasets." ) parser.add_argument( "--ground_truth", type=str, required=True, help="Path to the CSV file containing ground truth labels and transition fields.", ) parser.add_argument( "--predictions", type=str, required=True, help="Path to the CSV file containing predicted labels and transition fields.", ) args = parser.parse_args() results = score(args.ground_truth, args.predictions) print(json.dumps(results, indent=2))