PLUG-challenge / plug_challenge /benchmarks.py
alanclayrichard's picture
score bindingdb on only exact == measurements, accept partial submissions (single or few function only) with unsubmitted set to chance)
580f4e5
Raw History Blame Contribute Delete
19.5 kB
"""The eleven PLUG benchmarks: submission schema, ground-truth schema, metrics.
This module is the **single source of truth** for the challenge. Everything else
— the submission validator, the scorer, the leaderboard builder, the Space's
Submit tab and its per-benchmark leaderboard tabs, the participant-facing format
docs — is generated from ``BENCHMARKS`` rather than restating it, so a benchmark
cannot be described one way on the Space and scored another way by the backend.
Each benchmark contributes one file to the submission bundle. A bundle may leave
benchmarks out; each one missing counts as chance in the PLUG Score (see
``config.REQUIRE_COMPLETE_BUNDLE``).
Rows and tracks
---------------
A datapoint is one row of the benchmark as plug's own loader yields it
(``plug.benchmarks.<Benchmark>.rows()``), in that order, or one residue of such
a row for the per-residue benchmarks. The challenge runs two tracks over them:
``supervised``
The Lo-Hi split built by plug. Train on
its train/val rows, predict its held-out test rows.
``unsupervised``
Every row of every benchmark, unsplit — including the rows the Lo-Hi k-cut
dropped — for methods that are never fitted to these labels.
Only identifiers and splits are ever published. The labels stay with their
original sources (and, for scoring, in the private repo), because not every
benchmark's licence allows redistributing them — LP-PDBBind's does not.
Naming
------
``entity`` is what a split is decided over (a protein, a PDB chain, a ligand);
``datapoint`` is one scored row (a mutation, a residue, a pair, a measurement).
An entity contributes many datapoints. ``datapoint_id`` is the join key between
a manifest, a submission and the ground truth — see
``scripts/build_challenge_data.py`` for how it is derived.
"""
from dataclasses import dataclass, field
from typing import Literal
# The datapoint identifier column. Present in every manifest, every
# ground-truth file, and required in every submission file — it is the only
# thing a participant has to echo back. It is the row's position in plug's
# loader ("1234"), plus the 1-based residue for a per-residue benchmark
# ("1234:56").
ID_COLUMN = "datapoint_id"
# The Lo-Hi split of a row in every manifest and ground-truth file: "train",
# "val", "test", or "" for a row the k-cut dropped.
SPLIT_COLUMN = "split"
# The two leaderboards. Each submission belongs to exactly one.
TRACKS = ("supervised", "unsupervised")
TRACK_LABELS = {"supervised": "Supervised", "unsupervised": "Unsupervised"}
TRACK_DESCRIPTIONS = {
"supervised": (
"Trained on the Lo-Hi train/val splits and evaluated on the held-out, "
"homology-disjoint test split of each benchmark."
),
"unsupervised": (
"Never fitted to these labels, and evaluated on every row of each "
"benchmark, unsplit."
),
}
# STRING interaction modes scored by shs27k, in a fixed order — the order of the
# per-mode columns in both the ground truth and a submission.
SHS27K_MODES = (
"reaction",
"binding",
"catalysis",
"activation",
"inhibition",
"ptmod",
"expression",
)
# The three GO branches scored by cafa5, in a fixed order.
GO_ASPECTS = ("bp", "mf", "cc")
MetricKind = Literal[
"spearman",
"grouped_spearman",
"auroc",
"grouped_auroc",
"macro_auroc",
"fmax",
]
TaskKind = Literal["regression", "binary", "multilabel", "go_terms"]
@dataclass(frozen=True)
class MetricSpec:
"""One number reported for one benchmark.
Attributes
----------
key : str
Column stem used in score files and leaderboard CSVs (e.g. ``spearman``
becomes ``spearman_mean`` / ``spearman_std``).
label : str
How the metric is labelled in the Space's leaderboard header.
kind : MetricKind
Which function in ``metrics.py`` computes it. ``scoring.py`` dispatches
on this.
higher_is_better : bool
Sort direction. Every PLUG metric happens to be higher-is-better, but
the leaderboard reads this rather than assuming it.
aspect : str
For ``fmax``, the GO branch to restrict to — one of ``GO_ASPECTS``, or
``""`` for the macro-average over all three.
grouped_by : str
For the ``grouped_*`` kinds, the ground-truth column holding the group
label.
chance : float
The value random predictions score, which normalises to 0 for the
PLUG Score (see ``aggregate.normalise``): 0 for Spearman, 0.5 for
AUROC, 0 for Fmax. The best value is 1 for every metric.
sign_free : bool
True for a correlation, whose sign is a convention of which way the
label was written rather than a result: a Spearman of -0.99 is as
predictive as one of 0.99, so it is normalised on its magnitude.
"""
key: str
label: str
kind: MetricKind
higher_is_better: bool = True
aspect: str = ""
grouped_by: str = ""
chance: float = 0.0
sign_free: bool = False
@dataclass(frozen=True)
class BenchmarkSpec:
"""One PLUG benchmark: what participants upload and how it is scored.
Attributes
----------
name : str
The benchmark's ``plug`` registry name, and its directory name under
``data/``. Also the leaderboard tab slug.
label : str
Display name on the Space.
task : TaskKind
Shape of the prediction, which decides the validator applied
(``validation.py``) and the schema block rendered on the Submit tab.
filename : str
This benchmark's file inside the submission bundle.
pred_columns : tuple[str, ...]
Prediction columns a submission must carry, on top of ``ID_COLUMN``.
truth_columns : tuple[str, ...]
Label columns the ground-truth file carries, positionally matching
``pred_columns``.
metrics : tuple[MetricSpec, ...]
Every number reported for this benchmark. The **first** is the primary
metric: what the benchmark's own leaderboard sorts by and what feeds the
PLUG Score.
entity_column : str
The ground-truth column naming the entity a datapoint is about — the
unit the leakage-free split was decided over.
unit : str
What one scored row is, for participant-facing copy ("mutation",
"residue", "protein pair", ...).
long_form : bool
True for a benchmark whose submission has a variable number of rows per
datapoint (only ``cafa5``: one row per predicted GO term). A long-form
file is validated on the *set* of ids it covers rather than on an exact
row match.
extra_columns : tuple[str, ...]
Additional required submission columns for a long-form benchmark.
score_range : tuple[float, float] | None
When set, every prediction must fall inside this closed interval.
Probabilities are constrained to ``(0, 1)``; an unbounded regression
target leaves this ``None``.
allowed_values : dict[str, tuple[str, ...]]
Column -> the closed set of values it may take, for the categorical
columns of a long-form submission (cafa5's ``aspect``).
description : str
One line shown on the Submit tab and in the format docs.
manifest_columns : tuple[str, ...]
The identifier columns the public manifest carries beside
``datapoint_id``, ``row_index`` and ``split``: the protein(s) a row is
about, and ``position`` for a per-residue benchmark. Never a label, a
sequence, a mutation or a ligand.
"""
name: str
label: str
task: TaskKind
pred_columns: tuple[str, ...]
truth_columns: tuple[str, ...]
metrics: tuple[MetricSpec, ...]
entity_column: str
unit: str
description: str
long_form: bool = False
extra_columns: tuple[str, ...] = ()
score_range: tuple[float, float] | None = None
allowed_values: dict[str, tuple[str, ...]] = field(default_factory=dict)
manifest_columns: tuple[str, ...] = field(default=())
@property
def filename(self) -> str:
"""Name of this benchmark's file inside the submission bundle."""
return f"{self.name}.csv"
@property
def primary(self) -> MetricSpec:
"""The metric this benchmark's leaderboard sorts by and the PLUG Score uses."""
return self.metrics[0]
@property
def required_columns(self) -> tuple[str, ...]:
"""Every column a submission file for this benchmark must contain."""
return (ID_COLUMN, *self.extra_columns, *self.pred_columns)
@property
def per_residue(self) -> bool:
"""Whether a datapoint is one residue of a row rather than the row itself."""
return "position" in self.manifest_columns
@property
def needs_varying_predictions(self) -> bool:
"""Whether a constant prediction column makes this benchmark unscorable.
True for the rank statistics (Spearman, AUROC), which are undefined with
zero variance — a constant column there is rejected at validation rather
than scored as NaN.
False for Fmax, which sweeps a confidence threshold rather than ranking:
predicting every term at 1.0 means "I am confident in all of these", which
is a legitimate (and common) CAFA submission and scores perfectly well.
"""
return any(metric.kind != "fmax" for metric in self.metrics)
SPEARMAN = MetricSpec(key="spearman", label="Spearman's ρ", kind="spearman", sign_free=True)
AUROC = MetricSpec(key="auroc", label="AUROC", kind="auroc", chance=0.5)
def _per_entity(kind: MetricKind, entity_column: str, label: str, key: str) -> MetricSpec:
"""Build the per-entity counterpart of a pooled metric."""
correlation = kind == "grouped_spearman"
return MetricSpec(
key=key,
label=label,
kind=kind,
grouped_by=entity_column,
chance=0.0 if correlation else 0.5,
sign_free=correlation,
)
BENCHMARKS: tuple[BenchmarkSpec, ...] = (
# ---------------------------------------------------------------- stability
BenchmarkSpec(
name="megascale",
label="Megascale ΔΔG",
task="regression",
pred_columns=("pred",),
truth_columns=("ddg",),
metrics=(
SPEARMAN,
_per_entity("grouped_spearman", "pdb", "Spearman (per protein)",
"spearman_per_protein"),
),
entity_column="pdb",
unit="mutation",
manifest_columns=("pdb",),
description=(
"Predicted folding free-energy change (ΔΔG) for one single substitution "
"of a mini-protein."
),
),
BenchmarkSpec(
name="fireprot",
label="FireProt ΔΔG",
task="regression",
pred_columns=("pred",),
truth_columns=("ddg",),
metrics=(
SPEARMAN,
_per_entity("grouped_spearman", "pdb", "Spearman (per protein)",
"spearman_per_protein"),
),
entity_column="pdb",
unit="mutation",
manifest_columns=("pdb",),
description=(
"Predicted ΔΔG for one substitution of a natural protein, curated from "
"the literature."
),
),
# --------------------------------------------------------------- DMS fitness
BenchmarkSpec(
name="dms",
label="ProteinGym DMS",
task="regression",
pred_columns=("pred",),
truth_columns=("score",),
metrics=(
MetricSpec(
key="spearman_per_assay",
label="Spearman (per assay)",
kind="grouped_spearman",
grouped_by="dms_id",
sign_free=True,
),
SPEARMAN,
),
entity_column="dms_id",
unit="variant",
manifest_columns=("dms_id", "uniprot"),
description=(
"Predicted fitness for one variant in one deep mutational scanning assay. "
"Scored per assay and averaged, because assay scores share no common scale."
),
),
# ------------------------------------------------------------ GO / function
BenchmarkSpec(
name="cafa5",
label="CAFA5 GO",
task="go_terms",
pred_columns=("score",),
truth_columns=(),
metrics=(
MetricSpec(key="fmax", label="Fmax (macro)", kind="fmax"),
MetricSpec(key="fmax_bp", label="Fmax BP", kind="fmax", aspect="bp"),
MetricSpec(key="fmax_mf", label="Fmax MF", kind="fmax", aspect="mf"),
MetricSpec(key="fmax_cc", label="Fmax CC", kind="fmax", aspect="cc"),
),
entity_column="protein_id",
unit="protein",
long_form=True,
extra_columns=("aspect", "term"),
score_range=(0.0, 1.0),
allowed_values={"aspect": GO_ASPECTS},
manifest_columns=("protein_id",),
description=(
"Predicted Gene Ontology annotations, in CAFA's long form: one row per "
"(protein, branch, GO term) you predict, with a confidence in [0, 1]. "
"Terms you do not predict are simply absent — declining to annotate a "
"protein costs recall but not precision. Scored as target-centric Fmax "
"per GO branch (BP/MF/CC), macro-averaged over the three."
),
),
# ------------------------------------------------------------- allostery
BenchmarkSpec(
name="allobench",
label="AlloBench sites",
task="binary",
pred_columns=("pred",),
truth_columns=("is_allosteric_site",),
metrics=(
AUROC,
_per_entity("grouped_auroc", "target_id", "AUROC (per protein)",
"auroc_per_protein"),
),
entity_column="target_id",
unit="residue",
score_range=None,
manifest_columns=("target_id", "uniprot", "position"),
description=(
"Per-residue score that a residue belongs to an allosteric site. Any "
"monotone score works — only the ranking is used."
),
),
BenchmarkSpec(
name="passerrank",
label="PASSerRank sites",
task="binary",
pred_columns=("pred",),
truth_columns=("is_allosteric_site",),
metrics=(
AUROC,
_per_entity("grouped_auroc", "uniprot", "AUROC (per protein)",
"auroc_per_protein"),
),
entity_column="uniprot",
unit="residue",
manifest_columns=("uniprot", "position"),
description=(
"Per-residue score that a residue belongs to an allosteric site, over "
"the PASSerRank targets."
),
),
# --------------------------------------------------------------------- PPI
BenchmarkSpec(
name="ppi",
label="Human PPI",
task="binary",
pred_columns=("pred",),
truth_columns=("label",),
metrics=(AUROC,),
entity_column="id_a",
unit="protein pair",
manifest_columns=("id_a", "id_b"),
description=(
"Score that two human proteins interact. Pairs are undirected: your "
"score should not depend on which partner is listed first."
),
),
BenchmarkSpec(
name="shs27k",
label="STRING SHS27k modes",
task="multilabel",
pred_columns=tuple(f"pred_{mode}" for mode in SHS27K_MODES),
truth_columns=tuple(SHS27K_MODES),
metrics=(
MetricSpec(key="macro_auroc", label="Macro AUROC", kind="macro_auroc", chance=0.5),
),
entity_column="id_a",
unit="protein pair",
manifest_columns=("id_a", "id_b"),
description=(
"Seven scores per pair, one per STRING interaction mode. SHS27k ships no "
"negative pairs, so this is multi-label mode prediction rather than an "
"interact/does-not task. Scored as AUROC per mode, macro-averaged over "
"the modes present in the scored rows."
),
),
# ---------------------------------------------------------------- affinity
BenchmarkSpec(
name="lp-pdbbind",
label="LP-PDBBind affinity",
task="regression",
pred_columns=("pred",),
truth_columns=("value",),
metrics=(SPEARMAN,),
entity_column="pdb",
unit="complex",
manifest_columns=("pdb",),
description=(
"Predicted binding affinity for one protein–ligand complex."
),
),
BenchmarkSpec(
name="bindingdb",
label="BindingDB affinity",
task="regression",
pred_columns=("pred",),
truth_columns=("value",),
metrics=(
SPEARMAN,
_per_entity("grouped_spearman", "target_key", "Spearman (per target)",
"spearman_per_target"),
),
entity_column="target_key",
unit="measurement",
manifest_columns=("target_key", "uniprot"),
description=(
"Predicted binding affinity for one (target, ligand) measurement from "
"BindingDB. Only exact (`=`) measurements are scored. `target_key` is "
"plug's id for the target's sequence."
),
),
# ------------------------------------------------------------------- MD/RMSF
BenchmarkSpec(
name="atlas",
label="ATLAS RMSF",
task="regression",
pred_columns=("pred",),
truth_columns=("rmsf",),
metrics=(
SPEARMAN,
_per_entity("grouped_spearman", "pdb_chain", "Spearman (per chain)",
"spearman_per_chain"),
),
entity_column="pdb_chain",
unit="residue",
manifest_columns=("pdb_chain", "position"),
description=(
"Predicted per-residue flexibility (RMSF) from the ATLAS molecular "
"dynamics ensembles, averaged over the three replicas."
),
),
)
BENCHMARKS_BY_NAME: dict[str, BenchmarkSpec] = {b.name: b for b in BENCHMARKS}
BENCHMARK_NAMES: tuple[str, ...] = tuple(b.name for b in BENCHMARKS)
def select_track(frame, track: str):
"""Narrow a manifest or ground-truth frame to the rows a track is scored on.
Parameters
----------
frame : pd.DataFrame
Any frame carrying ``SPLIT_COLUMN``.
track : str
One of ``TRACKS``.
Returns
-------
pd.DataFrame
The Lo-Hi test rows for ``supervised``; every row for ``unsupervised``.
"""
if track not in TRACKS:
raise ValueError(f"Unknown track {track!r}. Expected one of: {', '.join(TRACKS)}")
if track == "unsupervised":
return frame
return frame[frame[SPLIT_COLUMN].astype(str) == "test"]
def get(name: str) -> BenchmarkSpec:
"""Look up a benchmark spec by its ``plug`` registry name.
Parameters
----------
name : str
The benchmark name, e.g. ``"megascale"``.
Returns
-------
BenchmarkSpec
That benchmark's spec.
Raises
------
KeyError
If ``name`` is not one of the eleven PLUG benchmarks.
"""
if name not in BENCHMARKS_BY_NAME:
raise KeyError(f"Unknown benchmark {name!r}. Expected one of: {', '.join(BENCHMARK_NAMES)}")
return BENCHMARKS_BY_NAME[name]