diff --git a/changelog.d/typed-read-header.rst b/changelog.d/typed-read-header.rst new file mode 100644 index 00000000..f032c01a --- /dev/null +++ b/changelog.d/typed-read-header.rst @@ -0,0 +1,5 @@ +**Add an immutable, structured header reader** + ``read_header`` returns an immutable single- or multi-segment header with + per-signal fields or segment references. It reads one physical header per + call, including a named segment inside a local ``.wfdb`` archive. + ``rdheader`` retains its existing return types and recursive option. diff --git a/docs/io.rst b/docs/io.rst index 1d1b152b..1d02e407 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -9,8 +9,64 @@ WFDB Records --------------- .. automodule:: wfdb.io - :members: rdrecord, rdheader, rdsamp, iter_dataframes, wrsamp, sampfreq, - signame, wfdbdesc, wfdbtime + :members: rdrecord, rdheader, read_header, rdsamp, iter_dataframes, + wrsamp, sampfreq, signame, wfdbdesc, wfdbtime + +``read_header`` returns a structured, immutable description of one WFDB header. +Its ``signals`` or ``segments`` entries describe the source file, while +``rdheader`` continues to return a mutable ``Record`` or ``MultiRecord``. +``n_frames`` counts base sample frames, and remains ``None`` when the header +omits the length. ``n_signals`` is the declared number of channels. +For a multi-segment record, ``read_header`` reads the main header only; each +``SegmentReference`` contains a name and length. To inspect a segment's +signal names, units, or calibration, pass its path to ``read_header`` in a +separate call. For a local ``.wfdb`` archive, pass the archive path with +``segment=reference.name`` instead. Both approaches work for a +variable-layout record's zero-length layout segment. A ``~`` entry represents +a gap and has no header to read. +For recursive loading of segment headers, use ``rdheader(..., +rd_segments=True)``. ``read_header`` describes one physical header per call; +it does not replace that recursive API. + +.. code-block:: python + + import wfdb + + multi = wfdb.read_header("sample-data/multi-segment/041s/041s") + assert isinstance(multi, wfdb.MultiSegmentHeader) + first = wfdb.read_header( + "sample-data/multi-segment/041s/" + multi.segments[0].name + ) + assert isinstance(first, wfdb.SingleSegmentHeader) + print(first.signals[0].name) + +For a multi-segment archive, read the main header and a referenced segment +from the same archive: + +.. code-block:: python + + multi = wfdb.read_header("041s.wfdb") + assert isinstance(multi, wfdb.MultiSegmentHeader) + first = wfdb.read_header("041s.wfdb", segment=multi.segments[0].name) + assert isinstance(first, wfdb.SingleSegmentHeader) + print(first.signals[0].name) + +In a signal header, an omitted ``baseline`` is resolved to ``adc_zero`` if +present, or zero otherwise. Omitted optional fields such as ``adc_zero``, +``adc_res``, and ``init_value`` remain ``None`` so callers can distinguish +them from values explicitly stated in the file. + +.. autoclass:: wfdb.io.SingleSegmentHeader + :no-index: + +.. autoclass:: wfdb.io.MultiSegmentHeader + :no-index: + +.. autoclass:: wfdb.io.SignalHeader + :no-index: + +.. autoclass:: wfdb.io.SegmentReference + :no-index: Use ``iter_dataframes`` to process long recordings without loading the whole signal into memory. Each chunk is a pandas DataFrame with the same columns diff --git a/src/wfdb/__init__.py b/src/wfdb/__init__.py index 1aafdad0..cfea99f6 100644 --- a/src/wfdb/__init__.py +++ b/src/wfdb/__init__.py @@ -21,6 +21,12 @@ get_record_list, set_db_index_url, ) +from wfdb.io.headers import ( + MultiSegmentHeader, + SegmentReference, + SignalHeader, + SingleSegmentHeader, +) from wfdb.io.record import ( MultiRecord, Record, @@ -29,6 +35,7 @@ rdheader, rdrecord, rdsamp, + read_header, sampfreq, signame, wfdbdesc, diff --git a/src/wfdb/io/__init__.py b/src/wfdb/io/__init__.py index eccbd0be..8288a181 100644 --- a/src/wfdb/io/__init__.py +++ b/src/wfdb/io/__init__.py @@ -21,6 +21,12 @@ get_record_list, set_db_index_url, ) +from wfdb.io.headers import ( + MultiSegmentHeader, + SegmentReference, + SignalHeader, + SingleSegmentHeader, +) from wfdb.io.record import ( SIGNAL_CLASSES, MultiRecord, @@ -31,6 +37,7 @@ rdheader, rdrecord, rdsamp, + read_header, sampfreq, signame, wfdbdesc, diff --git a/src/wfdb/io/headers.py b/src/wfdb/io/headers.py new file mode 100644 index 00000000..83089ffb --- /dev/null +++ b/src/wfdb/io/headers.py @@ -0,0 +1,138 @@ +"""Immutable descriptions of WFDB header files.""" + +import datetime +from dataclasses import dataclass + +from wfdb.io import _header + + +@dataclass(frozen=True) +class SignalHeader: + """Describe one signal line in a single-segment WFDB header. + + The values describe the stored signal, including its file layout and + calibration, not a selected or aligned array returned by ``rdrecord``. + ``baseline`` is resolved to ``adc_zero`` when given, or zero otherwise. + Omitted optional fields such as ``adc_zero``, ``adc_res``, and + ``init_value`` remain ``None`` even when WFDB defines an effective default. + """ + + name: str | None + file_name: str | None + format: str | None + samples_per_frame: int | None + skew: int | None + byte_offset: int | None + adc_gain: float | None + baseline: int | None + units: str | None + adc_res: int | None + adc_zero: int | None + init_value: int | None + checksum: int | None + block_size: int | None + + +@dataclass(frozen=True) +class SegmentReference: + """Name and frame count of a segment listed in a multi-segment header. + + The referenced segment's header is not loaded. Read that header separately + to inspect its signal names, units, and calibration. + """ + + name: str + n_frames: int + + +@dataclass(frozen=True) +class _HeaderBase: + """Hold the record-line fields shared by both header forms.""" + + record_name: str + n_signals: int + fs: float | int + n_frames: int | None + counter_frequency: float | None + base_counter: float | None + base_time: datetime.time | None + base_date: datetime.date | None + comments: tuple[str, ...] + + @property + def base_datetime(self) -> datetime.datetime | None: + """Return the header's date and time when both are present.""" + if self.base_date is None or self.base_time is None: + return None + return datetime.datetime.combine(self.base_date, self.base_time) + + +@dataclass(frozen=True) +class SingleSegmentHeader(_HeaderBase): + """Describe a header containing signal lines and no segment list.""" + + signals: tuple[SignalHeader, ...] + + +@dataclass(frozen=True) +class MultiSegmentHeader(_HeaderBase): + """Describe a header containing segment names and lengths. + + This describes the multi-segment header itself. Reading it does not load + the referenced segment headers or their signal samples. + """ + + n_segments: int + segments: tuple[SegmentReference, ...] + + @property + def layout(self) -> str | None: + """Return ``"variable"`` or ``"fixed"`` when segments are listed.""" + if not self.segments: + return None + return "variable" if self.segments[0].n_frames == 0 else "fixed" + + +def _from_parsed_header( + parsed: _header._ParsedSingleSegmentHeader | _header._ParsedMultiSegmentHeader, +) -> SingleSegmentHeader | MultiSegmentHeader: + """Build a public immutable description from a parsed header.""" + record_line = parsed.record_fields + common = dict( + record_name=record_line.record_name, + n_signals=record_line.n_sig, + fs=record_line.fs, + n_frames=record_line.sig_len, + counter_frequency=record_line.counter_freq, + base_counter=record_line.base_counter, + base_time=record_line.base_time, + base_date=record_line.base_date, + comments=parsed.comments, + ) + if isinstance(parsed, _header._ParsedSingleSegmentHeader): + signals = tuple( + SignalHeader( + name=signal.sig_name, + file_name=signal.file_name, + format=signal.fmt, + samples_per_frame=signal.samps_per_frame, + skew=signal.skew, + byte_offset=signal.byte_offset, + adc_gain=signal.adc_gain, + baseline=signal.baseline, + units=signal.units, + adc_res=signal.adc_res, + adc_zero=signal.adc_zero, + init_value=signal.init_value, + checksum=signal.checksum, + block_size=signal.block_size, + ) + for signal in parsed.signals or () + ) + return SingleSegmentHeader(**common, signals=signals) + + segments = tuple( + SegmentReference(name=segment.seg_name, n_frames=segment.seg_len) + for segment in parsed.segments + ) + return MultiSegmentHeader(**common, n_segments=record_line.n_seg, segments=segments) diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 46fe2e58..b1a78576 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -19,6 +19,11 @@ from wfdb.io._cloud import check_cloud_write, is_cloud_path, staged_cloud_write from wfdb.io._coreio import CLOUD_PROTOCOLS, _fsspec_open, _join_path, _split_path from wfdb.io.archive import WFDBArchive, archive_for_writing, is_archive_path +from wfdb.io.headers import ( + MultiSegmentHeader, + SingleSegmentHeader, + _from_parsed_header, +) # -------------- WFDB Signal Calibration and Classification ---------- # @@ -2288,10 +2293,68 @@ def _resolve_pn_dir(record_name, pn_dir): return record_name, pn_dir +def read_header( + path: str | os.PathLike[str], + *, + pn_dir: str | None = None, + segment: str | None = None, +) -> SingleSegmentHeader | MultiSegmentHeader: + """Read one WFDB header into an immutable, structured description. + + A single-segment header has ``signals``; a multi-segment header has + ``segments``. This function reads only the requested header file. It does + not load signal samples or follow multi-segment references. Read a + referenced segment header separately to obtain its signal metadata. For + a local ``.wfdb`` archive, pass the segment name in ``segment``. This + function does not replace ``rdheader(..., rd_segments=True)``. Values + include WFDB header defaults, but ``n_frames`` stays ``None`` if the + header omits the signal length; it is not inferred from a signal file. + + Parameters + ---------- + path : str or os.PathLike + Local record path or supported cloud or ``physionet://`` URI, without + the ``.hea`` extension. A local ``.wfdb`` archive path is also + accepted. + pn_dir : str, optional + PhysioNet database directory, as for ``rdheader``. An explicit + ``physionet://`` URI is preferred for new code. + segment : str, optional + Name of a segment or layout header inside a local ``.wfdb`` archive, + without the ``.hea`` extension. Requires an archive path. If omitted, + the archive's main header is read. + + Returns + ------- + SingleSegmentHeader or MultiSegmentHeader + Immutable record-line fields and signal or segment entries. + + Examples + -------- + >>> import wfdb + >>> header = wfdb.read_header("sample-data/100") + >>> header.n_signals + 2 + >>> header.signals[0].name + 'MLII' + + """ + if segment is not None: + if not is_archive_path(path): + raise ValueError("segment requires a local .wfdb archive path") + _check_archive_read_args(path, pn_dir) + with WFDBArchive(path, mode="r") as archive: + parsed = _header._parse_header_fields(archive.read_header(segment)) + else: + parsed = _read_header_fields(path, pn_dir) + return _from_parsed_header(parsed) + + def rdheader(record_name, pn_dir=None, rd_segments=False): """Read a WFDB header file and return a `Record` or `MultiRecord`. The record descriptors are the attributes of the returned object. + Use ``read_header`` for an immutable, structured header description. Parameters ---------- diff --git a/tests/test_read_header.py b/tests/test_read_header.py new file mode 100644 index 00000000..901ebd5b --- /dev/null +++ b/tests/test_read_header.py @@ -0,0 +1,180 @@ +"""Typed source-header reads alongside the legacy rdheader API.""" + +import datetime +import pickle +import zipfile +from dataclasses import FrozenInstanceError +from pathlib import Path + +import pytest + +import wfdb + + +def test_single_segment_header_is_structured_and_immutable(): + """A signal header groups calibration and storage fields per channel.""" + header = wfdb.read_header("sample-data/100") + + assert isinstance(header, wfdb.SingleSegmentHeader) + assert isinstance(header, wfdb.io.SingleSegmentHeader) + assert (header.record_name, header.n_signals, header.fs, header.n_frames) == ( + "100", + 2, + 360, + 650000, + ) + assert isinstance(header.signals, tuple) + assert not hasattr(header, "p_signal") + first = header.signals[0] + assert isinstance(first, wfdb.SignalHeader) + assert (first.name, first.file_name, first.format) == ( + "MLII", + "100.dat", + "212", + ) + assert (first.samples_per_frame, first.adc_gain, first.baseline) == ( + 1, + 200.0, + 1024, + ) + with pytest.raises(FrozenInstanceError): + header.n_frames = 5 + with pytest.raises(FrozenInstanceError): + first.name = "changed" + assert pickle.loads(pickle.dumps(header)) == header + + +def test_signal_header_keeps_source_skew(): + """The structured header describes skew even when a read aligns values.""" + header = wfdb.read_header("sample-data/100skew") + + assert [signal.skew for signal in header.signals] == [None, 3] + + +def test_read_header_needs_no_signal_file(tmp_path): + """Reading metadata does not open the data file named in the header.""" + path = Path(tmp_path) / "100" + path.with_suffix(".hea").write_bytes(Path("sample-data/100.hea").read_bytes()) + + header = wfdb.read_header(path) + + assert header.n_frames == 650000 + assert header.signals[0].file_name == "100.dat" + assert not path.with_suffix(".dat").exists() + + +def test_omitted_optional_signal_fields_remain_none(tmp_path): + """Keep omitted fields distinct from effective format defaults.""" + path = Path(tmp_path) / "t.hea" + path.write_text("t 1 100 1\nt.dat 16\n") + + signal = wfdb.read_header(path.with_suffix("")).signals[0] + + assert signal.baseline == 0 + assert signal.adc_zero is None + assert signal.adc_res is None + assert signal.init_value is None + + +def test_multisegment_headers_expose_segment_lines_only(tmp_path): + """A multi-segment header does not require its segment header files.""" + fixed = wfdb.read_header("sample-data/multi-segment/041s/041s") + assert isinstance(fixed, wfdb.MultiSegmentHeader) + assert fixed.layout == "fixed" + assert fixed.n_segments == 2 + assert isinstance(fixed.segments[0], wfdb.SegmentReference) + assert isinstance(fixed.segments[0], wfdb.io.SegmentReference) + assert [(segment.name, segment.n_frames) for segment in fixed.segments] == [ + ("041s01", 1000), + ("041s02", 1000), + ] + first_segment = wfdb.read_header( + Path("sample-data/multi-segment/041s") / fixed.segments[0].name + ) + assert isinstance(first_segment, wfdb.SingleSegmentHeader) + assert first_segment.signals[0].name == "III" + assert fixed.base_datetime == datetime.datetime(1994, 10, 26, 8, 26, 4) + + source = Path("sample-data/multi-segment/p000878/p000878-2137-10-26-16-57.hea") + target = Path(tmp_path) / source.name + target.write_bytes(source.read_bytes()) + variable = wfdb.read_header(target.with_suffix("")) + assert isinstance(variable, wfdb.MultiSegmentHeader) + assert variable.layout == "variable" + assert [(segment.name, segment.n_frames) for segment in variable.segments[:2]] == [ + ("3269321_layout", 0), + ("~", 3750), + ] + + +def test_omitted_length_remains_unknown_in_source_header(): + """A header read does not infer missing length from the signal file.""" + header = wfdb.read_header("sample-data/100-no-len") + selected = wfdb.rdrecord("sample-data/100-no-len", sampfrom=2, sampto=6) + + assert header.n_frames is None + assert selected.sig_len == 4 + + +def test_read_header_from_archive(tmp_path): + """The new reader accepts the same local archive form as rdheader.""" + path = Path(tmp_path) / "100.wfdb" + with zipfile.ZipFile(path, "w") as archive: + archive.write("sample-data/100.hea", "100.hea") + + header = wfdb.read_header(path) + + assert isinstance(header, wfdb.SingleSegmentHeader) + assert header.signals[0].name == "MLII" + + +def test_read_header_from_multisegment_archive(tmp_path): + """Select a referenced segment header from the same archive.""" + source = Path("sample-data/multi-segment/041s") + path = Path(tmp_path) / "041s.wfdb" + with zipfile.ZipFile(path, "w") as archive: + for name in ("041s", "041s01", "041s02"): + archive.write(source / f"{name}.hea", f"{name}.hea") + + main = wfdb.read_header(path) + assert isinstance(main, wfdb.MultiSegmentHeader) + first = wfdb.read_header(path, segment=main.segments[0].name) + assert isinstance(first, wfdb.SingleSegmentHeader) + assert first.record_name == "041s01" + assert first.signals[0].name == "III" + + with pytest.raises(FileNotFoundError, match="missing.hea"): + wfdb.read_header(path, segment="missing") + with pytest.raises(ValueError, match="pn_dir cannot be used"): + wfdb.read_header(path, pn_dir="mitdb", segment="041s01") + with pytest.raises(ValueError, match="requires a local .wfdb archive"): + wfdb.read_header(source / "041s", segment="041s01") + + +def test_read_layout_header_from_archive(tmp_path): + """A variable-layout segment can be read without signal files.""" + source = Path("sample-data/multi-segment/p000878") + name = "p000878-2137-10-26-16-57" + path = Path(tmp_path) / f"{name}.wfdb" + with zipfile.ZipFile(path, "w") as archive: + for header in (name, "3269321_layout"): + archive.write(source / f"{header}.hea", f"{header}.hea") + + main = wfdb.read_header(path) + assert isinstance(main, wfdb.MultiSegmentHeader) + assert main.layout == "variable" + layout = wfdb.read_header(path, segment=main.segments[0].name) + assert isinstance(layout, wfdb.SingleSegmentHeader) + assert layout.n_frames == 0 + assert len(layout.signals) == main.n_signals + + +def test_rdheader_keeps_legacy_return_type(): + """Existing callers still receive a mutable Record or MultiRecord.""" + single = wfdb.rdheader("sample-data/100") + multi = wfdb.rdheader("sample-data/multi-segment/041s/041s") + + assert isinstance(single, wfdb.Record) + assert isinstance(multi, wfdb.MultiRecord) + single.sig_name[0] = "changed" + assert single.sig_name[0] == "changed"