From 6ba6d86a4e3fbdd528d1a79ec4dd6be82ab6580a Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 17:45:51 -0500 Subject: [PATCH 1/2] Ignore an invalid base date in a header, with a warning rdheader raised a ValueError when the base date in the record line was not a DD/MM/YYYY date (such as 25.12.2020, 2020-12-25 or a year alone), so the whole record could not be read. Like the WFDB library, ignore such a date with a warning, and read the rest of the header. Fixes #415. --- changelog.d/invalid-base-date.rst | 6 +++++ src/wfdb/io/_header.py | 37 ++++++++++++++++++++++++++--- tests/test_record.py | 39 +++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+), 3 deletions(-) create mode 100644 changelog.d/invalid-base-date.rst diff --git a/changelog.d/invalid-base-date.rst b/changelog.d/invalid-base-date.rst new file mode 100644 index 00000000..c08c293c --- /dev/null +++ b/changelog.d/invalid-base-date.rst @@ -0,0 +1,6 @@ +**Read headers whose base date is not a valid DD/MM/YYYY date** + ``rdheader``, ``rdrecord`` and ``rdsamp`` raised a ``ValueError`` for a + header whose base date is in another form, such as ``25.12.2020``, + ``2020-12-25`` or just a year, so the record could not be read at all. As in + the WFDB library, such a date is now ignored with a warning: ``base_date`` + and ``base_datetime`` are None, 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..772e01ea 100644 --- a/src/wfdb/io/_header.py +++ b/src/wfdb/io/_header.py @@ -1,4 +1,5 @@ import datetime +import warnings from collections.abc import Sequence from typing import Any @@ -1017,6 +1018,36 @@ def wfdb_strptime(time_string: str) -> datetime.time: return datetime.datetime.strptime(time_string, time_fmt).time() +def _parse_base_date(base_date: str, record_line: str) -> datetime.date | None: + """Parse the base date of a record line, or warn and ignore it if invalid. + + As in the WFDB library, a date that is not a valid DD/MM/YYYY date is + ignored, so that the rest of the header can still be read. + + Parameters + ---------- + base_date : str + The base date read from the record line. + record_line : str + The record line, to show in the warning. + + Returns + ------- + datetime.date or None + The base date, or None if it is not valid. + + """ + try: + return 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=2, + ) + return None + + def _parse_record_line(record_line: str) -> dict: """Extract fields from a record line string into a dictionary. @@ -1071,9 +1102,9 @@ def _parse_record_line(record_line: str) -> dict: 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() + record_fields["base_date"] = _parse_base_date( + record_fields["base_date"], record_line + ) # 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..52046069 100644 --- a/tests/test_record.py +++ b/tests/test_record.py @@ -1877,3 +1877,42 @@ 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)] From 4c5460913c15f012fe13b9efb759b76f1fd422b0 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Mon, 23 Nov 2026 17:47:31 -0500 Subject: [PATCH 2/2] Ignore an invalid base time in a header too, and never read it in part The record line pattern takes the parts of the line that look like a time and a date, so "05-Feb-2020 11:39:16" was read as a base time of 5 seconds, and a year alone in place of the time raised a ValueError. Read the base time and date as the fifth and sixth fields instead, and ignore either one, with a warning, if it is not valid. --- changelog.d/invalid-base-date.rst | 12 ++--- src/wfdb/io/_header.py | 74 +++++++++++++++++++++---------- tests/test_record.py | 31 +++++++++++++ 3 files changed, 89 insertions(+), 28 deletions(-) diff --git a/changelog.d/invalid-base-date.rst b/changelog.d/invalid-base-date.rst index c08c293c..2dd90bdd 100644 --- a/changelog.d/invalid-base-date.rst +++ b/changelog.d/invalid-base-date.rst @@ -1,6 +1,8 @@ -**Read headers whose base date is not a valid DD/MM/YYYY date** +**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 in another form, such as ``25.12.2020``, - ``2020-12-25`` or just a year, so the record could not be read at all. As in - the WFDB library, such a date is now ignored with a warning: ``base_date`` - and ``base_datetime`` are None, and the rest of the record is read as usual. + 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 772e01ea..72660fb4 100644 --- a/src/wfdb/io/_header.py +++ b/src/wfdb/io/_header.py @@ -1,4 +1,5 @@ import datetime +import re import warnings from collections.abc import Sequence from typing import Any @@ -1018,34 +1019,56 @@ def wfdb_strptime(time_string: str) -> datetime.time: return datetime.datetime.strptime(time_string, time_fmt).time() -def _parse_base_date(base_date: str, record_line: str) -> datetime.date | None: - """Parse the base date of a record line, or warn and ignore it if invalid. +# 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})?") - As in the WFDB library, a date that is not a valid DD/MM/YYYY date is - ignored, so that the rest of the header can still be read. + +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 base date read from the record line. + The sixth field of the record line, or "" if there is none. record_line : str - The record line, to show in the warning. + The record line, to show in the warnings. Returns ------- - datetime.date or None - The base date, or None if it is not valid. + 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. """ - try: - return 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=2, - ) - return None + 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: @@ -1080,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) @@ -1099,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"] = _parse_base_date( - record_fields["base_date"], record_line - ) # 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 52046069..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 @@ -1916,3 +1917,33 @@ def test_valid_base_date_is_read_without_a_warning(tmp_path, recwarn): 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)