File size: 4,894 Bytes
5cc5437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Small released-checkpoint probe on generated contextual anomalies.

This is not the paper's full contextual benchmark. It is a sanity check that the
public univariate checkpoint can run zero-shot on contextual anomaly series and
emit anomaly-head scores end to end in this reproduction environment.
"""

from __future__ import annotations

import json
import os
import sys
from pathlib import Path

import numpy as np


ROOT = Path(__file__).resolve().parents[1]
TIME_RCD = ROOT / "official_Time-RCD"
OUT = ROOT / "outputs" / "deep_repro"


def best_f1(scores: np.ndarray, labels: np.ndarray) -> dict[str, float]:
    scores = np.asarray(scores, dtype=float).reshape(-1)
    labels = np.asarray(labels, dtype=int).reshape(-1)
    n = min(len(scores), len(labels))
    scores, labels = scores[:n], labels[:n]
    thresholds = np.unique(np.quantile(scores, np.linspace(0, 1, 201)))
    best = {"f1": 0.0, "precision": 0.0, "recall": 0.0, "threshold": float(thresholds[0])}
    for threshold in thresholds:
        pred = scores >= threshold
        tp = int(np.sum(pred & (labels == 1)))
        fp = int(np.sum(pred & (labels == 0)))
        fn = int(np.sum((~pred) & (labels == 1)))
        precision = tp / (tp + fp) if tp + fp else 0.0
        recall = tp / (tp + fn) if tp + fn else 0.0
        f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
        if f1 > best["f1"]:
            best = {"f1": float(f1), "precision": float(precision), "recall": float(recall), "threshold": float(threshold)}
    return best


def make_contextual(n_series: int = 20, length: int = 512) -> tuple[np.ndarray, np.ndarray]:
    rng = np.random.default_rng(12052)
    series = []
    labels = []
    for i in range(n_series):
        t = np.arange(length)
        period = rng.uniform(42, 90)
        phase = rng.uniform(0, 2 * np.pi)
        y = np.sin(2 * np.pi * t / period + phase)
        y += 0.24 * np.sin(2 * np.pi * t / (period / 3.0) + phase / 3)
        y += rng.normal(0, 0.06, length)
        lab = np.zeros(length, dtype=int)
        if i >= n_series // 2:
            start = int(rng.integers(150, 330))
            width = int(rng.integers(45, 85))
            end = min(length, start + width)
            local = np.arange(end - start)
            # Contextual: in-range and smooth, but locally violates the context
            # relationship between dominant and harmonic components.
            y[start:end] = 0.38 * np.sin(2 * np.pi * local / (period * 0.52) + phase)
            y[start:end] += rng.normal(0, 0.05, end - start)
            lab[start:end] = 1
        series.append(y)
        labels.append(lab)
    return np.concatenate(series).reshape(-1, 1).astype("float32"), np.concatenate(labels)


def reconstruction_like(data: np.ndarray) -> np.ndarray:
    flat = data.reshape(-1)
    return np.abs(flat - np.r_[flat[0], flat[:-1]])


def main() -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    sys.path.insert(0, str(TIME_RCD))
    old_cwd = Path.cwd()
    os.chdir(TIME_RCD)
    try:
        from models.TimeRCD import TimeRCDPretrainTester
        from models.time_rcd.time_rcd_config import default_config

        data, labels = make_contextual()
        config = default_config
        config.ts_config.patch_size = 16
        config.ts_config.num_features = 1
        config.win_size = 512
        config.batch_size = 4
        tester = TimeRCDPretrainTester("best_model/pretrain_checkpoint_best_uni.pth", config)
        score_batches, logit_batches = tester.zero_shot(data)
    finally:
        os.chdir(old_cwd)

    scores = np.concatenate([np.asarray(x).reshape(-1) for x in score_batches])
    logits = np.concatenate([np.asarray(x).reshape(-1) for x in logit_batches])
    rec = reconstruction_like(data)
    result = {
        "probe_scope": "20 generated contextual series, length 512; released univariate checkpoint; CPU/GPU auto device",
        "data_points": int(data.shape[0]),
        "anomaly_points": int(labels.sum()),
        "checkpoint": "https://huggingface.co/thu-sail-lab/Time-RCD",
        "code": "https://github.com/thu-sail-lab/Time-RCD",
        "anomaly_probability_best_f1": best_f1(scores, labels),
        "anomaly_logit_best_f1": best_f1(logits, labels),
        "reconstruction_like_best_f1": best_f1(rec, labels),
        "score_summary": {
            "prob_min": float(np.min(scores)),
            "prob_max": float(np.max(scores)),
            "prob_mean": float(np.mean(scores)),
            "logit_min": float(np.min(logits)),
            "logit_max": float(np.max(logits)),
            "logit_mean": float(np.mean(logits)),
        },
    }
    path = OUT / "timercd_checkpoint_probe.json"
    path.write_text(json.dumps(result, indent=2), encoding="utf-8")
    print(json.dumps(result, indent=2))
    print(f"wrote {path}")


if __name__ == "__main__":
    main()