File size: 10,037 Bytes
075087c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Reference baseline detectors for LeakDB, ported from the original MATLAB code (Vrachimis et al., 2018).

Detectors
  null     never raises an alarm (lower bound for RTP / F1 / SED)
  random   independent fair coin per time step (seeded)
  mnf      Minimum Night Flow detector (`algorithmMNF.m`): for each day d, MNF(d) is the minimum inflow of
           the day; mMNF(d) is the minimum MNF over the last `window` days that were not flagged; day d is
           flagged (all 48 steps labelled 1) if MNF(d) - mMNF(d) > lam * mMNF(d). The first `window` days
           are never flagged. Note: the day's label is applied from 00:00, before that night's minimum has
           been observed, so the detector looks ahead by up to one day (as in the reference code).
  ideal    returns the ground-truth labels (upper bound, sanity check)

Network inflow used by MNF
  hanoi    flow_link_1 (the pipe from reservoir 1; identical to -demand_node_1) - as in the reference code
  net1     -(demand_node_9 + demand_node_2): water supplied by reservoir 9 and tank 2 (the reference code
           only covered Hanoi)

Usage
  # predictions for one detector (Parquet with scenario, time_index, prediction) for leakdb_score.py
  python leakdb_baselines.py predict --data hf://datasets/KIOSCoE/LeakDB --network hanoi --split test \
      --detector mnf --lam 0.2 --out mnf_hanoi_test.parquet

  # full benchmark: tune MNF on validation, report all baselines on test (and on all scenarios)
  python leakdb_baselines.py benchmark --data hf://datasets/KIOSCoE/LeakDB --json baselines.json --markdown baselines.md
