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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
"""Metric implementations for the PLUG challenge.

Ported from ``plug-baselines/utils.py`` so that a leaderboard number and a
published baseline number are computed by the same arithmetic. Every function
here takes plain arrays and returns a plain float β€” nothing in this module
knows about submissions, S3/Hub storage, or benchmarks.

Three families cover all eleven benchmarks:

- **Rank correlation** (``spearman``, ``grouped_spearman``) β€” the ddG, DMS,
  affinity and RMSF benchmarks.
- **Ranking/detection** (``auroc``, ``macro_auroc``, ``grouped_auroc``) β€” the
  PPI and allosteric-site benchmarks.
- **CAFA Fmax** (``fmax``) β€” GO term prediction.
"""

import warnings

import numpy as np
import numpy.typing as npt
from loguru import logger
from scipy.stats import ConstantInputWarning, spearmanr
from sklearn.metrics import roc_auc_score

# Returned instead of a float when a metric is mathematically undefined for the
# data it was handed (a constant prediction column, a single-class label column,
# a group with one member). Callers decide whether that is a validation failure
# or a group to skip; nothing here raises.
UNDEFINED = float("nan")


def spearman(y_true: npt.ArrayLike, y_pred: npt.ArrayLike) -> float:
    """Spearman rank correlation, ignoring positions where either side is NaN.

    Parameters
    ----------
    y_true : npt.ArrayLike
        Ground-truth values.
    y_pred : npt.ArrayLike
        Predicted values.

    Returns
    -------
    float
        Spearman's rho, or ``UNDEFINED`` when fewer than two finite pairs
        remain or either side is constant (rho is undefined with zero variance β€”
        scipy returns NaN there rather than raising).

    """
    y_true = np.asarray(y_true, dtype=float)
    y_pred = np.asarray(y_pred, dtype=float)
    keep = ~(np.isnan(y_true) | np.isnan(y_pred))
    if keep.sum() < 2:
        return UNDEFINED
    # A constant column makes rho undefined; scipy warns and returns NaN, which
    # is exactly the UNDEFINED contract here, so the warning is noise.
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=ConstantInputWarning)
        rho = spearmanr(y_true[keep], y_pred[keep]).correlation
    return float(rho) if np.isfinite(rho) else UNDEFINED


def auroc(y_true: npt.ArrayLike, y_score: npt.ArrayLike) -> float:
    """Area under the ROC curve for a binary label.

    Parameters
    ----------
    y_true : npt.ArrayLike
        Binary labels (0/1 or bool).
    y_score : npt.ArrayLike
        Predicted scores; higher must mean "more likely positive".

    Returns
    -------
    float
        AUROC, or ``UNDEFINED`` when the labels are single-class (AUROC is
        undefined without both classes present).

    """
    y_true = np.asarray(y_true)
    y_score = np.asarray(y_score, dtype=float)
    if y_true.size == 0 or y_true.min() == y_true.max():
        return UNDEFINED
    return float(roc_auc_score(y_true, y_score))


def macro_auroc(y_true: npt.ArrayLike, y_score: npt.ArrayLike) -> float:
    """Mean AUROC over the label columns that have both classes present.

    Single-class columns are skipped rather than scored as 0.5, matching
    ``plug-baselines``: a mode no test pair carries says nothing about the
    submission either way.

    Parameters
    ----------
    y_true : npt.ArrayLike
        Binary label matrix, shape ``(n_samples, n_labels)``.
    y_score : npt.ArrayLike
        Predicted score matrix of the same shape.

    Returns
    -------
    float
        Macro-averaged AUROC, or ``UNDEFINED`` when no column is scorable.

    """
    y_true = np.asarray(y_true)
    y_score = np.asarray(y_score, dtype=float)
    per_label = [
        roc_auc_score(y_true[:, k], y_score[:, k])
        for k in range(y_true.shape[1])
        if y_true[:, k].min() != y_true[:, k].max()
    ]
    return float(np.mean(per_label)) if per_label else UNDEFINED


