File size: 9,758 Bytes
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49442cb
b78ff28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
"""Turn a validated submission bundle into per-benchmark metric values.

One function per submission (``score_bundle``) and one per benchmark
(``score_benchmark``); which arithmetic runs is decided entirely by the
``MetricSpec.kind`` values in ``benchmarks.py``, so adding a metric to a
benchmark is a one-line change there and needs no edit here.

Scoring is deliberately separate from validation: by the time anything in this
module runs, the frames are known to have the right columns, the right ids and
finite values, so the metric code can assume a clean join.
"""

import numpy as np
import pandas as pd
from loguru import logger

from . import metrics
from .benchmarks import GO_ASPECTS, ID_COLUMN, BenchmarkSpec, MetricSpec

# Bootstrap resampling is not implemented for the long-form (cafa5) scorer: a
# resample has to redraw whole targets and recount each one's annotations, and a
# 101-point Fmax sweep per resample is far too slow to run inside a submission
# request. Its std is reported as 0.0 and the point estimate is exact.
_BOOTSTRAP_UNSUPPORTED = ("fmax",)


def score_bundle(
    frames: dict[str, pd.DataFrame],
    truth: dict[str, pd.DataFrame],
    specs: tuple[BenchmarkSpec, ...],
    bootstrap_samples: int = 0,
    seed: int = 0,
) -> dict[str, dict[str, float]]:
    """Score every benchmark present in both the submission and the ground truth.

    Parameters
    ----------
    frames : dict[str, pd.DataFrame]
        Benchmark name -> validated predictions, as returned by
        ``validation.ValidationResult.frames``.
    truth : dict[str, pd.DataFrame]
        Benchmark name -> that benchmark's ground truth, narrowed to the track being scored.
    specs : tuple[BenchmarkSpec, ...]
        The benchmarks to score, in leaderboard order.
    bootstrap_samples : int
        Resamples per metric for the standard deviation. ``0`` reports point
        estimates only, which is the Space default — see ``config``.
    seed : int
        Seed for the bootstrap RNG, so rescoring a submission reproduces it.

    Returns
    -------
    dict[str, dict[str, float]]
        Benchmark name -> ``{"<metric>_mean": ..., "<metric>_std": ..., "n": ...}``.
        A benchmark absent from either input is absent from the result rather
        than scored as zero.

    """
    scores: dict[str, dict[str, float]] = {}
    for spec in specs:
        if spec.name not in frames or spec.name not in truth:
            continue
        scores[spec.name] = score_benchmark(
            spec,
            frames[spec.name],
            truth[spec.name],
            bootstrap_samples=bootstrap_samples,
            seed=seed,
        )
        logger.info(
            "Scored {}: {} = {:.4f} (n={})",
            spec.name,
            spec.primary.key,
            scores[spec.name][f"{spec.primary.key}_mean"],
            scores[spec.name]["n"],
        )
    return scores


def score_benchmark(
    spec: BenchmarkSpec,
    predictions: pd.DataFrame,
    truth: pd.DataFrame,
    bootstrap_samples: int = 0,
    seed: int = 0,
) -> dict[str, float]:
    """Compute every metric one benchmark reports.

    Parameters
    ----------
    spec : BenchmarkSpec
        The benchmark being scored.
    predictions : pd.DataFrame
        Validated predictions for this benchmark.
    truth : pd.DataFrame
        This benchmark's ground truth for the track being scored.
    bootstrap_samples : int
        Resamples per metric; ``0`` for point estimates only.
    seed : int
        Bootstrap RNG seed.

    Returns
    -------
    dict[str, float]
        ``{"<metric>_mean": ..., "<metric>_std": ..., "n": ...}`` for every metric
        in ``spec.metrics``. ``n`` is the number of scored rows (datapoints for a
        row-per-datapoint benchmark, annotated targets for cafa5).

    """
    if spec.long_form:
        return _score_long_form(spec, predictions, truth)

    merged = truth.merge(
        predictions[list(spec.required_columns)],
        on=ID_COLUMN,
        how="inner",
        validate="one_to_one",
    )
    out: dict[str, float] = {"n": float(len(merged))}
    for metric in spec.metrics:
        mean, std = _bootstrap_metric(spec, metric, merged, bootstrap_samples, seed)
        out[f"{metric.key}_mean"] = mean
        out[f"{metric.key}_std"] = std
    return out


def _bootstrap_metric(
    spec: BenchmarkSpec,
    metric: MetricSpec,
    merged: pd.DataFrame,
    bootstrap_samples: int,
    seed: int,
) -> tuple[float, float]:
    """Compute one metric's point estimate and bootstrap standard deviation."""
    groups = (
        merged[metric.grouped_by].to_numpy()
        if metric.grouped_by and metric.grouped_by in merged.columns
        else None
    )

    def on_rows(rows: np.ndarray) -> float:
        return _apply(spec, metric, merged.iloc[rows])

    return metrics.bootstrap(
        on_rows,
        n_samples=bootstrap_samples,
        n_rows=len(merged),
        seed=seed,
        groups=groups,
    )


