"""Tests for turning a validated bundle into metric values.""" import numpy as np import pandas as pd import pytest from plug_challenge import scoring from plug_challenge.benchmarks import BENCHMARK_NAMES, BENCHMARKS, ID_COLUMN, get from .conftest import make_predictions def test_every_benchmark_scores_and_reports_its_metrics(predictions, truth): scores = scoring.score_bundle(predictions, truth, BENCHMARKS) assert set(scores) == set(BENCHMARK_NAMES) for spec in BENCHMARKS: for metric in spec.metrics: assert f"{metric.key}_mean" in scores[spec.name] assert f"{metric.key}_std" in scores[spec.name] assert scores[spec.name]["n"] > 0 def test_perfect_predictions_reach_the_metric_ceiling(truth): perfect = make_predictions(truth, np.random.default_rng(0), noise=0.0) scores = scoring.score_bundle(perfect, truth, BENCHMARKS) for spec in BENCHMARKS: value = scores[spec.name][f"{spec.primary.key}_mean"] assert value == pytest.approx(1.0), f"{spec.name} scored {value}" def test_noisier_predictions_score_worse(truth): good = scoring.score_bundle( make_predictions(truth, np.random.default_rng(1), noise=0.1), truth, BENCHMARKS ) bad = scoring.score_bundle( make_predictions(truth, np.random.default_rng(1), noise=8.0), truth, BENCHMARKS ) key = f"{get('megascale').primary.key}_mean" assert good["megascale"][key] > bad["megascale"][key] def test_inverted_predictions_score_below_chance(truth): spec = get("ppi") inverted = pd.DataFrame( { ID_COLUMN: truth["ppi"][ID_COLUMN], "pred": 1.0 - truth["ppi"]["label"].to_numpy(dtype=float), } ) scores = scoring.score_benchmark(spec, inverted, truth["ppi"]) assert scores["auroc_mean"] == pytest.approx(0.0) def test_benchmarks_are_scored_independently(predictions, truth): """Corrupting one benchmark must not move any other benchmark's number.""" baseline = scoring.score_bundle(predictions, truth, BENCHMARKS) predictions["dms"]["pred"] = -predictions["dms"]["pred"] after = scoring.score_bundle(predictions, truth, BENCHMARKS) assert after["dms"] != baseline["dms"] for name in BENCHMARK_NAMES: if name != "dms": assert after[name] == baseline[name] def test_missing_ground_truth_skips_the_benchmark(predictions, truth): del truth["atlas"] scores = scoring.score_bundle(predictions, truth, BENCHMARKS) assert "atlas" not in scores assert len(scores) == len(BENCHMARK_NAMES) - 1 def test_bootstrap_adds_spread_without_moving_the_estimate(predictions, truth): spec = get("megascale") point = scoring.score_benchmark(spec, predictions["megascale"], truth["megascale"]) resampled = scoring.score_benchmark( spec, predictions["megascale"], truth["megascale"], bootstrap_samples=100, seed=0 ) assert point["spearman_std"] == 0.0 assert resampled["spearman_std"] > 0 # The resampled mean is a different estimator, but it should land nearby. assert resampled["spearman_mean"] == pytest.approx(point["spearman_mean"], abs=0.15) def test_cafa5_macro_is_the_mean_of_its_branches(predictions, truth): scores = scoring.score_benchmark(get("cafa5"), predictions["cafa5"], truth["cafa5"]) branches = [scores[f"fmax_{aspect}_mean"] for aspect in ("bp", "mf", "cc")] assert scores["fmax_mean"] == pytest.approx(float(np.mean(branches))) def test_cafa5_scores_false_positives_against_precision(truth): """A submission that predicts every term at full confidence should not score 1.""" gt = truth["cafa5"] confident_everything = pd.DataFrame( { ID_COLUMN: list(gt[ID_COLUMN]) * 2, "aspect": list(gt["aspect"]) * 2, "term": list(gt["term"]) + [f"{t}-decoy" for t in gt["term"]], "score": 1.0, } ) scores = scoring.score_benchmark(get("cafa5"), confident_everything, gt) assert 0.0 < scores["fmax_mean"] < 1.0 def test_shs27k_macro_auroc_skips_modes_with_one_class(truth): spec = get("shs27k") gt = truth["shs27k"].copy() gt[spec.truth_columns[0]] = 1 # this mode now has no negatives perfect = pd.DataFrame({ID_COLUMN: gt[ID_COLUMN]}) for truth_column, pred_column in zip(spec.truth_columns, spec.pred_columns, strict=True): perfect[pred_column] = gt[truth_column].to_numpy(dtype=float) scores = scoring.score_benchmark(spec, perfect, gt) assert scores["macro_auroc_mean"] == pytest.approx(1.0) def test_extra_prediction_rows_would_break_the_join(truth): """The one-to-one merge is a guard: a duplicated id must raise, not be averaged.""" spec = get("megascale") frame = pd.DataFrame( {ID_COLUMN: truth["megascale"][ID_COLUMN], "pred": 1.0} ) doubled = pd.concat([frame, frame.head(1)], ignore_index=True) with pytest.raises(pd.errors.MergeError): scoring.score_benchmark(spec, doubled, truth["megascale"]) def test_cafa5_reports_per_branch_target_counts(predictions, truth): scores = scoring.score_benchmark(get("cafa5"), predictions["cafa5"], truth["cafa5"]) # The synthetic fixture annotates every protein in every branch. n_proteins = truth["cafa5"][ID_COLUMN].nunique() assert scores["n"] == n_proteins for aspect in ("bp", "mf", "cc"): assert scores[f"fmax_{aspect}_n"] == n_proteins def test_cafa5_n_counts_annotated_targets_only(truth): """A protein with no annotations in any branch is not a scorable target.""" gt = truth["cafa5"] annotated = gt[gt[ID_COLUMN] != gt[ID_COLUMN].iloc[0]] predictions = annotated[[ID_COLUMN, "aspect", "term"]].copy() predictions["score"] = 1.0 scores = scoring.score_benchmark(get("cafa5"), predictions, annotated) assert scores["n"] == gt[ID_COLUMN].nunique() - 1 assert scores["fmax_mean"] == pytest.approx(1.0)