File size: 4,121 Bytes
ecaa1ff
 
7deba50
 
 
 
 
 
 
 
 
 
 
 
ecaa1ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7deba50
ecaa1ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7deba50
ecaa1ff
 
7deba50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecaa1ff
 
 
 
 
 
 
 
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
"""Monte-Carlo label-uncertainty interval, metric-agnostic.

Score and interval are both statistics of the same Monte Carlo run: each draw samples
an alpha and a gamma rate per stratum from their Beta posteriors, then keeps each
marked node with probability ``1 - alpha`` of its stratum and adds each unmarked node
with probability ``gamma`` of its stratum, and scores the metric against the perturbed
truth. The prediction is held fixed; only the truth moves. The score is the mean over
the draws, the band their [2.5%, 97.5%] quantile.

Aggregation over changes comes in two forms. Pooled (the default) scores the metric
once per draw over the nodes of every change concatenated into one population, so a
draw that strips a change of its defective nodes keeps the change in as negatives.
Per-case (``pooled=False``) scores each change separately and averages, dropping
changes where the metric is undefined (NaN).

This mirrors the evaluation notebook's ``theta_star`` with one change: the prediction is
the caller's real one, not a synthetic detector, so there is no skill grid -- one
prediction per change, one score per draw.
"""

from __future__ import annotations

from dataclasses import dataclass

import numpy as np

from coredd.metrics import is_rank
from coredd.noise import NoiseModel


@dataclass(frozen=True)
class Change:
    """One change reduced to its candidate nodes for scoring.

    ``y_true`` marks the released defective nodes, ``y_pred`` the predicted ones,
    ``scores`` the per-node prediction score (for rank metrics), and ``bin`` the
    confidence stratum of each node.
    """

    y_true: np.ndarray  # bool (n,)
    y_pred: np.ndarray  # bool (n,)
    scores: np.ndarray  # float (n,)
    bin: np.ndarray  # int (n,)


def interval(
    changes: list[Change],
    metric,
    noise: NoiseModel,
    *,
    draws: int = 10_000,
    band: tuple[float, float] = (0.025, 0.975),
    pooled: bool = True,
    rng: np.random.Generator,
) -> tuple[float, tuple[float, float]]:
    """Return the point score and the label-uncertainty band over the changes."""
    rank = is_rank(metric)
    index = noise.index()
    alpha_ab = noise.alpha_beta()
    gamma_ab = noise.gamma_beta()

    prepared = []
    for change in changes:
        rows = np.array([index[int(b)] for b in change.bin], dtype=int)
        prediction = change.scores if rank else change.y_pred
        prepared.append((change.y_true, prediction, rows))

    def evaluate(y_true: np.ndarray, prediction: np.ndarray) -> float:
        return float(metric(y_true, prediction))

    def rates() -> tuple[np.ndarray, np.ndarray]:
        alpha = rng.beta(alpha_ab[:, 0], alpha_ab[:, 1])
        gamma = rng.beta(gamma_ab[:, 0], gamma_ab[:, 1])
        return alpha, gamma

    def perturb(y_true: np.ndarray, rows: np.ndarray,
                alpha: np.ndarray, gamma: np.ndarray) -> np.ndarray:
        keep = rng.random(y_true.size) > alpha[rows]
        add = rng.random(y_true.size) < gamma[rows]
        return np.where(y_true, keep, add)

    agg = np.empty(draws, dtype=float)
    if pooled:
        y_true = np.concatenate([t for t, _, _ in prepared])
        prediction = np.concatenate([p for _, p, _ in prepared])
        rows = np.concatenate([r for _, _, r in prepared])
        for m in range(draws):
            alpha, gamma = rates()
            agg[m] = evaluate(perturb(y_true, rows, alpha, gamma), prediction)
    else:
        for m in range(draws):
            alpha, gamma = rates()
            agg[m] = _mean([
                evaluate(perturb(y_true, rows, alpha, gamma), prediction)
                for y_true, prediction, rows in prepared
            ])

    if np.isnan(agg).all():
        return float("nan"), (float("nan"), float("nan"))
    lo, hi = np.nanquantile(agg, band)
    return float(np.nanmean(agg)), (float(lo), float(hi))


def _mean(values: list[float]) -> float:
    """Mean over changes, ignoring NaN (a metric undefined for a change is dropped)."""
    array = np.asarray(values, dtype=float)
    if np.isnan(array).all():
        return float("nan")
    return float(np.nanmean(array))