PLUG-challenge / plug_challenge /validation.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
16 kB
"""Submission bundle validation.
A PLUG submission is a single ``.zip`` carrying one file per benchmark. This
module is the one place that decides whether such a bundle is scorable, and it
runs in three places against the same rules: in the Space before a submission is
accepted, in ``plug_challenge.cli`` so participants can check a bundle locally
before uploading, and in the tests.
Every check produces a ``SubmissionError`` naming the benchmark it belongs to, so
the Space can show a participant every problem in their bundle at once instead of
one per upload attempt.
"""
import zipfile
from dataclasses import dataclass, field
from pathlib import Path
import numpy as np
import pandas as pd
from loguru import logger
from .benchmarks import BENCHMARK_NAMES, BENCHMARKS, ID_COLUMN, BenchmarkSpec
# Reject a prediction column whose standard deviation is below this, for the
# benchmarks scored by a rank statistic: a constant column makes Spearman and
# AUROC undefined, and near-constant columns with a dither of noise are the usual
# way that gets smuggled past an equality check. Fmax is exempt β€” see
# BenchmarkSpec.needs_varying_predictions.
MIN_PREDICTION_STD = 1e-9
# Entries a zip archive may carry that are not submission files. macOS's
# Archive Utility adds both.
_IGNORED_ZIP_PREFIXES = ("__MACOSX/", ".")
@dataclass(frozen=True)
class SubmissionError:
"""A single reason a bundle cannot be scored.
Attributes
----------
benchmark : str
Which benchmark the problem is in, or ``"bundle"`` for a problem with
the archive itself.
message : str
Participant-facing description, specific enough to act on without
needing the scorer's source.
"""
benchmark: str
message: str
def __str__(self) -> str:
"""Render as ``benchmark: message`` for display on the Space."""
return f"{self.benchmark}: {self.message}"
@dataclass
class ValidationResult:
"""The outcome of validating one bundle.
Attributes
----------
errors : list[SubmissionError]
Problems that make the bundle unscorable. Empty means it is scorable.
warnings : list[SubmissionError]
Problems worth telling the participant about that do not block scoring β€”
today, only a benchmark left out of a bundle when the challenge accepts
partial ones.
frames : dict[str, pd.DataFrame]
Per-benchmark parsed predictions, populated only for the benchmarks that
validated cleanly β€” so a caller can score a partial bundle when the
challenge allows it.
"""
errors: list[SubmissionError] = field(default_factory=list)
warnings: list[SubmissionError] = field(default_factory=list)
frames: dict[str, pd.DataFrame] = field(default_factory=dict)
@property
def ok(self) -> bool:
"""True when the bundle can be scored (warnings do not count)."""
return not self.errors
def add(self, benchmark: str, message: str) -> None:
"""Record a blocking problem."""
self.errors.append(SubmissionError(benchmark=benchmark, message=message))
def warn(self, benchmark: str, message: str) -> None:
"""Record a non-blocking problem."""
self.warnings.append(SubmissionError(benchmark=benchmark, message=message))
def report(self, limit: int = 12) -> str:
"""Format the errors as a participant-facing message.
Parameters
----------
limit : int
Maximum number of errors to list before summarising the remainder,
so a badly wrong bundle does not produce an unreadable wall of text.
Returns
-------
str
One bullet per error.
"""
problems = self.errors or self.warnings
if not problems:
return "Bundle is valid."
lines = [f"- {problem}" for problem in problems[:limit]]
if len(problems) > limit:
lines.append(f"- ...and {len(problems) - limit} more.")
return "\n".join(lines)
def read_table(path: Path) -> pd.DataFrame:
"""Read a submission file, accepting either CSV or Parquet.
Parameters
----------
path : Path
Path to a ``.csv`` or ``.parquet`` file.
Returns
-------
pd.DataFrame
The parsed table.
Raises
------
ValueError
If the suffix is neither ``.csv`` nor ``.parquet``.
"""
suffix = path.suffix.lower()
if suffix == ".parquet":
return pd.read_parquet(path)
if suffix == ".csv":
return pd.read_csv(path)
raise ValueError(f"Expected a .csv or .parquet file, got {path.name!r}")
def bundle_members(bundle_path: Path) -> dict[str, str]:
"""Map each benchmark name to its entry in the bundle.
Matching is on the file's basename with its extension dropped, so a bundle
zipped from a directory (``plug_submission/megascale.csv``) works as well as
one zipped from loose files, and either ``.csv`` or ``.parquet`` is accepted
per benchmark.
Parameters
----------
bundle_path : Path
The uploaded ``.zip``.
Returns
-------
dict[str, str]
Benchmark name -> zip entry name, for the benchmarks present.
"""
found: dict[str, str] = {}
with zipfile.ZipFile(bundle_path) as archive:
for entry in archive.namelist():
if entry.endswith("/") or any(
part.startswith(_IGNORED_ZIP_PREFIXES) for part in entry.split("/")
):
continue
stem = Path(entry).stem
suffix = Path(entry).suffix.lower()
if stem in BENCHMARK_NAMES and suffix in (".csv", ".parquet"):
# A bundle listing the same benchmark twice (e.g. both a .csv and a
# .parquet) is ambiguous rather than harmless β€” keep the first and
# let validate_bundle report the duplicate.
found.setdefault(stem, entry)
return found
def validate_bundle(
bundle_path: Path,
expected_ids: dict[str, set[str]],
require_complete: bool = True,
) -> ValidationResult:
"""Validate a submission bundle end to end.
Parameters
----------
bundle_path : Path
The uploaded ``.zip``.
expected_ids : dict[str, set[str]]
Benchmark name -> the set of ``datapoint_id`` values the submission's
track covers (the Lo-Hi test rows, or every row), taken from the ground
truth or the public manifest. A benchmark missing from this map is
treated as not currently scorable and is skipped with an error.
require_complete : bool
When True (the challenge default), a bundle missing any benchmark is
rejected. When False, missing benchmarks are recorded as errors but the
benchmarks that are present still parse into ``frames``.
Returns
-------
ValidationResult
Errors found, and the parsed frames for the benchmarks that passed.
"""
result = ValidationResult()
if not bundle_path.exists():
result.add("bundle", f"File not found: {bundle_path}")
return result
if bundle_path.suffix.lower() != ".zip":
result.add(
"bundle",
f"Submissions must be a single .zip archive, got {bundle_path.suffix!r}.",
)
return result
try:
members = bundle_members(bundle_path)
except zipfile.BadZipFile as exc:
result.add("bundle", f"Could not read the zip archive β€” {exc}")
return result
if not members:
result.add(
"bundle",
"The archive holds none of the benchmark files. Expected one file per "
"benchmark, named <benchmark>.csv or <benchmark>.parquet.",
)
return result
missing = [name for name in BENCHMARK_NAMES if name not in members]
if missing:
message = (
f"Missing {len(missing)} of {len(BENCHMARK_NAMES)} benchmark files: "
f"{', '.join(missing)}. Expected one file per benchmark, named "
f"<benchmark>.csv or <benchmark>.parquet."
)
if require_complete:
result.add("bundle", message)
return result
# Partial bundles are allowed here, so an absent benchmark is something to
# report rather than a reason to refuse: the rest still scores, and each
# absent benchmark counts as chance in the PLUG Score.
result.warn("bundle", message)
with zipfile.ZipFile(bundle_path) as archive:
for spec in BENCHMARKS:
entry = members.get(spec.name)
if entry is None:
continue
if spec.name not in expected_ids:
result.add(
spec.name,
"This benchmark is not open for scoring yet β€” remove it from the "
"bundle or check the challenge status.",
)
continue
frame = _read_member(archive, entry, spec, result)
if frame is None:
continue
before = len(result.errors)
_validate_frame(frame, spec, expected_ids[spec.name], result)
if len(result.errors) == before:
result.frames[spec.name] = frame
logger.info(
"Validated bundle {}: {} benchmark(s) parsed, {} error(s), {} warning(s).",
bundle_path.name,
len(result.frames),
len(result.errors),
len(result.warnings),
)
return result
def _read_member(
archive: zipfile.ZipFile, entry: str, spec: BenchmarkSpec, result: ValidationResult
) -> pd.DataFrame | None:
"""Read one benchmark's file out of the bundle, recording a parse failure.
``datapoint_id`` is always read as a string: most ids are bare row numbers
(``"1234"``), which a CSV reader would otherwise parse as integers that no
longer join against the ground truth.
"""
try:
with archive.open(entry) as handle:
if entry.lower().endswith(".parquet"):
frame = pd.read_parquet(handle)
else:
frame = pd.read_csv(handle, dtype={ID_COLUMN: str})
except Exception as exc:
result.add(spec.name, f"Could not read {entry!r} β€” {exc}")
return None
if ID_COLUMN in frame.columns:
frame[ID_COLUMN] = frame[ID_COLUMN].astype(str)
return frame
def _validate_frame(
frame: pd.DataFrame,
spec: BenchmarkSpec,
expected: set[str],
result: ValidationResult,
) -> None:
"""Apply every schema and value check for one benchmark."""
absent = [column for column in spec.required_columns if column not in frame.columns]
if absent:
result.add(
spec.name,
f"Missing required column(s): {', '.join(absent)}. Expected "
f"{', '.join(spec.required_columns)} (column names are case-sensitive).",
)
return
if frame.empty:
result.add(spec.name, "File has no rows.")
return
ids = frame[ID_COLUMN].astype(str)
if spec.long_form:
_validate_long_form(frame, ids, spec, expected, result)
else:
_validate_row_per_datapoint(ids, spec, expected, result)
for column in spec.pred_columns:
_validate_predictions(frame[column], column, spec, result)
def _validate_row_per_datapoint(
ids: pd.Series, spec: BenchmarkSpec, expected: set[str], result: ValidationResult
) -> None:
"""Require exactly one row per scored datapoint, no duplicates, nothing extra."""
duplicated = ids[ids.duplicated()].unique()
if duplicated.size:
result.add(
spec.name,
f"{duplicated.size} duplicated {ID_COLUMN} value(s), e.g. "
f"{', '.join(map(str, duplicated[:3]))}. Exactly one row per "
f"{spec.unit} is expected.",
)
submitted = set(ids)
if submitted == expected:
return
absent, unknown = expected - submitted, submitted - expected
if absent:
result.add(
spec.name,
f"{len(absent)} of {len(expected)} {spec.unit}s in this track have no prediction, "
f"e.g. {', '.join(sorted(absent)[:3])}.",
)
if unknown:
result.add(
spec.name,
f"{len(unknown)} {ID_COLUMN} value(s) are not scored in this track, e.g. "
f"{', '.join(sorted(unknown)[:3])}. Submit predictions for this track's "
f"rows of the benchmark's manifest and nothing else.",
)
def _validate_long_form(
frame: pd.DataFrame,
ids: pd.Series,
spec: BenchmarkSpec,
expected: set[str],
result: ValidationResult,
) -> None:
"""Validate a variable-length submission (cafa5): a set of (id, term) pairs.
Unlike a row-per-datapoint benchmark, declining to predict a target is
allowed here β€” that is what Fmax's coverage term measures β€” so a missing id
is not an error. Predicting a target outside the track still is.
"""
unknown = set(ids) - expected
if unknown:
result.add(
spec.name,
f"{len(unknown)} {ID_COLUMN} value(s) are not scored in this track, e.g. "
f"{', '.join(sorted(unknown)[:3])}.",
)
for column in spec.extra_columns:
blank = frame[column].isna() | (frame[column].astype(str).str.strip() == "")
if blank.any():
result.add(spec.name, f"{int(blank.sum())} row(s) have an empty {column!r}.")
for column, allowed in spec.allowed_values.items():
bad = ~frame[column].astype(str).str.strip().str.lower().isin(allowed)
if bad.any():
result.add(
spec.name,
f"{int(bad.sum())} row(s) have an unrecognised {column!r}; expected "
f"one of {', '.join(allowed)}.",
)
pair_columns = [ID_COLUMN, *spec.extra_columns]
duplicated = frame.duplicated(subset=pair_columns)
if duplicated.any():
result.add(
spec.name,
f"{int(duplicated.sum())} duplicated ({', '.join(pair_columns)}) pair(s). "
"Predict each term at most once per protein.",
)
covered = len(set(ids) & expected)
if covered == 0:
result.add(
spec.name,
f"No row refers to a {spec.unit} in this track; nothing could be scored.",
)
def _validate_predictions(
column: pd.Series, name: str, spec: BenchmarkSpec, result: ValidationResult
) -> None:
"""Check one prediction column is numeric, finite, in range, and not constant."""
values = pd.to_numeric(column, errors="coerce")
non_numeric = values.isna() & column.notna()
if non_numeric.any():
result.add(
spec.name,
f"Column {name!r} has {int(non_numeric.sum())} non-numeric value(s).",
)
return
if values.isna().any():
result.add(
spec.name,
f"Column {name!r} has {int(values.isna().sum())} missing value(s); every "
"prediction is required.",
)
return
finite = np.isfinite(values.to_numpy(dtype=float))
if not finite.all():
result.add(
spec.name,
f"Column {name!r} has {int((~finite).sum())} infinite value(s).",
)
return
if spec.score_range is not None:
low, high = spec.score_range
outside = (values < low) | (values > high)
if outside.any():
result.add(
spec.name,
f"Column {name!r} has {int(outside.sum())} value(s) outside "
f"[{low}, {high}].",
)
if spec.needs_varying_predictions and float(values.std()) < MIN_PREDICTION_STD:
result.add(
spec.name,
f"Column {name!r} is constant (or all but constant). This benchmark's "
"metrics are rank statistics, so a constant column cannot be scored β€” "
"please submit real model outputs.",
)