PLUG-challenge / tests /test_real_data.py
alanclayrichard's picture
lohi splits and supervised and unsupervised tracks
49442cb
Raw History Blame Contribute Delete
8.49 kB
"""Integration tests against the real challenge data.
Skipped unless `scripts/build_challenge_data.py` has been run, so CI and a fresh
checkout stay synthetic-only. Run these after building the data and before
opening the challenge — they are the check that the manifests, the ground truth
and the scorer actually agree on real benchmarks, which no synthetic fixture can
tell you.
python scripts/build_challenge_data.py --plug /path/to/plug --split /path/to/lohi
pytest tests/test_real_data.py -v
"""
import zipfile
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from plug_challenge import aggregate, scoring
from plug_challenge.benchmarks import BENCHMARKS, ID_COLUMN, SPLIT_COLUMN, TRACKS, select_track
from plug_challenge.validation import validate_bundle
DATA = Path(".challenge-data")
PUBLIC = DATA / "public"
GROUND_TRUTH = DATA / "private" / "ground_truth"
pytestmark = pytest.mark.skipif(
not GROUND_TRUTH.exists(),
reason="run scripts/build_challenge_data.py first",
)
@pytest.fixture(scope="module")
def real_truth() -> dict[str, pd.DataFrame]:
"""Every benchmark's real ground truth that has been built, every row."""
truth = {}
for spec in BENCHMARKS:
path = GROUND_TRUTH / f"{spec.name}.parquet"
if path.exists():
frame = pd.read_parquet(path)
frame[ID_COLUMN] = frame[ID_COLUMN].astype(str)
truth[spec.name] = frame
return truth
@pytest.fixture(scope="module")
def real_manifests() -> dict[str, pd.DataFrame]:
"""Every benchmark's real public manifest that has been built."""
manifests = {}
for spec in BENCHMARKS:
path = PUBLIC / spec.name / "manifest.parquet"
if path.exists():
frame = pd.read_parquet(path)
frame[ID_COLUMN] = frame[ID_COLUMN].astype(str)
manifests[spec.name] = frame
return manifests
def test_all_eleven_benchmarks_were_built(real_truth, real_manifests):
missing = sorted({spec.name for spec in BENCHMARKS} - set(real_truth))
assert not missing, f"missing ground truth: {missing}"
assert len(real_manifests) == len(BENCHMARKS)
def test_manifest_ids_match_the_ground_truth(real_truth, real_manifests):
"""The join key a participant echoes back must be exactly what is scored."""
for spec in BENCHMARKS:
manifest_ids = set(real_manifests[spec.name][ID_COLUMN])
truth_ids = set(real_truth[spec.name][ID_COLUMN])
if spec.long_form:
# cafa5's ground truth is one row per annotation over a subset of the
# manifest's proteins (an unannotated protein has no rows).
assert truth_ids <= manifest_ids, spec.name
else:
assert manifest_ids == truth_ids, spec.name
def test_manifests_carry_ids_and_splits_only(real_manifests):
"""Nothing but identifiers and splits may be published: no label, sequence or ligand."""
for spec in BENCHMARKS:
columns = list(real_manifests[spec.name].columns)
expected = [ID_COLUMN, "row_index", *spec.manifest_columns, SPLIT_COLUMN]
assert columns == expected, spec.name
def test_protein_lists_carry_ids_and_splits_only():
for spec in BENCHMARKS:
proteins = pd.read_csv(PUBLIC / spec.name / "proteins.csv", keep_default_na=False)
assert list(proteins.columns) == ["node", "protein", "split"], spec.name
assert set(proteins["split"]) <= {"train", "val", "test", "excluded"}, spec.name
def test_every_benchmark_has_test_rows(real_manifests):
for spec in BENCHMARKS:
assert (real_manifests[spec.name][SPLIT_COLUMN] == "test").any(), spec.name
def test_datapoint_ids_are_unique(real_manifests):
for spec in BENCHMARKS:
ids = real_manifests[spec.name][ID_COLUMN]
assert ids.is_unique, f"{spec.name} has duplicate {ID_COLUMN} values"
def test_ground_truth_splits_match_the_manifest(real_truth, real_manifests):
for spec in BENCHMARKS:
manifest = real_manifests[spec.name].set_index(ID_COLUMN)[SPLIT_COLUMN]
truth = real_truth[spec.name].drop_duplicates(ID_COLUMN).set_index(ID_COLUMN)
assert (truth[SPLIT_COLUMN] == manifest.loc[truth.index]).all(), spec.name
def test_ground_truth_carries_every_grouping_column(real_truth):
"""A grouped metric silently degrades to ungrouped if its column is absent."""
for spec in BENCHMARKS:
columns = set(real_truth[spec.name].columns)
for metric in spec.metrics:
if metric.grouped_by:
assert metric.grouped_by in columns, f"{spec.name}: {metric.grouped_by}"
def _perfect_bundle(truth: dict[str, pd.DataFrame], path: Path) -> Path:
"""A submission that simply echoes the ground truth back."""
with zipfile.ZipFile(path, "w") as archive:
for spec in BENCHMARKS:
gt = truth[spec.name]
if spec.long_form:
frame = gt[[ID_COLUMN, "aspect", "term"]].copy()
frame["score"] = 1.0
else:
frame = pd.DataFrame({ID_COLUMN: gt[ID_COLUMN]})
for truth_column, pred_column in zip(
spec.truth_columns, spec.pred_columns, strict=True
):
values = gt[truth_column].to_numpy(dtype=float)
# A constant truth column would be rejected as a constant
# prediction, so nudge one row to keep the bundle valid.
if np.std(values) == 0 and values.size > 1:
values = values.copy()
values[0] += 1.0
frame[pred_column] = values
archive.writestr(spec.filename, frame.to_csv(index=False))
return path
@pytest.mark.parametrize("track", TRACKS)
def test_a_perfect_submission_validates_and_scores_one(
track, real_truth, real_manifests, tmp_path
):
"""The end-to-end contract: echoing the labels back scores a PLUG Score of 1."""
truth = {name: select_track(frame, track) for name, frame in real_truth.items()}
bundle = _perfect_bundle(truth, tmp_path / "perfect.zip")
expected = {
name: set(select_track(frame, track)[ID_COLUMN]) for name, frame in real_manifests.items()
}
result = validate_bundle(bundle, expected)
assert result.ok, result.report()
scores = scoring.score_bundle(result.frames, 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}"
assert aggregate.plug_score(scores) == pytest.approx(1.0)
def test_a_random_submission_scores_near_zero(real_truth, real_manifests, tmp_path):
"""A no-information supervised submission should land near chance, which is 0."""
rng = np.random.default_rng(0)
truth = {name: select_track(frame, "supervised") for name, frame in real_truth.items()}
bundle = tmp_path / "random.zip"
with zipfile.ZipFile(bundle, "w") as archive:
for spec in BENCHMARKS:
manifest = select_track(real_manifests[spec.name], "supervised")
if spec.long_form:
# Predict one arbitrary term per protein at random confidence.
frame = pd.DataFrame(
{
ID_COLUMN: manifest[ID_COLUMN],
"aspect": "bp",
"term": "GO:0008150",
"score": rng.uniform(size=len(manifest)),
}
)
else:
frame = pd.DataFrame({ID_COLUMN: manifest[ID_COLUMN]})
for pred_column in spec.pred_columns:
frame[pred_column] = rng.normal(size=len(manifest))
archive.writestr(spec.filename, frame.to_csv(index=False))
expected = {name: set(frame[ID_COLUMN]) for name, frame in truth.items()}
result = validate_bundle(bundle, expected)
assert result.ok, result.report()
scores = scoring.score_bundle(result.frames, truth, BENCHMARKS)
# cafa5 is excluded from the band check: a single-term submission's Fmax is set
# by that term's prevalence, not by chance ranking.
for spec in BENCHMARKS:
if spec.name == "cafa5":
continue
value = scores[spec.name][f"{spec.primary.key}_mean"]
normalised = aggregate.normalise(value, spec.primary)
assert abs(normalised) < 0.2, f"{spec.name} normalised to {normalised}"