diff --git a/src/wfdb/io/_header.py b/src/wfdb/io/_header.py index 56030b2d..57c49bfb 100644 --- a/src/wfdb/io/_header.py +++ b/src/wfdb/io/_header.py @@ -883,48 +883,18 @@ def _write_checked_header(self, write_dir, expanded, wfdb_archive): for field in (*RECORD_SPECS.index, *SIGNAL_SPECS.index) } header_fields["comments"] = self.comments - self.check_field("n_sig", header_fields=header_fields) - fields = ( - SIGNAL_SPECS.index - if expanded - else SIGNAL_SPECS.index.drop("samps_per_frame") - ) - snapshot = _capture_write_signal_fields(self, 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: - self.check_field(field, header_fields=header_fields) - for field, required_channels in sig_write_fields.items(): + def validate(field, required_channels="all", signal_snapshot=None): self.check_field( field, - required_channels=required_channels, - signal_snapshot=snapshot, + required_channels, + signal_snapshot=signal_snapshot, header_fields=header_fields, ) - self.check_field_cohesion( - rec_write_fields, list(sig_write_fields), signal_snapshot=snapshot - ) - self.wr_header_file( - rec_write_fields, - sig_write_fields, - write_dir, - wfdb_archive, - signal_snapshot=snapshot, - record_fields=header_fields, + + return _write_checked_single_header( + header_fields, expanded, validate, write_dir, wfdb_archive ) - return snapshot def get_write_fields(self, signal_snapshot=None): """Get the header fields to write, split into record and signal fields. @@ -1037,54 +1007,40 @@ def check_field_cohesion( N/A """ - # If there are no signal specification fields, there is nothing to check. - n_channels = ( - signal_snapshot.n_channels if signal_snapshot is not None else self.n_sig - ) - if n_channels > 0: - if signal_snapshot is not None: - storage = signal_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] - else: - file_names = self.file_name - formats = self.fmt - offsets = self.byte_offset - # The length of all signal specification fields must match n_sig - # even if some of its elements are None. - if signal_snapshot is None: - for f in sig_write_fields: - if len(getattr(self, f)) != self.n_sig: - raise ValueError( - "The length of field: " + f + " must match field n_sig." - ) - - # Each file_name must correspond to only one fmt, (and only one byte offset - # if defined). - datfmts = {} - for ch in range(n_channels): - if file_names[ch] not in datfmts: - datfmts[file_names[ch]] = formats[ch] - else: - if datfmts[file_names[ch]] != formats[ch]: - raise ValueError( - "Each file_name (dat file) specified must have the same fmt" - ) + if signal_snapshot is not None: + _check_signal_snapshot_cohesion(signal_snapshot) + return + has_channels = self.n_sig > 0 + if not has_channels: + return + for field in sig_write_fields: + if len(getattr(self, field)) != self.n_sig: + raise ValueError( + "The length of field: " + field + " must match field n_sig." + ) + datfmts = {} + for channel in range(self.n_sig): + name = self.file_name[channel] + if name not in datfmts: + datfmts[name] = self.fmt[channel] + elif datfmts[name] != self.fmt[channel]: + raise ValueError( + "Each file_name (dat file) specified must have the same fmt" + ) - datoffsets = {} - if offsets is not None: - # At least one byte offset value exists - for ch in range(n_channels): - if offsets[ch] is None: - continue - if file_names[ch] not in datoffsets: - datoffsets[file_names[ch]] = offsets[ch] - else: - if datoffsets[file_names[ch]] != offsets[ch]: - raise ValueError( - "Each file_name (dat file) specified must have the same byte offset" - ) + datoffsets = {} + if self.byte_offset is not None: + for channel in range(self.n_sig): + offset = self.byte_offset[channel] + if offset is None: + continue + name = self.file_name[channel] + if name not in datoffsets: + datoffsets[name] = offset + elif datoffsets[name] != offset: + raise ValueError( + "Each file_name (dat file) specified must have the same byte offset" + ) # Temporary pre-refactor path for #866 byte comparisons. def _legacy_wr_header_file( diff --git a/src/wfdb/io/_signal.py b/src/wfdb/io/_signal.py index 55e50567..3520e363 100644 --- a/src/wfdb/io/_signal.py +++ b/src/wfdb/io/_signal.py @@ -295,134 +295,36 @@ def check_sig_cohesion(self, write_fields, expanded, *, signal_snapshot=None): N/A """ - # Using list of arrays e_d_signal - if expanded: - if signal_snapshot is None: - # Preserve the direct method's historical defaulting behavior. - spf = self.samps_per_frame - for ch in range(len(spf)): - if spf[ch] is None: - spf[ch] = 1 - else: - spf = [ - channel.samps_per_frame or 1 for channel in signal_snapshot.channels - ] - - # Match the actual signal shape against stated length and number of channels - if self.n_sig != len(self.e_d_signal): - raise ValueError("n_sig does not match the length of e_d_signal") - for ch in range(self.n_sig): - if len(self.e_d_signal[ch]) != spf[ch] * self.sig_len: - raise ValueError( - f"Length of channel {ch} does not match " - f"samps_per_frame[{ch}]*sig_len" - ) + values = self.e_d_signal if expanded else self.d_signal + _check_dat_values( + signal_snapshot, + values, + expanded, + self.sig_len, + n_sig=self.n_sig, + formats=self.fmt, + samps_per_frame=self.samps_per_frame, + ) + if self.n_sig <= 0: + return - # For each channel (if any), make sure the digital format has no values out - # of bounds - for ch in range(self.n_sig): - fmt = ( - signal_snapshot.channels[ch].fmt - if signal_snapshot is not None - else self.fmt[ch] + # Direct callers may request checks of declared values. wr_dats passes + # an empty write_fields list and therefore skips these checks. + signal_field = "e_d_signal" if expanded else "d_signal" + if "checksum" in write_fields: + realchecksum = _digital_checksums(values, expanded=expanded) + if self.checksum != realchecksum: + print(f"The actual checksum of {signal_field} is: ", realchecksum) + raise ValueError( + f"checksum field does not match actual checksum of {signal_field}" ) - dmin, dmax = _digi_bounds(fmt) - - chmin = np.min(self.e_d_signal[ch]) - chmax = np.max(self.e_d_signal[ch]) - if (chmin < dmin) or (chmax > dmax): - raise IndexError( - "Channel " - + str(ch) - + " contain values outside allowed range [" - + str(dmin) - + ", " - + str(dmax) - + "] for fmt " - + str(fmt) - ) - - # Ensure that the checksums and initial value fields match the digital - # signal (if the fields are present) - if self.n_sig > 0: - if "checksum" in write_fields: - realchecksum = _digital_checksums( - self.e_d_signal, expanded=expanded - ) - if self.checksum != realchecksum: - print( - "The actual checksum of e_d_signal is: ", - realchecksum, - ) - raise ValueError( - "checksum field does not match actual checksum of e_d_signal" - ) - if "init_value" in write_fields: - realinit_value = _digital_initial_values( - self.e_d_signal, expanded=expanded - ) - if self.init_value != realinit_value: - print( - "The actual init_value of e_d_signal is: ", - realinit_value, - ) - raise ValueError( - "init_value field does not match actual init_value of e_d_signal" - ) - - # Using uniform d_signal - else: - # Match the actual signal shape against stated length and number of channels - if (self.sig_len, self.n_sig) != self.d_signal.shape: - print("sig_len: ", self.sig_len) - print("n_sig: ", self.n_sig) - print("d_signal.shape: ", self.d_signal.shape) - raise ValueError("sig_len and n_sig do not match shape of d_signal") - - # For each channel (if any), make sure the digital format has no values out - # of bounds - for ch in range(self.n_sig): - fmt = ( - signal_snapshot.channels[ch].fmt - if signal_snapshot is not None - else self.fmt[ch] + if "init_value" in write_fields: + realinit_value = _digital_initial_values(values, expanded=expanded) + if self.init_value != realinit_value: + print(f"The actual init_value of {signal_field} is: ", realinit_value) + raise ValueError( + f"init_value field does not match actual init_value of {signal_field}" ) - dmin, dmax = _digi_bounds(fmt) - - chmin = np.min(self.d_signal[:, ch]) - chmax = np.max(self.d_signal[:, ch]) - if (chmin < dmin) or (chmax > dmax): - raise IndexError( - "Channel " - + str(ch) - + " contain values outside allowed range [" - + str(dmin) - + ", " - + str(dmax) - + "] for fmt " - + str(fmt) - ) - - # Ensure that the checksums and initial value fields match the digital - # signal (if the fields are present) - if self.n_sig > 0: - if "checksum" in write_fields: - realchecksum = _digital_checksums(self.d_signal) - if self.checksum != realchecksum: - print("The actual checksum of d_signal is: ", realchecksum) - raise ValueError( - "checksum field does not match actual checksum of d_signal" - ) - if "init_value" in write_fields: - realinit_value = _digital_initial_values(self.d_signal) - if self.init_value != realinit_value: - print( - "The actual init_value of d_signal is: ", - realinit_value, - ) - raise ValueError( - "init_value field does not match actual init_value of d_signal" - ) def set_p_features(self, do_dac=False, expanded=False): """Set n_sig and sig_len using properties of the physical signal. @@ -2441,11 +2343,28 @@ def _np_dtype(bit_res, discrete): return "float" + str(max(np_res, 16)) -def _check_dat_values(signal_snapshot, values, expanded, sig_len): +def _check_dat_values( + signal_snapshot, + values, + expanded, + sig_len, + *, + n_sig=None, + formats=None, + samps_per_frame=None, +): """Check digital shapes and format bounds from explicit values.""" - n_sig = signal_snapshot.n_channels + if n_sig is None and signal_snapshot is not None: + n_sig = signal_snapshot.n_channels if expanded: - spf = [channel.samps_per_frame or 1 for channel in signal_snapshot.channels] + if signal_snapshot is None: + # Direct Record calls have historically filled this list in place. + spf = samps_per_frame + for ch in range(len(spf)): + if spf[ch] is None: + spf[ch] = 1 + else: + spf = [channel.samps_per_frame or 1 for channel in signal_snapshot.channels] if n_sig != len(values): raise ValueError("n_sig does not match the length of e_d_signal") for ch in range(n_sig): @@ -2460,8 +2379,12 @@ def _check_dat_values(signal_snapshot, values, expanded, sig_len): print("d_signal.shape: ", values.shape) raise ValueError("sig_len and n_sig do not match shape of d_signal") - for ch, channel in enumerate(signal_snapshot.channels): - fmt = channel.fmt + for ch in range(n_sig): + fmt = ( + signal_snapshot.channels[ch].fmt + if signal_snapshot is not None + else formats[ch] + ) dmin, dmax = _digi_bounds(fmt) samples = values[ch] if expanded else values[:, ch] chmin = np.min(samples) diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index cb3f0776..b0a75e4b 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -5625,11 +5625,10 @@ def _apply_flattened_write_fields(writer, expanded): @dataclass(eq=False) -class _WriteModel(BaseRecord, _header.HeaderMixin, _signal.SignalMixin): +class _WriteModel: """Capture one selected value form and current fields for a private write. - Arrays stay shared until conversion needs a new digital array. The model - temporarily retains the encoder mixins until the final #866 cleanup. + Arrays stay shared until conversion needs a new digital array. """ values: "np.ndarray | tuple[np.ndarray, ...]" diff --git a/tests/test_explicit_dat_writing.py b/tests/test_explicit_dat_writing.py index 413edcf7..6695a6f1 100644 --- a/tests/test_explicit_dat_writing.py +++ b/tests/test_explicit_dat_writing.py @@ -4,7 +4,14 @@ import pytest import wfdb -from wfdb.io import _signal +from wfdb.io import _header, _signal +from wfdb.io.record import BaseRecord, _WriteModel + + +def test_write_model_does_not_inherit_record_encoder_mixins(): + """The private model does not regain the legacy writer methods.""" + for legacy_base in (BaseRecord, _header.HeaderMixin, _signal.SignalMixin): + assert not issubclass(_WriteModel, legacy_base) def test_modern_dat_write_does_not_call_signal_mixin(tmp_path, monkeypatch): diff --git a/tests/test_incomplete_record_cohesion.py b/tests/test_incomplete_record_cohesion.py new file mode 100644 index 00000000..af4feefa --- /dev/null +++ b/tests/test_incomplete_record_cohesion.py @@ -0,0 +1,34 @@ +"""Direct cohesion checks retain errors on incomplete Record objects.""" + +import numpy as np +import pytest + +import wfdb + + +@pytest.mark.parametrize("expanded", [False, True]) +def test_signal_cohesion_without_channel_count(expanded): + """An unset n_sig keeps its error and expanded default mutation.""" + record = wfdb.Record( + n_sig=None, + sig_len=2, + fmt=["16"], + samps_per_frame=[None], + d_signal=np.array([[1], [2]], dtype=np.int16), + e_d_signal=[np.array([1, 2], dtype=np.int16)], + ) + message = ( + "n_sig does not match the length of e_d_signal" + if expanded + else "sig_len and n_sig do not match shape of d_signal" + ) + with pytest.raises(ValueError, match=message): + record.check_sig_cohesion([], expanded) + assert record.samps_per_frame == ([1] if expanded else [None]) + + +def test_header_cohesion_without_channel_count(): + """The existing comparison error occurs before reading signal fields.""" + record = wfdb.Record(n_sig=None, file_name=["x.dat"], fmt=["16"]) + with pytest.raises(TypeError, match="'>' not supported"): + record.check_field_cohesion([], ["fmt"])