"""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" )