"""Metric implementations for the PLUG challenge. Ported from ``plug-baselines/utils.py`` so that a leaderboard number and a published baseline number are computed by the same arithmetic. Every function here takes plain arrays and returns a plain float — nothing in this module knows about submissions, S3/Hub storage, or benchmarks. Three families cover all eleven benchmarks: - **Rank correlation** (``spearman``, ``grouped_spearman``) — the ddG, DMS, affinity and RMSF benchmarks. - **Ranking/detection** (``auroc``, ``macro_auroc``, ``grouped_auroc``) — the PPI and allosteric-site benchmarks. - **CAFA Fmax** (``fmax``) — GO term prediction. """ import warnings import numpy as np import numpy.typing as npt from loguru import logger from scipy.stats import ConstantInputWarning, spearmanr from sklearn.metrics import roc_auc_score # Returned instead of a float when a metric is mathematically undefined for the # data it was handed (a constant prediction column, a single-class label column, # a group with one member). Callers decide whether that is a validation failure # or a group to skip; nothing here raises. UNDEFINED = float("nan") def spearman(y_true: npt.ArrayLike, y_pred: npt.ArrayLike) -> float: """Spearman rank correlation, ignoring positions where either side is NaN. Parameters ---------- y_true : npt.ArrayLike Ground-truth values. y_pred : npt.ArrayLike Predicted values. Returns ------- float Spearman's rho, or ``UNDEFINED`` when fewer than two finite pairs remain or either side is constant (rho is undefined with zero variance — scipy returns NaN there rather than raising). """ y_true = np.asarray(y_true, dtype=float) y_pred = np.asarray(y_pred, dtype=float) keep = ~(np.isnan(y_true) | np.isnan(y_pred)) if keep.sum() < 2: return UNDEFINED # A constant column makes rho undefined; scipy warns and returns NaN, which # is exactly the UNDEFINED contract here, so the warning is noise. with warnings.catch_warnings(): warnings.simplefilter("ignore", category=ConstantInputWarning) rho = spearmanr(y_true[keep], y_pred[keep]).correlation return float(rho) if np.isfinite(rho) else UNDEFINED def auroc(y_true: npt.ArrayLike, y_score: npt.ArrayLike) -> float: """Area under the ROC curve for a binary label. Parameters ---------- y_true : npt.ArrayLike Binary labels (0/1 or bool). y_score : npt.ArrayLike Predicted scores; higher must mean "more likely positive". Returns ------- float AUROC, or ``UNDEFINED`` when the labels are single-class (AUROC is undefined without both classes present). """ y_true = np.asarray(y_true) y_score = np.asarray(y_score, dtype=float) if y_true.size == 0 or y_true.min() == y_true.max(): return UNDEFINED return float(roc_auc_score(y_true, y_score)) def macro_auroc(y_true: npt.ArrayLike, y_score: npt.ArrayLike) -> float: """Mean AUROC over the label columns that have both classes present. Single-class columns are skipped rather than scored as 0.5, matching ``plug-baselines``: a mode no test pair carries says nothing about the submission either way. Parameters ---------- y_true : npt.ArrayLike Binary label matrix, shape ``(n_samples, n_labels)``. y_score : npt.ArrayLike Predicted score matrix of the same shape. Returns ------- float Macro-averaged AUROC, or ``UNDEFINED`` when no column is scorable. """ y_true = np.asarray(y_true) y_score = np.asarray(y_score, dtype=float) per_label = [ roc_auc_score(y_true[:, k], y_score[:, k]) for k in range(y_true.shape[1]) if y_true[:, k].min() != y_true[:, k].max() ] return float(np.mean(per_label)) if per_label else UNDEFINED def fmax( y_true: npt.ArrayLike, y_score: npt.ArrayLike, step: float = 0.01, weights: npt.ArrayLike | None = None, ) -> dict[str, float | None]: """CAFA target-centric Fmax over a confidence-threshold sweep. Scores must be probabilities, hence the 0..1 grid. At each threshold, precision is averaged over the targets that predict at least one term while recall is averaged over every annotated target — that asymmetry is CAFA's: a target you decline to predict costs recall but not precision. Unannotated targets are dropped. Parameters ---------- y_true : npt.ArrayLike Boolean annotation matrix, shape ``(n_targets, n_terms)``. y_score : npt.ArrayLike Predicted probability matrix of the same shape. step : float Threshold grid spacing over ``[0, 1]``. weights : npt.ArrayLike | None Optional per-term information accretion, for the information-weighted variant. ``None`` weights every term equally. Returns ------- dict[str, float | None] ``fmax``, the ``threshold`` that achieved it, the ``precision`` and ``recall`` there, ``coverage`` (fraction of targets still predicting at that threshold), and the number of annotated ``targets``. Every value except ``targets`` is ``None`` when no target is annotated. """ y_true = np.asarray(y_true, dtype=bool) y_score = np.asarray(y_score, dtype=float) annotated = y_true.sum(axis=1) > 0 if not annotated.any(): return { "fmax": None, "threshold": None, "precision": None, "recall": None, "coverage": None, "targets": 0, } y_true, y_score = y_true[annotated], y_score[annotated] w = None if weights is None else np.asarray(weights, dtype=float) true_weight = (y_true * w).sum(axis=1) if w is not None else y_true.sum(axis=1).astype(float) best: dict[str, float | None] = { "fmax": 0.0, "threshold": None, "precision": None, "recall": None, "coverage": None, "targets": int(y_true.shape[0]), } for threshold in np.arange(0.0, 1.0 + step / 2, step): predicted = y_score >= threshold pred_weight = ( (predicted * w).sum(axis=1) if w is not None else predicted.sum(axis=1).astype(float) ) hit_weight = ( ((predicted & y_true) * w).sum(axis=1) if w is not None else (predicted & y_true).sum(axis=1).astype(float) ) predicting = pred_weight > 0 if not predicting.any(): continue precision = float((hit_weight[predicting] / pred_weight[predicting]).mean()) recall = float((hit_weight / true_weight).mean()) if precision + recall == 0: continue f1 = 2 * precision * recall / (precision + recall) current_best = best["fmax"] if current_best is None or f1 > current_best: best.update( fmax=f1, threshold=float(threshold), precision=precision, recall=recall, coverage=float(predicting.mean()), ) return best def grouped_spearman( y_true: npt.ArrayLike, y_pred: npt.ArrayLike, groups: npt.ArrayLike ) -> float: """Mean of the within-group Spearman correlations. Used where the ground-truth values are not on a common scale across groups and pooling them would measure between-group spread instead of within-group ranking — DMS (one assay per ``dms_id``) is the canonical case. Groups whose correlation is undefined (fewer than two points, or constant on either side) are skipped. Parameters ---------- y_true : npt.ArrayLike Ground-truth values. y_pred : npt.ArrayLike Predicted values. groups : npt.ArrayLike Group label per row. Returns ------- float Unweighted mean over scorable groups — every group counts once regardless of size — or ``UNDEFINED`` when no group is scorable. """ return _grouped_mean(spearman, y_true, y_pred, groups) def grouped_auroc(y_true: npt.ArrayLike, y_score: npt.ArrayLike, groups: npt.ArrayLike) -> float: """Mean of the within-group AUROCs. The per-protein counterpart to ``auroc`` for the per-residue benchmarks: it asks whether the sites are ranked correctly *within* each protein, which a pooled AUROC can hide when scores are calibrated differently per protein. Single-class groups are skipped. Parameters ---------- y_true : npt.ArrayLike Binary labels. y_score : npt.ArrayLike Predicted scores. groups : npt.ArrayLike Group label per row. Returns ------- float Unweighted mean over scorable groups, or ``UNDEFINED`` when no group is scorable. """ return _grouped_mean(auroc, y_true, y_score, groups) def _grouped_mean( metric, y_true: npt.ArrayLike, y_pred: npt.ArrayLike, groups: npt.ArrayLike ) -> float: """Apply ``metric`` within each group and average the defined results. Parameters ---------- metric : Callable[[npt.ArrayLike, npt.ArrayLike], float] A two-argument metric returning a float or ``UNDEFINED``. y_true : npt.ArrayLike Ground-truth values. y_pred : npt.ArrayLike Predicted values. groups : npt.ArrayLike Group label per row. Returns ------- float Mean over groups with a defined metric, or ``UNDEFINED`` if there are none. """ y_true = np.asarray(y_true) y_pred = np.asarray(y_pred) groups = np.asarray(groups) values = [] for group in np.unique(groups): mask = groups == group value = metric(y_true[mask], y_pred[mask]) if np.isfinite(value): values.append(value) if not values: logger.warning("No scorable groups — metric is undefined for this submission.") return UNDEFINED return float(np.mean(values)) def bootstrap( metric, n_samples: int, n_rows: int, seed: int = 0, groups: npt.ArrayLike | None = None, ) -> tuple[float, float]: """Resample row indices and return the mean and standard deviation of ``metric``. Resampling is at the row level by default. When ``groups`` is given, whole groups are resampled instead (every row of a drawn group comes along), which is the correct unit for the grouped metrics: a per-assay mean has as many independent observations as there are assays, not as there are variants. Parameters ---------- metric : Callable[[np.ndarray], float] Takes an array of row indices and returns that resample's metric value. n_samples : int Number of bootstrap resamples. ``0`` skips resampling entirely and returns the point estimate on all rows with a standard deviation of 0. n_rows : int Number of rows available to sample from. seed : int Seed for the resampling RNG, so a rescore reproduces the same interval. groups : npt.ArrayLike | None Optional group label per row; when given, groups rather than rows are the resampling unit. Returns ------- tuple[float, float] The mean and standard deviation of the metric over the resamples. With ``n_samples == 0``, the point estimate and ``0.0``. """ all_rows = np.arange(n_rows) if n_samples <= 0: return metric(all_rows), 0.0 rng = np.random.default_rng(seed) if groups is None: draws = [metric(rng.integers(0, n_rows, size=n_rows)) for _ in range(n_samples)] else: groups = np.asarray(groups) unique = np.unique(groups) rows_by_group = {g: all_rows[groups == g] for g in unique} draws = [] for _ in range(n_samples): drawn = unique[rng.integers(0, unique.size, size=unique.size)] draws.append(metric(np.concatenate([rows_by_group[g] for g in drawn]))) finite = np.asarray([d for d in draws if np.isfinite(d)], dtype=float) if finite.size == 0: return UNDEFINED, UNDEFINED return float(finite.mean()), float(finite.std()) def fmax_long( target_index: npt.ArrayLike, scores: npt.ArrayLike, is_true: npt.ArrayLike, true_per_target: npt.ArrayLike, step: float = 0.01, ) -> dict[str, float | None]: """CAFA Fmax computed from long-form predictions, without a dense matrix. Mathematically identical to ``fmax`` with equal term weights (the two are cross-checked against each other in the tests), but it consumes the ``(target, term, score)`` triples a submission actually carries. A dense ``targets × terms`` score matrix for CAFA5 runs to hundreds of megabytes, while this is linear in the number of predicted rows. Only annotated targets contribute, again matching CAFA: ``true_per_target`` carries a zero for an unannotated target and those targets are dropped from both the precision and the recall average. Parameters ---------- target_index : npt.ArrayLike Integer target index per predicted row, in ``[0, n_targets)``. scores : npt.ArrayLike Predicted confidence per row, in ``[0, 1]``. is_true : npt.ArrayLike Whether each predicted row's term is actually annotated on that target. true_per_target : npt.ArrayLike Number of annotated terms per target, length ``n_targets``. Zero marks an unannotated target. step : float Threshold grid spacing over ``[0, 1]``. Returns ------- dict[str, float | None] The same keys as ``fmax``. """ targets = np.asarray(target_index, dtype=np.int64) confidences = np.asarray(scores, dtype=float) correct = np.asarray(is_true, dtype=bool) true_counts = np.asarray(true_per_target, dtype=float) n_targets = true_counts.size annotated = true_counts > 0 n_annotated = int(annotated.sum()) if n_annotated == 0: return { "fmax": None, "threshold": None, "precision": None, "recall": None, "coverage": None, "targets": 0, } # Rows about unannotated targets cannot affect either average, so drop them up # front rather than masking inside the sweep. keep = annotated[targets] targets, confidences, correct = targets[keep], confidences[keep], correct[keep] best: dict[str, float | None] = { "fmax": 0.0, "threshold": None, "precision": None, "recall": None, "coverage": None, "targets": n_annotated, } for threshold in np.arange(0.0, 1.0 + step / 2, step): above = confidences >= threshold if not above.any(): continue hits = targets[above] predicted_per_target = np.bincount(hits, minlength=n_targets).astype(float) true_positive = np.bincount(hits[correct[above]], minlength=n_targets).astype(float) predicting = predicted_per_target > 0 if not predicting.any(): continue precision = float((true_positive[predicting] / predicted_per_target[predicting]).mean()) recall = float((true_positive[annotated] / true_counts[annotated]).mean()) if precision + recall == 0: continue f1 = 2 * precision * recall / (precision + recall) current_best = best["fmax"] if current_best is None or f1 > current_best: best.update( fmax=f1, threshold=float(threshold), precision=precision, recall=recall, coverage=float(predicting.sum() / n_annotated), ) return best