File size: 8,612 Bytes
ecaa1ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7deba50
ecaa1ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11d2b0b
 
 
 
 
 
 
 
 
 
 
 
 
ecaa1ff
 
7deba50
ecaa1ff
 
 
 
 
7deba50
 
 
 
 
 
 
ecaa1ff
 
11d2b0b
ecaa1ff
 
11d2b0b
ecaa1ff
 
 
7deba50
 
ecaa1ff
 
11d2b0b
ecaa1ff
 
11d2b0b
ecaa1ff
 
11d2b0b
 
 
 
 
 
ecaa1ff
11d2b0b
 
 
 
 
 
 
 
 
 
 
 
ecaa1ff
 
11d2b0b
 
ecaa1ff
 
 
 
 
11d2b0b
 
 
 
 
ecaa1ff
 
11d2b0b
ecaa1ff
 
 
 
 
 
 
 
 
11d2b0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecaa1ff
11d2b0b
 
 
 
 
 
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
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
"""The public benchmark API.

``Benchmark.load`` reads the released labels and the noise model; ``evaluate`` scores a
candidate's predictions and returns a point score with a label-uncertainty interval.

A candidate predicts **lines** (``Line(path, line, side, score)``). CoReDD lifts each
line to the syntax node that carries it -- the same projection that built the labels --
and scores on **nodes**: the released defective nodes are the truth, the predicted-onto
nodes are the prediction. The uncertainty comes from perturbing the truth (see
``perturbation``).
"""

from __future__ import annotations

import json
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path

import numpy as np
from sklearn.metrics import f1_score

from coredd.noise import NoiseModel
from coredd.perturbation import Change, interval
from coredd.history import RepositorySet


@dataclass(frozen=True)
class Line:
    """A predicted line: a file, a line number, its diff side, and a score.

    ``side`` is ``"after"`` for an added/context line or ``"base"`` for a deleted line.
    ``score`` is the prediction's confidence, used by rank metrics; it defaults to 1.0
    so a bare hit still ranks above the unpredicted nodes (score 0).
    """

    path: str
    line: int
    side: str
    score: float = 1.0


@dataclass(frozen=True)
class Result:
    """A benchmark score with its label-uncertainty band."""

    score: float
    interval: tuple[float, float]
    draws: int
    level: float = 0.95

    def __repr__(self) -> str:
        pct = int(round(self.level * 100))
        return (
            f"Score: {self.score:.2f}\n"
            f"{pct}% label-uncertainty interval: "
            f"[{self.interval[0]:.2f}, {self.interval[1]:.2f}]\n"
            f"Monte Carlo draws: {self.draws:,}"
        )


