Skip to content

Commit 78a9a58

Browse files
authored
Ignore an invalid base time or date in a header, with a warning (#668)
Fixes #415. `rdheader`, and so `rdrecord` and `rdsamp`, could not read a record whose header has a base time or date in another form: | Record line ends with | Before | Now | |---|---|---| | `10:30:00 25.12.2020` (or `2020-12-25`, `31/02/2020`) | `ValueError` | time read, date ignored with a warning | | `2020` (a year in place of the time) | `ValueError` | time ignored with a warning | | `05-Feb-2020 11:39:16` (2020 and 2021 Challenges) | base time read as 00:00:05, no warning | both ignored, with a warning for each | As the issue suggests, this follows the WFDB library, which ignores a date that isn't DD/MM/YYYY and reads the rest of the record. The base time and date are now read as the fifth and sixth fields of the record line, not as whatever part of the line the record line pattern matches, so a value in another form is never read in part. Valid headers are read as before: the base time and date of all 88 headers in `sample-data` are the same as on `main`. Writing is unchanged: `wrheader` writes `base_time` and `base_date` from `datetime` objects, which are always in the WFDB form. ## Testing - New tests for invalid dates, invalid times, the date-before-time order and a valid date (no warning). The invalid cases fail on `main`. - `pytest`: all offline and network tests pass. Ruff and the docs build pass. <sub>@tompollard 🟥 red 🦥 sloth · aspen</sub>
2 parents 11a56cf + 4c54609 commit 78a9a58

3 files changed

Lines changed: 143 additions & 6 deletions

File tree

‎changelog.d/invalid-base-date.rst‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
**Read headers whose base time or date is in another form**
2+
``rdheader``, ``rdrecord`` and ``rdsamp`` raised a ``ValueError`` for a
3+
header whose base date is not a DD/MM/YYYY date (such as ``25.12.2020``)
4+
or whose base time is a year, so the record could not be read at all, and
5+
read a time and date in another order (such as ``05-Feb-2020 11:39:16``,
6+
in the 2020 and 2021 Challenges) as a wrong time. As in the WFDB library, a
7+
base time or date that is not valid is now ignored with a warning, and the
8+
rest of the record is read as usual.

‎src/wfdb/io/_header.py‎

Lines changed: 65 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import datetime
2+
import re
3+
import warnings
24
from collections.abc import Sequence
35
from typing import Any
46

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

10191021

1022+
# A base time: SS, MM:SS or HH:MM:SS, with optional fractions of a second
1023+
_rx_base_time = re.compile(r"\d{1,2}(:\d{1,2}){0,2}(\.\d{1,6})?")
1024+
1025+
1026+
def _parse_base_time_date(base_time: str, base_date: str, record_line: str):
1027+
"""Parse the base time and date of a record line, ignoring invalid ones.
1028+
1029+
As in the WFDB library, a time or date that is not valid is ignored, with
1030+
a warning, so that the rest of the header can still be read.
1031+
1032+
Parameters
1033+
----------
1034+
base_time : str
1035+
The fifth field of the record line, or "" if there is none.
1036+
base_date : str
1037+
The sixth field of the record line, or "" if there is none.
1038+
record_line : str
1039+
The record line, to show in the warnings.
1040+
1041+
Returns
1042+
-------
1043+
base_time : datetime.time or None
1044+
The base time, or None if it is missing or not valid.
1045+
base_date : datetime.date or None
1046+
The base date, or None if it is missing or not valid.
1047+
1048+
"""
1049+
time = date = None
1050+
if base_time:
1051+
if _rx_base_time.fullmatch(base_time):
1052+
try:
1053+
time = wfdb_strptime(base_time)
1054+
except ValueError:
1055+
pass
1056+
if time is None:
1057+
warnings.warn(
1058+
"The base time is not a valid HH:MM:SS time, so it is ignored. "
1059+
f"Record line: {record_line.strip()!r}",
1060+
stacklevel=3,
1061+
)
1062+
if base_date:
1063+
try:
1064+
date = datetime.datetime.strptime(base_date, "%d/%m/%Y").date()
1065+
except ValueError:
1066+
warnings.warn(
1067+
"The base date is not a valid DD/MM/YYYY date, so it is ignored. "
1068+
f"Record line: {record_line.strip()!r}",
1069+
stacklevel=3,
1070+
)
1071+
return time, date
1072+
1073+
10201074
def _parse_record_line(record_line: str) -> dict:
10211075
"""Extract fields from a record line string into a dictionary.
10221076
@@ -1049,10 +1103,21 @@ def _parse_record_line(record_line: str) -> dict:
10491103
record_fields["base_time"],
10501104
record_fields["base_date"],
10511105
) = match.groups()
1106+
# The base time and date are the fifth and sixth fields. Read them whole,
1107+
# rather than the part that the pattern matches, so that a value in
1108+
# another form (such as "05-Feb-2020") is ignored rather than misread.
1109+
fields = record_line.split()
1110+
record_fields["base_time"], record_fields["base_date"] = _parse_base_time_date(
1111+
fields[4] if len(fields) > 4 else "",
1112+
fields[5] if len(fields) > 5 else "",
1113+
record_line,
1114+
)
10521115

10531116
for field in RECORD_SPECS.index:
10541117
# Replace empty strings with their read defaults (which are
10551118
# mostly None)
1119+
if field in ("base_time", "base_date"):
1120+
continue
10561121
if record_fields[field] == "":
10571122
record_fields[field] = RECORD_SPECS.loc[field, "read_default"]
10581123
# Typecast non-empty strings for non-string (numerical/datetime)
@@ -1068,12 +1133,6 @@ def _parse_record_line(record_line: str) -> dict:
10681133
if round(fs, 8) == float(int(fs)):
10691134
fs = int(fs)
10701135
record_fields["fs"] = fs
1071-
elif field == "base_time":
1072-
record_fields["base_time"] = wfdb_strptime(record_fields["base_time"])
1073-
elif field == "base_date":
1074-
record_fields["base_date"] = datetime.datetime.strptime(
1075-
record_fields["base_date"], "%d/%m/%Y"
1076-
).date()
10771136

10781137
# This is not a standard WFDB field, but is useful to set.
10791138
if record_fields["base_date"] and record_fields["base_time"]:

‎tests/test_record.py‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import datetime
22
import os
3+
import re
34

45
import numpy as np
56
import pandas as pd
@@ -1877,3 +1878,72 @@ def test_checksums_float_matches_per_channel_sum(self):
18771878
signal = np.array([[0.1, 0.0]] * 10)
18781879
expected = [int(np.sum(col) % 65536) for col in np.transpose(signal)]
18791880
assert wfdb.io._signal._checksums(signal) == expected
1881+
1882+
1883+
def write_record_with_date(tmp_path, date):
1884+
"""Write a small record, and give its record line the base date `date`."""
1885+
wfdb.wrsamp(
1886+
"dated",
1887+
fs=250,
1888+
units=["mV"],
1889+
sig_name=["I"],
1890+
p_signal=np.linspace(-1, 1, 10)[:, None],
1891+
fmt=["16"],
1892+
write_dir=str(tmp_path),
1893+
)
1894+
header = tmp_path / "dated.hea"
1895+
lines = header.read_text().splitlines(keepends=True)
1896+
lines[0] = f"dated 1 250 10 10:30:00 {date}\n"
1897+
header.write_text("".join(lines))
1898+
return str(tmp_path / "dated")
1899+
1900+
1901+
@pytest.mark.parametrize("date", ["25.12.2020", "2020-12-25", "2020", "31/02/2020"])
1902+
def test_invalid_base_date_is_ignored_with_a_warning(tmp_path, date):
1903+
"""As in the WFDB library, a date that is not DD/MM/YYYY is ignored."""
1904+
record_name = write_record_with_date(tmp_path, date)
1905+
1906+
with pytest.warns(UserWarning, match="base date is not a valid DD/MM/YYYY"):
1907+
record = wfdb.rdrecord(record_name)
1908+
1909+
assert record.base_date is None
1910+
assert record.base_time == datetime.time(10, 30)
1911+
assert record.base_datetime is None
1912+
np.testing.assert_allclose(record.p_signal[:, 0], np.linspace(-1, 1, 10), atol=0.01)
1913+
1914+
1915+
def test_valid_base_date_is_read_without_a_warning(tmp_path, recwarn):
1916+
record = wfdb.rdheader(write_record_with_date(tmp_path, "25/12/2020"))
1917+
assert record.base_date == datetime.date(2020, 12, 25)
1918+
assert record.base_datetime == datetime.datetime(2020, 12, 25, 10, 30)
1919+
assert not [w for w in recwarn if "base date" in str(w.message)]
1920+
1921+
1922+
@pytest.mark.parametrize(
1923+
("time_and_date", "warning"),
1924+
[
1925+
# The 2020 and 2021 Challenges put the date, with dashes, first
1926+
("05-Feb-2020 11:39:16", "base time .* base date"),
1927+
# A year alone, in place of the time
1928+
("2020", "base time"),
1929+
("25:00:00 25/12/2020", "base time"),
1930+
],
1931+
)
1932+
def test_invalid_base_time_is_ignored_with_a_warning(tmp_path, time_and_date, warning):
1933+
"""An invalid time is ignored whole, not read in part as a wrong time."""
1934+
record_name = write_record_with_date(tmp_path, "")
1935+
header = tmp_path / "dated.hea"
1936+
lines = header.read_text().splitlines(keepends=True)
1937+
lines[0] = f"dated 1 250 10 {time_and_date}\n"
1938+
header.write_text("".join(lines))
1939+
1940+
with pytest.warns(UserWarning) as warnings:
1941+
record = wfdb.rdrecord(record_name)
1942+
1943+
messages = " ".join(str(w.message) for w in warnings)
1944+
assert re.search(warning.replace(" .* ", ".*"), messages)
1945+
assert record.base_time is None
1946+
assert record.base_datetime is None
1947+
assert record.sig_len == 10
1948+
if time_and_date.endswith("25/12/2020"):
1949+
assert record.base_date == datetime.date(2020, 12, 25)

0 commit comments

Comments
 (0)