from __future__ import annotations from typing import Any import numpy as np import pandas as pd from .data import expand_triplets def auroc_safe(y_true: pd.Series | np.ndarray, y_score: pd.Series | np.ndarray) -> float: """Rank-based AUROC with average ranks for ties.""" y = pd.Series(y_true).astype(float) s = pd.to_numeric(pd.Series(y_score), errors="coerce") mask = np.isfinite(y) & np.isfinite(s) y = y[mask].astype(int) s = s[mask].astype(float) if y.nunique() < 2: return float("nan") n_pos = int((y == 1).sum()) n_neg = int((y == 0).sum()) if n_pos == 0 or n_neg == 0: return float("nan") ranks = s.rank(method="average") pos_rank_sum = float(ranks[y == 1].sum()) return (pos_rank_sum - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg) def _score_column(predictions: pd.DataFrame, requested: str | None) -> str: if requested and requested in predictions.columns: return requested for candidate in ("score", "score_norm", "raw_score"): if candidate in predictions.columns: return candidate raise ValueError("Predictions must contain a score column, e.g. score or score_norm.") def _standardize_negative_index(df: pd.DataFrame) -> pd.DataFrame: df = df.copy() if "negative_index" in df.columns: df["negative_index"] = pd.to_numeric(df["negative_index"], errors="coerce").fillna(-1).astype(int) return df def align_predictions( dataset_df: pd.DataFrame, predictions: pd.DataFrame, score_col: str | None = None, ) -> pd.DataFrame: """Align model scores to EditJudge-Bench triplets. Supported prediction schemas: 1. Expanded rows with label/edit_type/negative_type/score already present. 2. Rows keyed by sample_id or parquet_row_index plus example_type and negative_index. 3. Rows keyed by sample_id or parquet_row_index plus instruction text. """ predictions = _standardize_negative_index(predictions) score_col = _score_column(predictions, score_col) predictions = predictions.rename(columns={score_col: "score"}).copy() predictions["score"] = pd.to_numeric(predictions["score"], errors="coerce") expanded_cols = {"label", "edit_type", "negative_type", "score"} if expanded_cols.issubset(predictions.columns): out = predictions.copy() if "ground_truth" not in out.columns: out["ground_truth"] = out["label"].astype(bool) return out triplets = expand_triplets(dataset_df) key = "sample_id" if "sample_id" in predictions.columns else "parquet_row_index" if key not in predictions.columns: raise ValueError("Predictions must contain sample_id or parquet_row_index.") if {"example_type", "negative_index"}.issubset(predictions.columns): join_cols = [key, "example_type", "negative_index"] elif "instruction" in predictions.columns: join_cols = [key, "instruction"] else: raise ValueError( "Predictions must include either example_type+negative_index or instruction." ) keep_cols = join_cols + ["score"] + [ col for col in ("raw_score", "raw_output", "model", "method") if col in predictions.columns ] merged = triplets.merge(predictions[keep_cols], on=join_cols, how="left", validate="one_to_one") missing = int(merged["score"].isna().sum()) if missing: raise ValueError(f"Could not align {missing} triplets to prediction scores.") return merged def compute_overall_metrics(aligned: pd.DataFrame) -> pd.DataFrame: per_edit = per_edit_type_auc(aligned) row: dict[str, Any] = { "global_auc": auroc_safe(aligned["label"], aligned["score"]), "macro_edit_auc": per_edit["auc"].mean(), "n_triplets": int(len(aligned)), "n_edits": int(aligned["sample_id"].nunique()) if "sample_id" in aligned.columns else np.nan, } return pd.DataFrame([row]) def per_edit_type_auc(aligned: pd.DataFrame) -> pd.DataFrame: rows = [] for edit_type, group in aligned.groupby("edit_type", sort=True): rows.append( { "edit_type": edit_type, "auc": auroc_safe(group["label"], group["score"]), "n_triplets": int(len(group)), "n_edits": int(group["sample_id"].nunique()) if "sample_id" in group.columns else np.nan, } ) return pd.DataFrame(rows) def per_negative_type_auc(aligned: pd.DataFrame) -> pd.DataFrame: positives = aligned[aligned["label"] == 1] negatives = aligned[aligned["label"] == 0] rows = [] for negative_type, neg_group in negatives.groupby("negative_type", sort=True): group = pd.concat([positives, neg_group], ignore_index=True) rows.append( { "negative_type": negative_type, "auc": auroc_safe(group["label"], group["score"]), "n_negative_triplets": int(len(neg_group)), "n_positive_triplets": int(len(positives)), } ) return pd.DataFrame(rows) def semantic_vs_noedit_summary(per_negative: pd.DataFrame) -> pd.DataFrame: semantic_names = {"counterfactual", "cross_type", "wrong_object"} semantic = per_negative[per_negative["negative_type"].isin(semantic_names)] no_edit = per_negative[per_negative["negative_type"].eq("no_edit")] return pd.DataFrame( [ { "semantic_auc": semantic["auc"].mean(), "no_edit_auc": no_edit["auc"].mean(), "semantic_negative_types": ",".join(sorted(semantic["negative_type"].unique())), } ] )