File size: 8,185 Bytes
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
"""Synthetic fixtures for the PLUG challenge tests.

Everything here is generated from a fixed seed — no real benchmark data, no real
labels — so the tests run anywhere and the fixtures can be regenerated freely.
The point is to exercise every *shape* of benchmark: one row per mutation, one
row per residue, one row per pair, seven columns per pair, and cafa5's long form.

Three in four datapoints are in the Lo-Hi ``test`` split and the rest in
``train``, so the supervised track scores a strict subset of what the
unsupervised track does.
"""

import zipfile
from pathlib import Path

import numpy as np
import pandas as pd
import pytest

from plug_challenge.benchmarks import (
    BENCHMARKS,
    GO_ASPECTS,
    ID_COLUMN,
    SPLIT_COLUMN,
    select_track,
)

N_DATAPOINTS = 40
N_GROUPS = 4
SEED = 0


def _ids(benchmark: str, n: int) -> list[str]:
    """Deterministic fake datapoint ids."""
    return [f"{benchmark}-{i:04d}" for i in range(n)]


def _splits(n: int) -> list[str]:
    """Every fourth datapoint in train, the rest in test."""
    return ["train" if i % 4 == 3 else "test" for i in range(n)]


def _groups(n: int) -> list[str]:
    """Round-robin group labels, so every grouped metric has several groups."""
    return [f"g{i % N_GROUPS}" for i in range(n)]


def make_ground_truth(rng: np.random.Generator) -> dict[str, pd.DataFrame]:
    """Build a synthetic ground truth for all eleven benchmarks.

    Parameters
    ----------
    rng : np.random.Generator
        Seeded generator.

    Returns
    -------
    dict[str, pd.DataFrame]
        Benchmark name -> ground truth frame with the columns the scorer needs.

    """
    truth: dict[str, pd.DataFrame] = {}
    for spec in BENCHMARKS:
        ids = _ids(spec.name, N_DATAPOINTS)
        if spec.long_form:
            rows = []
            for datapoint_id, split in zip(ids, _splits(N_DATAPOINTS), strict=True):
                for aspect in GO_ASPECTS:
                    for term in range(3):
                        rows.append(
                            {
                                ID_COLUMN: datapoint_id,
                                "protein_id": datapoint_id.replace(spec.name, "P"),
                                "aspect": aspect,
                                "term": f"GO:{aspect}{term:05d}",
                                SPLIT_COLUMN: split,
                            }
                        )
            truth[spec.name] = pd.DataFrame(rows)
            continue

        frame = pd.DataFrame({ID_COLUMN: ids, SPLIT_COLUMN: _splits(N_DATAPOINTS)})
        for column in spec.manifest_columns:
            if column == "position":
                frame[column] = np.arange(1, N_DATAPOINTS + 1)
            else:
                frame[column] = _groups(N_DATAPOINTS)
        # Grouped metrics read their own column; make sure it exists and varies.
        for metric in spec.metrics:
            if metric.grouped_by:
                frame[metric.grouped_by] = _groups(N_DATAPOINTS)
        for column in spec.truth_columns:
            if spec.task in ("binary", "multilabel"):
                frame[column] = rng.integers(0, 2, size=N_DATAPOINTS)
            else:
                frame[column] = rng.normal(size=N_DATAPOINTS)
        truth[spec.name] = frame
    return truth


