Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ The [documentation](https://wfdb.readthedocs.io/) covers the full
[plotting](https://wfdb.readthedocs.io/en/latest/plot.html), and
[processing](https://wfdb.readthedocs.io/en/latest/processing.html). The
[demo notebook](https://github.com/MIT-LCP/wfdb-python/blob/main/demo.ipynb)
shows more examples. Report bugs or request features in the
is an offline walkthrough using bundled sample data. Report bugs or request
features in the
[issue tracker](https://github.com/MIT-LCP/wfdb-python/issues).

## Contributing and citing
Expand Down
4 changes: 4 additions & 0 deletions changelog.d/demo-notebook.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
**Refresh the demo notebook**
The demo notebook now runs through bundled examples without network access,
uses the current reading and writing APIs, and writes copies only to a
temporary directory. Saved outputs and obsolete examples have been removed.
4 changes: 4 additions & 0 deletions changelog.d/processing-comparator.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
**Add the correctly spelled annotation comparator**
``processing.Comparator`` is the class used by
``processing.compare_annotations``. The existing ``processing.Comparitor``
name remains an alias to the same class.
78,478 changes: 126 additions & 78,352 deletions demo.ipynb

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion docs/processing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ Annotation Evaluators

.. automodule:: wfdb.processing
:no-index:
:members: Comparitor, compare_annotations, benchmark_mitdb
:members: Comparator, compare_annotations, benchmark_mitdb

``Comparitor`` remains an alias for ``Comparator`` for existing code.


Beat-by-beat Comparison
Expand Down
1 change: 1 addition & 0 deletions src/wfdb/processing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
)
from wfdb.processing.beat_comparison import BxbResult, bxb, bxb_record, sumstats
from wfdb.processing.evaluate import (
Comparator,
Comparitor,
benchmark_mitdb,
compare_annotations,
Expand Down
51 changes: 27 additions & 24 deletions src/wfdb/processing/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def _sample_difference(reference, test):
return reference - test


class Comparitor:
class Comparator:
"""The class to implement and hold comparisons between two sets of annotations.

See methods `compare`, `print_summary` and `plot`.
Expand Down Expand Up @@ -44,12 +44,12 @@ class Comparitor:
>>> xqrs = processing.XQRS(sig=sig[:, 0], fs=fields['fs'])
>>> xqrs.detect(verbose=False)

>>> comparitor = processing.Comparitor(ann_ref.sample[1:],
>>> comparator = processing.Comparator(ann_ref.sample[1:],
... xqrs.qrs_inds,
... int(0.1 * fields['fs']),
... sig[:, 0])
>>> comparitor.compare()
>>> comparitor.print_summary()
>>> comparator.compare()
>>> comparator.print_summary()
35 reference annotations, 34 test annotations
<BLANKLINE>
True Positives (matched samples): 34
Expand All @@ -58,7 +58,7 @@ class Comparitor:
<BLANKLINE>
Sensitivity: 0.9714 (34/35)
Positive Predictivity: 1.0000 (34/34)
>>> comparitor.plot()
>>> comparator.plot()

"""

Expand Down Expand Up @@ -419,10 +419,13 @@ def plot(self, sig_style="", title=None, figsize=None, return_fig=False):
return fig, ax


Comparitor = Comparator


def compare_annotations(ref_sample, test_sample, window_width, signal=None):
"""Compare reference annotation locations against test locations.

See the Comparitor class docstring for more information.
See the Comparator class docstring for more information.

Parameters
----------
Expand All @@ -439,7 +442,7 @@ def compare_annotations(ref_sample, test_sample, window_width, signal=None):

Returns
-------
comparitor : Comparitor object
comparator : Comparator object
Object containing parameters about the two sets of annotations.

Examples
Expand All @@ -453,22 +456,22 @@ def compare_annotations(ref_sample, test_sample, window_width, signal=None):
>>> xqrs = processing.XQRS(sig=sig[:, 0], fs=fields['fs'])
>>> xqrs.detect(verbose=False)

>>> comparitor = processing.compare_annotations(ann_ref.sample[1:],
>>> comparator = processing.compare_annotations(ann_ref.sample[1:],
... xqrs.qrs_inds,
... int(0.1 * fields['fs']),
... sig[:, 0])
>>> comparitor.plot()
>>> comparator.plot()

"""
comparitor = Comparitor(
comparator = Comparator(
ref_sample=ref_sample,
test_sample=test_sample,
window_width=window_width,
signal=signal,
)
comparitor.compare()
comparator.compare()

return comparitor
return comparator


def benchmark_mitdb(detector, verbose=False, print_results=False):
Expand All @@ -486,8 +489,8 @@ def benchmark_mitdb(detector, verbose=False, print_results=False):

Returns
-------
comparitors : dictionary
Dictionary of Comparitor objects run on the records, keyed on
comparators : dictionary
Dictionary of Comparator objects run on the records, keyed on
the record names.
sensitivity : float
Aggregate sensitivity.
Expand All @@ -504,7 +507,7 @@ def benchmark_mitdb(detector, verbose=False, print_results=False):
--------
>>> from wfdb.processing import benchmark_mitdb, xqrs_detect

>>> comparitors, spec, pp = benchmark_mitdb(xqrs_detect)
>>> comparators, spec, pp = benchmark_mitdb(xqrs_detect)

"""
record_list = get_record_list("mitdb")
Expand All @@ -516,13 +519,13 @@ def benchmark_mitdb(detector, verbose=False, print_results=False):
# Run detector and compare against reference annotations for all
# records
with Pool(cpu_count() - 1) as p:
comparitors = p.starmap(benchmark_mitdb_record, args)
comparators = p.starmap(benchmark_mitdb_record, args)

# Calculate aggregate stats
sensitivity = np.mean([c.sensitivity for c in comparitors])
positive_predictivity = np.mean([c.positive_predictivity for c in comparitors])
sensitivity = np.mean([c.sensitivity for c in comparators])
positive_predictivity = np.mean([c.positive_predictivity for c in comparators])

comparitors = dict(zip(record_list, comparitors))
comparators = dict(zip(record_list, comparators))

print("Benchmark complete")

Expand All @@ -533,10 +536,10 @@ def benchmark_mitdb(detector, verbose=False, print_results=False):
)
for record_name in record_list:
print("Record %s:" % record_name)
comparitors[record_name].print_summary()
comparators[record_name].print_summary()
print("\n\n")

return comparitors, sensitivity, positive_predictivity
return comparators, sensitivity, positive_predictivity


def benchmark_mitdb_record(rec, detector, verbose):
Expand All @@ -553,7 +556,7 @@ def benchmark_mitdb_record(rec, detector, verbose):

Returns
-------
comparitor : Comparitor object
comparator : Comparator object
Object containing parameters about the two sets of annotations.

"""
Expand All @@ -562,11 +565,11 @@ def benchmark_mitdb_record(rec, detector, verbose):

qrs_inds = detector(sig=sig[:, 0], fs=fields["fs"], verbose=verbose)

comparitor = compare_annotations(
comparator = compare_annotations(
ref_sample=ann_ref.sample[1:],
test_sample=qrs_inds,
window_width=int(0.1 * fields["fs"]),
)
if verbose:
print("Finished record %s" % rec)
return comparitor
return comparator
38 changes: 19 additions & 19 deletions tests/test_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,13 +570,13 @@ class TestCompareAnnotations:

def test_test_annotation_matched_once(self):
"""A test annotation isn't matched to two reference annotations."""
comparitor = processing.compare_annotations(
comparator = processing.compare_annotations(
np.array([0, 2, 4, 5]), np.array([1, 5]), window_width=6
)

assert comparitor.matching_sample_nums.tolist() == [0, -1, -1, 1]
assert (comparitor.tp, comparitor.fp, comparitor.fn) == (2, 0, 2)
assert comparitor.positive_predictivity == 1.0
assert comparator.matching_sample_nums.tolist() == [0, -1, -1, 1]
assert (comparator.tp, comparator.fp, comparator.fn) == (2, 0, 2)
assert comparator.positive_predictivity == 1.0

def test_random_annotations(self):
"""Matches are unique, in order and within the window."""
Expand All @@ -585,35 +585,35 @@ def test_random_annotations(self):
ref = np.sort(rng.choice(40, rng.integers(1, 9), replace=False))
test = np.sort(rng.choice(40, rng.integers(1, 9), replace=False))
window_width = int(rng.integers(1, 10))
comparitor = processing.compare_annotations(ref, test, window_width)
comparator = processing.compare_annotations(ref, test, window_width)

matches = comparitor.matching_sample_nums
matches = comparator.matching_sample_nums
matched = matches[matches != -1]
assert np.all(np.diff(matched) > 0)
assert np.all(np.abs(ref[matches != -1] - test[matched]) < window_width)
assert 0 <= comparitor.fp <= len(test)
assert 0 <= comparator.fp <= len(test)

def test_compare_annotations_empty_ref(self):
"""When reference annotations are empty, sensitivity should be NaN."""
comparitor = processing.compare_annotations(
comparator = processing.compare_annotations(
np.array([]), np.array([10, 20, 30]), 5
)
assert math.isnan(comparitor.sensitivity)
assert comparitor.positive_predictivity == 0.0
assert math.isnan(comparator.sensitivity)
assert comparator.positive_predictivity == 0.0

def test_compare_annotations_empty_test(self):
"""When test annotations are empty, PPV should be NaN."""
comparitor = processing.compare_annotations(
comparator = processing.compare_annotations(
np.array([10, 20, 30]), np.array([]), 5
)
assert comparitor.sensitivity == 0.0
assert math.isnan(comparitor.positive_predictivity)
assert comparator.sensitivity == 0.0
assert math.isnan(comparator.positive_predictivity)

def test_compare_annotations_both_empty(self):
"""When both annotation arrays are empty, both metrics should be NaN."""
comparitor = processing.compare_annotations(np.array([]), np.array([]), 5)
assert math.isnan(comparitor.sensitivity)
assert math.isnan(comparitor.positive_predictivity)
comparator = processing.compare_annotations(np.array([]), np.array([]), 5)
assert math.isnan(comparator.sensitivity)
assert math.isnan(comparator.positive_predictivity)


class TestQrs:
Expand All @@ -627,12 +627,12 @@ def test_xqrs(self):
xqrs = processing.XQRS(sig=sig[:, 0], fs=fields["fs"])
xqrs.detect()

comparitor = processing.compare_annotations(
comparator = processing.compare_annotations(
ann_ref.sample[1:], xqrs.qrs_inds, int(0.1 * fields["fs"])
)

assert comparitor.sensitivity > 0.99
assert comparitor.positive_predictivity > 0.99
assert comparator.sensitivity > 0.99
assert comparator.positive_predictivity > 0.99

def test_xqrs_backsearch_checks_each_peak_once(self):
"""Backsearch does not recheck rejected peaks in a gap (issue #352)."""
Expand Down
33 changes: 33 additions & 0 deletions tests/test_processing_comparator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""Correctly spelled comparator class and legacy alias."""

import pickle

import numpy as np

from wfdb import processing
from wfdb.processing.evaluate import Comparator, Comparitor


def test_comparator_and_comparitor_are_the_same_class():
assert processing.Comparator is processing.Comparitor
assert Comparator is Comparitor is processing.Comparator
assert Comparator.__name__ == "Comparator"


def test_compare_annotations_returns_comparator():
result = processing.compare_annotations(
ref_sample=np.array([10, 20]),
test_sample=np.array([11, 19]),
window_width=2,
)
assert type(result) is Comparator
assert result.tp == 2


def test_new_and_old_pickle_paths_resolve():
instance = Comparator(np.array([10]), np.array([10]), 1)
assert type(pickle.loads(pickle.dumps(instance))) is Comparator

# Protocol 0 GLOBAL represents the module and class path used by old pickles.
legacy_class = pickle.loads(b"cwfdb.processing.evaluate\nComparitor\n.")
assert legacy_class is Comparator
Loading