"""
from __future__ import annotations

import argparse
import itertools
import json
import sys
import time

import numpy as np

from leakdb_score import iter_scenarios, score

STEPS_PER_DAY = 48
INFLOW_COLUMNS = {"hanoi": ["flow_link_1"], "net1": ["demand_node_9", "demand_node_2"]}


def network_inflow(network, df):
    if network == "hanoi":
        return df["flow_link_1"].to_numpy()
    if network == "net1":
        return -(df["demand_node_9"] + df["demand_node_2"]).to_numpy()
    raise ValueError(network)


# --------------------------------------------------------------------------------------------- detectors
def null_detector(n_steps):
    return np.zeros(n_steps, np.int8)


def random_detector(n_steps, rng):
    return rng.integers(0, 2, n_steps).astype(np.int8)


def mnf_detector(inflow, lam=0.2, window=10, steps_per_day=STEPS_PER_DAY):
    """Minimum Night Flow detector, a line-by-line port of algorithmMNF.m (w = window, gamma = lam)."""
    inflow = np.asarray(inflow, float)
    if len(inflow) % steps_per_day:
        raise ValueError("inflow length must be a whole number of days")
    mnf = inflow.reshape(-1, steps_per_day).min(axis=1)          # MATLAB: min(reshape(flow, 48, 365))
    k = list(range(window))                                       # days used for the reference minimum
    day_label = np.zeros(len(mnf), np.int8)
    for j in range(window, len(mnf)):
        ref = mnf[k].min()
        if mnf[j] - ref > ref * lam:
            day_label[j] = 1
        else:                                                     # unflagged days update the window
            k.append(j)
            k.pop(0)
    return np.repeat(day_label, steps_per_day)


# --------------------------------------------------------------------------------------------- data
def load(data, network, split):
    """Scenario ids, label matrix and inflow matrix for one network and split."""
    ids, labels, inflow = [], [], []
    for sid, df in iter_scenarios(data, network, split, columns=INFLOW_COLUMNS[network]):
        df = df.sort_values("time_index")
        ids.append(sid)
        labels.append(df["label"].to_numpy(np.int8))
        inflow.append(network_inflow(network, df))
    order = np.argsort(ids)
    return np.array(ids)[order], np.vstack(labels)[order], np.vstack(inflow)[order]


def run_detector(name, labels, inflow, lam=0.2, window=10, seed=0):
    n, T = labels.shape
    if name == "ideal":
        return labels.copy()
    if name == "null":
        return np.zeros((n, T), np.int8)
    if name == "random":
        rng = np.random.default_rng(seed)
        return np.vstack([random_detector(T, rng) for _ in range(n)])
    if name == "mnf":
        return np.vstack([mnf_detector(f, lam, window) for f in inflow])
    raise ValueError(name)


# --------------------------------------------------------------------------------------------- commands
def cmd_predict(args):
    import pandas as pd
    ids, labels, inflow = load(args.data, args.network, args.split)
    pred = run_detector(args.detector, labels, inflow, args.lam, args.window, args.seed)
    T = labels.shape[1]
    out = pd.DataFrame({"scenario": np.repeat(ids, T).astype(np.int16),
                        "time_index": np.tile(np.arange(1, T + 1, dtype=np.int32), len(ids)),
                        "prediction": pred.ravel()})
    out.to_parquet(args.out, index=False) if args.out.endswith(".parquet") else out.to_csv(args.out, index=False)
    print(f"wrote {len(out):,} predictions for {len(ids)} scenarios to {args.out}")


def _metrics(y, p):
    s = score(y, p)
    return {k: round(s[k], 2) for k in ("RTP", "RTN", "F1", "SED")} | {
        "events_detected": f"{s['n_events_detected']}/{s['n_events']}"}


def cmd_benchmark(args):
    lams = [round(x, 2) for x in np.arange(0.05, 0.501, 0.05)]
    windows = [5, 7, 10, 14, 21]
    results = {}
    for net in args.networks:
        t0 = time.time()
        data = {sp: load(args.data, net, sp) for sp in ("train", "validation", "test")}
        print(f"[{net}] loaded {sum(len(d[0]) for d in data.values())} scenarios in {time.time() - t0:.0f}s", flush=True)
        _, yv, fv = data["validation"]
        grid = []
        for w, lam in itertools.product(windows, lams):
            s = score(yv, run_detector("mnf", yv, fv, lam, w))
            grid.append(dict(window=w, lam=lam, F1=s["F1"], SED=s["SED"], RTP=s["RTP"], RTN=s["RTN"]))
        best = max(grid, key=lambda g: (g["F1"], g["SED"]))
        print(f"[{net}] MNF tuned on validation (max F1): window={best['window']} lam={best['lam']} "
              f"F1={best['F1']:.2f}", flush=True)

        detectors = [("Ideal", "ideal", {}), ("Null", "null", {}), ("Random", "random", {"seed": args.seed}),
                     ("MNF λ=0.10, w=10 (paper)", "mnf", {"lam": 0.10, "window": 10}),
                     ("MNF λ=0.20, w=10 (paper)", "mnf", {"lam": 0.20, "window": 10}),
                     ("MNF λ=0.30, w=10 (paper)", "mnf", {"lam": 0.30, "window": 10}),
                     (f"MNF λ={best['lam']:.2f}, w={best['window']} (tuned on validation)", "mnf",
                      {"lam": best["lam"], "window": best["window"]})]
        y_all = np.vstack([d[1] for d in data.values()])
        f_all = np.vstack([d[2] for d in data.values()])
        _, yt, ft = data["test"]
        rows = []
        for label, name, kw in detectors:
            rows.append(dict(detector=label,
                             test=_metrics(yt, run_detector(name, yt, ft, **kw)),
                             all_scenarios=_metrics(y_all, run_detector(name, y_all, f_all, **kw))))
        results[net] = dict(n_scenarios={sp: int(len(d[0])) for sp, d in data.items()},
                            tuning=dict(criterion="max F1 on validation", best=best, grid=grid), results=rows)
        print(f"[{net}] done in {time.time() - t0:.0f}s", flush=True)

    if args.json:
        with open(args.json, "w") as fh:
            json.dump(results, fh, indent=2, ensure_ascii=False)
    md = to_markdown(results)
    if args.markdown:
        with open(args.markdown, "w") as fh:
            fh.write(md)
    print(md)


def to_markdown(results):
    names = {"net1": "Net1_CMH", "hanoi": "Hanoi_CMH"}
    out = []
    for net, r in results.items():
        n = r["n_scenarios"]
        out.append(f"**{names.get(net, net)}** — test split ({n['test']} scenarios) and all {sum(n.values())} scenarios; scores in %.\n")
        out.append("| detector | RTP | RTN | F1 | SED | RTP (all) | RTN (all) | F1 (all) | SED (all) |")
        out.append("|---|---|---|---|---|---|---|---|---|")
        for row in r["results"]:
            t, a = row["test"], row["all_scenarios"]
            out.append(f"| {row['detector']} | {t['RTP']:.2f} | {t['RTN']:.2f} | {t['F1']:.2f} | {t['SED']:.2f} | "
                       f"{a['RTP']:.2f} | {a['RTN']:.2f} | {a['F1']:.2f} | {a['SED']:.2f} |")
        out.append("")
    return "\n".join(out)


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    p = sub.add_parser("predict", help="write predictions of one detector for one network/split")
    p.add_argument("--data", required=True, help="hf://datasets/<owner>/<repo> or a local dataset folder")
    p.add_argument("--network", required=True, choices=list(INFLOW_COLUMNS))
    p.add_argument("--split", default="test", choices=["train", "validation", "test"])
    p.add_argument("--detector", required=True, choices=["null", "random", "mnf", "ideal"])
    p.add_argument("--lam", type=float, default=0.2, help="MNF threshold gain (default 0.2)")
    p.add_argument("--window", type=int, default=10, help="MNF window in days (default 10)")
    p.add_argument("--seed", type=int, default=0)
    p.add_argument("--out", required=True, help=".parquet or .csv")
    b = sub.add_parser("benchmark", help="tune MNF on validation, score all baselines on test and on all scenarios")
    b.add_argument("--data", required=True)
    b.add_argument("--networks", nargs="+", default=["net1", "hanoi"], choices=list(INFLOW_COLUMNS))
    b.add_argument("--seed", type=int, default=0)
    b.add_argument("--json"); b.add_argument("--markdown")
    args = ap.parse_args(argv)
    {"predict": cmd_predict, "benchmark": cmd_benchmark}[args.cmd](args)


if __name__ == "__main__":
    sys.exit(main())