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
8 changes: 8 additions & 0 deletions changelog.d/wrann-multichar-symbols.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
**Write custom annotation symbols of more than one character**
``wrann`` and ``Annotation.wrann`` failed with a ``TypeError`` when a custom
label's symbol had more than one character, and symbols were limited to 3
characters. Symbols may now have any length (and still no whitespace), as
in the WFDB library, and ``rdann`` reads them. A custom label is stored as
a note of at most 255 Latin-1 characters ("<number> <symbol>
<description>"), and ``wrann`` now raises a ``ValueError`` for a longer one,
which it used to write as a file that could not be read.
45 changes: 24 additions & 21 deletions src/wfdb/io/annotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,15 +501,11 @@ def check_field(self, field):
+ " field must be integer-like"
)

if not isinstance(symbol[i], str_types) or len(symbol[i]) not in [
1,
2,
3,
]:
if not isinstance(symbol[i], str_types) or not symbol[i]:
raise ValueError(
"The symbol values of the "
+ field
+ " field must be strings of length 1 to 3"
+ " field must be non-empty strings"
)

if bool(re.search("[ \t\n\r\f\v]", symbol[i])):
Expand Down Expand Up @@ -550,11 +546,9 @@ def check_field(self, field):

if field == "symbol":
for e in uniq_elements:
if len(e) not in [1, 2, 3]:
if not e:
raise ValueError(
"Subelements of the "
+ field
+ " field must be strings of length 1 to 3"
"Subelements of the " + field + " field must not be empty"
)
if bool(re.search("[ \t\n\r\f\v]", e)):
raise ValueError(
Expand Down Expand Up @@ -1587,17 +1581,26 @@ def custom_triplet_bytes(custom_triplet):
All the bytes converted from the tiplet.

"""
# Structure: 0, NOTE, len(aux_note), aux_note, codenumber, space, codesymbol, space,
# description, (0 null if necessary)
# Remember, aux_note string includes 'number(s)<space><symbol><space><description>''
annbytes = (
[0, 88, len(custom_triplet[2]) + 3 + len(str(custom_triplet[0])), 252]
+ [ord(c) for c in str(custom_triplet[0])]
+ [32]
+ [ord(custom_triplet[1])]
+ [32]
+ [ord(c) for c in custom_triplet[2]]
)
# Structure: 0, NOTE, len(aux_note), aux_note, (0 null if necessary), where
# aux_note is '<label_store><space><symbol><space><description>'. The
# symbol may have more than one character. As for any note, its length
# is stored in one byte, so it can have at most 255 Latin-1 characters.
label_store, symbol, description = custom_triplet
note = f"{label_store} {symbol} {description}"
try:
encoded = note.encode("latin-1")
except UnicodeEncodeError:
raise ValueError(
f"The custom label {note!r} contains characters that can't be "
"written (only Latin-1 characters are supported)"
) from None
if len(encoded) > 255:
raise ValueError(
"A custom label's number, symbol and description, separated by "
f"spaces, must be at most 255 characters, but {note[:20]!r}... has "
f"{len(encoded)}"
)
annbytes = [0, 88, len(encoded), 252] + list(encoded)

if len(annbytes) % 2:
annbytes.append(0)
Expand Down
59 changes: 59 additions & 0 deletions tests/test_annotation.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import functools
import os
import pathlib
import re
Expand Down Expand Up @@ -599,3 +600,61 @@ def test_rdann_summarize_labels_without_annotations():
assert ann.ann_len == 0
assert ann.contained_labels.empty
assert "n_occurrences" in ann.contained_labels.columns


@pytest.mark.parametrize("symbol", ["Z", "AB", "PV2", "ABCD", "LONGSYMBOL"])
def test_wrann_custom_symbol_of_several_characters(tmp_path, symbol):
"""Custom labels may have symbols of more than one character (#411)."""
custom_labels = pd.DataFrame(
{"label_store": [42], "symbol": [symbol], "description": ["custom beat"]}
)
wfdb.wrann(
"custom",
"atr",
np.array([10, 20, 30]),
symbol=["N", symbol, "N"],
custom_labels=custom_labels,
write_dir=str(tmp_path),
)

ann = wfdb.rdann(str(tmp_path / "custom"), "atr")

np.testing.assert_array_equal(ann.sample, [10, 20, 30])
assert ann.symbol == ["N", symbol, "N"]
assert ann.custom_labels.values.tolist() == [[42, symbol, "custom beat"]]


@pytest.mark.parametrize(("description_length", "fits"), [(248, True), (249, False)])
def test_wrann_custom_label_note_fits_in_255_bytes(tmp_path, description_length, fits):
"""A custom label's note ("42 PV2 <description>") has a one-byte length."""
description = "d" * description_length
write = functools.partial(
wfdb.wrann,
"custom",
"atr",
np.array([10]),
symbol=["PV2"],
custom_labels=[(42, "PV2", description)],
write_dir=str(tmp_path),
)
if fits:
write()
ann = wfdb.rdann(str(tmp_path / "custom"), "atr")
assert ann.custom_labels.values.tolist() == [[42, "PV2", description]]
else:
with pytest.raises(ValueError, match="at most 255 characters"):
write()
assert not (tmp_path / "custom.atr").exists()


def test_wrann_custom_label_must_be_latin1(tmp_path):
with pytest.raises(ValueError, match="Latin-1"):
wfdb.wrann(
"custom",
"atr",
np.array([10]),
symbol=["Z"],
custom_labels=[(42, "Z", "1 \u20ac beat")],
write_dir=str(tmp_path),
)
assert not (tmp_path / "custom.atr").exists()
Loading