File size: 8,494 Bytes
b78ff28
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
49442cb
b78ff28
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
 
b78ff28
49442cb
 
 
b78ff28
 
49442cb
b78ff28
49442cb
 
 
 
 
 
 
 
b78ff28
 
 
 
 
 
 
 
49442cb
b78ff28
49442cb
 
 
b78ff28
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
49442cb
b78ff28
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
49442cb
 
 
 
b78ff28
49442cb
 
 
 
 
b78ff28
 
 
49442cb
b78ff28
 
 
 
 
 
49442cb
 
b78ff28
49442cb
b78ff28
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
49442cb
b78ff28
 
 
 
 
 
49442cb
 
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"""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}"