def make_predictions(
    truth: dict[str, pd.DataFrame], rng: np.random.Generator, noise: float = 0.5
) -> dict[str, pd.DataFrame]:
    """Build predictions correlated with a ground truth.

    Parameters
    ----------
    truth : dict[str, pd.DataFrame]
        The ground truth to predict.
    rng : np.random.Generator
        Seeded generator.
    noise : float
        Standard deviation of the noise added to the signal. 0 gives a perfect
        submission; a large value gives a near-random one.

    Returns
    -------
    dict[str, pd.DataFrame]
        Benchmark name -> a valid submission frame.

    """
    frames: dict[str, pd.DataFrame] = {}
    for spec in BENCHMARKS:
        gt = truth[spec.name]
        if spec.long_form:
            # Predict every true annotation plus one false positive per protein.
            rows = []
            for datapoint_id, group in gt.groupby(ID_COLUMN):
                for _, row in group.iterrows():
                    rows.append(
                        {
                            ID_COLUMN: datapoint_id,
                            "aspect": row["aspect"],
                            "term": row["term"],
                            "score": float(rng.uniform(0.6, 1.0)),
                        }
                    )
                rows.append(
                    {
                        ID_COLUMN: datapoint_id,
                        "aspect": "bp",
                        "term": "GO:decoy",
                        "score": float(rng.uniform(0.0, 0.3)),
                    }
                )
            frames[spec.name] = pd.DataFrame(rows)
            continue

        frame = pd.DataFrame({ID_COLUMN: gt[ID_COLUMN]})
        for truth_column, pred_column in zip(
            spec.truth_columns, spec.pred_columns, strict=True
        ):
            signal = gt[truth_column].to_numpy(dtype=float)
            values = signal + rng.normal(scale=noise, size=signal.size)
            if spec.score_range is not None:
                low, high = spec.score_range
                values = np.clip(values, low, high)
            frame[pred_column] = values
        frames[spec.name] = frame
    return frames


def for_track(
    frames: dict[str, pd.DataFrame], truth: dict[str, pd.DataFrame], track: str
) -> dict[str, pd.DataFrame]:
    """Narrow per-benchmark predictions to the datapoints one track scores.

    Parameters
    ----------
    frames : dict[str, pd.DataFrame]
        Predictions over every datapoint.
    truth : dict[str, pd.DataFrame]
        The ground truth, every datapoint with its split.
    track : str
        The track to narrow to.

    Returns
    -------
    dict[str, pd.DataFrame]
        The same predictions, keeping only the track's datapoints.

    """
    return {
        name: frame[frame[ID_COLUMN].isin(set(select_track(truth[name], track)[ID_COLUMN]))]
        for name, frame in frames.items()
    }


def write_bundle(frames: dict[str, pd.DataFrame], path: Path) -> Path:
    """Zip per-benchmark frames into a submission bundle.

    Parameters
    ----------
    frames : dict[str, pd.DataFrame]
        Benchmark name -> submission frame.
    path : Path
        Destination ``.zip``.

    Returns
    -------
    Path
        ``path``, for chaining.

    """
    with zipfile.ZipFile(path, "w") as archive:
        for name, frame in frames.items():
            archive.writestr(f"{name}.csv", frame.to_csv(index=False))
    return path


@pytest.fixture
def rng() -> np.random.Generator:
    """A seeded generator, so every test run sees the same data."""
    return np.random.default_rng(SEED)


@pytest.fixture
def truth(rng: np.random.Generator) -> dict[str, pd.DataFrame]:
    """Synthetic ground truth for all eleven benchmarks."""
    return make_ground_truth(rng)


@pytest.fixture
def expected_ids(truth: dict[str, pd.DataFrame]) -> dict[str, set[str]]:
    """The id sets an unsupervised submission must cover: every datapoint."""
    return {name: set(frame[ID_COLUMN].astype(str)) for name, frame in truth.items()}


@pytest.fixture
def predictions(truth: dict[str, pd.DataFrame]) -> dict[str, pd.DataFrame]:
    """A valid, informative submission for the synthetic ground truth."""
    return make_predictions(truth, np.random.default_rng(SEED + 1))


@pytest.fixture
def bundle(predictions: dict[str, pd.DataFrame], tmp_path: Path) -> Path:
    """A valid unsupervised-track bundle on disk: every datapoint predicted."""
    return write_bundle(predictions, tmp_path / "plug_submission.zip")


@pytest.fixture
def supervised_bundle(
    predictions: dict[str, pd.DataFrame], truth: dict[str, pd.DataFrame], tmp_path: Path
) -> Path:
    """A valid supervised-track bundle on disk: the test datapoints only."""
    return write_bundle(
        for_track(predictions, truth, "supervised"), tmp_path / "plug_supervised.zip"
    )