Skip to content
Merged
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
115 changes: 109 additions & 6 deletions src/wfdb/io/_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,31 @@ def _capture_write_signal_fields(record, fields) -> _SignalFieldSnapshot:
return _capture_signal_fields(record, fields)


def _capture_write_signal_fields_from_values(
values: Mapping[str, object], n_channels: int, fields
) -> _SignalFieldSnapshot:
"""Capture write channels from explicit parallel field values."""
field_names = tuple(fields)
for field in field_names:
value = values[field]
if value is not None and not isinstance(value, list):
raise TypeError(f"Field `{field}` must be a list.")
present = frozenset(field for field in field_names if values[field] is not None)
for field in field_names:
if field in present and len(values[field]) != n_channels:
raise ValueError(f"{field} must have {n_channels} channel entries")
channels = tuple(
_ParsedSignalLine(
**{
field: values[field][channel] if field in present else None
for field in SIGNAL_SPECS.index
}
)
for channel in range(n_channels)
)
return _SignalFieldSnapshot(n_channels, channels, present)


@dataclass(frozen=True)
class _ParsedSegmentLine:
"""Fields from one segment line in a multi-segment header."""
Expand Down Expand Up @@ -496,6 +521,89 @@ def _single_segment_write_fields(record_fields, n_sig, snapshot, check_n_sig):
return selected_record, selected_signal


def _check_signal_snapshot_cohesion(snapshot: _SignalFieldSnapshot) -> None:
"""Check that channels sharing a signal file agree on format and offset."""
if snapshot.n_channels == 0:
return
storage = snapshot.storage
file_names = [channel.file_name for channel in storage]
formats = [channel.fmt for channel in storage]
offsets = [channel.byte_offset for channel in storage]

datfmts = {}
for channel in range(snapshot.n_channels):
if file_names[channel] not in datfmts:
datfmts[file_names[channel]] = formats[channel]
elif datfmts[file_names[channel]] != formats[channel]:
raise ValueError(
"Each file_name (dat file) specified must have the same fmt"
)

datoffsets = {}
if offsets is not None:
for channel in range(snapshot.n_channels):
if offsets[channel] is None:
continue
if file_names[channel] not in datoffsets:
datoffsets[file_names[channel]] = offsets[channel]
elif datoffsets[file_names[channel]] != offsets[channel]:
raise ValueError(
"Each file_name (dat file) specified must have the same byte offset"
)


def _write_header_lines(record_name, header_lines, write_dir, wfdb_archive):
"""Write explicit header lines to a folder or open archive."""
file_name = record_name + ".hea"
if wfdb_archive is not None:
content = "".join(f"{line}\n" for line in header_lines)
wfdb_archive.write(file_name, content.encode("utf-8"))
else:
util.lines_to_file(file_name, write_dir, header_lines)


def _write_checked_single_header(
header_fields, expanded, validate_field, write_dir, wfdb_archive
) -> _SignalFieldSnapshot:
"""Validate and write a single-segment header from explicit fields."""
validate_field("n_sig")
fields = (
SIGNAL_SPECS.index if expanded else SIGNAL_SPECS.index.drop("samps_per_frame")
)
snapshot = _capture_write_signal_fields_from_values(
header_fields, header_fields["n_sig"], fields
)
rec_write_fields = _select_record_header_fields(header_fields, multi_segment=False)
if header_fields["comments"] is not None:
# Keep the legacy field list until the legacy path is removed.
rec_write_fields.append("comments")
sig_write_fields = (
_select_signal_header_fields(snapshot.channels)
if snapshot.n_channels > 0
else None
)
if not expanded:
sig_write_fields.pop("samps_per_frame", None)

for field in rec_write_fields:
validate_field(field)
for field, required_channels in sig_write_fields.items():
validate_field(
field,
required_channels=required_channels,
signal_snapshot=snapshot,
)
_check_signal_snapshot_cohesion(snapshot)
lines = _serialize_single_header_lines(
header_fields,
snapshot.channels,
rec_write_fields,
sig_write_fields,
)
_write_header_lines(header_fields["record_name"], lines, write_dir, wfdb_archive)
return snapshot


class BaseHeaderMixin:
"""Mixin class with multi-segment header methods.

Expand Down Expand Up @@ -647,12 +755,7 @@ def _write_header_lines(self, header_lines, write_dir, wfdb_archive):
N/A

"""
file_name = self.record_name + ".hea"
if wfdb_archive is not None:
content = "".join(f"{line}\n" for line in header_lines)
wfdb_archive.write(file_name, content.encode("utf-8"))
else:
util.lines_to_file(file_name, write_dir, header_lines)
_write_header_lines(self.record_name, header_lines, write_dir, wfdb_archive)


class HeaderMixin(BaseHeaderMixin):
Expand Down
28 changes: 27 additions & 1 deletion src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -5175,6 +5175,29 @@ def file_exists(file_name):
)


def _write_model_header(writer, expanded, write_dir, archive):
"""Write a model header from its current fields without encoder methods."""
values = vars(writer)
header_fields = {
field: values.get(field)
for field in (*_header.RECORD_SPECS.index, *_header.SIGNAL_SPECS.index)
}
header_fields["comments"] = values["comments"]

def validate(field, required_channels="all", signal_snapshot=None):
_check_field_value(
field,
header_fields[field],
required_channels,
signal_snapshot=signal_snapshot,
lookup=header_fields.__getitem__,
)

return _header._write_checked_single_header(
header_fields, expanded, validate, write_dir, archive
)


def _write_prepared_files(writer, expanded, write_dir, wfdb_archive):
"""Write checked header and signal files from prepared encoder fields."""
# A layout header with no signal files has only a header to write.
Expand All @@ -5196,7 +5219,10 @@ def _write_prepared_files(writer, expanded, write_dir, wfdb_archive):
if wfdb_archive is None and has_signal_files and writer.file_name:
writer._warn_about_replacing_other_files(write_dir)
with archive_for_writing(wfdb_archive, write_dir) as archive:
snapshot = writer._write_checked_header(write_dir, expanded, archive)
if isinstance(writer, _WriteModel):
snapshot = _write_model_header(writer, expanded, write_dir, archive)
else:
snapshot = writer._write_checked_header(write_dir, expanded, archive)
if has_signal_files:
writer.wr_dats(
expanded=expanded,
Expand Down
30 changes: 30 additions & 0 deletions tests/test_explicit_header_writing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Modern header writes use explicit fields instead of inherited methods."""

import numpy as np
import pytest

import wfdb
from wfdb.io import _header


def test_modern_header_write_does_not_call_header_mixin(tmp_path, monkeypatch):
"""Modern writes validate and serialize headers without writer methods."""

def unexpected_call(*_args, **_kwargs):
pytest.fail("called an inherited header writer")

monkeypatch.setattr(_header.HeaderMixin, "_write_checked_header", unexpected_call)
monkeypatch.setattr(_header.HeaderMixin, "check_field_cohesion", unexpected_call)
monkeypatch.setattr(_header.HeaderMixin, "wr_header_file", unexpected_call)
monkeypatch.setattr(_header.BaseHeaderMixin, "_write_header_lines", unexpected_call)
wfdb.write_signals(
tmp_path / "copy",
np.array([[0.0], [0.1], [0.2]]),
fs=125,
kind="physical",
formats="16",
channel_names=["I"],
units=["mV"],
)

assert (tmp_path / "copy.hea").exists()
Loading