Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 5,932 Bytes
b78ff28 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | """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)
|