ceo-mof 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ceo_mof/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ """CEO-MOF: MOW-ECG R-peak detection with expanding-statistics context features."""
2
+ __version__ = "0.2.0"
ceo_mof/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
ceo_mof/checks.py ADDED
@@ -0,0 +1,288 @@
1
+ """
2
+ Verification (is the pipeline the same as MOW-ECG?) and pre-run checks (are the new
3
+ features what we intend, and what information do they carry?).
4
+
5
+ verify:
6
+ 1. vectorised MOF == pymof (random data with ties, 1/3/8 features; real windows)
7
+ 2. port == the notebook's own v5 code with real pymof (R-peaks identical, 0.6/0.3)
8
+ 3. R1 == the earlier experiments' R1 (TP/FP/FN at all 80 settings, reference CSV)
9
+
10
+ check (pre-run, from the experiment design):
11
+ 1. causality: features from f[0..i] only equal the features at i from the full record
12
+ 2. formulas: expanding stats vs direct numpy / scipy over f[0..i] and D_r[r..i]
13
+ 3. baseline: amplitude through the scaled path gives the same MOF/detections as R1
14
+ 4. spread: within-window MAD and range of each feature (unscaled) next to amplitude
15
+ 5. time link: |Spearman| between each scaled feature and the position in the window
16
+ + whether the preprocessing filter uses future samples
17
+ """
18
+ import time
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import pandas as pd
23
+
24
+ from . import data as D
25
+ from . import features as FE
26
+ from . import mow_ecg as M
27
+ from .evaluate import match
28
+ from .experiment import GLOBAL, IRPS, MRIS, RUNGS, TOL_MS, Run, window_scores
29
+ from .mof import mof_1d, mof_from_dist, mof_pymof, sq_col
30
+
31
+ REFERENCE_DIR = Path(__file__).resolve().parent / "reference"
32
+
33
+
34
+ # ============================================================================ VERIFY
35
+ def verify_mof(run, rec):
36
+ from scipy.spatial.distance import cdist
37
+ lines = ["1) Vectorised MOF vs pymof"]
38
+ rng = np.random.default_rng(0)
39
+ ok = True
40
+ for name, X in [("random 1-D, heavy ties", np.round(rng.normal(size=(400, 1)) * 3)),
41
+ ("random 3-D, heavy ties", np.round(rng.normal(size=(300, 3)) * 2)),
42
+ ("random 8-D continuous", rng.normal(size=(300, 8)))]:
43
+ a = mof_pymof(X)
44
+ b = mof_from_dist(cdist(X, X))
45
+ c = mof_from_dist(sum(sq_col(X[:, k]) for k in range(X.shape[1])))
46
+ d1, d2 = np.abs(a - b).max(), np.abs(a - c).max()
47
+ ok &= d1 == 0 and d2 < 1e-9
48
+ lines.append(f" {name:24s} max|diff| cdist {d1:.3g} squared {d2:.3g}")
49
+ f, _, fs = run.load(rec)
50
+ F = FE.expanding_features(f)
51
+ wins = M.windows(len(f), fs)
52
+ picks = [wins[i] for i in (0, 1, len(wins) // 2, len(wins) - 1)]
53
+ worst = {}
54
+ for lo, hi in picks:
55
+ ours = window_scores(f[lo:hi], F[lo:hi], ["R1", "A2", "B123", "AB1"])
56
+ Z = FE.scale_window(np.column_stack([F[lo:hi], FE.tpos(hi - lo)]))
57
+ idx = {c: k for k, c in enumerate(FE.ALL_COLS)}
58
+ for r in ours:
59
+ X = f[lo:hi] if r == "R1" else Z[:, [idx[c] for c in RUNGS[r]]]
60
+ worst[r] = max(worst.get(r, 0.0), float(np.abs(ours[r] - mof_pymof(X)).max()))
61
+ r1_bit = worst["R1"] == 0.0
62
+ ok &= r1_bit and max(worst.values()) < 1e-9
63
+ lines.append(f" record {rec}, {len(picks)} windows: max|diff| " +
64
+ ", ".join(f"{k} {v:.3g}" for k, v in worst.items()))
65
+ lines.append(f" R1 bit-identical to pymof: {r1_bit}")
66
+ lines.append(f" -> {'PASS' if ok else 'FAIL'}")
67
+ return ok, lines
68
+
69
+
70
+ def _port_vs_notebook_one(args):
71
+ data_dir, rec, lead = args
72
+ from .notebook_ref import notebook_r_peaks
73
+ sig, ref, fs = D.load_record(data_dir, rec, lead)
74
+ t = time.time()
75
+ nb = notebook_r_peaks(sig, fs)
76
+ t_nb = time.time() - t
77
+ det, _ = M.mow_ecg(sig, fs, *GLOBAL)
78
+ return rec, nb, det, match(ref, det, fs, TOL_MS), t_nb
79
+
80
+
81
+ def verify_port(run, records, workers):
82
+ from joblib import Parallel, delayed
83
+ lines = [f"2) Port vs the notebook's own v5 code (real pymof), IRP {GLOBAL[0]} / MRI {GLOBAL[1]}"]
84
+ if run.filter_mode != "zerophase":
85
+ return True, lines + [" skipped: the notebook uses the zero-phase filter"]
86
+ res = Parallel(n_jobs=workers)(delayed(_port_vs_notebook_one)((run.data_dir, r, run.lead))
87
+ for r in records)
88
+ ok = True
89
+ for rec, nb, det, m, t_nb in res:
90
+ same = nb == det
91
+ ok &= same
92
+ lines.append(f" {rec}: notebook {len(nb)} peaks ({t_nb:.0f} s), port {len(det)} peaks -> "
93
+ f"{'IDENTICAL' if same else 'DIFFERENT'} (TP {m['TP']} FP {m['FP']} FN {m['FN']})")
94
+ lines.append(f" -> {'PASS' if ok else 'FAIL'}")
95
+ return ok, lines
96
+
97
+
98
+ def _r1_grid_one(args):
99
+ run, rec = args
100
+ g, _, _ = run.run_record(rec, ["R1"])
101
+ return g
102
+
103
+
104
+ def verify_r1_previous(run, records, workers):
105
+ from joblib import Parallel, delayed
106
+ lines = ["3) R1 vs the earlier experiments (TP/FP/FN at all 80 settings)"]
107
+ ref_path = REFERENCE_DIR / "r1_previous_grid.csv"
108
+ if run.filter_mode != "zerophase" or run.lead != "MLII":
109
+ return True, lines + [" skipped: the earlier runs used the zero-phase filter and MLII"]
110
+ prev = pd.read_csv(ref_path, dtype={"record": str})
111
+ grids = Parallel(n_jobs=workers)(delayed(_r1_grid_one)((run, r)) for r in records)
112
+ ok = True
113
+ for g in grids:
114
+ rec = g.record.iloc[0]
115
+ a = g[["irp", "mri", "TP", "FP", "FN"]].round({"irp": 2, "mri": 2}).sort_values(["irp", "mri"])
116
+ b = prev[prev.record == rec][["irp", "mri", "TP", "FP", "FN"]].round(
117
+ {"irp": 2, "mri": 2}).sort_values(["irp", "mri"])
118
+ same = len(b) == 80 and np.array_equal(a.to_numpy(), b.to_numpy())
119
+ ok &= same
120
+ lines.append(f" {rec}: {'all 80 settings IDENTICAL' if same else 'DIFFERENT'}")
121
+ lines.append(f" -> {'PASS' if ok else 'FAIL'}")
122
+ return ok, lines
123
+
124
+
125
+ def verify(run, records, workers, notebook_records=None):
126
+ out_lines, all_ok = [], True
127
+ for fn in (lambda: verify_mof(run, records[0]),
128
+ lambda: verify_port(run, notebook_records or records, workers),
129
+ lambda: verify_r1_previous(run, records, workers)):
130
+ ok, lines = fn()
131
+ all_ok &= ok
132
+ out_lines += lines + [""]
133
+ print("\n".join(lines), flush=True)
134
+ out_lines.append(f"VERIFY: {'ALL PASS' if all_ok else 'SOMETHING FAILED'}")
135
+ folder = run.out / "checks"
136
+ folder.mkdir(parents=True, exist_ok=True)
137
+ (folder / f"verify_{run.tag}.txt").write_text("\n".join(out_lines), encoding="utf-8")
138
+ print(out_lines[-1])
139
+ return all_ok
140
+
141
+
142
+ # ============================================================================ PRE-RUN CHECKS
143
+ def check_causality(f, n_pos=20, seed=1):
144
+ F = FE.expanding_features(f)
145
+ rng = np.random.default_rng(seed)
146
+ pos = np.sort(rng.integers(4, len(f), n_pos))
147
+ ok = all(np.array_equal(FE.expanding_features(f[:i + 1])[i], F[i]) for i in pos)
148
+ return ok, f"1) Causality: features from f[0..i] equal full-record features at {n_pos} random i: " \
149
+ f"{'PASS (bit-equal)' if ok else 'FAIL'}"
150
+
151
+
152
+ def check_formulas(f, n_pos=10, seed=2):
153
+ from scipy.stats import kurtosis, skew
154
+ F = FE.expanding_features(f)
155
+ Dr = {r: FE.backward_diff(f, r) for r in range(4)}
156
+ rng = np.random.default_rng(seed)
157
+ pos = np.sort(np.r_[[4, 50], rng.integers(100, len(f), n_pos - 2)])
158
+ worst = 0.0
159
+ for i in pos:
160
+ x = f[:i + 1]
161
+ refs = [np.mean(x), np.std(x), skew(x), kurtosis(x, fisher=False)]
162
+ got = F[i, 1:5]
163
+ for r, (cm, cs) in zip((1, 2, 3), ((5, 6), (7, 8), (9, 10))):
164
+ seg = Dr[r][r:i + 1]
165
+ refs += [np.mean(seg), np.std(seg)]
166
+ got = np.r_[got, F[i, cm], F[i, cs]]
167
+ refs = np.asarray(refs)
168
+ rel = np.abs(got - refs) / np.maximum(np.abs(refs), 1e-12)
169
+ worst = max(worst, float(rel.max()))
170
+ # Eq. 4 written out
171
+ assert np.isclose(Dr[2][i], f[i] - 2 * f[i - 1] + f[i - 2])
172
+ assert np.isclose(Dr[3][i], f[i] - 3 * f[i - 1] + 3 * f[i - 2] - f[i - 3])
173
+ ok = worst < 1e-8
174
+ return ok, f"2) Formulas: max relative difference vs numpy/scipy at {len(pos)} positions = " \
175
+ f"{worst:.2e}: {'PASS' if ok else 'FAIL'}"
176
+
177
+
178
+ def _baseline_one(args):
179
+ run, rec = args
180
+ f, _, fs = run.load(rec)
181
+ wins = M.windows(len(f), fs)
182
+ F = FE.expanding_features(f)
183
+ r1, xs = [], []
184
+ for lo, hi in wins:
185
+ sc = window_scores(f[lo:hi], F[lo:hi], ["R1", "X_scaled"])
186
+ r1.append(sc["R1"])
187
+ xs.append(sc["X_scaled"])
188
+ bit = all(np.array_equal(a, b) for a, b in zip(r1, xs))
189
+ same_det = True
190
+ if not bit:
191
+ cen = M.centred_windows(f, wins)
192
+ same_det = all(M.mow_ecg_from_scores(f, fs, r1, float(i), float(m), wins, cen) ==
193
+ M.mow_ecg_from_scores(f, fs, xs, float(i), float(m), wins, cen)
194
+ for i in IRPS for m in MRIS)
195
+ return rec, bit, same_det
196
+
197
+
198
+ def check_baseline(run, records, workers):
199
+ from joblib import Parallel, delayed
200
+ res = Parallel(n_jobs=workers)(delayed(_baseline_one)((run, r)) for r in records)
201
+ ok = all(b or s for _, b, s in res)
202
+ detail = ", ".join(f"{r} {'bit-equal' if b else ('same detections' if s else 'DIFFERENT')}"
203
+ for r, b, s in res)
204
+ return ok, f"3) Baseline: amplitude through the scaled path vs R1: {detail}: {'PASS' if ok else 'FAIL'}"
205
+
206
+
207
+ def _diagnostics_one(args):
208
+ """Per window: unscaled MAD and range per feature; |Spearman| of scaled feature vs tpos."""
209
+ from scipy.stats import rankdata
210
+ run, rec = args
211
+ f, _, fs = run.load(rec)
212
+ F = FE.expanding_features(f)
213
+ wins = M.windows(len(f), fs)
214
+ b = int(5 * 60 * fs)
215
+ rows = []
216
+ for lo, hi in wins:
217
+ n = hi - lo
218
+ Fw = np.column_stack([F[lo:hi], FE.tpos(n)])
219
+ mad = np.median(np.abs(Fw - np.median(Fw, 0)), 0)
220
+ rng_ = np.ptp(Fw, 0)
221
+ Z = FE.scale_window(Fw)
222
+ rt = rankdata(FE.tpos(n))
223
+ for k, c in enumerate(FE.ALL_COLS):
224
+ z = Z[:, k]
225
+ if np.ptp(z) == 0:
226
+ rho = np.nan
227
+ else:
228
+ rho = abs(np.corrcoef(rankdata(z), rt)[0, 1])
229
+ rows.append(dict(record=rec, lo=lo, early=lo < b, feature=c, mad=mad[k], range=rng_[k],
230
+ abs_spearman_tpos=rho))
231
+ return pd.DataFrame(rows)
232
+
233
+
234
+ def check_diagnostics(run, records, workers):
235
+ from joblib import Parallel, delayed
236
+ df = pd.concat(Parallel(n_jobs=workers)(delayed(_diagnostics_one)((run, r)) for r in records),
237
+ ignore_index=True)
238
+ spread = df.groupby("feature")[["mad", "range"]].median().loc[FE.ALL_COLS]
239
+ amp = spread.loc["x"]
240
+ spread["mad_vs_amplitude"] = spread["mad"] / amp["mad"]
241
+ spread["range_vs_amplitude"] = spread["range"] / amp["range"]
242
+ link = pd.DataFrame({
243
+ "all_windows": df.groupby("feature").abs_spearman_tpos.median(),
244
+ "first_5min": df[df.early].groupby("feature").abs_spearman_tpos.median(),
245
+ "rest": df[~df.early].groupby("feature").abs_spearman_tpos.median()}).loc[FE.ALL_COLS]
246
+ return spread, link
247
+
248
+
249
+ def check_filter_causal(run, rec):
250
+ sig, _, fs = D.load_record(run.data_dir, rec, run.lead)
251
+ n = min(len(sig), 20 * fs)
252
+ s = sig[:n].copy()
253
+ i = n // 2
254
+ a = M.preprocess(s, fs, run.filter_mode)[i]
255
+ s2 = s.copy()
256
+ s2[i + fs:] += 500.0 # change samples 1 s and more after i
257
+ b = M.preprocess(s2, fs, run.filter_mode)[i]
258
+ uses_future = not np.isclose(a, b, rtol=0, atol=1e-9)
259
+ return uses_future, (f"Filter ({run.filter_mode}): the filtered value at time i "
260
+ f"{'DEPENDS' if uses_future else 'does not depend'} on later samples "
261
+ f"(changed by {abs(b - a):.3g} when samples from i+1 s on were shifted)")
262
+
263
+
264
+ def prerun_checks(run, records, workers):
265
+ t0 = time.time()
266
+ f, _, fs = run.load(records[0])
267
+ lines = [f"Pre-run checks (filter {run.filter_mode}, lead {run.lead}); records {', '.join(records)}", ""]
268
+ results = []
269
+ for ok, line in (check_causality(f), check_formulas(f), check_baseline(run, records, workers)):
270
+ results.append(ok)
271
+ lines.append(line)
272
+ print(line, flush=True)
273
+ spread, link = check_diagnostics(run, records, workers)
274
+ fmt = lambda t: t.to_string(float_format=lambda v: f"{v:.3g}")
275
+ lines += ["", "4) Spread inside a 3 s window, unscaled (median over windows)", fmt(spread), "",
276
+ "5) Link to time position: median |Spearman| between the scaled feature and its position",
277
+ " in the window (1 = the feature just rises or falls steadily across the window)", fmt(link), ""]
278
+ _, fl = check_filter_causal(run, records[0])
279
+ lines += [fl, "", f"Checks 1-3: {'ALL PASS' if all(results) else 'SOMETHING FAILED'}",
280
+ f"Time: {time.time() - t0:.0f} s"]
281
+ folder = run.out / "checks"
282
+ folder.mkdir(parents=True, exist_ok=True)
283
+ spread.to_csv(folder / f"spread_{run.tag}.csv")
284
+ link.to_csv(folder / f"time_link_{run.tag}.csv")
285
+ text = "\n".join(lines)
286
+ (folder / f"prerun_checks_{run.tag}.txt").write_text(text, encoding="utf-8")
287
+ print("\n" + text[text.find("4) Spread"):])
288
+ return all(results)
ceo_mof/cli.py ADDED
@@ -0,0 +1,76 @@
1
+ """Command line: ceo-mof <command> (or python -m ceo_mof <command>)
2
+
3
+ download get MIT-BIH from PhysioNet into --data-dir
4
+ verify MOF == pymof; port == your notebook (real pymof); R1 == earlier experiments
5
+ check pre-run checks for the expanding features (causality, formulas, baseline,
6
+ spread, time link, filter)
7
+ run the experiment: all rungs, all 80 IRP/MRI settings, report
8
+ report rebuild the report from saved results (no recomputation)
9
+ """
10
+ import argparse
11
+ import os
12
+ import sys
13
+ import time
14
+
15
+ for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
16
+ os.environ.setdefault(_v, "1")
17
+
18
+
19
+ def main(argv=None):
20
+ from . import data as D
21
+ from .experiment import LADDER, Run, run_all, write_report
22
+
23
+ ap = argparse.ArgumentParser(prog="ceo-mof", description=__doc__,
24
+ formatter_class=argparse.RawDescriptionHelpFormatter)
25
+ ap.add_argument("command", choices=["download", "verify", "check", "run", "report"])
26
+ ap.add_argument("--data-dir", default="mitdb", help="folder with MIT-BIH .hea/.dat/.atr files")
27
+ ap.add_argument("--out", default="results_expanding", help="output folder")
28
+ ap.add_argument("--records", default=None,
29
+ help='"quick" (100,105,108,203,228,233), "all", or e.g. "100,203". '
30
+ "Default: quick for verify/check, all for run/report")
31
+ ap.add_argument("--notebook-records", default="100",
32
+ help="records for the notebook comparison in verify (slow: ~1-2 min each)")
33
+ ap.add_argument("--rungs", default=None, help=f'comma list, default all: {",".join(LADDER)}')
34
+ ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 1))
35
+ ap.add_argument("--filter", default="zerophase", choices=["zerophase", "causal"],
36
+ help="zerophase = MOW-ECG as in the notebook; causal = forward-only variant")
37
+ ap.add_argument("--lead", default="MLII", help='"MLII" or a channel number, e.g. "0"')
38
+ a = ap.parse_args(argv)
39
+
40
+ run = Run(a.data_dir, a.out, a.filter, a.lead)
41
+ default_records = "quick" if a.command in ("verify", "check") else "all"
42
+ records = D.parse_records(a.records or default_records)
43
+ rungs = a.rungs.split(",") if a.rungs else None
44
+
45
+ if a.command == "download":
46
+ D.download_mitdb(a.data_dir)
47
+ print(f"MIT-BIH downloaded to {a.data_dir}")
48
+ return 0
49
+ missing = [r for r in records if not (run.data_dir / f"{r}.hea").exists()]
50
+ if missing:
51
+ print(f"Missing records in {run.data_dir}: {', '.join(missing)}. "
52
+ f"Run `ceo-mof download --data-dir {a.data_dir}` or set --data-dir.")
53
+ return 2
54
+ if a.command == "verify":
55
+ from .checks import verify
56
+ nb = D.parse_records(a.notebook_records) if a.notebook_records else records
57
+ return 0 if verify(run, records, a.workers, nb) else 1
58
+ if a.command == "check":
59
+ from .checks import prerun_checks
60
+ return 0 if prerun_checks(run, records, a.workers) else 1
61
+ if a.command == "run":
62
+ t0 = time.time()
63
+ grid, split, _ = run_all(run, records, rungs, a.workers)
64
+ write_report(run, grid, split, records, time.time() - t0)
65
+ return 0
66
+ if a.command == "report":
67
+ import pandas as pd
68
+ folder = run.out / "report" / run.tag
69
+ grid = pd.read_csv(folder / "grid_all_records.csv", dtype={"record": str})
70
+ split = pd.read_csv(folder / "split_all_records.csv", dtype={"record": str})
71
+ write_report(run, grid, split, records)
72
+ return 0
73
+
74
+
75
+ if __name__ == "__main__":
76
+ sys.exit(main())
ceo_mof/data.py ADDED
@@ -0,0 +1,48 @@
1
+ """MIT-BIH loading. Same choices as the earlier ladder experiments:
2
+ MLII lead (lead 0 if absent; only record 114 differs), full 30-min record, raw ADC values,
3
+ reference = beat annotations only."""
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+ ALL_RECORDS = ["100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "111", "112",
9
+ "113", "114", "115", "116", "117", "118", "119", "121", "122", "123", "124", "200",
10
+ "201", "202", "203", "205", "207", "208", "209", "210", "212", "213", "214", "215",
11
+ "217", "219", "220", "221", "222", "223", "228", "230", "231", "232", "233", "234"]
12
+ QUICK_RECORDS = ["100", "105", "108", "203", "228", "233"]
13
+ EXCLUDE = {"thesis": {"104", "107", "118", "207", "217"}, # primary (thesis)
14
+ "aami": {"102", "104", "107", "217"}} # paced records (ANSI/AAMI EC57)
15
+
16
+ # WFDB beat codes (isqrs). '!' (ventricular flutter wave) is not a beat.
17
+ # Gives exactly the per-record beat counts used in the earlier experiments.
18
+ BEAT_SYMBOLS = set("NLRBAaJSVrFejnE/fQ?")
19
+
20
+
21
+ def parse_records(spec):
22
+ if spec == "quick":
23
+ return list(QUICK_RECORDS)
24
+ if spec == "all":
25
+ return list(ALL_RECORDS)
26
+ return [r.strip() for r in spec.split(",") if r.strip()]
27
+
28
+
29
+ def load_record(data_dir, rec, lead="MLII"):
30
+ """Returns (signal as float64 raw ADC, reference beat sample indices, fs)."""
31
+ import wfdb
32
+ path = str(Path(data_dir) / rec)
33
+ r = wfdb.rdrecord(path)
34
+ a = wfdb.rdann(path, "atr")
35
+ if lead == "MLII":
36
+ ch = r.sig_name.index("MLII") if "MLII" in r.sig_name else 0
37
+ else:
38
+ ch = int(lead)
39
+ sig = r.adc()[:, ch].astype(np.float64)
40
+ ref = np.array([s for s, c in zip(a.sample, a.symbol) if c in BEAT_SYMBOLS], dtype=np.int64)
41
+ return sig, ref, int(r.fs)
42
+
43
+
44
+ def download_mitdb(data_dir):
45
+ """Download MIT-BIH (about 100 MB) from PhysioNet into data_dir."""
46
+ import wfdb
47
+ Path(data_dir).mkdir(parents=True, exist_ok=True)
48
+ wfdb.dl_database("mitdb", str(data_dir), annotators=["atr"])
ceo_mof/evaluate.py ADDED
@@ -0,0 +1,37 @@
1
+ """Matching and metrics.
2
+
3
+ Matching follows calculate_detection_metrics in MOW_ECG_v5.ipynb: detections in time
4
+ order; each takes the first unmatched reference beat within +/- tolerance (50 ms ->
5
+ int(50 * fs / 1000) = 18 samples at 360 Hz)."""
6
+ import numpy as np
7
+
8
+
9
+ def match(ref, det, fs, tol_ms=50):
10
+ ref = np.sort(np.asarray(ref, dtype=np.int64))
11
+ det = np.sort(np.asarray(det, dtype=np.int64))
12
+ tol = int(tol_ms * fs / 1000)
13
+ used = np.zeros(len(ref), dtype=bool)
14
+ tp = fp = 0
15
+ for d in det:
16
+ a = np.searchsorted(ref, d - tol, side="left")
17
+ b = np.searchsorted(ref, d + tol, side="right")
18
+ hit = False
19
+ for i in range(a, b):
20
+ if not used[i]:
21
+ used[i] = True
22
+ tp += 1
23
+ hit = True
24
+ break
25
+ if not hit:
26
+ fp += 1
27
+ return dict(TP=tp, FP=fp, FN=int(len(ref) - used.sum()))
28
+
29
+
30
+ def metrics(tp, fp, fn):
31
+ tp, fp, fn = (np.asarray(v, dtype=float) for v in (tp, fp, fn))
32
+ with np.errstate(divide="ignore", invalid="ignore"):
33
+ return dict(Se=100 * tp / (tp + fn),
34
+ PPV=100 * tp / (tp + fp),
35
+ DER=100 * (fp + fn) / (tp + fn), # thesis Eq. 66
36
+ DER_TP=100 * (fp + fn) / tp, # older scripts
37
+ F1=100 * 2 * tp / (2 * tp + fp + fn))