def fmax(
    y_true: npt.ArrayLike,
    y_score: npt.ArrayLike,
    step: float = 0.01,
    weights: npt.ArrayLike | None = None,
) -> dict[str, float | None]:
    """CAFA target-centric Fmax over a confidence-threshold sweep.

    Scores must be probabilities, hence the 0..1 grid. At each threshold,
    precision is averaged over the targets that predict at least one term while
    recall is averaged over every annotated target β€” that asymmetry is CAFA's: a
    target you decline to predict costs recall but not precision. Unannotated
    targets are dropped.

    Parameters
    ----------
    y_true : npt.ArrayLike
        Boolean annotation matrix, shape ``(n_targets, n_terms)``.
    y_score : npt.ArrayLike
        Predicted probability matrix of the same shape.
    step : float
        Threshold grid spacing over ``[0, 1]``.
    weights : npt.ArrayLike | None
        Optional per-term information accretion, for the information-weighted
        variant. ``None`` weights every term equally.

    Returns
    -------
    dict[str, float | None]
        ``fmax``, the ``threshold`` that achieved it, the ``precision`` and
        ``recall`` there, ``coverage`` (fraction of targets still predicting at
        that threshold), and the number of annotated ``targets``. Every value
        except ``targets`` is ``None`` when no target is annotated.

    """
    y_true = np.asarray(y_true, dtype=bool)
    y_score = np.asarray(y_score, dtype=float)
    annotated = y_true.sum(axis=1) > 0
    if not annotated.any():
        return {
            "fmax": None,
            "threshold": None,
            "precision": None,
            "recall": None,
            "coverage": None,
            "targets": 0,
        }
    y_true, y_score = y_true[annotated], y_score[annotated]
    w = None if weights is None else np.asarray(weights, dtype=float)
    true_weight = (y_true * w).sum(axis=1) if w is not None else y_true.sum(axis=1).astype(float)

    best: dict[str, float | None] = {
        "fmax": 0.0,
        "threshold": None,
        "precision": None,
        "recall": None,
        "coverage": None,
        "targets": int(y_true.shape[0]),
    }
    for threshold in np.arange(0.0, 1.0 + step / 2, step):
        predicted = y_score >= threshold
        pred_weight = (
            (predicted * w).sum(axis=1) if w is not None else predicted.sum(axis=1).astype(float)
        )
        hit_weight = (
            ((predicted & y_true) * w).sum(axis=1)
            if w is not None
            else (predicted & y_true).sum(axis=1).astype(float)
        )
        predicting = pred_weight > 0
        if not predicting.any():
            continue
        precision = float((hit_weight[predicting] / pred_weight[predicting]).mean())
        recall = float((hit_weight / true_weight).mean())
        if precision + recall == 0:
            continue
        f1 = 2 * precision * recall / (precision + recall)
        current_best = best["fmax"]
        if current_best is None or f1 > current_best:
            best.update(
                fmax=f1,
                threshold=float(threshold),
                precision=precision,
                recall=recall,
                coverage=float(predicting.mean()),
            )
    return best


def grouped_spearman(
    y_true: npt.ArrayLike, y_pred: npt.ArrayLike, groups: npt.ArrayLike
) -> float:
    """Mean of the within-group Spearman correlations.

    Used where the ground-truth values are not on a common scale across groups
    and pooling them would measure between-group spread instead of within-group
    ranking β€” DMS (one assay per ``dms_id``) is the canonical case. Groups whose
    correlation is undefined (fewer than two points, or constant on either side)
    are skipped.

    Parameters
    ----------
    y_true : npt.ArrayLike
        Ground-truth values.
    y_pred : npt.ArrayLike
        Predicted values.
    groups : npt.ArrayLike
        Group label per row.

    Returns
    -------
    float
        Unweighted mean over scorable groups β€” every group counts once
        regardless of size β€” or ``UNDEFINED`` when no group is scorable.

    """
    return _grouped_mean(spearman, y_true, y_pred, groups)


def grouped_auroc(y_true: npt.ArrayLike, y_score: npt.ArrayLike, groups: npt.ArrayLike) -> float:
    """Mean of the within-group AUROCs.

    The per-protein counterpart to ``auroc`` for the per-residue benchmarks:
    it asks whether the sites are ranked correctly *within* each protein, which
    a pooled AUROC can hide when scores are calibrated differently per protein.
    Single-class groups are skipped.

    Parameters
    ----------
    y_true : npt.ArrayLike
        Binary labels.
    y_score : npt.ArrayLike
        Predicted scores.
    groups : npt.ArrayLike
        Group label per row.

    Returns
    -------
    float
        Unweighted mean over scorable groups, or ``UNDEFINED`` when no group is
        scorable.

    """
    return _grouped_mean(auroc, y_true, y_score, groups)


def _grouped_mean(
    metric, y_true: npt.ArrayLike, y_pred: npt.ArrayLike, groups: npt.ArrayLike
) -> float:
    """Apply ``metric`` within each group and average the defined results.

    Parameters
    ----------
    metric : Callable[[npt.ArrayLike, npt.ArrayLike], float]
        A two-argument metric returning a float or ``UNDEFINED``.
    y_true : npt.ArrayLike
        Ground-truth values.
    y_pred : npt.ArrayLike
        Predicted values.
    groups : npt.ArrayLike
        Group label per row.

    Returns
    -------
    float
        Mean over groups with a defined metric, or ``UNDEFINED`` if there are
        none.

    """
    y_true = np.asarray(y_true)
    y_pred = np.asarray(y_pred)
    groups = np.asarray(groups)
    values = []
    for group in np.unique(groups):
        mask = groups == group
        value = metric(y_true[mask], y_pred[mask])
        if np.isfinite(value):
            values.append(value)
    if not values:
        logger.warning("No scorable groups β€” metric is undefined for this submission.")
        return UNDEFINED
    return float(np.mean(values))


