From d422965fd6279c77620631ed314f96eae779c054 Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Thu, 3 Dec 2026 13:48:41 -0500 Subject: [PATCH] Remove temporary writer parity implementations --- src/wfdb/io/_header.py | 192 ----- src/wfdb/io/_signal.py | 8 +- src/wfdb/io/record.py | 183 ----- src/wfdb/io/signal_values.py | 92 --- src/wfdb/io/signal_write.py | 169 +---- tests/fixtures/writer_bytes/README.md | 4 + .../writer_bytes/legacy_byte_offset/copy.dat | Bin 0 -> 9 bytes .../writer_bytes/legacy_byte_offset/copy.hea | 2 + .../legacy_expanded_digital/copy.hea | 3 + .../legacy_expanded_digital/copy_1.dat | Bin 0 -> 12 bytes .../legacy_expanded_digital/copy_2.dat | 1 + .../writer_bytes/legacy_fixed_master/copy.hea | 3 + .../legacy_fixed_master/part0.dat | Bin 0 -> 6 bytes .../legacy_fixed_master/part0.hea | 2 + .../legacy_fixed_master/part1.dat | Bin 0 -> 6 bytes .../legacy_fixed_master/part1.hea | 2 + .../legacy_physical_calibration/copy.dat | Bin 0 -> 16 bytes .../legacy_physical_calibration/copy.hea | 3 + tests/test_header_encoder_parity.py | 660 ------------------ tests/test_write_model_boundaries.py | 71 ++ tests/test_writer_byte_fixtures.py | 92 +++ 21 files changed, 188 insertions(+), 1299 deletions(-) create mode 100644 tests/fixtures/writer_bytes/legacy_byte_offset/copy.dat create mode 100644 tests/fixtures/writer_bytes/legacy_byte_offset/copy.hea create mode 100644 tests/fixtures/writer_bytes/legacy_expanded_digital/copy.hea create mode 100644 tests/fixtures/writer_bytes/legacy_expanded_digital/copy_1.dat create mode 100644 tests/fixtures/writer_bytes/legacy_expanded_digital/copy_2.dat create mode 100644 tests/fixtures/writer_bytes/legacy_fixed_master/copy.hea create mode 100644 tests/fixtures/writer_bytes/legacy_fixed_master/part0.dat create mode 100644 tests/fixtures/writer_bytes/legacy_fixed_master/part0.hea create mode 100644 tests/fixtures/writer_bytes/legacy_fixed_master/part1.dat create mode 100644 tests/fixtures/writer_bytes/legacy_fixed_master/part1.hea create mode 100644 tests/fixtures/writer_bytes/legacy_physical_calibration/copy.dat create mode 100644 tests/fixtures/writer_bytes/legacy_physical_calibration/copy.hea delete mode 100644 tests/test_header_encoder_parity.py create mode 100644 tests/test_write_model_boundaries.py diff --git a/src/wfdb/io/_header.py b/src/wfdb/io/_header.py index 57c49bfb..b0d83cf7 100644 --- a/src/wfdb/io/_header.py +++ b/src/wfdb/io/_header.py @@ -831,51 +831,6 @@ def wrheader(self, write_dir="", expanded=True, wfdb_archive=None): """ self._write_checked_header(write_dir, expanded, wfdb_archive) - # Temporary pre-refactor path for #866 differential tests. - def _legacy_write_checked_header(self, write_dir, expanded, wfdb_archive): - """Validate and write a header using one channel snapshot.""" - self.check_field("n_sig") - fields = ( - SIGNAL_SPECS.index - if expanded - else SIGNAL_SPECS.index.drop("samps_per_frame") - ) - snapshot = _capture_write_signal_fields(self, fields) - # Get all the fields used to write the header - # sig_write_fields is a dictionary of - # {field_name:required_channels} - rec_write_fields, sig_write_fields = self.get_write_fields(snapshot) - if not expanded: - sig_write_fields.pop("samps_per_frame", None) - - # Check the validity of individual fields used to write the header - # Record specification fields (and comments) - for field in rec_write_fields: - self.check_field(field) - - # Signal specification fields. - for field in sig_write_fields: - self.check_field( - field, - required_channels=sig_write_fields[field], - signal_snapshot=snapshot, - ) - - # Check the cohesion of fields used to write the header - self.check_field_cohesion( - rec_write_fields, list(sig_write_fields), signal_snapshot=snapshot - ) - - # Write the header file using the specified fields - self.wr_header_file( - rec_write_fields, - sig_write_fields, - write_dir, - wfdb_archive, - signal_snapshot=snapshot, - ) - return snapshot - def _write_checked_header(self, write_dir, expanded, wfdb_archive): """Validate and write a header from one explicit field snapshot.""" header_fields = { @@ -1042,86 +997,6 @@ def check_field_cohesion( "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( - self, - rec_write_fields, - sig_write_fields, - write_dir, - wfdb_archive=None, - *, - signal_snapshot=None, - ): - """Write a header file using the specified fields. - - Converts Record attributes into appropriate WFDB format strings. - - Parameters - ---------- - rec_write_fields : list - List of record specification fields to write. - sig_write_fields : dict - Dictionary of signal specification fields to write, values - being equal to a list of channels to write for each field. - write_dir : str - The directory in which to write the header file. - wfdb_archive : WFDBArchive, optional - An open .wfdb archive to write the header file to, instead of - `write_dir`. - - Returns - ------- - N/A - - """ - # Create record specification line - record_line = "" - # Traverse the ordered dictionary - for field in RECORD_SPECS.index: - # If the field is being used, add it with its delimiter - if field in rec_write_fields: - string_field = self.preprocess_header(field) - record_line += RECORD_SPECS.loc[field, "delimiter"] + string_field - # The 'base_counter' field needs to be closed with ')' - if field == "base_counter": - record_line += ")" - - header_lines = [record_line] - - # Create signal specification lines (if any) one channel at a time - n_channels = ( - signal_snapshot.n_channels if signal_snapshot is not None else self.n_sig - ) - if n_channels > 0: - signal_lines = n_channels * [""] - for ch in range(n_channels): - # Traverse the signal fields - for field in SIGNAL_SPECS.index: - # If the field is being used, add each of its - # elements with the delimiter to the appropriate - # line - if field in sig_write_fields and ch in sig_write_fields[field]: - value = ( - getattr(signal_snapshot.channels[ch], field) - if signal_snapshot is not None - else getattr(self, field)[ch] - ) - signal_lines[ch] += SIGNAL_SPECS.loc[field, "delimiter"] + str( - value - ) - # The 'baseline' field needs to be closed with ')' - if field == "baseline": - signal_lines[ch] += ")" - - header_lines += signal_lines - - # Create comment lines (if any) - if "comments" in rec_write_fields: - comment_lines = ["# " + comment for comment in self.comments] - header_lines += comment_lines - - self._write_header_lines(header_lines, write_dir, wfdb_archive) - def wr_header_file( self, rec_write_fields, @@ -1184,23 +1059,6 @@ def set_defaults(self): for field in self.get_write_fields(): self.set_default(field) - # Temporary pre-refactor path for #866 differential tests. - def _legacy_wrheader(self, write_dir="", wfdb_archive=None): - """Write a multi-segment header through the legacy validation path.""" - - # Get all the fields used to write the header - write_fields = self.get_write_fields() - - # Check the validity of individual fields used to write the header - for field in write_fields: - self.check_field(field) - - # Check the cohesion of fields used to write the header - self.check_field_cohesion() - - # Write the header file using the specified fields - self.wr_header_file(write_fields, write_dir, wfdb_archive) - def wrheader(self, write_dir="", wfdb_archive=None): """Write a multi-segment WFDB header file. @@ -1328,56 +1186,6 @@ def check_field_cohesion(self, *, header_fields=None): "The sum of the 'seg_len' fields do not match the 'sig_len' field" ) - # Temporary pre-refactor path for #866 byte comparisons. - def _legacy_wr_header_file(self, write_fields, write_dir, wfdb_archive=None): - """Write a header file using the specified fields. - - Parameters - ---------- - write_fields : list - All the default required fields, the user defined fields, - and their dependencies. - write_dir : str - The output directory in which the header is written. - wfdb_archive : WFDBArchive, optional - An open .wfdb archive to write the header file to, instead of - `write_dir`. - - Returns - ------- - N/A - - """ - # Create record specification line - record_line = "" - # Traverse the ordered dictionary - for field in RECORD_SPECS.index: - # If the field is being used, add it with its delimiter - if field in write_fields: - string_field = self.preprocess_header(field) - record_line += RECORD_SPECS.loc[field, "delimiter"] + string_field - - header_lines = [record_line] - - # Create segment specification lines - segment_lines = self.n_seg * [""] - # For both fields, add each of its elements with the delimiter - # to the appropriate line - for field in SEGMENT_SPECS.index: - for seg_num in range(self.n_seg): - segment_lines[seg_num] += SEGMENT_SPECS.loc[field, "delimiter"] + str( - getattr(self, field)[seg_num] - ) - - header_lines = header_lines + segment_lines - - # Create comment lines (if any) - if "comments" in write_fields: - comment_lines = ["# " + comment for comment in self.comments] - header_lines += comment_lines - - self._write_header_lines(header_lines, write_dir, wfdb_archive) - def wr_header_file( self, write_fields, diff --git a/src/wfdb/io/_signal.py b/src/wfdb/io/_signal.py index 3520e363..ccd7a560 100644 --- a/src/wfdb/io/_signal.py +++ b/src/wfdb/io/_signal.py @@ -927,11 +927,11 @@ def calc_checksum(self, expanded=False): values = self.e_d_signal if expanded else self.d_signal return _digital_checksums(values, expanded=expanded) - # Temporary pre-refactor path for #866 differential tests and direct calls. - def _legacy_wr_dat_files( + # Keep direct Record.wr_dat_files calls working without a write snapshot. + def _write_dat_files_from_record( self, expanded=False, write_dir="", wfdb_archive=None, *, signal_snapshot=None ): - """Write dat files through the legacy field-grouping path.""" + """Write dat files from a Record without a prepared write snapshot.""" # Get the set of dat files to be written, and # the channels to be written to each file. storage = signal_snapshot.storage if signal_snapshot is not None else None @@ -1012,7 +1012,7 @@ def wr_dat_files( """ if signal_snapshot is None: - return self._legacy_wr_dat_files( + return self._write_dat_files_from_record( expanded=expanded, write_dir=write_dir, wfdb_archive=wfdb_archive ) values = self.e_d_signal if expanded else self.d_signal diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index b0a75e4b..d6aec748 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -5104,42 +5104,6 @@ def _get_wanted_channels(wanted_sig_names, record_sig_names, pad=False): # ------------------- /Reading Records -------------------# -def _legacy_write_prepared_files(writer, expanded, write_dir, wfdb_archive): - """Keep the prior checksum path for #866 differential tests.""" - # A layout header with no signal files has only a header to write. - has_signal_files = writer.n_sig > 0 and ( - writer.file_name is None or any(name != "~" for name in writer.file_name) - ) - if has_signal_files and writer.file_name is not None and "~" in writer.file_name: - raise ValueError( - "Writing a record with both null signals (file name '~') and " - "signals with samples is not supported" - ) - - # Keep an omitted checksum, or a supplied checksum equal modulo 65536. - if writer.checksum is not None and has_signal_files: - checksums = writer.calc_checksum(expanded=expanded) - for channel, previous in enumerate(writer.checksum): - if ( - previous is None - or (checksums[channel] - previous) % _signal.CHECKSUM_MODULUS == 0 - ): - checksums[channel] = previous - writer.checksum = checksums - - 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 has_signal_files: - writer.wr_dats( - expanded=expanded, - write_dir=write_dir, - wfdb_archive=archive, - signal_snapshot=snapshot, - ) - - 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 "" @@ -6021,153 +5985,6 @@ def _require_signal_alignment(record: Record, alignment: str | None) -> None: ) -def _legacy_write_record( - path: str | os.PathLike[str], - record: Record, - *, - kind: str | None = None, - layout: str | None = None, - signal_alignment: str | None = None, -) -> None: - """Write the current values of a single-segment ``Record`` to ``path``. - - The destination is a local record stem, a supported cloud URI, or a local - ``.wfdb`` archive path. A selected or flattened record is written as its - current in-memory view, rather than reconstructing the source file layout. - The caller's record is not changed. ``MultiRecord`` writing is not yet - supported by this function; use ``MultiRecord.wrsamp`` for that case. - - Parameters - ---------- - path : str or os.PathLike - Output record stem without ``.hea`` or ``.dat``, or a local ``.wfdb`` - archive path. - record : Record - The loaded, single-segment record to write. - kind : {"physical", "digital"}, optional - Signal kind to write when needed to select one loaded form. - layout : {"uniform", "expanded"}, optional - Signal layout to write when needed to select one loaded form. - signal_alignment : {"aligned", "raw"}, optional - Alignment of the selected values. Required when any channel has - nonzero skew. This does not shift samples or change ``record``. - Either value has no effect when the record has no skew. - - Returns - ------- - None - - Notes - ----- - Digital values are written directly. Physical values are converted to - digital samples and may differ after reading because of quantization. - Missing calibration and header defaults are calculated for physical values. - Digital values require ``fmt``, ``adc_gain``, and ``baseline``. Source - byte offsets are not copied to the new file. This function does not promise - byte-for-byte reproduction of source files. If ``n_sig`` is set, it must - match the selected signal array's channel count. Retained per-channel - header fields must have that same number of entries. A ``ValueError`` - lists all mismatches before any files are written. ``byte_offset`` is - cleared, and ``init_value`` and ``checksum`` are regenerated, so their - input lengths are not checked. If ``n_sig`` is unset, the writer derives - it from the selected array on a copy of the record. If ``sig_len`` is set, - it must match the selected values' frame count; otherwise, the writer - derives it from those values. New nonzero skew on samples already aligned - during reading is rejected before writing files. Writing a record with - nonzero skew requires an explicit alignment choice. - Pass ``signal_alignment="raw"`` after replacing aligned values with raw - values. - To write raw unaligned values with source skew, read with - ``signal_alignment="raw"`` first; changing - that read's skew is rejected because the values may lack the extra samples. - A manually reduced channel list can retain source skew when its values - remain in source order; use ``read_record(..., channels=[...])`` when - selecting channels from a source. A short raw-aligned read cannot - be written with nonzero skew because it lacks the extra tail samples - needed to preserve alignment. Read the full source or clear skew first. - - """ - if isinstance(record, MultiRecord): - raise TypeError("write_record does not yet support MultiRecord") - if not isinstance(record, Record): - raise TypeError("record must be a Record") - if kind not in (None, "physical", "digital"): - raise ValueError("kind must be 'physical' or 'digital'") - if layout not in (None, "uniform", "expanded"): - raise ValueError("layout must be 'uniform' or 'expanded'") - - forms = { - ("physical", "uniform"): "p_signal", - ("digital", "uniform"): "d_signal", - ("physical", "expanded"): "e_p_signal", - ("digital", "expanded"): "e_d_signal", - } - available = [ - (form, field) - for form, field in forms.items() - if getattr(record, field) is not None - and (kind is None or form[0] == kind) - and (layout is None or form[1] == layout) - ] - if not available: - raise ValueError("No loaded signal values match kind and layout") - if len(available) > 1: - raise ValueError("Multiple signal forms are loaded; specify kind and/or layout") - (selected_kind, selected_layout), selected_field = available[0] - - path = os.fspath(path) - archive_path = path if is_archive_path(path) else None - if archive_path is not None and is_cloud_path(path): - raise ValueError("Writing .wfdb archives to cloud storage is unsupported") - stem = path[: -len(".wfdb")] if archive_path is not None else path - write_dir, record_name = _split_path(stem) - if not record_name or "." in record_name: - raise ValueError("path must be a record stem without a file extension") - check_cloud_write(write_dir, archive_path) - - _require_signal_alignment(record, signal_alignment) - if signal_alignment is not None: - record = copy.copy(record) - record._declare_signal_alignment(signal_alignment, selected_field) - snapshot = _snapshot_record_write_channels(record, selected_field, selected_layout) - _validate_record_write_frames(record, selected_field, selected_layout, snapshot) - writable = _prepare_record_for_write(record, record_name, snapshot) - _skew_for_write(writable) - for field in forms.values(): - if field != selected_field: - setattr(writable, field, None) - - if selected_kind == "physical": - if writable.fmt is None and ( - writable.adc_gain is not None or writable.baseline is not None - ): - raise ValueError("fmt is required when adc_gain or baseline is set") - if (writable.adc_gain is None) != (writable.baseline is None): - raise ValueError("adc_gain and baseline must be provided together") - elif selected_kind == "digital": - missing = [ - field - for field in ("fmt", "adc_gain", "baseline") - if getattr(writable, field) is None - ] - if missing: - raise ValueError( - "Digital values require " + ", ".join(missing) + " to write" - ) - if getattr(writable, "source_segments", None) is None: - writable.set_d_features( - do_adc=selected_kind == "physical", - expanded=selected_layout == "expanded", - ) - writable.set_defaults() - - writable.wrsamp( - expanded=selected_layout == "expanded", - write_dir=write_dir, - wfdb_archive=archive_path, - ) - - def write_record( path: str | os.PathLike[str], record: Record, diff --git a/src/wfdb/io/signal_values.py b/src/wfdb/io/signal_values.py index 5f36082f..e985e557 100644 --- a/src/wfdb/io/signal_values.py +++ b/src/wfdb/io/signal_values.py @@ -180,98 +180,6 @@ def to_legacy_record(self): ) return copy.deepcopy(source) - def _legacy_write( - self, - path: str | os.PathLike, - *, - signal_alignment: str | None = None, - formats: str | tuple[str, ...] | list[str] | None = None, - ) -> None: - """Write this selected view under a new record name. - - ``path`` is a local record stem, a supported writable cloud URI, or - a local ``.wfdb`` archive path. The destination directory must exist - for a local record stem. This method prepares a private record from - the current metadata and selected values, then calls the existing - writer. Preparation shares the loaded signal arrays; encoding may - allocate converted arrays. The read result and its arrays are unchanged. - - The written record preserves the selected frames and channels. Physical - values are subject to encoding precision, and a format change can - change digital missing-value markers. The source file layout and bytes - are not preserved. Flattened multi-segment data is written as one - record. When a selected channel has nonzero skew, pass - ``signal_alignment="aligned"`` for aligned values or ``"raw"`` for - values that retain file skew. Already applied skew is not applied again. - A short read made with ``signal_alignment="raw"`` cannot be written with - nonzero skew because the selected arrays omit tail samples needed - to preserve the aligned view. - - Parameters - ---------- - path : str or os.PathLike - Destination record stem or local ``.wfdb`` archive path. The - basename must contain only letters, digits, hyphens, or - underscores. - signal_alignment : {"aligned", "raw"}, optional - Alignment of the selected values. Required when any channel has - nonzero skew. This does not shift samples. Either value has no - effect when the record has no skew. - formats : str or sequence of str, optional - Target storage format for all channels or one format per channel. - Required for digital channels whose loaded source segments do not - establish one format. Values must fit the target format, excluding - its reserved missing-sample marker. - """ - ( - destination, - directory, - name, - archive, - expanded, - selected_formats, - source, - ) = _prepare_signal_read_write(self, path, formats) - from wfdb.io.record import ( - _prepare_record_for_write, - _require_signal_alignment, - _snapshot_record_write_channels, - ) - - field = ("e_" if expanded else "") + ( - "p_signal" if self.signals.kind == "physical" else "d_signal" - ) - values = self.signals.values - if self.signals.kind == "digital": - values = _digital_values_for_write(values, selected_formats, expanded) - setattr(source, field, list(values) if expanded else values) - _require_signal_alignment(source, signal_alignment) - if signal_alignment is not None: - source._declare_signal_alignment(signal_alignment, field) - snapshot = _snapshot_record_write_channels( - source, field, "expanded" if expanded else "uniform" - ) - record = _prepare_record_for_write(source, name, snapshot) - if ( - self.signals.kind == "physical" - and all( - field is not None and all(value is not None for value in field) - for field in (record.adc_gain, record.baseline) - ) - and all(fmt is not None for fmt in selected_formats) - ): - _validate_physical_values_for_write( - values, - selected_formats, - record.adc_gain, - record.baseline, - expanded, - ) - if archive: - record.wrsamp(expanded=expanded, wfdb_archive=destination) - else: - record.wrsamp(expanded=expanded, write_dir=directory) - def write( self, path: str | os.PathLike, diff --git a/src/wfdb/io/signal_write.py b/src/wfdb/io/signal_write.py index cf3195fc..7603d9e1 100644 --- a/src/wfdb/io/signal_write.py +++ b/src/wfdb/io/signal_write.py @@ -7,10 +7,7 @@ import numpy as np from wfdb.io._signal import WRITABLE_FMTS -from wfdb.io.signal_values import ( - _digital_values_for_write, - _validate_physical_values_for_write, -) +from wfdb.io.signal_values import _digital_values_for_write def _channels(values, kind, samples_per_frame): @@ -182,170 +179,6 @@ def _validate_write_signals_arguments( ) -def _legacy_write_signals( - path, - values, - *, - fs, - kind, - formats, - channel_names, - units, - samples_per_frame=None, - adc_gain=None, - baseline=None, - missing=None, - base_date=None, - base_time=None, - comments=None, -) -> None: - """Write a single-segment WFDB record from physical or digital arrays. - - A 2D array has one sample per channel per frame. A sequence of 1D arrays - has expanded channels and requires ``samples_per_frame``. Storage formats - and value kind are explicit; neither is inferred from the values. Physical - NaN means missing, while digital masked arrays carry missing positions. - Plain digital arrays require ``missing="none"``. - - Parameters - ---------- - path : str or os.PathLike - Destination record stem, writable cloud URI, or local ``.wfdb`` archive. - values : ndarray or sequence of ndarray - Uniform 2D values or one expanded 1D array per channel. - fs : int or float - Base sampling frequency, in frames per second. - kind : {"physical", "digital"} - Interpretation of the values. The input dtype must match this kind; - physical values are converted to digital samples for storage. - formats : str or sequence of str - WFDB storage format for all channels or one per channel. - channel_names, units : sequence of str - Names and physical units of the channels. Names must be nonempty and - unique. Supply new names when writing data read from a file with blank - or duplicate names. - samples_per_frame : sequence of int, optional - Required for expanded values; rejected for uniform values. - adc_gain : sequence of float, optional - Positive gain per channel. Required for digital values. For physical - values, supply it together with ``baseline`` or omit both to calculate - calibration from the data. Separate chunks can get different calibration. - baseline : sequence of int, optional - Digital baseline per channel, paired with ``adc_gain``. - missing : {"none"}, optional - Required for plain digital arrays to declare that every value is valid. - Omit for masked digital arrays and physical arrays. To supply a separate - mask, pass ``np.ma.array(values, mask=mask)`` as ``values``. For expanded - values with a mix of masked and plain channels, ``"none"`` declares - only the plain channels to have no missing samples. - base_date : datetime.date, optional - Record's starting date. - base_time : datetime.time, optional - Record's starting time. - comments : sequence of str, optional - Header comments. - - Returns - ------- - None - The input arrays are not modified. - """ - from wfdb.io.record import Record, write_record - - ( - arrays, - expanded, - n_frames, - spf, - formats, - names, - units, - adc_gain, - baseline, - comments, - ) = _validate_write_signals_arguments( - values, - fs, - kind, - formats, - channel_names, - units, - samples_per_frame, - adc_gain, - baseline, - missing, - base_date, - base_time, - comments, - ) - n_channels = len(arrays) - - file_names = ( - ["signal.dat"] * n_channels - if len(set(formats)) == 1 - else [f"channel_{index}.dat" for index in range(n_channels)] - ) - record = Record( - record_name="signal", - fs=fs, - n_sig=n_channels, - sig_len=n_frames, - sig_name=names, - units=units, - fmt=formats, - file_name=file_names, - samps_per_frame=list(spf) if expanded else None, - adc_gain=adc_gain, - baseline=baseline, - base_date=base_date, - base_time=base_time, - comments=comments, - ) - if kind == "digital": - selected = ( - values - if all(isinstance(array, np.ma.MaskedArray) for array in arrays) - else ( - tuple( - array - if isinstance(array, np.ma.MaskedArray) - else np.ma.array(array, copy=False) - for array in values - ) - if expanded - else np.ma.array(values, copy=False) - ) - ) - encoded = _digital_values_for_write(selected, formats, expanded) - if expanded: - record.e_d_signal = list(encoded) - else: - record.d_signal = encoded - else: - if expanded: - record.e_p_signal = list(values) - else: - record.p_signal = values - if adc_gain is not None: - _validate_physical_values_for_write( - values, formats, adc_gain, baseline, expanded - ) - record.set_d_features(do_adc=True, expanded=expanded) - if adc_gain is None: - _validate_physical_values_for_write( - values, formats, record.adc_gain, record.baseline, expanded - ) - record.e_p_signal = None - record.p_signal = None - - write_record( - os.fspath(path), - record, - kind="digital", - layout="expanded" if expanded else "uniform", - ) - - def write_signals( path, values, diff --git a/tests/fixtures/writer_bytes/README.md b/tests/fixtures/writer_bytes/README.md index 59bfb097..b68eb99b 100644 --- a/tests/fixtures/writer_bytes/README.md +++ b/tests/fixtures/writer_bytes/README.md @@ -16,6 +16,10 @@ Additional cases pin counter frequency, fractional sampling frequency, base counter, comments, formats 32/508/516/524 in both layouts, and equivalent or stale declared checksums. Fixed error tests in the same test module cover omitted and partial checksums and invalid single- and multi-segment headers. +The `legacy_*` cases pin the public `Record.wrsamp` path for physical values +with calculated calibration, expanded digital values, and a byte offset, plus +the public `MultiRecord.wrsamp` path for a fixed-layout master. They were +generated with the same 5.17.0 commit as the other cases. They were generated on this branch, before any source changes, with: diff --git a/tests/fixtures/writer_bytes/legacy_byte_offset/copy.dat b/tests/fixtures/writer_bytes/legacy_byte_offset/copy.dat new file mode 100644 index 0000000000000000000000000000000000000000..86d163f4512192bc7838f701b0bcbca0087cb648 GIT binary patch literal 9 QcmZQzU|?imVqj(f0012T2LJ#7 literal 0 HcmV?d00001 diff --git a/tests/fixtures/writer_bytes/legacy_byte_offset/copy.hea b/tests/fixtures/writer_bytes/legacy_byte_offset/copy.hea new file mode 100644 index 00000000..b59ac969 --- /dev/null +++ b/tests/fixtures/writer_bytes/legacy_byte_offset/copy.hea @@ -0,0 +1,2 @@ +copy 1 125 3 +copy.dat 16+3 200.0(0)/mV 16 0 1 6 0 I diff --git a/tests/fixtures/writer_bytes/legacy_expanded_digital/copy.hea b/tests/fixtures/writer_bytes/legacy_expanded_digital/copy.hea new file mode 100644 index 00000000..0c1a984a --- /dev/null +++ b/tests/fixtures/writer_bytes/legacy_expanded_digital/copy.hea @@ -0,0 +1,3 @@ +copy 2 125 3 +copy_1.dat 16x2 200.0(0)/mV 16 0 1 21 0 I +copy_2.dat 212x1 100.0(0)/mV 12 0 -1 65530 0 II diff --git a/tests/fixtures/writer_bytes/legacy_expanded_digital/copy_1.dat b/tests/fixtures/writer_bytes/legacy_expanded_digital/copy_1.dat new file mode 100644 index 0000000000000000000000000000000000000000..a6afd2976100cf1b675f6fa994993fc58b34735c GIT binary patch literal 12 TcmZQ%U}9iqU}0coU}FFP0DJ%z literal 0 HcmV?d00001 diff --git a/tests/fixtures/writer_bytes/legacy_expanded_digital/copy_2.dat b/tests/fixtures/writer_bytes/legacy_expanded_digital/copy_2.dat new file mode 100644 index 00000000..b80fe361 --- /dev/null +++ b/tests/fixtures/writer_bytes/legacy_expanded_digital/copy_2.dat @@ -0,0 +1 @@ +ÿÿþý \ No newline at end of file diff --git a/tests/fixtures/writer_bytes/legacy_fixed_master/copy.hea b/tests/fixtures/writer_bytes/legacy_fixed_master/copy.hea new file mode 100644 index 00000000..8b1adeeb --- /dev/null +++ b/tests/fixtures/writer_bytes/legacy_fixed_master/copy.hea @@ -0,0 +1,3 @@ +copy/2 1 100 6 +part0 3 +part1 3 diff --git a/tests/fixtures/writer_bytes/legacy_fixed_master/part0.dat b/tests/fixtures/writer_bytes/legacy_fixed_master/part0.dat new file mode 100644 index 0000000000000000000000000000000000000000..ca0ca0c3192c1cfa47d6f6c18f3d190cd823bf5d GIT binary patch literal 6 NcmZQzU}Ruo0000E00aO4 literal 0 HcmV?d00001 diff --git a/tests/fixtures/writer_bytes/legacy_fixed_master/part0.hea b/tests/fixtures/writer_bytes/legacy_fixed_master/part0.hea new file mode 100644 index 00000000..362efe3f --- /dev/null +++ b/tests/fixtures/writer_bytes/legacy_fixed_master/part0.hea @@ -0,0 +1,2 @@ +part0 1 100 3 +part0.dat 16 200.0(0)/mV 16 0 0 3 0 I diff --git a/tests/fixtures/writer_bytes/legacy_fixed_master/part1.dat b/tests/fixtures/writer_bytes/legacy_fixed_master/part1.dat new file mode 100644 index 0000000000000000000000000000000000000000..6007a59200c87b3fa362d9a4d8022bc661d7aad9 GIT binary patch literal 6 NcmZQ%U}9iq0000Q00#g7 literal 0 HcmV?d00001 diff --git a/tests/fixtures/writer_bytes/legacy_fixed_master/part1.hea b/tests/fixtures/writer_bytes/legacy_fixed_master/part1.hea new file mode 100644 index 00000000..2e2fcb56 --- /dev/null +++ b/tests/fixtures/writer_bytes/legacy_fixed_master/part1.hea @@ -0,0 +1,2 @@ +part1 1 100 3 +part1.dat 16 200.0(0)/mV 16 0 1 6 0 I diff --git a/tests/fixtures/writer_bytes/legacy_physical_calibration/copy.dat b/tests/fixtures/writer_bytes/legacy_physical_calibration/copy.dat new file mode 100644 index 0000000000000000000000000000000000000000..9edde1dca78331bf923a57d2f674038bb570006e GIT binary patch literal 16 XcmZQ<_%F|JfU$w0f#Jdb`hWERGs6cw literal 0 HcmV?d00001 diff --git a/tests/fixtures/writer_bytes/legacy_physical_calibration/copy.hea b/tests/fixtures/writer_bytes/legacy_physical_calibration/copy.hea new file mode 100644 index 00000000..861df6f4 --- /dev/null +++ b/tests/fixtures/writer_bytes/legacy_physical_calibration/copy.hea @@ -0,0 +1,3 @@ +copy 2 125 4 +copy.dat 16 163835.0(-32767)/mV 16 0 -32767 16384 0 I +copy.dat 16 81916.66666666667(-8192)/mV 16 0 8191 65534 0 II diff --git a/tests/test_header_encoder_parity.py b/tests/test_header_encoder_parity.py deleted file mode 100644 index 810c367a..00000000 --- a/tests/test_header_encoder_parity.py +++ /dev/null @@ -1,660 +0,0 @@ -"""Temporary byte comparisons while both writer paths exist.""" - -import copy -from datetime import date, time -from pathlib import Path - -import numpy as np -import pytest - -import wfdb -from wfdb.io import _header, _signal -from wfdb.io import record as record_module -from wfdb.io import signal_write as signal_write_module -from wfdb.io.signal_values import SignalRead - -HEADERS = tuple(sorted(Path("sample-data").rglob("*.hea"))) -EXPECTED_UNREADABLE = { - Path("sample-data/1003.hea"): FileNotFoundError, - Path("sample-data/multi-segment/p000878/3269321_layout.hea"): ValueError, - Path("sample-data/multi-segment/s00001/3248903_layout.hea"): ValueError, - Path("sample-data/multi-segment/s00001/3975656_layout.hea"): ValueError, - Path("sample-data/multi-segment/s00001/s00001-2896-10-09-01-56n.hea"): ValueError, - Path("sample-data/multi-segment/s25047/3234460_0002.hea"): ValueError, - Path("sample-data/multi-segment/s25047/3234460_0005.hea"): ValueError, - Path("sample-data/multi-segment/s25047/3234460_0007.hea"): ValueError, - Path("sample-data/multi-segment/s25047/3234460_0009.hea"): ValueError, - Path("sample-data/multi-segment/s25047/3234460_0011.hea"): ValueError, - Path("sample-data/multi-segment/s25047/3234460_layout.hea"): ValueError, -} -LEGACY_WRITE_PATCHES = ( - (wfdb, "write_signals", signal_write_module._legacy_write_signals), - ( - signal_write_module, - "write_signals", - signal_write_module._legacy_write_signals, - ), - (SignalRead, "write", SignalRead._legacy_write), - (wfdb, "write_record", record_module._legacy_write_record), - (record_module, "write_record", record_module._legacy_write_record), - ( - _signal.SignalMixin, - "wr_dat_files", - _signal.SignalMixin._legacy_wr_dat_files, - ), - ( - record_module, - "_write_prepared_files", - record_module._legacy_write_prepared_files, - ), - ( - _header.HeaderMixin, - "_write_checked_header", - _header.HeaderMixin._legacy_write_checked_header, - ), - ( - _header.HeaderMixin, - "wr_header_file", - _header.HeaderMixin._legacy_wr_header_file, - ), - ( - _header.MultiHeaderMixin, - "wrheader", - _header.MultiHeaderMixin._legacy_wrheader, - ), - ( - _header.MultiHeaderMixin, - "wr_header_file", - _header.MultiHeaderMixin._legacy_wr_header_file, - ), -) -READABLE_MASTER_HEADERS = ( - "sample-data/multi-segment/041s/041s", - "sample-data/multi-segment/fixed1/v102s", - "sample-data/multi-segment/s00001/s00001-2896-10-09-01-56", - "sample-data/multi-segment/s00001/s00001-2896-10-10-00-31", - "sample-data/multi-segment/s25047/s25047-2704-05-04-10-44", -) - - -def _files(root): - """Capture every file a write produced, including a partial write.""" - return { - path.relative_to(root).as_posix(): path.read_bytes() - for path in root.rglob("*") - if path.is_file() - } - - -def _compare_writes(tmp_path, monkeypatch, write, legacy_patches=LEGACY_WRITE_PATCHES): - """Write through each serializer and compare outcomes and all file bytes.""" - outcomes = [] - for legacy in (True, False): - root = tmp_path / ("legacy" if legacy else "explicit") - root.mkdir() - with monkeypatch.context() as patch: - if legacy: - for owner, name, implementation in legacy_patches: - patch.setattr(owner, name, implementation) - try: - write(root / "copy") - except Exception as error: - outcome = (type(error), str(error).replace(str(root), "")) - else: - outcome = None - outcomes.append((outcome, _files(root))) - assert outcomes[0] == outcomes[1] - return outcomes[0] - - -@pytest.mark.parametrize("header", HEADERS, ids=lambda path: str(path)) -@pytest.mark.parametrize("kind", ["physical", "digital"]) -@pytest.mark.parametrize("layout", ["uniform", "expanded"]) -def test_sample_record_bytes_match_legacy_header_serializer( - tmp_path, monkeypatch, header, kind, layout -): - """Every readable sample header writes identical files in both paths.""" - try: - source = wfdb.read_record( - header.with_suffix(""), - stop=8, - kind=kind, - layout=layout, - combine_segments=True, - ) - except (FileNotFoundError, ValueError) as error: - expected = EXPECTED_UNREADABLE.get(header) - if expected is None or not isinstance(error, expected): - raise - pytest.skip(f"known unreadable sample: {type(error).__name__}") - assert header not in EXPECTED_UNREADABLE, "update the expected unreadable list" - if not isinstance(source, wfdb.Record) or source.n_sig == 0: - pytest.skip("sample has no loaded signal values") - - def write(path): - wfdb.write_record(path, source, signal_alignment="aligned") - - _compare_writes(tmp_path, monkeypatch, write) - - -def test_record_line_details_match_legacy_header_serializer(tmp_path, monkeypatch): - """Counter, fractional frequency, date, time, and comments keep their bytes.""" - record = wfdb.Record( - record_name="source", - n_sig=1, - fs=128.0, - counter_freq=250.25, - base_counter=12, - sig_len=3, - base_time=time(8, 26, 4, 120000), - base_date=date(2020, 2, 3), - comments=["record comment"], - sig_name=["I"], - units=["mV"], - fmt=["16"], - adc_gain=[200.0], - baseline=[0], - d_signal=np.array([[1], [2], [3]], dtype="int16"), - ) - - def write(path): - wfdb.write_record(path, record) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert "copy.hea" in files - - -def test_masked_mixed_formats_match_legacy_header_serializer(tmp_path, monkeypatch): - """The array writer preserves both format-specific missing markers.""" - values = np.ma.array( - [[1, 2], [0, 0], [3, 4]], - mask=[[False, False], [True, True], [False, False]], - dtype="int16", - ) - - def write(path): - wfdb.write_signals( - path, - values, - fs=125, - kind="digital", - formats=["16", "212"], - channel_names=["I", "II"], - units=["mV", "mV"], - adc_gain=[200.0, 200.0], - baseline=[0, 0], - ) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert "copy.hea" in files - - -@pytest.mark.parametrize("calibration", ["explicit", "inferred"]) -def test_physical_array_writer_matches_legacy(tmp_path, monkeypatch, calibration): - """Physical conversion and missing values keep their output bytes.""" - values = np.array([[0.1, 0.2], [np.nan, -0.3], [0.4, 0.5]]) - - def write(path): - kwargs = ( - {"adc_gain": [200.0, 100.0], "baseline": [0, 0]} - if calibration == "explicit" - else {} - ) - wfdb.write_signals( - path, - values, - fs=125, - kind="physical", - formats=["16", "24"], - channel_names=["I", "II"], - units=["mV", "mV"], - **kwargs, - ) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert len([name for name in files if name.endswith(".dat")]) == 2 - - -@pytest.mark.parametrize("fmt", _signal.WRITABLE_FMTS) -@pytest.mark.parametrize("expanded", [False, True]) -def test_all_dat_formats_match_legacy_write(tmp_path, monkeypatch, fmt, expanded): - """Both array layouts produce identical bytes for every writable format.""" - uniform = np.array([[1, -2], [3, 4], [-5, 6], [7, -8]], dtype=np.int16) - values = [uniform[:, 0].repeat(2), uniform[:, 1].repeat(2)] if expanded else uniform - - def write(path): - wfdb.write_signals( - path, - values, - fs=125, - kind="digital", - formats=fmt, - channel_names=["I", "II"], - units=["mV", "mV"], - samples_per_frame=[2, 2] if expanded else None, - adc_gain=[200.0, 200.0], - baseline=[0, 0], - missing="none", - ) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert "copy.dat" in files - - -def test_expanded_mixed_formats_and_masks_match_legacy_write(tmp_path, monkeypatch): - """Different sample rates and missing markers retain per-file bytes.""" - values = [ - np.ma.array([1, 2, 3, 4], mask=[0, 1, 0, 0], dtype=np.int16), - np.ma.array([-1, -2], mask=[0, 1], dtype=np.int16), - ] - - def write(path): - wfdb.write_signals( - path, - values, - fs=125, - kind="digital", - formats=["16", "212"], - channel_names=["I", "II"], - units=["mV", "mV"], - samples_per_frame=[2, 1], - adc_gain=[200.0, 200.0], - baseline=[0, 0], - ) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert len([name for name in files if name.endswith(".dat")]) == 2 - - -def test_dat_byte_offset_matches_legacy_write(tmp_path, monkeypatch): - """A direct Record write retains the declared leading bytes.""" - - def write(path): - record = wfdb.Record( - record_name="copy", - n_sig=1, - fs=125, - sig_len=3, - sig_name=["I"], - units=["mV"], - fmt=["16"], - adc_gain=[200.0], - baseline=[0], - d_signal=np.array([[1], [2], [3]], dtype=np.int16), - ) - record.set_d_features() - record.byte_offset = [3] - record.set_defaults() - record.wrsamp(write_dir=str(path.parent)) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert files["copy.dat"].startswith(b"\0\0\0") - - -@pytest.mark.parametrize("expanded", [False, True]) -@pytest.mark.parametrize("declaration", ["omitted", "partial", "equivalent", "stale"]) -def test_declared_checksums_match_legacy_write( - tmp_path, monkeypatch, expanded, declaration -): - """Checksum declarations keep the legacy output or error.""" - uniform = np.array([[1, -2], [3, 4], [-5, 6]], dtype=np.int16) - - def write(path): - record = wfdb.Record( - record_name="copy", - n_sig=2, - fs=125, - sig_len=3, - sig_name=["I", "II"], - units=["mV", "mV"], - fmt=["16", "16"], - adc_gain=[200.0, 200.0], - baseline=[0, 0], - samps_per_frame=[1, 1], - e_d_signal=[uniform[:, 0].copy(), uniform[:, 1].copy()] - if expanded - else None, - d_signal=None if expanded else uniform.copy(), - ) - record.set_d_features(expanded=expanded) - calculated = record.checksum - record.checksum = { - "omitted": None, - "partial": [None, calculated[1]], - "equivalent": [calculated[0] + 65536, calculated[1] - 65536], - "stale": [calculated[0] + 1, calculated[1] - 1], - }[declaration] - record.set_defaults() - record.wrsamp(expanded=expanded, write_dir=str(path.parent)) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - if declaration in ("omitted", "partial"): - assert outcome is not None - assert files == {} - else: - assert outcome is None - assert "copy.hea" in files - header = wfdb.rdheader(str(tmp_path / "explicit" / "copy")) - assert header.init_value == [1, -2] - assert header.checksum == ( - [131071, -65528] if declaration == "equivalent" else [65535, 8] - ) - - -def test_modern_write_does_not_call_record_checksum_method(tmp_path, monkeypatch): - """The write path calculates checksums from explicit digital arrays.""" - source = wfdb.read_record( - "sample-data/100", stop=8, kind="digital", layout="uniform" - ) - - def fail_if_called(*args, **kwargs): - raise AssertionError("Record.calc_checksum was called") - - monkeypatch.setattr(wfdb.Record, "calc_checksum", fail_if_called) - wfdb.write_record(tmp_path / "copy", source) - assert (tmp_path / "copy.hea").exists() - - -@pytest.mark.parametrize("kind", ["physical", "digital"]) -@pytest.mark.parametrize("layout", ["uniform", "expanded"]) -def test_full_flattened_multi_segment_bytes_match(tmp_path, monkeypatch, kind, layout): - """A full-length flattened multi-segment write has identical bytes.""" - source = wfdb.read_record( - "sample-data/multi-segment/041s/041s", kind=kind, layout=layout - ) - - def write(path): - wfdb.write_record(path, source, signal_alignment="aligned") - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert "copy.hea" in files - - -@pytest.mark.parametrize("kind", ["physical", "digital"]) -@pytest.mark.parametrize("layout", ["uniform", "expanded"]) -def test_selected_skewed_record_bytes_match_legacy_write( - tmp_path, monkeypatch, kind, layout -): - """Selected, aligned skewed values keep their exact written bytes.""" - source = wfdb.read_record( - "sample-data/100skew", - stop=20, - channels=[1, 0], - kind=kind, - layout=layout, - ) - - def write(path): - wfdb.write_record(path, source, signal_alignment="aligned") - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert "copy.hea" in files - - -def test_short_raw_skew_write_error_matches_legacy(tmp_path, monkeypatch): - """An incomplete raw read fails before either path creates a file.""" - source = wfdb.read_record( - "sample-data/100skew", - stop=20, - kind="digital", - layout="uniform", - signal_alignment="raw", - ) - - def write(path): - wfdb.write_record(path, source, signal_alignment="raw") - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is not None - assert files == {} - - -def test_write_record_does_not_create_a_record_adapter(tmp_path, monkeypatch): - """The modern writer converts to private model state at the boundary.""" - source = wfdb.read_record( - "sample-data/100", stop=8, kind="digital", layout="uniform" - ) - - def fail_if_called(*args, **kwargs): - raise AssertionError("legacy Record write adapter was called") - - monkeypatch.setattr(record_module, "_prepare_record_for_write", fail_if_called) - monkeypatch.setattr(wfdb.Record, "wrsamp", fail_if_called) - wfdb.write_record(tmp_path / "copy", source) - assert (tmp_path / "copy.hea").exists() - - -def test_signal_read_write_bytes_match_legacy_header_serializer(tmp_path, monkeypatch): - """SignalRead.write uses the same header bytes through either path.""" - read = wfdb.read_signals( - "sample-data/100", kind="digital", layout="uniform", stop=32 - ) - - def write(path): - read.write(path) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert "copy.hea" in files - - -@pytest.mark.parametrize("kind", ["physical", "digital"]) -@pytest.mark.parametrize("layout", ["uniform", "expanded"]) -def test_selected_signal_read_model_bytes_match_legacy( - tmp_path, monkeypatch, kind, layout -): - """SignalRead writes selected skewed channels identically.""" - source = wfdb.read_signals( - "sample-data/100skew", - stop=20, - channels=[1, 0], - kind=kind, - layout=layout, - ) - - def write(path): - source.write(path, signal_alignment="aligned") - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert "copy.hea" in files - - -def test_signal_read_masked_write_matches_legacy(tmp_path, monkeypatch): - """A masked digital read retains gaps through both write paths.""" - source_values = np.ma.array( - [[1, 2], [0, 0], [3, 4]], - mask=[[False, False], [True, True], [False, False]], - dtype=np.int16, - ) - wfdb.write_signals( - tmp_path / "source", - source_values, - fs=125, - kind="digital", - formats=["16", "212"], - channel_names=["I", "II"], - units=["mV", "mV"], - adc_gain=[200.0, 200.0], - baseline=[0, 0], - ) - source = wfdb.read_signals(tmp_path / "source", kind="digital", layout="uniform") - - def write(path): - source.write(path) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert len([name for name in files if name.endswith(".dat")]) == 2 - - -def test_signal_read_write_does_not_call_record_writer(tmp_path, monkeypatch): - """SignalRead sends selected values through private write state.""" - source = wfdb.read_signals( - "sample-data/100", stop=8, kind="digital", layout="uniform" - ) - - def fail_if_called(*args, **kwargs): - raise AssertionError("Record.wrsamp was called") - - monkeypatch.setattr(wfdb.Record, "wrsamp", fail_if_called) - source.write(tmp_path / "copy") - assert (tmp_path / "copy.hea").exists() - - -def test_write_signals_does_not_construct_a_record(tmp_path, monkeypatch): - """The array writer creates private write state directly.""" - - def fail_if_called(*args, **kwargs): - raise AssertionError("Record constructor was called") - - monkeypatch.setattr(record_module, "Record", fail_if_called) - wfdb.write_signals( - tmp_path / "copy", - np.array([[1], [2], [3]], dtype=np.int16), - fs=125, - kind="digital", - formats="16", - channel_names=["I"], - units=["mV"], - adc_gain=[200.0], - baseline=[0], - missing="none", - ) - assert (tmp_path / "copy.hea").exists() - - -def test_multi_segment_header_matches_legacy_serializer(tmp_path, monkeypatch): - """A master header and its segment files remain byte-identical.""" - - def write(path): - segments = [] - for index in range(2): - segment = wfdb.Record( - record_name=f"part{index}", - n_sig=1, - fs=100, - sig_len=3, - sig_name=["I"], - units=["mV"], - fmt=["16"], - adc_gain=[200.0], - baseline=[0], - d_signal=np.array([[index], [index + 1], [index + 2]]), - ) - segment.set_d_features() - segment.set_defaults() - segments.append(segment) - multi = wfdb.MultiRecord( - record_name="copy", - n_sig=1, - fs=100, - sig_len=6, - seg_name=[segment.record_name for segment in segments], - seg_len=[3, 3], - segments=segments, - layout="fixed", - ) - multi.wrsamp(write_dir=str(path.parent)) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert "copy.hea" in files - - -@pytest.mark.parametrize("source_path", READABLE_MASTER_HEADERS) -def test_unflattened_sample_master_bytes_match(tmp_path, monkeypatch, source_path): - """Real master headers, layout segments, and null segments keep their bytes.""" - source = wfdb.read_record( - source_path, kind="digital", layout="uniform", combine_segments=False - ) - assert isinstance(source, wfdb.MultiRecord) - - def write(path): - writable = copy.deepcopy(source) - writable.record_name = "copy" - for segment in writable.segments: - if segment is None or segment.file_name is None: - continue - groups = { - name: f"{segment.record_name}_{index}.dat" - for index, name in enumerate(dict.fromkeys(segment.file_name)) - if name != "~" - } - segment.file_name = [groups.get(name, name) for name in segment.file_name] - writable.wrsamp(write_dir=str(path.parent)) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert "copy.hea" in files - - -def test_incomplete_variable_layout_master_header_bytes_match(tmp_path, monkeypatch): - """An available master header can be compared without missing segments.""" - source = wfdb.rdheader("sample-data/multi-segment/p000878/p000878-2137-10-26-16-57") - assert isinstance(source, wfdb.MultiRecord) - - def write(path): - writable = copy.copy(source) - writable.record_name = "copy" - writable.wrheader(write_dir=str(path.parent)) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is None - assert set(files) == {"copy.hea"} - - -@pytest.mark.parametrize( - ("field", "value"), - [ - ("record_name", "bad name"), - ("fs", -1), - ("sig_len", -1), - ("fmt", ["invalid", "212"]), - ("sig_name", [" I", "II"]), - ], -) -def test_invalid_single_header_errors_match_legacy(tmp_path, monkeypatch, field, value): - """Invalid record and signal fields fail identically before writing.""" - - def write(path): - record = wfdb.rdheader("sample-data/100") - record.record_name = "copy" - setattr(record, field, value) - record.wrheader(write_dir=str(path.parent)) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is not None - assert files == {} - - -@pytest.mark.parametrize( - ("field", "value"), - [ - ("record_name", "bad name"), - ("fs", -1), - ("n_seg", -1), - ("seg_len", [1]), - ("seg_name", ["bad name"]), - ], -) -def test_invalid_multi_header_errors_match_legacy(tmp_path, monkeypatch, field, value): - """Invalid master fields fail identically before writing.""" - - def write(path): - record = wfdb.rdheader("sample-data/multi-segment/041s/041s") - record.record_name = "copy" - setattr(record, field, value) - record.wrheader(write_dir=str(path.parent)) - - outcome, files = _compare_writes(tmp_path, monkeypatch, write) - assert outcome is not None - assert files == {} diff --git a/tests/test_write_model_boundaries.py b/tests/test_write_model_boundaries.py new file mode 100644 index 00000000..22ab48f8 --- /dev/null +++ b/tests/test_write_model_boundaries.py @@ -0,0 +1,71 @@ +"""Modern writers do not use public Record methods as adapters.""" + +import numpy as np + +import wfdb +from wfdb.io import record as record_module + + +def test_modern_write_does_not_call_record_checksum_method(tmp_path, monkeypatch): + """Checksum calculation uses explicit digital arrays.""" + source = wfdb.read_record( + "sample-data/100", stop=8, kind="digital", layout="uniform" + ) + + def fail_if_called(*_args, **_kwargs): + raise AssertionError("Record.calc_checksum was called") + + monkeypatch.setattr(wfdb.Record, "calc_checksum", fail_if_called) + wfdb.write_record(tmp_path / "copy", source) + assert (tmp_path / "copy.hea").exists() + + +def test_write_record_does_not_create_a_record_adapter(tmp_path, monkeypatch): + """write_record converts current fields at the private write boundary.""" + source = wfdb.read_record( + "sample-data/100", stop=8, kind="digital", layout="uniform" + ) + + def fail_if_called(*_args, **_kwargs): + raise AssertionError("legacy Record write adapter was called") + + monkeypatch.setattr(record_module, "_prepare_record_for_write", fail_if_called) + monkeypatch.setattr(wfdb.Record, "wrsamp", fail_if_called) + wfdb.write_record(tmp_path / "copy", source) + assert (tmp_path / "copy.hea").exists() + + +def test_signal_read_write_does_not_call_record_writer(tmp_path, monkeypatch): + """SignalRead writes selected values through private state.""" + source = wfdb.read_signals( + "sample-data/100", stop=8, kind="digital", layout="uniform" + ) + + def fail_if_called(*_args, **_kwargs): + raise AssertionError("Record.wrsamp was called") + + monkeypatch.setattr(wfdb.Record, "wrsamp", fail_if_called) + source.write(tmp_path / "copy") + assert (tmp_path / "copy.hea").exists() + + +def test_write_signals_does_not_construct_a_record(tmp_path, monkeypatch): + """The array writer creates private write state directly.""" + + def fail_if_called(*_args, **_kwargs): + raise AssertionError("Record constructor was called") + + monkeypatch.setattr(record_module, "Record", fail_if_called) + wfdb.write_signals( + tmp_path / "copy", + np.array([[1], [2], [3]], dtype=np.int16), + fs=125, + kind="digital", + formats="16", + channel_names=["I"], + units=["mV"], + adc_gain=[200.0], + baseline=[0], + missing="none", + ) + assert (tmp_path / "copy.hea").exists() diff --git a/tests/test_writer_byte_fixtures.py b/tests/test_writer_byte_fixtures.py index 42e26ae4..5032c15b 100644 --- a/tests/test_writer_byte_fixtures.py +++ b/tests/test_writer_byte_fixtures.py @@ -199,6 +199,94 @@ def _archive(path): read.write(path.with_suffix(".wfdb")) +def _legacy_physical_calibration(path): + record = wfdb.Record( + record_name=path.name, + n_sig=2, + fs=125, + sig_len=4, + sig_name=["I", "II"], + units=["mV", "mV"], + fmt=["16", "16"], + p_signal=np.array([[0.0, 0.2], [0.1, -0.3], [np.nan, 0.0], [0.4, 0.5]]), + ) + record.set_d_features(do_adc=True) + record.set_defaults() + record.wrsamp(write_dir=str(path.parent)) + + +def _legacy_expanded_digital(path): + record = wfdb.Record( + record_name=path.name, + n_sig=2, + fs=125, + sig_len=3, + sig_name=["I", "II"], + units=["mV", "mV"], + fmt=["16", "212"], + adc_gain=[200.0, 100.0], + baseline=[0, 0], + samps_per_frame=[2, 1], + e_d_signal=[ + np.array([1, 2, 3, 4, 5, 6], dtype=np.int16), + np.array([-1, -2, -3], dtype=np.int16), + ], + ) + record.set_d_features(expanded=True) + record.set_defaults() + record.wrsamp(expanded=True, write_dir=str(path.parent)) + + +def _legacy_byte_offset(path): + record = wfdb.Record( + record_name=path.name, + n_sig=1, + fs=125, + sig_len=3, + sig_name=["I"], + units=["mV"], + fmt=["16"], + adc_gain=[200.0], + baseline=[0], + d_signal=np.array([[1], [2], [3]], dtype=np.int16), + ) + record.set_d_features() + record.byte_offset = [3] + record.set_defaults() + record.wrsamp(write_dir=str(path.parent)) + + +def _legacy_fixed_master(path): + segments = [] + for index in range(2): + segment = wfdb.Record( + record_name=f"part{index}", + n_sig=1, + fs=100, + sig_len=3, + sig_name=["I"], + units=["mV"], + fmt=["16"], + adc_gain=[200.0], + baseline=[0], + d_signal=np.array([[index], [index + 1], [index + 2]]), + ) + segment.set_d_features() + segment.set_defaults() + segments.append(segment) + multi = wfdb.MultiRecord( + record_name=path.name, + n_sig=1, + fs=100, + sig_len=6, + seg_name=[segment.record_name for segment in segments], + seg_len=[3, 3], + segments=segments, + layout="fixed", + ) + multi.wrsamp(write_dir=str(path.parent)) + + CASES = { "masked_mixed_formats": _masked_mixed_formats, "expanded_mixed_spf": _expanded_mixed_spf, @@ -210,6 +298,10 @@ def _archive(path): "flattened_multisegment": _flattened_multisegment, "variable_master": _variable_master, "archive": _archive, + "legacy_physical_calibration": _legacy_physical_calibration, + "legacy_expanded_digital": _legacy_expanded_digital, + "legacy_byte_offset": _legacy_byte_offset, + "legacy_fixed_master": _legacy_fixed_master, } for _fmt in ("32", "508", "516", "524"):