class Benchmark:
    """The released benchmark: labels, noise model, and repository clones."""

    def __init__(self, records: list[dict], repositories: RepositorySet,
                 noise_path: Path) -> None:
        self._records = records
        self._repositories = repositories
        self._noise_path = noise_path
        self._by_key = {
            self.key(record["repository"], record["pr"]): record for record in records
        }

    @classmethod
    def load(cls, repositories: str | Path, *, labels: str | Path,
             noise: str | Path) -> "Benchmark":
        """Load the benchmark against local clones under *repositories*.

        ``labels`` (the released ``labels.jsonl``) and ``noise`` (the ``noise.json``
        noise model) are the benchmark's released data files and are supplied by the
        caller; both are required.
        """
        records = _read_labels(labels)
        return cls(records, RepositorySet(repositories), Path(noise))

    @staticmethod
    def key(repository: str, pr: int, base: str | None = None,
            after: str | None = None) -> str:
        """The prediction key for a change.

        ``owner/repo#pr`` maps the prediction to a change; the optional
        ``@base..after`` suffix names the diff the prediction is made against, and both
        SHAs flow through to the node match. Omit them to build the mapping key used to
        index a change; supply them (a released node's ``base``/``after``) to predict.
        """
        change = f"{repository}#{pr}"
        if base is not None and after is not None:
            return f"{change}@{base}..{after}"
        return change

    def evaluate(self, predictions: Mapping[str, Iterable[Line]], *,
                 metric=f1_score, pooled: bool = True,
                 draws: int = 10_000, seed: int | None = 0) -> Result:
        """Score *predictions* and return the point score with its uncertainty band.

        ``predictions`` maps a change key (:meth:`key`, ``owner/repo#pr``) to its
        predicted lines; a change absent from the map is scored with no prediction.
        Score and interval are the mean and the [2.5%, 97.5%] quantile of the metric
        over the Monte Carlo draws that perturb the labels at the audited rates.
        Scoring is over the candidate syntax nodes N(c) of each change. With ``pooled``
        (the default) the metric runs once over the nodes of every change pooled into
        one population; with ``pooled=False`` it runs per change and is averaged
        equally across changes, dropping changes where it is undefined (NaN) -- the
        form per-case metrics such as :func:`coredd.metrics.mrr` are reported in.
        """
        prepared = _normalise(predictions)
        empty = _Prediction(base=None, after=None, lines=[])
        noise = NoiseModel.load(self._noise_path)
        changes = [
            self._change(record, prepared.get(key, empty))
            for key, record in self._by_key.items()
        ]
        rng = np.random.default_rng(seed)
        score, band = interval(changes, metric, noise, draws=draws, pooled=pooled,
                               rng=rng)
        return Result(score=score, interval=band, draws=draws)

    def _change(self, record: dict, prediction: "_Prediction") -> Change:
        nodes = record["nodes"]
        projection = self._repositories.projection(record["repository"])
        predicted = self._predict(projection, prediction)
        return self._node_change(nodes, predicted)

    def _predict(self, projection, prediction: "_Prediction") -> dict:
        # A prediction carries the (base, after) diff it is made against, in the key
        # ``owner/repo#pr@base..after``. Lines are lifted against that after commit, and
        # the resulting node keeps the (base, after) so it matches a label node only when
        # both the span and the diff agree -- a prediction against a different diff hits
        # nothing. Lines that lift to no node (blank/comment/non-Python) drop out.
        scores: dict[tuple, float] = {}
        if prediction.after is None:
            return scores
        for line in prediction.lines:
            # A prediction may name a commit the local clone does not have (a wrong or
            # unknown diff); that lifts to nothing rather than raising -- it simply hits
            # no label node.
            try:
                node = projection.project(
                    prediction.after, line.path, line.line, line.side
                )
            except (ValueError, KeyError):
                continue
            if node is None:
                continue
            key = (node.path, node.start, node.end, prediction.base, prediction.after)
            scores[key] = max(scores.get(key, float("-inf")), line.score)
        return scores

    def _node_change(self, nodes: list[dict], predicted: dict) -> Change:
        y_true, y_pred, scores, bins = [], [], [], []
        for node in nodes:
            key = (
                node["path"], tuple(node["start"]), tuple(node["end"]),
                node["base"], node["after"],
            )
            hit = key in predicted
            y_true.append("provenance" in node)
            y_pred.append(hit)
            scores.append(predicted[key] if hit else 0.0)
            bins.append(int(node["bin"]))
        return Change(
            y_true=np.asarray(y_true, dtype=bool),
            y_pred=np.asarray(y_pred, dtype=bool),
            scores=np.asarray(scores, dtype=float),
            bin=np.asarray(bins, dtype=int),
        )


@dataclass(frozen=True)
class _Prediction:
    """A change's predicted lines together with the diff they are made against."""

    base: str | None
    after: str | None
    lines: list[Line]


def _normalise(
    predictions: Mapping[str, Iterable[Line]],
) -> dict[str, "_Prediction"]:
    # The key is ``owner/repo#pr@base..after``: the ``owner/repo#pr`` part maps the
    # prediction to a change, and the ``@base..after`` part names the diff it is made
    # against. Both SHAs flow through to the node match, so a prediction against a
    # different diff than the released one lifts to nodes that match nothing.
    prepared: dict[str, "_Prediction"] = {}
    for key, lines in predictions.items():
        change, _, diff = key.partition("@")
        base, after = (None, None)
        if diff:
            base, _, after = diff.partition("..")
            base, after = base or None, after or None
        prepared[change] = _Prediction(base=base, after=after, lines=list(lines))
    return prepared


def _read_labels(labels: str | Path) -> list[dict]:
    text = Path(labels).read_text(encoding="utf-8")
    return [json.loads(line) for line in text.splitlines() if line.strip()]