"""Turn a validated submission bundle into per-benchmark metric values. One function per submission (``score_bundle``) and one per benchmark (``score_benchmark``); which arithmetic runs is decided entirely by the ``MetricSpec.kind`` values in ``benchmarks.py``, so adding a metric to a benchmark is a one-line change there and needs no edit here. Scoring is deliberately separate from validation: by the time anything in this module runs, the frames are known to have the right columns, the right ids and finite values, so the metric code can assume a clean join. """ import numpy as np import pandas as pd from loguru import logger from . import metrics from .benchmarks import GO_ASPECTS, ID_COLUMN, BenchmarkSpec, MetricSpec # Bootstrap resampling is not implemented for the long-form (cafa5) scorer: a # resample has to redraw whole targets and recount each one's annotations, and a # 101-point Fmax sweep per resample is far too slow to run inside a submission # request. Its std is reported as 0.0 and the point estimate is exact. _BOOTSTRAP_UNSUPPORTED = ("fmax",) def score_bundle( frames: dict[str, pd.DataFrame], truth: dict[str, pd.DataFrame], specs: tuple[BenchmarkSpec, ...], bootstrap_samples: int = 0, seed: int = 0, ) -> dict[str, dict[str, float]]: """Score every benchmark present in both the submission and the ground truth. Parameters ---------- frames : dict[str, pd.DataFrame] Benchmark name -> validated predictions, as returned by ``validation.ValidationResult.frames``. truth : dict[str, pd.DataFrame] Benchmark name -> that benchmark's ground truth, narrowed to the track being scored. specs : tuple[BenchmarkSpec, ...] The benchmarks to score, in leaderboard order. bootstrap_samples : int Resamples per metric for the standard deviation. ``0`` reports point estimates only, which is the Space default — see ``config``. seed : int Seed for the bootstrap RNG, so rescoring a submission reproduces it. Returns ------- dict[str, dict[str, float]] Benchmark name -> ``{"_mean": ..., "_std": ..., "n": ...}``. A benchmark absent from either input is absent from the result rather than scored as zero. """ scores: dict[str, dict[str, float]] = {} for spec in specs: if spec.name not in frames or spec.name not in truth: continue scores[spec.name] = score_benchmark( spec, frames[spec.name], truth[spec.name], bootstrap_samples=bootstrap_samples, seed=seed, ) logger.info( "Scored {}: {} = {:.4f} (n={})", spec.name, spec.primary.key, scores[spec.name][f"{spec.primary.key}_mean"], scores[spec.name]["n"], ) return scores def score_benchmark( spec: BenchmarkSpec, predictions: pd.DataFrame, truth: pd.DataFrame, bootstrap_samples: int = 0, seed: int = 0, ) -> dict[str, float]: """Compute every metric one benchmark reports. Parameters ---------- spec : BenchmarkSpec The benchmark being scored. predictions : pd.DataFrame Validated predictions for this benchmark. truth : pd.DataFrame This benchmark's ground truth for the track being scored. bootstrap_samples : int Resamples per metric; ``0`` for point estimates only. seed : int Bootstrap RNG seed. Returns ------- dict[str, float] ``{"_mean": ..., "_std": ..., "n": ...}`` for every metric in ``spec.metrics``. ``n`` is the number of scored rows (datapoints for a row-per-datapoint benchmark, annotated targets for cafa5). """ if spec.long_form: return _score_long_form(spec, predictions, truth) merged = truth.merge( predictions[list(spec.required_columns)], on=ID_COLUMN, how="inner", validate="one_to_one", ) out: dict[str, float] = {"n": float(len(merged))} for metric in spec.metrics: mean, std = _bootstrap_metric(spec, metric, merged, bootstrap_samples, seed) out[f"{metric.key}_mean"] = mean out[f"{metric.key}_std"] = std return out def _bootstrap_metric( spec: BenchmarkSpec, metric: MetricSpec, merged: pd.DataFrame, bootstrap_samples: int, seed: int, ) -> tuple[float, float]: """Compute one metric's point estimate and bootstrap standard deviation.""" groups = ( merged[metric.grouped_by].to_numpy() if metric.grouped_by and metric.grouped_by in merged.columns else None ) def on_rows(rows: np.ndarray) -> float: return _apply(spec, metric, merged.iloc[rows]) return metrics.bootstrap( on_rows, n_samples=bootstrap_samples, n_rows=len(merged), seed=seed, groups=groups, ) def _apply(spec: BenchmarkSpec, metric: MetricSpec, merged: pd.DataFrame) -> float: """Dispatch one ``MetricSpec`` against a merged truth/prediction frame.""" truth_column = spec.truth_columns[0] if spec.truth_columns else "" pred_column = spec.pred_columns[0] if metric.kind == "spearman": return metrics.spearman(merged[truth_column], merged[pred_column]) if metric.kind == "auroc": return metrics.auroc(merged[truth_column], merged[pred_column]) if metric.kind == "grouped_spearman": return metrics.grouped_spearman( merged[truth_column], merged[pred_column], merged[metric.grouped_by] ) if metric.kind == "grouped_auroc": return metrics.grouped_auroc( merged[truth_column], merged[pred_column], merged[metric.grouped_by] ) if metric.kind == "macro_auroc": return metrics.macro_auroc( merged[list(spec.truth_columns)].to_numpy(), merged[list(spec.pred_columns)].to_numpy(), ) raise ValueError(f"{spec.name}: metric kind {metric.kind!r} has no scorer here") def _score_long_form( spec: BenchmarkSpec, predictions: pd.DataFrame, truth: pd.DataFrame ) -> dict[str, float]: """Score cafa5: Fmax per GO branch plus the macro-average over the branches. ``truth`` is long form as well — one row per ``(datapoint_id, aspect, term)`` annotation — so both sides are reduced to the same three arrays per aspect and handed to ``metrics.fmax_long``. """ pred = predictions.copy() pred["aspect"] = pred["aspect"].astype(str).str.strip().str.lower() pred["term"] = pred["term"].astype(str).str.strip() gt = truth.copy() gt["aspect"] = gt["aspect"].astype(str).str.strip().str.lower() gt["term"] = gt["term"].astype(str).str.strip() # Every scored protein is a target, annotated or not — an unannotated one is # dropped inside fmax_long, but it must be in the index so that a prediction # about it is still counted against precision. targets = pd.Index(sorted(set(gt[ID_COLUMN].astype(str)) | set(pred[ID_COLUMN].astype(str)))) target_of = {target: i for i, target in enumerate(targets)} out: dict[str, float] = {} per_aspect: dict[str, float] = {} for aspect in GO_ASPECTS: result = _fmax_for_aspect(aspect, pred, gt, targets, target_of) value = result["fmax"] per_aspect[aspect] = float("nan") if value is None else float(value) out[f"fmax_{aspect}_mean"] = per_aspect[aspect] out[f"fmax_{aspect}_std"] = 0.0 # Per-branch target counts differ a lot (a protein commonly carries BP # annotations but no CC ones), so each is reported rather than collapsed. out[f"fmax_{aspect}_n"] = float(result["targets"] or 0) finite = [v for v in per_aspect.values() if np.isfinite(v)] out["fmax_mean"] = float(np.mean(finite)) if finite else metrics.UNDEFINED out["fmax_std"] = 0.0 # `n` is the number of scored targets carrying at least one annotation in any # branch — the targets this benchmark could score at all. out["n"] = float(gt[ID_COLUMN].astype(str).nunique()) return out def _fmax_for_aspect( aspect: str, pred: pd.DataFrame, gt: pd.DataFrame, targets: pd.Index, target_of: dict[str, int], ) -> dict[str, float | None]: """Reduce one GO branch to long-form arrays and Fmax them.""" gt_aspect = gt[gt["aspect"] == aspect] pred_aspect = pred[pred["aspect"] == aspect] true_per_target = np.zeros(len(targets), dtype=float) if not gt_aspect.empty: counts = gt_aspect.groupby(gt_aspect[ID_COLUMN].astype(str))["term"].nunique() for target, count in counts.items(): true_per_target[target_of[str(target)]] = float(count) if pred_aspect.empty: return { "fmax": None if not true_per_target.any() else 0.0, "threshold": None, "precision": None, "recall": None, "coverage": 0.0, "targets": int((true_per_target > 0).sum()), } annotated_pairs = set( zip(gt_aspect[ID_COLUMN].astype(str), gt_aspect["term"], strict=True) ) target_index = np.asarray( [target_of[t] for t in pred_aspect[ID_COLUMN].astype(str)], dtype=np.int64 ) is_true = np.asarray( [ (t, term) in annotated_pairs for t, term in zip( pred_aspect[ID_COLUMN].astype(str), pred_aspect["term"], strict=True ) ], dtype=bool, ) return metrics.fmax_long( target_index=target_index, scores=pred_aspect["score"].to_numpy(dtype=float), is_true=is_true, true_per_target=true_per_target, )