File size: 10,360 Bytes
e6cdfd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""READ-Bench leaderboard — official evaluation harness (self-contained).

This file is the single source of truth for how a submission is scored. It has
**no dependency on any private package** — only ``datasets`` + ``numpy`` — so a
submitter can clone the public results repo and reproduce their number exactly.

A submission provides a ``method.py`` exposing:

    def rank(query: dict, corpus: list[dict]) -> list[int]:
        '''Return corpus INDICES ordered most- to least-relevant to `query`.
        You may read ts_values / channels / entry metadata, but NEVER
        query["class_label"] (the hidden target). Corpus class_labels may be
        read only if your method is declared supervised / label-aware.'''

The harness loads the public dataset, rebuilds the official corpus/query split
for each dataset and pollution level, calls ``rank`` per query, and computes
NDCG@10 (plus P/HR/NDCG@{1,5,20} and macro-F1) with the paper's metric, then
macro-averages across datasets. Run::

    python eval_submission.py --submission submissions/my-method --out results.json
"""

from __future__ import annotations

import argparse
import importlib.util
import json
import random
import sys
from pathlib import Path
from typing import Callable, Dict, List, Tuple

import numpy as np

REPO = "c3aiia3c/read-bench"
DATASETS = [
    "ctsr", "damadics", "exathlon", "hai", "mit_bih", "petrobras_3w",
    "rats40k", "rcaeval", "road", "telecom_ts", "tennessee_eastman", "voraus",
]
# Official pollution levels: fraction of the corpus that is Normal.
POLLUTION = {"rho0": 0.0, "rho10": 0.10, "rho20": 0.20}
TOPK = (1, 3, 5, 10, 20)
PRIMARY_METRIC = "NDCG@10"
SEED = 42
LABEL_NORMAL = "Normal"


# --------------------------------------------------------------------------
# Metric — vendored verbatim from the paper's implementation so submissions
# score identically to the published numbers.
# --------------------------------------------------------------------------

def score_retrieval(score_matrix: np.ndarray, corpus_labels: np.ndarray,
                    query_labels: np.ndarray, topk: Tuple[int, ...] = TOPK) -> dict:
    """Score a (Q, N) score matrix (higher = better). P/HR/NDCG@K + macro-F1."""
    order = np.argsort(-score_matrix, axis=1, kind="stable")
    ranked = corpus_labels[order]
    n_rel = (corpus_labels == query_labels[:, None]).sum(axis=1)
    return _metrics_from_ranked(ranked, query_labels, n_rel, topk)


def score_from_ranked(ranked: np.ndarray, corpus_labels: np.ndarray,
                      query_labels: np.ndarray, topk: Tuple[int, ...] = TOPK) -> dict:
    """Score from a (Q, N) matrix of corpus indices already ranked per query."""
    ranked_labels = corpus_labels[ranked]
    n_rel = (corpus_labels == query_labels[:, None]).sum(axis=1)
    return _metrics_from_ranked(ranked_labels, query_labels, n_rel, topk)


def _metrics_from_ranked(ranked, query_labels, n_rel, topk) -> dict:
    rel = (ranked == query_labels[:, None])
    n_rel = np.maximum(n_rel, 1)
    metrics: Dict[str, float] = {}
    for k in topk:
        rel_k = rel[:, :k]
        metrics[f"P@{k}"] = float(rel_k.mean())
        metrics[f"HR@{k}"] = float(rel_k.any(axis=1).mean())
        discounts = 1.0 / np.log2(np.arange(2, k + 2))
        dcg = (rel_k * discounts).sum(axis=1)
        ideal = np.array([discounts[:min(int(nr), k)].sum() for nr in n_rel])
        metrics[f"NDCG@{k}"] = float(np.where(ideal > 0, dcg / ideal, 0.0).mean())

    def _majority(top5):
        counts: dict = {}
        order: list = []
        for lbl in top5:
            if lbl not in counts:
                counts[lbl] = 0
                order.append(lbl)
            counts[lbl] += 1
        return max(order, key=lambda l: counts[l])

    top5 = [_majority(ranked[q, :5].tolist()) for q in range(len(query_labels))]
    classes = np.unique(query_labels)
    f1s = []
    for cls in classes:
        tp = sum(p == cls and t == cls for p, t in zip(top5, query_labels))
        fp = sum(p == cls and t != cls for p, t in zip(top5, query_labels))
        fn = sum(p != cls and t == cls for p, t in zip(top5, query_labels))
        pr = tp / (tp + fp) if tp + fp else 0.0
        rc = tp / (tp + fn) if tp + fn else 0.0
        f1s.append(2 * pr * rc / (pr + rc) if pr + rc else 0.0)
    metrics["macro_F1"] = float(np.mean(f1s)) if f1s else 0.0
    return metrics


# --------------------------------------------------------------------------
# Official split reconstruction (self-contained; mirrors the paper protocol).
# Corpus = train-split anomalies (+ Normals to the pollution fraction),
# query = test-split anomalies. Deterministic given SEED.
# --------------------------------------------------------------------------

def _is_anom(e: dict) -> bool:
    return e.get("label") != LABEL_NORMAL


def _subsample_normals(normals: List[dict], n: int, rng: random.Random) -> List[dict]:
    if n >= len(normals):
        return list(normals)
    return rng.sample(normals, n)


def build_eval_split(rows: List[dict], pollution: float, seed: int = SEED,
                     ) -> Tuple[List[dict], List[dict]]:
    """Return ``(corpus, query)`` for one dataset at one pollution level.

    Corpus = train anomalies + enough train Normals to make ``pollution`` of the
    corpus Normal; query = test anomalies. All deterministic given ``seed``.
    """
    rng = random.Random(seed)
    train = [r for r in rows if r["native_split"] == "train"]
    test = [r for r in rows if r["native_split"] == "test"]

    corpus_anom = [r for r in train if _is_anom(r)]
    query = [r for r in test if _is_anom(r)]
    if not query:  # degenerate datasets: fall back to all test rows
        query = list(test)

    corpus = list(corpus_anom)
    if pollution > 0 and corpus_anom:
        # n_normal / (n_anom + n_normal) = pollution  ->  solve for n_normal
        n_norm = round(pollution / (1 - pollution) * len(corpus_anom))
        train_normals = [r for r in train if not _is_anom(r)]
        corpus += _subsample_normals(train_normals, n_norm, rng)
    rng.shuffle(corpus)
    return corpus, query


# --------------------------------------------------------------------------
# Submission loading + running.
# --------------------------------------------------------------------------

def load_method(submission_dir: Path) -> Callable[[dict, List[dict]], List[int]]:
    """Import ``method.py`` from a submission dir and return its ``rank``."""
    method_path = submission_dir / "method.py"
    if not method_path.exists():
        raise FileNotFoundError(f"no method.py in {submission_dir}")
    spec = importlib.util.spec_from_file_location("submission_method", method_path)
    mod = importlib.util.module_from_spec(spec)
    sys.modules["submission_method"] = mod
    spec.loader.exec_module(mod)
    if not hasattr(mod, "rank"):
        raise AttributeError("method.py must define rank(query, corpus) -> list[int]")
    return mod.rank


def _label_array(entries: List[dict]) -> np.ndarray:
    return np.array([e["class_label"] for e in entries], dtype=object)


def eval_dataset(rank_fn, rows: List[dict], pollution: float) -> dict:
    """Run the method over one dataset at one pollution level -> metrics dict."""
    corpus, query = build_eval_split(rows, pollution)
    corpus_labels = _label_array(corpus)
    query_labels = _label_array(query)

    # Hide the query's class_label from the method (anti-cheat on the target).
    masked_queries = [{k: v for k, v in q.items() if k != "class_label"} for q in query]

    ranked = np.zeros((len(query), len(corpus)), dtype=np.int64)
    for i, q in enumerate(masked_queries):
        order = rank_fn(q, corpus)
        order = list(dict.fromkeys(int(j) for j in order))  # dedupe, keep order
        missing = [j for j in range(len(corpus)) if j not in set(order)]
        full = (order + missing)[:len(corpus)]
        ranked[i] = full
    return score_from_ranked(ranked, corpus_labels, query_labels)


def evaluate(submission_dir: Path, datasets: List[str] = None,
             repo: str = REPO, token: str = None) -> dict:
    """Full evaluation of a submission -> results dict (also written as results.json)."""
    from datasets import load_dataset

    datasets = datasets or DATASETS
    rank_fn = load_method(submission_dir)

    per_dataset: Dict[str, Dict[str, dict]] = {}
    for name in datasets:
        ds = load_dataset(repo, name, token=token)
        rows = list(ds["train"]) + list(ds["test"])
        per_dataset[name] = {}
        for level, rho in POLLUTION.items():
            per_dataset[name][level] = eval_dataset(rank_fn, rows, rho)

    # Macro-average across datasets, per pollution level.
    summary: Dict[str, Dict[str, float]] = {}
    all_metrics = next(iter(next(iter(per_dataset.values())).values())).keys()
    for level in POLLUTION:
        summary[level] = {}
        for metric in all_metrics:
            vals = [per_dataset[d][level][metric] for d in datasets]
            summary[level][metric] = float(np.mean(vals))

    return {
        "primary_metric": PRIMARY_METRIC,
        "headline": {level: summary[level][PRIMARY_METRIC] for level in POLLUTION},
        "summary_macro_avg": summary,
        "per_dataset": per_dataset,
        "datasets": datasets,
    }


def main(argv=None) -> None:
    p = argparse.ArgumentParser(description=__doc__,
                                formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--submission", required=True, type=Path,
                   help="submission dir containing method.py + metadata.yaml")
    p.add_argument("--out", type=Path, default=None,
                   help="write results JSON here (default: <submission>/results.json)")
    p.add_argument("--datasets", nargs="*", default=None, help="subset (default: all 12)")
    p.add_argument("--repo", default=REPO)
    p.add_argument("--token", default=None, help="HF token (only needed if repo is private)")
    args = p.parse_args(argv)

    results = evaluate(args.submission, args.datasets, args.repo, args.token)
    out = args.out or (args.submission / "results.json")
    out.write_text(json.dumps(results, indent=2))
    h = results["headline"]
    print(f"NDCG@10  rho0={h['rho0']:.4f}  rho10={h['rho10']:.4f}  rho20={h['rho20']:.4f}")
    print(f"wrote {out}")


if __name__ == "__main__":
    main()