"""Metrics for the benchmark, with the sklearn calling convention. Every metric is called ``metric(y_true, y_pred)`` on 1-D arrays over candidate nodes -- by default the nodes of every change pooled together, with ``pooled=False`` the nodes of one change at a time -- so any scikit-learn classification metric drops in unchanged and CoReDD stays metric-agnostic. This module only keeps what scikit-learn does not provide: the ``rank`` marker, ``mrr``, and an ``auroc`` wrapper that is NaN where ``roc_auc_score`` raises, so a degenerate change is dropped from a per-case average rather than aborting the run. A metric is either **label** (``y_pred`` is boolean: which nodes were predicted) or **rank** (``y_pred`` is a per-node score). The ``rank`` marker tells the evaluator to hand the metric the node scores rather than a boolean mask. Pass ``sklearn.metrics`` functions directly for label metrics; they are treated as label by default. """ from __future__ import annotations import numpy as np from sklearn.metrics import roc_auc_score def rank(func): """Mark a metric as consuming per-node scores rather than a boolean mask.""" func.rank = True return func def is_rank(metric) -> bool: """Whether a metric expects scores (``rank``) instead of a boolean prediction.""" return bool(getattr(metric, "rank", False)) @rank def mrr(y_true, scores) -> float: """Reciprocal rank of the first true positive under the score order; NaN if none.""" y_true = np.asarray(y_true, dtype=bool) scores = np.asarray(scores, dtype=float) order = np.argsort(-scores, kind="stable") ranked = y_true[order] if not ranked.any(): return float("nan") return 1.0 / (int(np.argmax(ranked)) + 1) @rank def auroc(y_true, scores) -> float: """ROC AUC; NaN when there is no positive or no negative to separate.""" y_true = np.asarray(y_true, dtype=bool) if not y_true.any() or y_true.all(): return float("nan") return float(roc_auc_score(y_true, scores))