From a618ab1b869fc26fc787637a174821f28f2ac098 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Fri, 27 Nov 2026 23:20:04 -0500 Subject: [PATCH 1/5] Add typed read_header API --- changelog.d/typed-read-header.rst | 4 + docs/io.rst | 25 +++++- src/wfdb/__init__.py | 7 ++ src/wfdb/io/__init__.py | 7 ++ src/wfdb/io/headers.py | 132 ++++++++++++++++++++++++++++++ src/wfdb/io/record.py | 39 +++++++++ tests/test_read_header.py | 119 +++++++++++++++++++++++++++ 7 files changed, 331 insertions(+), 2 deletions(-) create mode 100644 changelog.d/typed-read-header.rst create mode 100644 src/wfdb/io/headers.py create mode 100644 tests/test_read_header.py diff --git a/changelog.d/typed-read-header.rst b/changelog.d/typed-read-header.rst new file mode 100644 index 00000000..d933835f --- /dev/null +++ b/changelog.d/typed-read-header.rst @@ -0,0 +1,4 @@ +**Add a typed header reader** + ``read_header`` returns an immutable single- or multi-segment header with + per-signal or per-segment entries. ``rdheader`` retains its existing return + types. diff --git a/docs/io.rst b/docs/io.rst index 1d1b152b..3f80b307 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -9,8 +9,29 @@ 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 typed, 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 +segment entry contains its name and length, without loading that segment's +header or samples. + +.. autoclass:: wfdb.io.SingleSegmentHeader + :no-index: + +.. autoclass:: wfdb.io.MultiSegmentHeader + :no-index: + +.. autoclass:: wfdb.io.SignalHeader + :no-index: + +.. autoclass:: wfdb.io.SegmentHeader + :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..793d8947 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, + SegmentHeader, + 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..b2ee819b 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, + SegmentHeader, + 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..b8b4dd85 --- /dev/null +++ b/src/wfdb/io/headers.py @@ -0,0 +1,132 @@ +"""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 reflect WFDB's interpreted header defaults. They describe the + stored signal, including its file layout and calibration, not a selected + or aligned array returned by ``rdrecord``. + """ + + 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 SegmentHeader: + """Describe one segment line in a multi-segment WFDB header.""" + + 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[SegmentHeader, ...] + + @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( + SegmentHeader(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..22f0ed81 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -19,6 +19,7 @@ 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 _from_parsed_header # -------------- WFDB Signal Calibration and Classification ---------- # @@ -2288,10 +2289,48 @@ def _resolve_pn_dir(record_name, pn_dir): return record_name, pn_dir +def read_header(path, *, pn_dir=None): + """Read one WFDB header into an immutable, typed 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. Values include + WFDB header defaults, but ``n_frames`` stays ``None`` if the header omits + the signal length; this function does not infer it 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. + + 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' + + """ + return _from_parsed_header(_read_header_fields(path, pn_dir)) + + 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, typed header description. Parameters ---------- diff --git a/tests/test_read_header.py b/tests/test_read_header.py new file mode 100644 index 00000000..b86bc684 --- /dev/null +++ b/tests/test_read_header.py @@ -0,0 +1,119 @@ +"""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_typed_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 typed header describes file 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_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 [(segment.name, segment.n_frames) for segment in fixed.segments] == [ + ("041s01", 1000), + ("041s02", 1000), + ] + 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 typed 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_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" From 55ff3b44a1d1b7c5c3c7be7bddf4a0f0e45e5e88 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Sat, 28 Nov 2026 12:09:53 -0500 Subject: [PATCH 2/5] Clarify omitted fields in typed signal headers --- docs/io.rst | 4 ++++ src/wfdb/io/headers.py | 8 +++++--- tests/test_read_header.py | 13 +++++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/docs/io.rst b/docs/io.rst index 3f80b307..0cf64895 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -20,6 +20,10 @@ omits the length. ``n_signals`` is the declared number of channels. For a multi-segment record, ``read_header`` reads the main header only; each segment entry contains its name and length, without loading that segment's header or samples. +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: diff --git a/src/wfdb/io/headers.py b/src/wfdb/io/headers.py index b8b4dd85..3e2e3fd7 100644 --- a/src/wfdb/io/headers.py +++ b/src/wfdb/io/headers.py @@ -10,9 +10,11 @@ class SignalHeader: """Describe one signal line in a single-segment WFDB header. - The values reflect WFDB's interpreted header defaults. They describe the - stored signal, including its file layout and calibration, not a selected - or aligned array returned by ``rdrecord``. + 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 diff --git a/tests/test_read_header.py b/tests/test_read_header.py index b86bc684..f43da89d 100644 --- a/tests/test_read_header.py +++ b/tests/test_read_header.py @@ -63,6 +63,19 @@ def test_read_header_needs_no_signal_file(tmp_path): 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") From ea0b256a4602091cc707ced030e655bc93bc4ff9 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Sat, 28 Nov 2026 12:23:58 -0500 Subject: [PATCH 3/5] Address public header API review --- changelog.d/typed-read-header.rst | 6 +++--- docs/io.rst | 24 +++++++++++++++++++++--- src/wfdb/__init__.py | 2 +- src/wfdb/io/__init__.py | 2 +- src/wfdb/io/headers.py | 12 ++++++++---- src/wfdb/io/record.py | 18 +++++++++++++----- src/wfdb/py.typed | 1 + tests/test_read_header.py | 7 +++++++ 8 files changed, 55 insertions(+), 17 deletions(-) create mode 100644 src/wfdb/py.typed diff --git a/changelog.d/typed-read-header.rst b/changelog.d/typed-read-header.rst index d933835f..a07b40ec 100644 --- a/changelog.d/typed-read-header.rst +++ b/changelog.d/typed-read-header.rst @@ -1,4 +1,4 @@ -**Add a typed header reader** +**Add an immutable header reader with published type information** ``read_header`` returns an immutable single- or multi-segment header with - per-signal or per-segment entries. ``rdheader`` retains its existing return - types. + per-signal fields or segment references. It reads one physical header per + call. ``rdheader`` retains its existing return types and recursive option. diff --git a/docs/io.rst b/docs/io.rst index 0cf64895..8f317e1a 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -18,8 +18,26 @@ Its ``signals`` or ``segments`` entries describe the source file, while ``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 -segment entry contains its name and length, without loading that segment's -header or samples. +``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. This also works 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) + 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 @@ -34,7 +52,7 @@ them from values explicitly stated in the file. .. autoclass:: wfdb.io.SignalHeader :no-index: -.. autoclass:: wfdb.io.SegmentHeader +.. autoclass:: wfdb.io.SegmentReference :no-index: Use ``iter_dataframes`` to process long recordings without loading the whole diff --git a/src/wfdb/__init__.py b/src/wfdb/__init__.py index 793d8947..cfea99f6 100644 --- a/src/wfdb/__init__.py +++ b/src/wfdb/__init__.py @@ -23,7 +23,7 @@ ) from wfdb.io.headers import ( MultiSegmentHeader, - SegmentHeader, + SegmentReference, SignalHeader, SingleSegmentHeader, ) diff --git a/src/wfdb/io/__init__.py b/src/wfdb/io/__init__.py index b2ee819b..8288a181 100644 --- a/src/wfdb/io/__init__.py +++ b/src/wfdb/io/__init__.py @@ -23,7 +23,7 @@ ) from wfdb.io.headers import ( MultiSegmentHeader, - SegmentHeader, + SegmentReference, SignalHeader, SingleSegmentHeader, ) diff --git a/src/wfdb/io/headers.py b/src/wfdb/io/headers.py index 3e2e3fd7..83089ffb 100644 --- a/src/wfdb/io/headers.py +++ b/src/wfdb/io/headers.py @@ -34,8 +34,12 @@ class SignalHeader: @dataclass(frozen=True) -class SegmentHeader: - """Describe one segment line in a multi-segment WFDB header.""" +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 @@ -79,7 +83,7 @@ class MultiSegmentHeader(_HeaderBase): """ n_segments: int - segments: tuple[SegmentHeader, ...] + segments: tuple[SegmentReference, ...] @property def layout(self) -> str | None: @@ -128,7 +132,7 @@ def _from_parsed_header( return SingleSegmentHeader(**common, signals=signals) segments = tuple( - SegmentHeader(name=segment.seg_name, n_frames=segment.seg_len) + 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 22f0ed81..e76b53ca 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -19,7 +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 _from_parsed_header +from wfdb.io.headers import ( + MultiSegmentHeader, + SingleSegmentHeader, + _from_parsed_header, +) # -------------- WFDB Signal Calibration and Classification ---------- # @@ -2289,14 +2293,18 @@ def _resolve_pn_dir(record_name, pn_dir): return record_name, pn_dir -def read_header(path, *, pn_dir=None): +def read_header( + path: str | os.PathLike[str], *, pn_dir: str | None = None +) -> SingleSegmentHeader | MultiSegmentHeader: """Read one WFDB header into an immutable, typed 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. Values include - WFDB header defaults, but ``n_frames`` stays ``None`` if the header omits - the signal length; this function does not infer it from a signal file. + not load signal samples or follow multi-segment references. Read a + referenced segment header separately to obtain its signal metadata. 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 ---------- diff --git a/src/wfdb/py.typed b/src/wfdb/py.typed new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/src/wfdb/py.typed @@ -0,0 +1 @@ + diff --git a/tests/test_read_header.py b/tests/test_read_header.py index f43da89d..04ede4df 100644 --- a/tests/test_read_header.py +++ b/tests/test_read_header.py @@ -82,10 +82,17 @@ def test_multisegment_headers_expose_segment_lines_only(tmp_path): 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") From 380f1574cb2a487f4649d522d5d1f5dfad6d5353 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Sat, 28 Nov 2026 12:52:44 -0500 Subject: [PATCH 4/5] Read segment headers from WFDB archives --- changelog.d/typed-read-header.rst | 3 ++- docs/io.rst | 17 +++++++++++-- src/wfdb/io/record.py | 22 ++++++++++++++--- tests/test_read_header.py | 41 +++++++++++++++++++++++++++++++ 4 files changed, 77 insertions(+), 6 deletions(-) diff --git a/changelog.d/typed-read-header.rst b/changelog.d/typed-read-header.rst index a07b40ec..5ec89ada 100644 --- a/changelog.d/typed-read-header.rst +++ b/changelog.d/typed-read-header.rst @@ -1,4 +1,5 @@ **Add an immutable header reader with published type information** ``read_header`` returns an immutable single- or multi-segment header with per-signal fields or segment references. It reads one physical header per - call. ``rdheader`` retains its existing return types and recursive option. + 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 8f317e1a..13ba75fe 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -20,8 +20,10 @@ 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. This also works for a variable-layout record's zero-length -layout segment. A ``~`` entry represents a gap and has no header to read. +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. @@ -38,6 +40,17 @@ it does not replace that recursive API. 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 diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index e76b53ca..c0aaa88d 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -2294,14 +2294,18 @@ def _resolve_pn_dir(record_name, pn_dir): def read_header( - path: str | os.PathLike[str], *, pn_dir: str | None = None + path: str | os.PathLike[str], + *, + pn_dir: str | None = None, + segment: str | None = None, ) -> SingleSegmentHeader | MultiSegmentHeader: """Read one WFDB header into an immutable, typed 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. This + 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. @@ -2315,6 +2319,10 @@ def read_header( 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 ------- @@ -2331,7 +2339,15 @@ def read_header( 'MLII' """ - return _from_parsed_header(_read_header_fields(path, pn_dir)) + 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): diff --git a/tests/test_read_header.py b/tests/test_read_header.py index 04ede4df..461a567e 100644 --- a/tests/test_read_header.py +++ b/tests/test_read_header.py @@ -128,6 +128,47 @@ def test_read_header_from_archive(tmp_path): 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") From 09d87ca420ebf62e068e4e29e06ec450046bcf96 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Sat, 28 Nov 2026 15:27:25 -0500 Subject: [PATCH 5/5] Defer package-wide type marker --- changelog.d/typed-read-header.rst | 2 +- docs/io.rst | 2 +- src/wfdb/io/record.py | 4 ++-- src/wfdb/py.typed | 1 - tests/test_read_header.py | 6 +++--- 5 files changed, 7 insertions(+), 8 deletions(-) delete mode 100644 src/wfdb/py.typed diff --git a/changelog.d/typed-read-header.rst b/changelog.d/typed-read-header.rst index 5ec89ada..f032c01a 100644 --- a/changelog.d/typed-read-header.rst +++ b/changelog.d/typed-read-header.rst @@ -1,4 +1,4 @@ -**Add an immutable header reader with published type information** +**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. diff --git a/docs/io.rst b/docs/io.rst index 13ba75fe..1d02e407 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -12,7 +12,7 @@ WFDB Records :members: rdrecord, rdheader, read_header, rdsamp, iter_dataframes, wrsamp, sampfreq, signame, wfdbdesc, wfdbtime -``read_header`` returns a typed, immutable description of one WFDB header. +``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 diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index c0aaa88d..b1a78576 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -2299,7 +2299,7 @@ def read_header( pn_dir: str | None = None, segment: str | None = None, ) -> SingleSegmentHeader | MultiSegmentHeader: - """Read one WFDB header into an immutable, typed description. + """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 @@ -2354,7 +2354,7 @@ 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, typed header description. + Use ``read_header`` for an immutable, structured header description. Parameters ---------- diff --git a/src/wfdb/py.typed b/src/wfdb/py.typed deleted file mode 100644 index 8b137891..00000000 --- a/src/wfdb/py.typed +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/test_read_header.py b/tests/test_read_header.py index 461a567e..901ebd5b 100644 --- a/tests/test_read_header.py +++ b/tests/test_read_header.py @@ -11,7 +11,7 @@ import wfdb -def test_single_segment_header_is_typed_and_immutable(): +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") @@ -45,7 +45,7 @@ def test_single_segment_header_is_typed_and_immutable(): def test_signal_header_keeps_source_skew(): - """The typed header describes file skew even when a read aligns values.""" + """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] @@ -117,7 +117,7 @@ def test_omitted_length_remains_unknown_in_source_header(): def test_read_header_from_archive(tmp_path): - """The typed reader accepts the same local archive form as rdheader.""" + """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")