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/invalid-base-date.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
**Read headers whose base time or date is in another form**
``rdheader``, ``rdrecord`` and ``rdsamp`` raised a ``ValueError`` for a
header whose base date is not a DD/MM/YYYY date (such as ``25.12.2020``)
or whose base time is a year, so the record could not be read at all, and
read a time and date in another order (such as ``05-Feb-2020 11:39:16``,
in the 2020 and 2021 Challenges) as a wrong time. As in the WFDB library, a
base time or date that is not valid is now ignored with a warning, and the
rest of the record is read as usual.
71 changes: 65 additions & 6 deletions src/wfdb/io/_header.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import datetime
import re
import warnings
from collections.abc import Sequence
from typing import Any

Expand Down Expand Up @@ -1017,6 +1019,58 @@ def wfdb_strptime(time_string: str) -> datetime.time:
return datetime.datetime.strptime(time_string, time_fmt).time()


# A base time: SS, MM:SS or HH:MM:SS, with optional fractions of a second
_rx_base_time = re.compile(r"\d{1,2}(:\d{1,2}){0,2}(\.\d{1,6})?")


def _parse_base_time_date(base_time: str, base_date: str, record_line: str):
"""Parse the base time and date of a record line, ignoring invalid ones.
As in the WFDB library, a time or date that is not valid is ignored, with
a warning, so that the rest of the header can still be read.
Parameters
----------
base_time : str
The fifth field of the record line, or "" if there is none.
base_date : str
The sixth field of the record line, or "" if there is none.
record_line : str
The record line, to show in the warnings.
Returns
-------
base_time : datetime.time or None
The base time, or None if it is missing or not valid.
base_date : datetime.date or None
The base date, or None if it is missing or not valid.
"""
time = date = None
if base_time:
if _rx_base_time.fullmatch(base_time):
try:
time = wfdb_strptime(base_time)
except ValueError:
pass
if time is None:
warnings.warn(
"The base time is not a valid HH:MM:SS time, so it is ignored. "
f"Record line: {record_line.strip()!r}",
stacklevel=3,
)
if base_date:
try:
date = datetime.datetime.strptime(base_date, "%d/%m/%Y").date()
except ValueError:
warnings.warn(
"The base date is not a valid DD/MM/YYYY date, so it is ignored. "
f"Record line: {record_line.strip()!r}",
stacklevel=3,
)
return time, date


def _parse_record_line(record_line: str) -> dict:
"""Extract fields from a record line string into a dictionary.
Expand Down Expand Up @@ -1049,10 +1103,21 @@ def _parse_record_line(record_line: str) -> dict:
record_fields["base_time"],
record_fields["base_date"],
) = match.groups()
# The base time and date are the fifth and sixth fields. Read them whole,
# rather than the part that the pattern matches, so that a value in
# another form (such as "05-Feb-2020") is ignored rather than misread.
fields = record_line.split()
record_fields["base_time"], record_fields["base_date"] = _parse_base_time_date(
fields[4] if len(fields) > 4 else "",
fields[5] if len(fields) > 5 else "",
record_line,
)

for field in RECORD_SPECS.index:
# Replace empty strings with their read defaults (which are
# mostly None)
if field in ("base_time", "base_date"):
continue
if record_fields[field] == "":
record_fields[field] = RECORD_SPECS.loc[field, "read_default"]
# Typecast non-empty strings for non-string (numerical/datetime)
Expand All @@ -1068,12 +1133,6 @@ def _parse_record_line(record_line: str) -> dict:
if round(fs, 8) == float(int(fs)):
fs = int(fs)
record_fields["fs"] = fs
elif field == "base_time":
record_fields["base_time"] = wfdb_strptime(record_fields["base_time"])
elif field == "base_date":
record_fields["base_date"] = datetime.datetime.strptime(
record_fields["base_date"], "%d/%m/%Y"
).date()

# This is not a standard WFDB field, but is useful to set.
if record_fields["base_date"] and record_fields["base_time"]:
Expand Down
70 changes: 70 additions & 0 deletions tests/test_record.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import datetime
import os
import re

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -1877,3 +1878,72 @@ def test_checksums_float_matches_per_channel_sum(self):
signal = np.array([[0.1, 0.0]] * 10)
expected = [int(np.sum(col) % 65536) for col in np.transpose(signal)]
assert wfdb.io._signal._checksums(signal) == expected


def write_record_with_date(tmp_path, date):
"""Write a small record, and give its record line the base date `date`."""
wfdb.wrsamp(
"dated",
fs=250,
units=["mV"],
sig_name=["I"],
p_signal=np.linspace(-1, 1, 10)[:, None],
fmt=["16"],
write_dir=str(tmp_path),
)
header = tmp_path / "dated.hea"
lines = header.read_text().splitlines(keepends=True)
lines[0] = f"dated 1 250 10 10:30:00 {date}\n"
header.write_text("".join(lines))
return str(tmp_path / "dated")


@pytest.mark.parametrize("date", ["25.12.2020", "2020-12-25", "2020", "31/02/2020"])
def test_invalid_base_date_is_ignored_with_a_warning(tmp_path, date):
"""As in the WFDB library, a date that is not DD/MM/YYYY is ignored."""
record_name = write_record_with_date(tmp_path, date)

with pytest.warns(UserWarning, match="base date is not a valid DD/MM/YYYY"):
record = wfdb.rdrecord(record_name)

assert record.base_date is None
assert record.base_time == datetime.time(10, 30)
assert record.base_datetime is None
np.testing.assert_allclose(record.p_signal[:, 0], np.linspace(-1, 1, 10), atol=0.01)


def test_valid_base_date_is_read_without_a_warning(tmp_path, recwarn):
record = wfdb.rdheader(write_record_with_date(tmp_path, "25/12/2020"))
assert record.base_date == datetime.date(2020, 12, 25)
assert record.base_datetime == datetime.datetime(2020, 12, 25, 10, 30)
assert not [w for w in recwarn if "base date" in str(w.message)]


@pytest.mark.parametrize(
("time_and_date", "warning"),
[
# The 2020 and 2021 Challenges put the date, with dashes, first
("05-Feb-2020 11:39:16", "base time .* base date"),
# A year alone, in place of the time
("2020", "base time"),
("25:00:00 25/12/2020", "base time"),
],
)
def test_invalid_base_time_is_ignored_with_a_warning(tmp_path, time_and_date, warning):
"""An invalid time is ignored whole, not read in part as a wrong time."""
record_name = write_record_with_date(tmp_path, "")
header = tmp_path / "dated.hea"
lines = header.read_text().splitlines(keepends=True)
lines[0] = f"dated 1 250 10 {time_and_date}\n"
header.write_text("".join(lines))

with pytest.warns(UserWarning) as warnings:
record = wfdb.rdrecord(record_name)

messages = " ".join(str(w.message) for w in warnings)
assert re.search(warning.replace(" .* ", ".*"), messages)
assert record.base_time is None
assert record.base_datetime is None
assert record.sig_len == 10
if time_and_date.endswith("25/12/2020"):
assert record.base_date == datetime.date(2020, 12, 25)
Loading