def _apply(spec: BenchmarkSpec, metric: MetricSpec, merged: pd.DataFrame) -> float:
    """Dispatch one ``MetricSpec`` against a merged truth/prediction frame."""
    truth_column = spec.truth_columns[0] if spec.truth_columns else ""
    pred_column = spec.pred_columns[0]

    if metric.kind == "spearman":
        return metrics.spearman(merged[truth_column], merged[pred_column])
    if metric.kind == "auroc":
        return metrics.auroc(merged[truth_column], merged[pred_column])
    if metric.kind == "grouped_spearman":
        return metrics.grouped_spearman(
            merged[truth_column], merged[pred_column], merged[metric.grouped_by]
        )
    if metric.kind == "grouped_auroc":
        return metrics.grouped_auroc(
            merged[truth_column], merged[pred_column], merged[metric.grouped_by]
        )
    if metric.kind == "macro_auroc":
        return metrics.macro_auroc(
            merged[list(spec.truth_columns)].to_numpy(),
            merged[list(spec.pred_columns)].to_numpy(),
        )
    raise ValueError(f"{spec.name}: metric kind {metric.kind!r} has no scorer here")


def _score_long_form(
    spec: BenchmarkSpec, predictions: pd.DataFrame, truth: pd.DataFrame
) -> dict[str, float]:
    """Score cafa5: Fmax per GO branch plus the macro-average over the branches.

    ``truth`` is long form as well — one row per ``(datapoint_id, aspect, term)``
    annotation — so both sides are reduced to the same three arrays per aspect
    and handed to ``metrics.fmax_long``.
    """
    pred = predictions.copy()
    pred["aspect"] = pred["aspect"].astype(str).str.strip().str.lower()
    pred["term"] = pred["term"].astype(str).str.strip()
    gt = truth.copy()
    gt["aspect"] = gt["aspect"].astype(str).str.strip().str.lower()
    gt["term"] = gt["term"].astype(str).str.strip()

    # Every scored protein is a target, annotated or not — an unannotated one is
    # dropped inside fmax_long, but it must be in the index so that a prediction
    # about it is still counted against precision.
    targets = pd.Index(sorted(set(gt[ID_COLUMN].astype(str)) | set(pred[ID_COLUMN].astype(str))))
    target_of = {target: i for i, target in enumerate(targets)}

    out: dict[str, float] = {}
    per_aspect: dict[str, float] = {}
    for aspect in GO_ASPECTS:
        result = _fmax_for_aspect(aspect, pred, gt, targets, target_of)
        value = result["fmax"]
        per_aspect[aspect] = float("nan") if value is None else float(value)
        out[f"fmax_{aspect}_mean"] = per_aspect[aspect]
        out[f"fmax_{aspect}_std"] = 0.0
        # Per-branch target counts differ a lot (a protein commonly carries BP
        # annotations but no CC ones), so each is reported rather than collapsed.
        out[f"fmax_{aspect}_n"] = float(result["targets"] or 0)

    finite = [v for v in per_aspect.values() if np.isfinite(v)]
    out["fmax_mean"] = float(np.mean(finite)) if finite else metrics.UNDEFINED
    out["fmax_std"] = 0.0
    # `n` is the number of scored targets carrying at least one annotation in any
    # branch — the targets this benchmark could score at all.
    out["n"] = float(gt[ID_COLUMN].astype(str).nunique())
    return out


def _fmax_for_aspect(
    aspect: str,
    pred: pd.DataFrame,
    gt: pd.DataFrame,
    targets: pd.Index,
    target_of: dict[str, int],
) -> dict[str, float | None]:
    """Reduce one GO branch to long-form arrays and Fmax them."""
    gt_aspect = gt[gt["aspect"] == aspect]
    pred_aspect = pred[pred["aspect"] == aspect]

    true_per_target = np.zeros(len(targets), dtype=float)
    if not gt_aspect.empty:
        counts = gt_aspect.groupby(gt_aspect[ID_COLUMN].astype(str))["term"].nunique()
        for target, count in counts.items():
            true_per_target[target_of[str(target)]] = float(count)

    if pred_aspect.empty:
        return {
            "fmax": None if not true_per_target.any() else 0.0,
            "threshold": None,
            "precision": None,
            "recall": None,
            "coverage": 0.0,
            "targets": int((true_per_target > 0).sum()),
        }

    annotated_pairs = set(
        zip(gt_aspect[ID_COLUMN].astype(str), gt_aspect["term"], strict=True)
    )
    target_index = np.asarray(
        [target_of[t] for t in pred_aspect[ID_COLUMN].astype(str)], dtype=np.int64
    )
    is_true = np.asarray(
        [
            (t, term) in annotated_pairs
            for t, term in zip(
                pred_aspect[ID_COLUMN].astype(str), pred_aspect["term"], strict=True
            )
        ],
        dtype=bool,
    )
    return metrics.fmax_long(
        target_index=target_index,
        scores=pred_aspect["score"].to_numpy(dtype=float),
        is_true=is_true,
        true_per_target=true_per_target,
    )