Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions changelog.d/typed-read-header.rst
Original file line number Diff line number Diff line change
@@ -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.
60 changes: 58 additions & 2 deletions docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions src/wfdb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -29,6 +35,7 @@
rdheader,
rdrecord,
rdsamp,
read_header,
sampfreq,
signame,
wfdbdesc,
Expand Down
7 changes: 7 additions & 0 deletions src/wfdb/io/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -31,6 +37,7 @@
rdheader,
rdrecord,
rdsamp,
read_header,
sampfreq,
signame,
wfdbdesc,
Expand Down
138 changes: 138 additions & 0 deletions src/wfdb/io/headers.py
Original file line number Diff line number Diff line change
@@ -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)
63 changes: 63 additions & 0 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ---------- #

Expand Down Expand Up @@ -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
----------
Expand Down
Loading
Loading