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
104 changes: 70 additions & 34 deletions src/wfdb/io/_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,58 @@ class _ParsedMultiSegmentHeader:
comments: tuple[str, ...]


def _auto_signal_file_names(
record_name, n_sig, formats, samps_per_frame, snapshot=None
):
"""Choose signal file names from explicit channel fields."""
if snapshot is None:
fmt = formats or [None] * n_sig
spf = samps_per_frame or [None] * n_sig
n_channels = n_sig
else:
fmt = [channel.fmt for channel in snapshot.channels]
spf = [channel.samps_per_frame for channel in snapshot.channels]
n_channels = snapshot.n_channels
num_groups = 0
group_number = []
prev_fmt = prev_spf = None
channels_in_group = 0

for ch_fmt, ch_spf in zip(fmt, spf):
if ch_fmt != prev_fmt:
num_groups += 1
channels_in_group = 0
elif ch_fmt in ("508", "516", "524"):
if channels_in_group >= 8 or ch_spf != prev_spf:
num_groups += 1
channels_in_group = 0
group_number.append(num_groups)
channels_in_group += 1
prev_fmt = ch_fmt
prev_spf = ch_spf

if num_groups < 2:
return [record_name + ".dat"] * n_channels
digits = len(str(group_number[-1]))
return [
record_name + "_" + str(group).rjust(digits, "0") + ".dat"
for group in group_number
]


def _single_segment_write_fields(record_fields, n_sig, snapshot, check_n_sig):
"""Select write fields from explicit record and channel values."""
selected_record = _select_record_header_fields(record_fields, multi_segment=False)
if record_fields["comments"] is not None:
# Preserve the existing get_write_fields result until encoder cleanup.
selected_record.append("comments")
check_n_sig("n_sig")
selected_signal = (
_select_signal_header_fields(snapshot.channels) if n_sig > 0 else None
)
return selected_record, selected_signal


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

Expand Down Expand Up @@ -798,6 +850,17 @@ def get_write_fields(self, signal_snapshot=None):
for each field.

"""
if signal_snapshot is not None:
record_fields = {
field: getattr(self, field)
for field in RECORD_SPECS.index
if field != "n_seg"
}
record_fields["comments"] = self.comments
return _single_segment_write_fields(
record_fields, self.n_sig, signal_snapshot, self.check_field
)

# Record specification fields
rec_write_fields = self.get_write_subset("record")

Expand All @@ -816,40 +879,13 @@ def get_write_fields(self, signal_snapshot=None):
return rec_write_fields, sig_write_fields

def _auto_signal_file_names(self, signal_snapshot=None):
if signal_snapshot is None:
fmt = self.fmt or [None] * self.n_sig
spf = self.samps_per_frame or [None] * self.n_sig
n_channels = self.n_sig
else:
fmt = [channel.fmt for channel in signal_snapshot.channels]
spf = [channel.samps_per_frame for channel in signal_snapshot.channels]
n_channels = signal_snapshot.n_channels
num_groups = 0
group_number = []
prev_fmt = prev_spf = None
channels_in_group = 0

for ch_fmt, ch_spf in zip(fmt, spf):
if ch_fmt != prev_fmt:
num_groups += 1
channels_in_group = 0
elif ch_fmt in ("508", "516", "524"):
if channels_in_group >= 8 or ch_spf != prev_spf:
num_groups += 1
channels_in_group = 0
group_number.append(num_groups)
channels_in_group += 1
prev_fmt = ch_fmt
prev_spf = ch_spf

if num_groups < 2:
return [self.record_name + ".dat"] * n_channels
else:
digits = len(str(group_number[-1]))
return [
self.record_name + "_" + str(g).rjust(digits, "0") + ".dat"
for g in group_number
]
return _auto_signal_file_names(
self.record_name,
self.n_sig,
self.fmt,
self.samps_per_frame,
signal_snapshot,
)

def set_default(self, field, *, signal_snapshot=None):
"""Set a missing attribute to its default value, if it has one.
Expand Down
90 changes: 55 additions & 35 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -1723,37 +1723,7 @@ def _warn_about_replacing_other_files(self, write_dir):
N/A

