diff --git a/changelog.d/apply-range-fields.rst b/changelog.d/apply-range-fields.rst new file mode 100644 index 00000000..8e6e8f1d --- /dev/null +++ b/changelog.d/apply-range-fields.rst @@ -0,0 +1,2 @@ +**Keep every annotation field in Annotation.apply_range** + ``Annotation.apply_range`` now keeps the same annotations in every field that is set, including ``symbol`` and ``description``, which it used to leave unchanged, so that they no longer matched ``sample``. It also works on an annotation read by ``rdann`` with the default ``return_label_elements``, where ``label_store`` is ``None``, instead of failing with a ``TypeError``. diff --git a/src/wfdb/io/annotation.py b/src/wfdb/io/annotation.py index 0f9090b8..be02fe73 100644 --- a/src/wfdb/io/annotation.py +++ b/src/wfdb/io/annotation.py @@ -236,6 +236,12 @@ def __eq__(self, other): def apply_range(self, sampfrom=0, sampto=None): """Keep only the annotation items between the desired sample values. + Every field with one value per annotation that is set (such as + `symbol` and `aux_note`) is kept for the same annotations. Fields that + are not set are left as None. If the labels have been summarized in + `contained_labels`, the summary is made again for the annotations that + are kept. + Parameters ---------- sampfrom : int, optional @@ -245,18 +251,36 @@ def apply_range(self, sampfrom=0, sampto=None): there is no upper limit. """ + n_annotations = len(self.sample) kept = self.sample >= sampfrom if sampto is not None: kept &= self.sample <= sampto kept_inds = np.flatnonzero(kept) - for field in ["sample", "label_store", "subtype", "chan", "num"]: - setattr(self, field, getattr(self, field)[kept_inds]) - - self.aux_note = [self.aux_note[i] for i in kept_inds] + for field in [ + "sample", + "label_store", + "symbol", + "description", + "subtype", + "chan", + "num", + "aux_note", + ]: + values = getattr(self, field) + if values is None or np.ndim(values) == 0 or len(values) != n_annotations: + continue + if isinstance(values, np.ndarray): + setattr(self, field, values[kept_inds]) + else: + setattr(self, field, [values[i] for i in kept_inds]) self.ann_len = len(self.sample) + # A summary of the labels would still count the annotations removed + if self.contained_labels is not None: + self.get_contained_labels() + def wrann(self, write_fs=False, write_dir=""): """Write a WFDB annotation file from this object. diff --git a/tests/test_annotation.py b/tests/test_annotation.py index bece35e2..534d9adc 100644 --- a/tests/test_annotation.py +++ b/tests/test_annotation.py @@ -468,6 +468,49 @@ def rdheader(*args, **kwargs): wfdb.rdann(str(tmp_path / "err"), "atr") +@pytest.mark.parametrize( + "label_elements", [None, ["label_store", "symbol", "description"]] +) +def test_apply_range_keeps_every_field_consistent(label_elements): + """apply_range gives the same result as reading only that range.""" + kwargs = {} if label_elements is None else {"return_label_elements": label_elements} + ann = wfdb.rdann("sample-data/100", "atr", **kwargs) + ann.apply_range(sampfrom=600000, sampto=620000) + + expected = wfdb.rdann( + "sample-data/100", "atr", sampfrom=600000, sampto=620000, **kwargs + ) + assert ann.ann_len == expected.ann_len == 71 + for field in ["sample", "subtype", "chan", "num"]: + np.testing.assert_array_equal(getattr(ann, field), getattr(expected, field)) + for field in ["label_store", "symbol", "description", "aux_note"]: + value, expected_value = getattr(ann, field), getattr(expected, field) + if expected_value is None: + # Fields that are not set stay None + assert value is None + else: + assert list(value) == list(expected_value) + + +@pytest.mark.parametrize(("sampfrom", "sampto"), [(600000, 620000), (10**9, None)]) +def test_apply_range_updates_the_label_summary(sampfrom, sampto): + """A summary made before apply_range counts only the annotations kept.""" + ann = wfdb.rdann("sample-data/100", "atr", summarize_labels=True) + ann.apply_range(sampfrom=sampfrom, sampto=sampto) + + expected = wfdb.rdann( + "sample-data/100", + "atr", + sampfrom=sampfrom, + sampto=sampto, + summarize_labels=True, + ) + assert ann.contained_labels["n_occurrences"].sum() == ann.ann_len + pd.testing.assert_frame_equal( + ann.contained_labels.sort_index(), expected.contained_labels.sort_index() + ) + + def test_rdann_sampfrom_without_sampto(): """rdann with only sampfrom returns the annotations from sampfrom onwards.""" full = wfdb.rdann("sample-data/100", "atr")