Repository navigation
Expand file tree
/
Copy pathevaluate.py
More file actions
420 lines (339 loc) · 14.7 KB
/
Copy pathevaluate.py
File metadata and controls
420 lines (339 loc) · 14.7 KB
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import matplotlib.pyplot as plt
from multiprocessing import cpu_count, Pool
import numpy as np
import requests
from ..io.annotation import rdann
from ..io.download import get_record_list
from ..io.record import rdsamp
class Comparitor(object):
"""
The class to implement and hold comparisons between two sets of
annotations.
See methods `print_summary` and `plot`.
Examples
--------
>>> import wfdb
>>> from wfdb import processing
>>> sig, fields = wfdb.rdsamp('sample-data/100', channels=[0])
>>> ann_ref = wfdb.rdann('sample-data/100','atr')
>>> xqrs = processing.XQRS(sig=sig[:,0], fs=fields['fs'])
>>> xqrs.detect()
>>> comparitor = processing.Comparitor(ann_ref.sample[1:],
xqrs.qrs_inds,
int(0.1 * fields['fs']),
sig[:,0])
>>> comparitor.compare()
>>> comparitor.print_summary()
>>> comparitor.plot()
"""
def __init__(self, ref_sample, test_sample, window_width, signal=None):
"""
Parameters
----------
ref_sample : numpy array
An array of the reference sample locations
test_sample : numpy array
An array of the comparison sample locations
window_width : int
The width of the window
signal : 1d numpy array, optional
The signal array the annotation samples are labelling. Only used
for plotting.
"""
if min(np.diff(ref_sample)) < 0 or min(np.diff(test_sample)) < 0:
raise ValueError(('The sample locations must be monotonically'
+ ' increasing'))
self.ref_sample = ref_sample
self.test_sample = test_sample
self.n_ref = len(ref_sample)
self.n_test = len(test_sample)
self.window_width = window_width
# The matching test sample number for each reference annotation.
# -1 for indices with no match
self.matching_sample_nums = -1 * np.ones(self.n_ref, dtype='int')
self.signal = signal
# TODO: rdann return annotations.where
def _calc_stats(self):
"""
Calculate performance statistics after the two sets of annotations
are compared.
Example:
-------------------
ref=500 test=480
{ 30 { 470 } 10 }
-------------------
tp = 470
fp = 10
fn = 30
specificity = 470 / 500
positive_predictivity = 470 / 480
false_positive_rate = 10 / 480
"""
# Reference annotation indices that were detected
self.matched_ref_inds = np.where(self.matching_sample_nums != -1)[0]
# Reference annotation indices that were missed
self.unmatched_ref_inds = np.where(self.matching_sample_nums == -1)[0]
# Test annotation indices that were matched to a reference annotation
self.matched_test_inds = self.matching_sample_nums[
self.matching_sample_nums != -1]
# Test annotation indices that were unmatched to a reference annotation
self.unmatched_test_inds = np.setdiff1d(np.array(range(self.n_test)),
self.matched_test_inds, assume_unique=True)
# Sample numbers that were matched and unmatched
self.matched_ref_sample = self.ref_sample[self.matched_ref_inds]
self.unmatched_ref_sample = self.ref_sample[self.unmatched_ref_inds]
self.matched_test_sample = self.test_sample[self.matched_test_inds]
self.unmatched_test_sample = self.test_sample[self.unmatched_test_inds]
# True positives = matched reference samples
self.tp = len(self.matched_ref_inds)
# False positives = extra test samples not matched
self.fp = self.n_test - self.tp
# False negatives = undetected reference samples
self.fn = self.n_ref - self.tp
# No tn attribute
self.specificity = float(self.tp) / self.n_ref
self.positive_predictivity = float(self.tp) / self.n_test
self.false_positive_rate = float(self.fp) / self.n_test
def compare(self):
"""
Main comparison function
"""
test_samp_num = 0
ref_samp_num = 0
# Iterate through the reference sample numbers
while ref_samp_num < self.n_ref and test_samp_num < self.n_test:
# Get the closest testing sample number for this reference sample
closest_samp_num, smallest_samp_diff = (
self._get_closest_samp_num(ref_samp_num, test_samp_num))
# Get the closest testing sample number for the next reference
# sample. This doesn't need to be called for the last index.
if ref_samp_num < self.n_ref - 1:
closest_samp_num_next, smallest_samp_diff_next = (
self._get_closest_samp_num(ref_samp_num + 1, test_samp_num))
else:
# Set non-matching value if there is no next reference sample
# to compete for the test sample
closest_samp_num_next = -1
# Found a contested test sample number. Decide which reference
# sample it belongs to.
if closest_samp_num == closest_samp_num_next:
# If the sample is closer to the next reference sample,
# assign it to the next refernece sample.
if smallest_samp_diff_next < smallest_samp_diff:
# Get the next closest sample for this reference sample.
# Can this be empty? Need to catch case where nothing left?
closest_samp_num, smallest_samp_diff = (
self._get_closest_samp_num(ref_samp_num, test_samp_num))
# If no clash, it is straightforward.
# Assign the reference-test pair if close enough
if smallest_samp_diff < self.window_width:
self.matching_sample_nums[ref_samp_num] = closest_samp_num
ref_samp_num += 1
test_samp_num = closest_samp_num + 1
self._calc_stats()
def _get_closest_samp_num(self, ref_samp_num, start_test_samp_num):
"""
Return the closest testing sample number for the given reference
sample number. Limit the search from start_test_samp_num.
"""
if start_test_samp_num >= self.n_test:
raise ValueError('Invalid starting test sample number.')
ref_samp = self.ref_sample[ref_samp_num]
test_samp = self.test_sample[start_test_samp_num]
samp_diff = ref_samp - test_samp
# Initialize running parameters
closest_samp_num = start_test_samp_num
smallest_samp_diff = abs(samp_diff)
# Iterate through the testing samples
for test_samp_num in range(start_test_samp_num, self.n_test):
test_samp = self.test_sample[test_samp_num]
samp_diff = ref_samp - test_samp
abs_samp_diff = abs(samp_diff)
# Found a better match
if abs(samp_diff) < smallest_samp_diff:
closest_samp_num = test_samp_num
smallest_samp_diff = abs_samp_diff
# Stop iterating when the ref sample is first passed or reached
if samp_diff <= 0:
break
return closest_samp_num, smallest_samp_diff
def print_summary(self):
"""
Print summary metrics of the annotation comparisons.
"""
# True positives = matched reference samples
self.tp = len(self.matched_ref_inds)
# False positives = extra test samples not matched
self.fp = self.n_test - self.tp
# False negatives = undetected reference samples
self.fn = self.n_ref - self.tp
# No tn attribute
self.specificity = self.tp / self.n_ref
self.positive_predictivity = self.tp / self.n_test
self.false_positive_rate = self.fp / self.n_test
print('%d reference annotations, %d test annotations\n'
% (self.n_ref, self.n_test))
print('True Positives (matched samples): %d' % self.tp)
print('False Positives (unmatched test samples: %d' % self.fp)
print('False Negatives (unmatched reference samples): %d\n' % self.fn)
print('Specificity: %.4f (%d/%d)'
% (self.specificity, self.tp, self.n_ref))
print('Positive Predictivity: %.4f (%d/%d)'
% (self.positive_predictivity, self.tp, self.n_test))
print('False Positive Rate: %.4f (%d/%d)'
% (self.false_positive_rate, self.fp, self.n_test))
def plot(self, sig_style='', title=None, figsize=None,
return_fig=False):
"""
Plot the comparison of two sets of annotations, possibly
overlaid on their original signal.
Parameters
----------
sig_style : str, optional
The matplotlib style of the signal
title : str, optional
The title of the plot
figsize: tuple, optional
Tuple pair specifying the width, and height of the figure.
It is the'figsize' argument passed into matplotlib.pyplot's
`figure` function.
return_fig : bool, optional
Whether the figure is to be returned as an output argument.
"""
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(1, 1, 1)
legend = ['Signal',
'Matched Reference Annotations (%d/%d)' % (self.tp, self.n_ref),
'Unmatched Reference Annotations (%d/%d)' % (self.fn, self.n_ref),
'Matched Test Annotations (%d/%d)' % (self.tp, self.n_test),
'Unmatched Test Annotations (%d/%d)' % (self.fp, self.n_test)
]
# Plot the signal if any
if self.signal is not None:
ax.plot(self.signal, sig_style)
# Plot reference annotations
ax.plot(self.matched_ref_sample,
self.signal[self.matched_ref_sample], 'ko')
ax.plot(self.unmatched_ref_sample,
self.signal[self.unmatched_ref_sample], 'ko',
fillstyle='none')
# Plot test annotations
ax.plot(self.matched_test_sample,
self.signal[self.matched_test_sample], 'g+')
ax.plot(self.unmatched_test_sample,
self.signal[self.unmatched_test_sample], 'rx')
ax.legend(legend)
# Just plot annotations
else:
# Plot reference annotations
ax.plot(self.matched_ref_sample, np.ones(self.tp), 'ko')
ax.plot(self.unmatched_ref_sample, np.ones(self.fn), 'ko',
fillstyle='none')
# Plot test annotations
ax.plot(self.matched_test_sample, 0.5 * np.ones(self.tp), 'g+')
ax.plot(self.unmatched_test_sample, 0.5 * np.ones(self.fp), 'rx')
ax.legend(legend[1:])
if title:
ax.set_title(title)
ax.set_xlabel('time/sample')
fig.show()
if return_fig:
return fig, ax
def compare_annotations(ref_sample, test_sample, window_width, signal=None):
"""
Compare a set of reference annotation locations against a set of
test annotation locations.
See the Comparitor class docstring for more information.
Parameters
----------
ref_sample : 1d numpy array
Array of reference sample locations
test_sample : 1d numpy array
Array of test sample locations to compare
window_width : int
The maximum absolute difference in sample numbers that is
permitted for matching annotations.
signal : 1d numpy array, optional
The original signal of the two annotations. Only used for
plotting.
Returns
-------
comparitor : Comparitor object
Object containing parameters about the two sets of annotations
Examples
--------
>>> import wfdb
>>> from wfdb import processing
>>> sig, fields = wfdb.rdsamp('sample-data/100', channels=[0])
>>> ann_ref = wfdb.rdann('sample-data/100','atr')
>>> xqrs = processing.XQRS(sig=sig[:,0], fs=fields['fs'])
>>> xqrs.detect()
>>> comparitor = processing.compare_annotations(ann_ref.sample[1:],
xqrs.qrs_inds,
int(0.1 * fields['fs']),
sig[:,0])
>>> comparitor.print_summary()
>>> comparitor.plot()
"""
comparitor = Comparitor(ref_sample=ref_sample, test_sample=test_sample,
window_width=window_width, signal=signal)
comparitor.compare()
return comparitor
def benchmark_mitdb(detector, verbose=False):
"""
Benchmark a qrs detector against mitdb's records.
Parameters
----------
detector : function
The detector function.
verbose : bool, optional
The verbose option of the detector function.
Returns
-------
comparitors : list
List of Comparitor objects run on the records.
specificity : float
Aggregate specificity.
positive_predictivity : float
Aggregate positive_predictivity.
false_positive_rate : float
Aggregate false_positive_rate.
Notes
-----
TODO:
- remove non-qrs detections from reference annotations
- allow kwargs
Examples
--------
>>> import wfdb
>> from wfdb.processing import benchmark_mitdb, xqrs_detect
>>> comparitors, a, b, c = benchmark_mitdb(xqrs_detect)
"""
record_list = get_record_list('mitdb')
n_records = len(record_list)
# Function arguments for starmap
args = zip(record_list, n_records * [detector], n_records * [verbose])
# Run detector and compare against reference annotations for all
# records
with Pool(cpu_count() - 1) as p:
comparitors = p.starmap(benchmark_mitdb_record, args)
# Calculate aggregate stats
specificity = np.mean([c.specificity for c in comparitors])
positive_predictivity = np.mean(
[c.positive_predictivity for c in comparitors])
false_positive_rate = np.mean(
[c.false_positive_rate for c in comparitors])
print('Benchmark complete')
return comparitors, specificity, positive_predictivity, false_positive_rate
def benchmark_mitdb_record(rec, detector, verbose):
"""
Benchmark a single mitdb record
"""
sig, fields = rdsamp(rec, pb_dir='mitdb', channels=[0])
ann_ref = rdann(rec, pb_dir='mitdb', extension='atr')
qrs_inds = detector(sig=sig[:,0], fs=fields['fs'], verbose=verbose)
comparitor = compare_annotations(ref_sample=ann_ref.sample[1:],
test_sample=qrs_inds,
window_width=int(0.1 * fields['fs']))
print('Finished record %s' % rec)
return comparitor