"""
record_name = self.record_name or ""

def file_exists(file_name):
path = _join_path(os.fspath(write_dir), file_name)
if is_cloud_path(write_dir):
opened = _fsspec_open(path)
return opened.fs.exists(opened.path)
return os.path.exists(path)

existing = [
file_name
for file_name in dict.fromkeys(self.file_name)
if file_name and file_name != "~" and file_exists(file_name)
]
if not existing:
return
try:
header = rdheader(_join_path(os.fspath(write_dir), record_name))
own = set(getattr(header, "file_name", None) or [])
except Exception:
# No readable header of this record, so no file is its own yet
own = set()
others = [file_name for file_name in existing if file_name not in own]
if others:
warnings.warn(
f"Writing record {record_name!r} replaces existing signal files "
f"{', '.join(others)}, which are named by `file_name`, not "
"`record_name`. To write a copy of a record under a new name, "
"set `file_name` too.",
stacklevel=_caller_stacklevel(),
)
_warn_about_replacing_other_files(self.record_name, self.file_name, write_dir)

def _arrange_fields(self, channels, sampfrom, smooth_frames):
"""Arrange/edit object fields to reflect user channel and/or signal range input.
Expand Down Expand Up @@ -5170,6 +5140,41 @@ def _legacy_write_prepared_files(writer, expanded, write_dir, wfdb_archive):
)


def _warn_about_replacing_other_files(record_name, file_names, write_dir):
"""Warn when target signal files belong to another record."""
record_name = record_name or ""

def file_exists(file_name):
path = _join_path(os.fspath(write_dir), file_name)
if is_cloud_path(write_dir):
opened = _fsspec_open(path)
return opened.fs.exists(opened.path)
return os.path.exists(path)

existing = [
file_name
for file_name in dict.fromkeys(file_names)
if file_name and file_name != "~" and file_exists(file_name)
]
if not existing:
return
try:
header = rdheader(_join_path(os.fspath(write_dir), record_name))
own = set(getattr(header, "file_name", None) or [])
except Exception:
# No readable header of this record, so no file is its own yet.
own = set()
others = [file_name for file_name in existing if file_name not in own]
if others:
warnings.warn(
f"Writing record {record_name!r} replaces existing signal files "
f"{', '.join(others)}, which are named by `file_name`, not "
"`record_name`. To write a copy of a record under a new name, "
"set `file_name` too.",
stacklevel=_caller_stacklevel(),
)


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 Down Expand Up @@ -5597,8 +5602,9 @@ class _WriteModel(BaseRecord, _header.HeaderMixin, _signal.SignalMixin):
skew: tuple[int | None, ...] | None
from_segments: bool

# Keep the legacy overwrite warning until the final encoder cleanup.
_warn_about_replacing_other_files = Record._warn_about_replacing_other_files
def _warn_about_replacing_other_files(self, write_dir):
"""Warn from this model's current destination fields."""
_warn_about_replacing_other_files(self.record_name, self.file_name, write_dir)

def check_field(
self,
Expand Down Expand Up @@ -5835,7 +5841,15 @@ def _prepare_defaults(self) -> None:
snapshot = _header._capture_write_signal_fields(
self, _header.SIGNAL_SPECS.index
)
record_fields, signal_fields = self.get_write_fields(snapshot)
values = {
field: getattr(self, field)
for field in _header.RECORD_SPECS.index
if field != "n_seg"
}
values["comments"] = self.comments
record_fields, signal_fields = _header._single_segment_write_fields(
values, self.n_sig, snapshot, self.check_field
)
for field in record_fields:
self._apply_default(field)
for field in signal_fields:
Expand All @@ -5847,7 +5861,13 @@ def _apply_default(self, field, snapshot=None) -> None:
field, getattr(self, field, None), self.n_sig, self.fmt, snapshot
)
if value is _header._AUTO_FILE_NAME:
value = self._auto_signal_file_names(snapshot)
value = _header._auto_signal_file_names(
self.record_name,
self.n_sig,
self.fmt,
self.samps_per_frame,
snapshot,
)
if value is not None:
setattr(self, field, value)

Expand Down
44 changes: 44 additions & 0 deletions tests/test_explicit_write_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""The write model derives defaults without inherited header helpers."""

import numpy as np
import pytest

import wfdb
from wfdb.io import _header
from wfdb.io.record import _WriteModel


def test_write_model_prepares_defaults_without_header_helpers(monkeypatch):
"""The model uses field values and a snapshot for its defaults."""
record = wfdb.Record(
record_name="copy",
fs=125,
n_sig=1,
sig_len=3,
p_signal=np.array([[0.0], [0.1], [0.2]]),
fmt=["16"],
adc_gain=[200.0],
baseline=[0],
units=["mV"],
sig_name=["I"],
)
model = _WriteModel.from_record(record, "p_signal", "uniform", None)
model.record_name = "copy"

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

monkeypatch.setattr(_header.HeaderMixin, "get_write_fields", unexpected_helper)
monkeypatch.setattr(
_header.HeaderMixin, "_auto_signal_file_names", unexpected_helper
)
model._prepare_defaults()

assert model.file_name == ["copy.dat"]


def test_write_model_owns_overwrite_warning():
"""The model no longer binds the Record warning method."""
assert _WriteModel._warn_about_replacing_other_files is not (
wfdb.Record._warn_about_replacing_other_files
)
Loading