diff --git a/changelog.d/invalid-base-date.rst b/changelog.d/invalid-base-date.rst new file mode 100644 index 00000000..2dd90bdd --- /dev/null +++ b/changelog.d/invalid-base-date.rst @@ -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. diff --git a/src/wfdb/io/_header.py b/src/wfdb/io/_header.py index 1e77d708..72660fb4 100644 --- a/src/wfdb/io/_header.py +++ b/src/wfdb/io/_header.py @@ -1,4 +1,6 @@ import datetime +import re +import warnings from collections.abc import Sequence from typing import Any @@ -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. @@ -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) @@ -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"]: diff --git a/tests/test_record.py b/tests/test_record.py index a77f7f64..50c1558b 100644 --- a/tests/test_record.py +++ b/tests/test_record.py @@ -1,5 +1,6 @@ import datetime import os +import re import numpy as np import pandas as pd @@ -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)