def bootstrap(
    metric,
    n_samples: int,
    n_rows: int,
    seed: int = 0,
    groups: npt.ArrayLike | None = None,
) -> tuple[float, float]:
    """Resample row indices and return the mean and standard deviation of ``metric``.

    Resampling is at the row level by default. When ``groups`` is given, whole
    groups are resampled instead (every row of a drawn group comes along), which
    is the correct unit for the grouped metrics: a per-assay mean has as many
    independent observations as there are assays, not as there are variants.

    Parameters
    ----------
    metric : Callable[[np.ndarray], float]
        Takes an array of row indices and returns that resample's metric value.
    n_samples : int
        Number of bootstrap resamples. ``0`` skips resampling entirely and
        returns the point estimate on all rows with a standard deviation of 0.
    n_rows : int
        Number of rows available to sample from.
    seed : int
        Seed for the resampling RNG, so a rescore reproduces the same interval.
    groups : npt.ArrayLike | None
        Optional group label per row; when given, groups rather than rows are
        the resampling unit.

    Returns
    -------
    tuple[float, float]
        The mean and standard deviation of the metric over the resamples. With
        ``n_samples == 0``, the point estimate and ``0.0``.

    """
    all_rows = np.arange(n_rows)
    if n_samples <= 0:
        return metric(all_rows), 0.0

    rng = np.random.default_rng(seed)
    if groups is None:
        draws = [metric(rng.integers(0, n_rows, size=n_rows)) for _ in range(n_samples)]
    else:
        groups = np.asarray(groups)
        unique = np.unique(groups)
        rows_by_group = {g: all_rows[groups == g] for g in unique}
        draws = []
        for _ in range(n_samples):
            drawn = unique[rng.integers(0, unique.size, size=unique.size)]
            draws.append(metric(np.concatenate([rows_by_group[g] for g in drawn])))

    finite = np.asarray([d for d in draws if np.isfinite(d)], dtype=float)
    if finite.size == 0:
        return UNDEFINED, UNDEFINED
    return float(finite.mean()), float(finite.std())


def fmax_long(
    target_index: npt.ArrayLike,
    scores: npt.ArrayLike,
    is_true: npt.ArrayLike,
    true_per_target: npt.ArrayLike,
    step: float = 0.01,
) -> dict[str, float | None]:
    """CAFA Fmax computed from long-form predictions, without a dense matrix.

    Mathematically identical to ``fmax`` with equal term weights (the two are
    cross-checked against each other in the tests), but it consumes the
    ``(target, term, score)`` triples a submission actually carries. A dense
    ``targets Γ— terms`` score matrix for CAFA5 runs to hundreds of megabytes,
    while this is linear in the number of predicted rows.

    Only annotated targets contribute, again matching CAFA: ``true_per_target``
    carries a zero for an unannotated target and those targets are dropped from
    both the precision and the recall average.

    Parameters
    ----------
    target_index : npt.ArrayLike
        Integer target index per predicted row, in ``[0, n_targets)``.
    scores : npt.ArrayLike
        Predicted confidence per row, in ``[0, 1]``.
    is_true : npt.ArrayLike
        Whether each predicted row's term is actually annotated on that target.
    true_per_target : npt.ArrayLike
        Number of annotated terms per target, length ``n_targets``. Zero marks an
        unannotated target.
    step : float
        Threshold grid spacing over ``[0, 1]``.

    Returns
    -------
    dict[str, float | None]
        The same keys as ``fmax``.

    """
    targets = np.asarray(target_index, dtype=np.int64)
    confidences = np.asarray(scores, dtype=float)
    correct = np.asarray(is_true, dtype=bool)
    true_counts = np.asarray(true_per_target, dtype=float)
    n_targets = true_counts.size

    annotated = true_counts > 0
    n_annotated = int(annotated.sum())
    if n_annotated == 0:
        return {
            "fmax": None,
            "threshold": None,
            "precision": None,
            "recall": None,
            "coverage": None,
            "targets": 0,
        }

    # Rows about unannotated targets cannot affect either average, so drop them up
    # front rather than masking inside the sweep.
    keep = annotated[targets]
    targets, confidences, correct = targets[keep], confidences[keep], correct[keep]

    best: dict[str, float | None] = {
        "fmax": 0.0,
        "threshold": None,
        "precision": None,
        "recall": None,
        "coverage": None,
        "targets": n_annotated,
    }
    for threshold in np.arange(0.0, 1.0 + step / 2, step):
        above = confidences >= threshold
        if not above.any():
            continue
        hits = targets[above]
        predicted_per_target = np.bincount(hits, minlength=n_targets).astype(float)
        true_positive = np.bincount(hits[correct[above]], minlength=n_targets).astype(float)
        predicting = predicted_per_target > 0
        if not predicting.any():
            continue
        precision = float((true_positive[predicting] / predicted_per_target[predicting]).mean())
        recall = float((true_positive[annotated] / true_counts[annotated]).mean())
        if precision + recall == 0:
            continue
        f1 = 2 * precision * recall / (precision + recall)
        current_best = best["fmax"]
        if current_best is None or f1 > current_best:
            best.update(
                fmax=f1,
                threshold=float(threshold),
                precision=precision,
                recall=recall,
                coverage=float(predicting.sum() / n_annotated),
            )
    return best