LeakDB / scripts /leakdb_score.py
eldemet's picture
Upload folder using huggingface_hub (part 7)
075087c verified
Raw History Blame Contribute Delete
11.5 kB
#!/usr/bin/env python3
"""LeakDB scoring: a Python port of the reference MATLAB `scoring_algorithm.m`.
Scores binary leak predictions (one 0/1 value per scenario and 30-min time step) against the LeakDB labels,
with the metrics of Vrachimis et al. (2018), "LeakDB: a benchmark dataset for leakage diagnosis in water
distribution networks", WDSA/CCWI 2018:
RTP true-positive rate (recall) over all time steps of all scenarios, % (paper eq. 2)
RTN true-negative rate (specificity), % (eq. 3)
F1 2TP / (2TP + FP + FN), with TP/FP/FN pooled over all scenarios, % (eq. 4)
SED early-detection score: sum of per-event scores / number of events, % (eq. 5, as in the code)
plus precision, accuracy and Matthews correlation (pooled) for convenience.
Early-detection score (as implemented in the reference code). For each leak event (a run of label 1) starting
at t_f and ending at t_e, the window is t_f ... t_e + 10 steps (5 h). Let x be the offset of the first
predicted 1 in the window. The event counts as detected only if more than 75 % of the predictions from that
first detection to the end of the window are 1; it then scores 2 / (1 + exp(alpha * x / tau)), where
tau = t_e - t_f + 10 and alpha = 5, otherwise 0. SED = sum of event scores / number of events.
(The paper text gives alpha = 6; the released MATLAB code, reproduced here, uses alpha = 5.)
The reference code divides by the number of events. The paper (eq. 6) instead normalises by the score of
the ideal detector, which is below 100 % because a perfect detector is silent during the 10-step extension
and short leaks then fail the 75 % persistence test; that variant is returned as `SED_ideal_normalised`.
`matlab_compat=True` reproduces the reference code exactly (verified against it in GNU Octave to 1e-12),
including one quirk: when an event ends less than 10 steps before the end of the year, the reference code
shortens the 10-step extension for that event *and for every later event in the matrix*, so scores depend
on scenario order. The default mode shortens it for that event only. In the 1000-scenario release 15 leaks
end that late, so use `--matlab-compat` only to reproduce numbers computed with the MATLAB code.
Usage as a library:
from leakdb_score import score
result = score(y_true, y_pred) # arrays of shape (n_scenarios, n_steps) with 0/1 values
Usage from the command line (predictions as Parquet or CSV with columns scenario, time_index, prediction):
python leakdb_score.py --predictions preds.parquet --network net1 --split test \
--data hf://datasets/KIOSCoE/LeakDB # or a local copy of the dataset repository
"""
from __future__ import annotations
import argparse
import json
import math
import sys
import numpy as np
EXTENSION_STEPS = 10 # tau_FP: 5 h at 30-min steps
PERSISTENCE = 0.75 # P%: detections must persist for > 75 % of the remaining window
ALPHA = 5.0 # sigmoid steepness used in the reference MATLAB code
def _as_matrix(x, name):
a = np.asarray(x)
if a.ndim == 1:
a = a[None, :]
if a.ndim != 2:
raise ValueError(f"{name} must be 1-D or 2-D (scenarios x time steps)")
if not np.isin(a, (0, 1)).all():
raise ValueError(f"{name} must contain only 0 and 1")
return a.astype(np.int8)
def confusion(y_true, y_pred):
"""Pooled confusion-matrix counts over all scenarios and time steps."""
t, p = _as_matrix(y_true, "y_true"), _as_matrix(y_pred, "y_pred")
if t.shape != p.shape:
raise ValueError(f"shape mismatch: y_true {t.shape} vs y_pred {p.shape}")
return dict(TP=int(((t == 1) & (p == 1)).sum()), TN=int(((t == 0) & (p == 0)).sum()),
FP=int(((t == 0) & (p == 1)).sum()), FN=int(((t == 1) & (p == 0)).sum()))
def _events(labels, matlab_compat):
"""(start, end) index pairs (0-based, inclusive) of the runs of 1 in one scenario's labels."""
if matlab_compat: # reference code: starts from 0->1 transitions, ends from 1->0 transitions, paired by order
d = np.diff(labels.astype(int))
return list(zip(np.flatnonzero(d == 1) + 1, np.flatnonzero(d == -1)))
d = np.diff(np.r_[0, labels.astype(int), 0])
return list(zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1) - 1))
def early_detection(y_true, y_pred, extension=EXTENSION_STEPS, persistence=PERSISTENCE, alpha=ALPHA,
matlab_compat=False, return_events=False):
"""Normalised early-detection score SED (%) and, optionally, the per-event scores."""
t, p = _as_matrix(y_true, "y_true"), _as_matrix(y_pred, "y_pred")
if t.shape != p.shape:
raise ValueError(f"shape mismatch: y_true {t.shape} vs y_pred {p.shape}")
n_steps = t.shape[1]
ext_state = extension # matlab_compat: the reference code keeps shortening this
total, events = 0.0, []
for i in range(t.shape[0]):
for start, end in _events(t[i], matlab_compat):
if matlab_compat:
if end + ext_state > n_steps - 1:
ext_state = n_steps - 1 - end
ext = ext_state
else:
ext = min(extension, n_steps - 1 - end)
tau = end - start + ext
window = p[i, start:start + tau + 1]
hits = np.flatnonzero(window == 1)
s, delay = 0.0, None
if len(hits):
delay = int(hits[0])
if window[delay:].mean() > persistence:
s = 1.0 if tau == 0 else 2.0 / (1.0 + math.exp(alpha / tau * delay))
else:
delay = None
total += s
events.append(dict(row=i, start=int(start), end=int(end), delay=delay, score=s))
sed = 100.0 * total / len(events) if events else float("nan")
return (sed, events) if return_events else sed
def score(y_true, y_pred, matlab_compat=False, **sed_kwargs):
"""All LeakDB metrics (percentages) for 0/1 arrays of shape (n_scenarios, n_steps)."""
c = confusion(y_true, y_pred)
TP, TN, FP, FN = c["TP"], c["TN"], c["FP"], c["FN"]
pct = lambda a, b: 100.0 * a / b if b else float("nan")
denom = math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN))
sed, events = early_detection(y_true, y_pred, matlab_compat=matlab_compat, return_events=True, **sed_kwargs)
sed_ideal = early_detection(y_true, y_true, matlab_compat=matlab_compat, **sed_kwargs)
return dict(RTP=pct(TP, TP + FN), RTN=pct(TN, TN + FP), F1=pct(2 * TP, 2 * TP + FP + FN), SED=sed,
SED_ideal_normalised=100.0 * sed / sed_ideal if sed_ideal else float("nan"),
precision=pct(TP, TP + FP), accuracy=pct(TP + TN, TP + TN + FP + FN),
MCC=(TP * TN - FP * FN) / denom if denom else float("nan"),
n_scenarios=int(np.asarray(y_true).shape[0]) if np.asarray(y_true).ndim == 2 else 1,
n_events=len(events), n_events_detected=sum(e["score"] > 0 for e in events), **c)
# ---------------------------------------------------------------------------------------------------------
# Loading ground truth from the Hugging Face dataset (or a local copy) and aligning predictions
# ---------------------------------------------------------------------------------------------------------
NETWORK_CONFIGS = {"net1": "net1_timeseries", "hanoi": "hanoi_timeseries"}
def _filesystem(root):
if root.startswith("hf://"):
from huggingface_hub import HfFileSystem
return HfFileSystem(), root[len("hf://"):]
import fsspec
return fsspec.filesystem("file"), root
def list_split_files(root, network, split):
fs, base = _filesystem(root.rstrip("/"))
files = sorted(fs.glob(f"{base}/data/{NETWORK_CONFIGS[network]}/{split}-*.parquet"))
if not files:
raise FileNotFoundError(f"no files for {network}/{split} under {root}")
return fs, files
def iter_scenarios(root, network, split, columns=()):
"""Yield (scenario_id, DataFrame) one scenario at a time (each Parquet row group is one scenario)."""
import pyarrow.parquet as pq
fs, files = list_split_files(root, network, split)
cols = list(dict.fromkeys(["scenario", "time_index", "label", *columns]))
for f in files:
with fs.open(f, "rb") as fh:
pf = pq.ParquetFile(fh)
for g in range(pf.num_row_groups):
df = pf.read_row_group(g, columns=cols).to_pandas()
yield int(df["scenario"].iloc[0]), df
def load_labels(root, network, split):
"""(scenario ids, label matrix) for one network and split."""
ids, rows = [], []
for sid, df in iter_scenarios(root, network, split):
ids.append(sid)
rows.append(df.sort_values("time_index")["label"].to_numpy(np.int8))
order = np.argsort(ids)
return np.array(ids)[order], np.vstack(rows)[order]
def predictions_matrix(pred, scenario_ids, n_steps):
"""Pivot a predictions table (scenario, time_index, prediction) to a matrix aligned with scenario_ids."""
import pandas as pd
need = {"scenario", "time_index", "prediction"}
if not need <= set(pred.columns):
raise ValueError(f"predictions need columns {sorted(need)}, got {list(pred.columns)}")
pred = pred[pred["scenario"].isin(scenario_ids)]
missing = sorted(set(scenario_ids) - set(pred["scenario"].unique()))
if missing:
raise ValueError(f"predictions missing for {len(missing)} scenario(s), e.g. {missing[:10]}")
m = pred.pivot_table(index="scenario", columns="time_index", values="prediction", aggfunc="first")
m = m.reindex(index=scenario_ids, columns=range(1, n_steps + 1))
if m.isna().any().any():
raise ValueError(f"predictions missing for {int(m.isna().sum().sum())} (scenario, time_index) pairs")
return m.to_numpy().astype(np.int8)
def _read_table(path):
import pandas as pd
return pd.read_parquet(path) if str(path).endswith(".parquet") else pd.read_csv(path)
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--predictions", required=True, help="Parquet/CSV with columns scenario, time_index, prediction")
ap.add_argument("--network", required=True, choices=list(NETWORK_CONFIGS))
ap.add_argument("--split", default="test", choices=["train", "validation", "test"])
ap.add_argument("--data", required=True, help="hf://datasets/<owner>/<repo> or a local dataset folder")
ap.add_argument("--matlab-compat", action="store_true", help="reproduce the reference MATLAB code exactly")
ap.add_argument("--json", help="also write the result to this JSON file")
args = ap.parse_args(argv)
ids, y_true = load_labels(args.data, args.network, args.split)
y_pred = predictions_matrix(_read_table(args.predictions), ids, y_true.shape[1])
result = dict(network=args.network, split=args.split, **score(y_true, y_pred, matlab_compat=args.matlab_compat))
for k in ("RTP", "RTN", "F1", "SED"):
print(f"{k:4s} {result[k]:7.2f} %")
print(f"events detected: {result['n_events_detected']}/{result['n_events']} "
f"(scenarios: {result['n_scenarios']}, TP={result['TP']}, FP={result['FP']}, FN={result['FN']}, TN={result['TN']})")
if args.json:
with open(args.json, "w") as fh:
json.dump(result, fh, indent=2)
return result
if __name__ == "__main__":
sys.exit(0 if main() else 1)