Skip to content

Commit a96668a

Browse files
authored
Fix ann2rr intervals split by non-beat annotations (#584)
## Problem Fixes #479. `ann2rr` currently differences every annotation sample, including rhythm changes and comments. A rhythm marker between two beats splits one RR interval into two. For example, at 100 Hz, beats at samples 100, 200 and 300 with rhythm markers at 0, 150 and 250 and a comment at 400 produce `[0, 100, 50, 50, 50, 50, 100]` instead of `[100, 100, 100]`. ## Changes - Select QRS annotation codes using the existing `is_qrs` table before calculating intervals. Read numeric `label_store` values so renamed symbols and gaps in the standard symbol table do not change classification. - Keep the first interval measured from sample zero to the first selected annotation, and return an empty array when no annotations are selected. - Add the trailing optional argument `all_annotations=True` to retain the previous all-annotation behavior. This is also useful for comment annotations produced by `rr2ann` when no symbols are supplied. - Update the documentation and add regression tests with locally written annotation files and the existing `sample-data/100` fixture. The default beat-only selection and the all-annotation opt-in follow the [WFDB command-line ann2rr behavior](https://www.physionet.org/physiotools/wag/ann2rr-1.htm). The [WFDB RR tutorial](https://archive.physionet.org/tutorials/hrv/) describes the initial interval's time-zero convention. **Compatibility:** callers that intentionally used non-beat annotations should pass `all_annotations=True`. The existing `start_time` / `stop_time` filtering and unit conversion logic are unchanged. ## Validation Windows, Python 3.12.14: ```text python -m pytest tests/test_hr.py -q --tb=short 50 passed python -m pytest tests/test_processing.py tests/test_annotation.py -k "not test_1 and not test_2 and not test_3" -q --tb=short 11 passed, 3 deselected python -m ruff format --check wfdb/processing/hr.py tests/test_hr.py 2 files already formatted python -m ruff check wfdb/processing/hr.py tests/test_hr.py All checks passed! git diff --cached --check ``` The new tests cover mixed beat/rhythm/comment annotations, all standard beat and non-beat symbols, sample/second/minute/hour output, coincident markers, a single beat, empty selection, a renamed beat symbol, printed output and the compatibility option. Against the unmodified implementation they report **29 failed, 21 passed**; restoring that implementation in an isolated copy reproduces the same failures. The three deselected annotation tests fetch data from PhysioNet. This is a targeted local test run, not a claim that the full test matrix has passed.
2 parents 501487f + 620475d commit a96668a

3 files changed

Lines changed: 155 additions & 13 deletions

File tree

‎docs/changes.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ Unreleased
7777
**Read and write .wfdb archive files**
7878
A record can be stored in a single ``.wfdb`` archive file (a ZIP file containing the header and signal files). ``rdrecord``, ``rdsamp``, ``rdheader`` and ``rdann`` read a record or its annotations from an archive when given the path of the archive, and ``wrsamp`` writes a record into an archive with the new ``wfdb_archive`` argument.
7979

80+
**Use only beat annotations in ann2rr**
81+
``ann2rr`` now computes intervals between beat (QRS) annotations only, as the WFDB ``ann2rr`` program does, so rhythm changes, comments and other non-beat annotations no longer split an RR interval in two. The first interval is still measured from the start of the record. To include all annotations as before, pass ``all_annotations=True`` (the equivalent of ``ann2rr -A``).
82+
8083
Version 4.3.1 (Feb 2026)
8184
-----------------------------
8285

‎src/wfdb/processing/hr.py‎

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import numpy as np
44

55
from wfdb.io import download
6-
from wfdb.io.annotation import rdann, wrann
6+
from wfdb.io.annotation import is_qrs, rdann, wrann
77

88

99
def compute_hr(sig_len, qrs_inds, fs):
@@ -177,9 +177,14 @@ def ann2rr(
177177
stop_time=None,
178178
format=None,
179179
as_array=True,
180+
all_annotations=False,
180181
):
181182
"""Obtain RR interval series from ECG annotation files.
182183
184+
By default, only QRS (beat) annotations are used. The first interval
185+
is measured from the beginning of the record to the first selected
186+
annotation.
187+
183188
Parameters
184189
----------
185190
record_name : str
@@ -201,20 +206,27 @@ def ann2rr(
201206
printed in units of sample intervals. Other formats include
202207
's' (seconds), 'm' (minutes), 'h' (hours). Set to 'None' for samples.
203208
as_array : bool, optional
204-
If True, return an an 'ndarray', else print the output.
209+
If True, return an 'ndarray', else print the output.
210+
all_annotations : bool, optional
211+
If True, include all annotation types, rather than only QRS
212+
annotations. This retains the behavior of earlier versions and
213+
corresponds to the WFDB ann2rr application's -A option.
205214
206215
Returns
207216
-------
208-
N/A
217+
out_interval : ndarray or None
218+
The intervals in the requested units, or None when printing.
219+
An empty array is returned if no annotations are selected.
209220
210221
Examples
211222
--------
212-
>>> wfdb.ann2rr('sample-data/100', 'atr', as_array=False)
213-
>>> 18
214-
>>> 59
215-
>>> ...
216-
>>> 250
217-
>>> 257
223+
>>> from wfdb import processing
224+
>>> processing.ann2rr('sample-data/100', 'atr', as_array=False)
225+
77
226+
293
227+
...
228+
250
229+
257
218230
219231
"""
220232
if (pn_dir is not None) and ("." not in pn_dir):
@@ -223,10 +235,17 @@ def ann2rr(
223235
dir_list[0], download.get_version(dir_list[0]), *dir_list[1:]
224236
)
225237

226-
ann = rdann(record_name, extension, pn_dir=pn_dir)
238+
ann = rdann(
239+
record_name, extension, pn_dir=pn_dir, return_label_elements=["label_store"]
240+
)
241+
242+
samples = ann.sample
243+
if not all_annotations:
244+
samples = samples[np.isin(ann.label_store, np.flatnonzero(is_qrs))]
227245

228-
rr_interval = calc_rr(ann.sample, fs=ann.fs)
229-
rr_interval = np.insert(rr_interval, 0, ann.sample[0])
246+
rr_interval = calc_rr(samples, fs=ann.fs)
247+
if samples.size:
248+
rr_interval = np.insert(rr_interval, 0, samples[0])
230249

231250
time_interval = rr_interval / ann.fs
232251
if start_time is not None:
@@ -265,7 +284,8 @@ def rr2ann(rr_array, record_name, extension, fs=250, as_time=False):
265284
the shape of the input array is '(n_annot,2)', then treat the second
266285
column as the annotation mnemonic ('N', 'V', etc.). If a second column
267286
is not specified, then the default annotation will the '"' which
268-
specifies a comment.
287+
specifies a comment. Use ``ann2rr(..., all_annotations=True)`` to
288+
include these comment annotations when extracting intervals.
269289
record_name : str
270290
The record name of the WFDB annotation file. ie. for file '100.atr',
271291
record_name='100'.

‎tests/test_hr.py‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
"""Tests for RR interval extraction from annotation files."""
2+
3+
import numpy as np
4+
import pytest
5+
6+
import wfdb
7+
from wfdb import processing
8+
9+
10+
@pytest.fixture
11+
def mixed_annotations(tmp_path):
12+
wfdb.wrann(
13+
"mixed",
14+
"atr",
15+
np.array([0, 100, 150, 200, 250, 300, 400]),
16+
symbol=["+", "N", "+", "V", "+", "N", '"'],
17+
aux_note=["(N", "", "(AFIB", "", "(N", "", "note"],
18+
fs=100,
19+
write_dir=str(tmp_path),
20+
)
21+
return str(tmp_path / "mixed")
22+
23+
24+
@pytest.mark.parametrize(
25+
"format, divisor", [(None, 1), ("s", 100), ("m", 6000), ("h", 360000)]
26+
)
27+
def test_ann2rr_ignores_non_beats(mixed_annotations, format, divisor):
28+
intervals = processing.ann2rr(mixed_annotations, "atr", format=format)
29+
np.testing.assert_allclose(intervals, np.array([100, 100, 100]) / divisor)
30+
assert intervals.dtype.kind == ("i" if format is None else "f")
31+
32+
33+
def test_ann2rr_all_annotations(mixed_annotations):
34+
intervals = processing.ann2rr(mixed_annotations, "atr", all_annotations=True)
35+
np.testing.assert_array_equal(intervals, [0, 100, 50, 50, 50, 50, 100])
36+
37+
38+
@pytest.mark.parametrize("symbol", list("NLRaVFJASEj/QB?!enfr"))
39+
def test_ann2rr_beat_types(tmp_path, symbol):
40+
# Include codes above the gaps in the standard annotation label table.
41+
wfdb.wrann(
42+
"beats",
43+
"atr",
44+
np.array([100, 200]),
45+
symbol=[symbol, symbol],
46+
fs=100,
47+
write_dir=str(tmp_path),
48+
)
49+
intervals = processing.ann2rr(str(tmp_path / "beats"), "atr")
50+
np.testing.assert_array_equal(intervals, [100, 100])
51+
52+
53+
@pytest.mark.parametrize("symbol", list('~|sT*D"=p^t+u[]@x()'))
54+
def test_ann2rr_no_beats(tmp_path, symbol):
55+
wfdb.wrann(
56+
"nonbeats",
57+
"atr",
58+
np.array([100, 200]),
59+
symbol=[symbol, symbol],
60+
fs=100,
61+
write_dir=str(tmp_path),
62+
)
63+
intervals = processing.ann2rr(str(tmp_path / "nonbeats"), "atr")
64+
assert intervals.shape == (0,)
65+
assert intervals.dtype == np.int64
66+
67+
68+
@pytest.mark.parametrize("sample", [0, 100])
69+
def test_ann2rr_single_beat(tmp_path, sample):
70+
wfdb.wrann(
71+
"single",
72+
"atr",
73+
np.array([sample, sample]),
74+
symbol=["+", "N"],
75+
fs=100,
76+
write_dir=str(tmp_path),
77+
)
78+
intervals = processing.ann2rr(str(tmp_path / "single"), "atr")
79+
# The first interval remains measured from time zero, not the first marker.
80+
np.testing.assert_array_equal(intervals, [sample])
81+
82+
83+
def test_ann2rr_custom_symbol(tmp_path):
84+
wfdb.wrann(
85+
"custom",
86+
"atr",
87+
np.array([100, 200]),
88+
symbol=["Z", "Z"],
89+
custom_labels=[(1, "Z", "Renamed normal beat")],
90+
fs=100,
91+
write_dir=str(tmp_path),
92+
)
93+
intervals = processing.ann2rr(str(tmp_path / "custom"), "atr")
94+
np.testing.assert_array_equal(intervals, [100, 100])
95+
96+
97+
def test_ann2rr_print(mixed_annotations, capsys):
98+
assert processing.ann2rr(mixed_annotations, "atr", as_array=False) is None
99+
assert capsys.readouterr().out == "100\n100\n100\n"
100+
101+
102+
def test_ann2rr_empty_annotation(monkeypatch):
103+
ann = wfdb.Annotation(
104+
record_name="empty",
105+
extension="atr",
106+
fs=100,
107+
sample=np.array([], dtype=np.int64),
108+
label_store=np.array([], dtype=int),
109+
)
110+
monkeypatch.setattr(processing.hr, "rdann", lambda *args, **kwargs: ann)
111+
for all_annotations in [False, True]:
112+
intervals = processing.ann2rr("empty", "atr", all_annotations=all_annotations)
113+
assert intervals.shape == (0,)
114+
115+
116+
def test_ann2rr_sample_record():
117+
intervals = processing.ann2rr("sample-data/100", "atr")
118+
np.testing.assert_array_equal(intervals[:3], [77, 293, 292])
119+
assert len(intervals) == 2273

0 commit comments

Comments
 (0)