diff --git a/changelog.d/physical-recorddata-write-calibration.rst b/changelog.d/physical-recorddata-write-calibration.rst new file mode 100644 index 00000000..ada5c24d --- /dev/null +++ b/changelog.d/physical-recorddata-write-calibration.rst @@ -0,0 +1,6 @@ +**Choose calibration when writing physical RecordData** + ``RecordData.write`` and ``write_record`` now accept paired ``adc_gain`` and + ``baseline`` options for physical ``RecordData``. The options are validated + before files are created and leave the loaded data unchanged. Explicit + calibration and format changes that recode missing samples regenerate + sample-dependent header fields, including initial values and checksums. diff --git a/changelog.d/write-missing-adc-defaults.rst b/changelog.d/write-missing-adc-defaults.rst new file mode 100644 index 00000000..fad75384 --- /dev/null +++ b/changelog.d/write-missing-adc-defaults.rst @@ -0,0 +1,5 @@ +**Fill required ADC fields when writing derived signal declarations** + Writing a selected or edited record whose source header omits ``adc_res`` + or ``adc_zero`` now fills those fields when a derived initial value or + checksum requires them on the output signal line. This also fixes legacy + partial writes of such records. diff --git a/docs/io.rst b/docs/io.rst index e92abdf3..84cf2b0e 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -697,6 +697,18 @@ The supported writable signal formats are those of ``Record.wrsamp``: 80, groupings fail through the existing writer. Encoding can allocate converted arrays, so large writes may use substantial memory. +For physical values, pass ``adc_gain`` and ``baseline`` together to control +the conversion to stored integers. Each must contain one value per selected +channel. Gains must be positive and finite; baselines must be signed 32-bit +integers. The options apply only to the new file and do not change the loaded +arrays or source metadata. When a flattened read has no unambiguous format +for a channel, pass ``formats`` as well. The writer checks the calibrated +values against each format's range and missing marker before creating files. +It recalculates initial values and checksums when calibration changes or a +format change recodes missing samples. Digital ``RecordData`` uses +``with_calibration`` to change its +calibration; mutable ``Record`` objects use their existing fields. + For digital writes, the writer infers each selected channel's target format only when its loaded source segments agree. Pass ``formats="16"`` for all channels or ``formats=["16", "212"]`` to choose per channel when source diff --git a/src/wfdb/io/_header.py b/src/wfdb/io/_header.py index b0d83cf7..23c80e12 100644 --- a/src/wfdb/io/_header.py +++ b/src/wfdb/io/_header.py @@ -585,6 +585,46 @@ def _write_checked_single_header( if not expanded: sig_write_fields.pop("samps_per_frame", None) + # Derived initial values and checksums make these positional fields + # necessary even when the source header omitted them. Fill only the + # channels whose outgoing signal lines require the fields, leaving the + # writer's public attributes untouched. + filled = False + for field in ("adc_res", "adc_zero"): + required = sig_write_fields.get(field, ()) + current = header_fields[field] + if not required or ( + current is not None + and ( + not isinstance(current, (list, tuple)) + or len(current) != snapshot.n_channels + ) + ): + continue + values = [None] * snapshot.n_channels if current is None else list(current) + changed = False + for channel in required: + if values[channel] is not None: + continue + if field == "adc_res": + fmt = snapshot.channels[channel].fmt + if fmt not in _signal.BIT_RES: + continue + values[channel] = _signal._fmt_res(fmt) + else: + values[channel] = 0 + changed = True + if changed: + header_fields[field] = values + filled = True + if filled: + snapshot = _capture_write_signal_fields_from_values( + header_fields, header_fields["n_sig"], fields + ) + sig_write_fields = _select_signal_header_fields(snapshot.channels) + 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(): diff --git a/src/wfdb/io/_record_data_edits.py b/src/wfdb/io/_record_data_edits.py index 3a697a7e..44114c0f 100644 --- a/src/wfdb/io/_record_data_edits.py +++ b/src/wfdb/io/_record_data_edits.py @@ -10,7 +10,11 @@ from wfdb.io import _header from wfdb.io._read_model import _adjust_time, _metadata_for_view -from wfdb.io.signal_values import ExpandedSignals, _from_read_model +from wfdb.io.signal_values import ( + ExpandedSignals, + _from_read_model, + _validated_channel_calibration, +) def _clean_signals(signals): @@ -364,13 +368,6 @@ def replace_record_comments(read, comments): return _replace_record_metadata(read, comments=comments) -def _calibration_fields(values, field, count): - """Require one calibration value for each loaded channel.""" - if not isinstance(values, (list, tuple)) or len(values) != count: - raise ValueError(f"{field} must contain one value per loaded channel") - return tuple(values) - - def replace_record_calibration(read, adc_gain, baseline, mode): """Change digital calibration while preserving one chosen signal meaning.""" if read.signals.kind != "digital": @@ -381,36 +378,8 @@ def replace_record_calibration(read, adc_gain, baseline, mode): if mode not in ("rescale", "reinterpret"): raise ValueError("mode must be 'rescale' or 'reinterpret'") count = read.metadata.n_signals - adc_gain = _calibration_fields(adc_gain, "adc_gain", count) - baseline = _calibration_fields(baseline, "baseline", count) - gains = [] - offsets = [] - for index, (gain, offset) in enumerate(zip(adc_gain, baseline, strict=True)): - if isinstance(gain, (bool, np.bool_)) or not isinstance( - gain, (int, float, np.integer, np.floating) - ): - raise ValueError(f"adc_gain[{index}] must be a positive finite number") - try: - gain = float(gain) - except OverflowError as error: - raise ValueError( - f"adc_gain[{index}] must be a positive finite number" - ) from error - if not np.isfinite(gain) or gain <= 0: - raise ValueError(f"adc_gain[{index}] must be a positive finite number") - if isinstance(offset, (bool, np.bool_)): - raise ValueError(f"baseline[{index}] must be a signed 32-bit integer") - try: - offset = operator.index(offset) - except TypeError as error: - raise ValueError( - f"baseline[{index}] must be a signed 32-bit integer" - ) from error - if not -(2**31) <= offset <= 2**31 - 1: - raise ValueError(f"baseline[{index}] must be a signed 32-bit integer") - gains.append(gain) - offsets.append(int(offset)) - calibration = (tuple(gains), tuple(offsets)) + calibration = _validated_channel_calibration(adc_gain, baseline, count) + gains, offsets = calibration if mode == "reinterpret": return _replace_record_metadata(read, calibration=calibration) diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 154c43df..96cb5b7e 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -6018,6 +6018,8 @@ def write_record( layout: str | None = None, signal_alignment: str | None = None, formats: str | tuple[str, ...] | list[str] | None = None, + adc_gain: list[float] | tuple[float, ...] | None = None, + baseline: list[int] | tuple[int, ...] | None = None, ) -> None: """Write the current values of a ``Record`` or ``RecordData`` to ``path``. @@ -6048,6 +6050,12 @@ def write_record( formats : str or sequence of str, optional Target storage format for all channels or one format per channel of ``RecordData``. Not accepted for ``Record``; use its ``fmt`` field. + adc_gain : sequence of float, optional + Positive finite gain for each physical ``RecordData`` channel. Provide + together with ``baseline``. Not accepted for ``Record``. + baseline : sequence of int, optional + Signed 32-bit baseline for each physical ``RecordData`` channel. + Provide together with ``adc_gain``. Not accepted for ``Record``. Returns ------- @@ -6058,8 +6066,9 @@ def write_record( ``RecordData`` and its ``write`` method produce identical files. For a ``Record``, 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. + quantization. For ``Record``, missing calibration and header defaults are + calculated for physical values. For physical ``RecordData``, paired + ``adc_gain`` and ``baseline`` options override its selected calibration. Digital values require a storage format, ``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 @@ -6093,12 +6102,23 @@ def write_record( "kind and layout apply only to Record; RecordData already " "has one signal kind and layout" ) - record.write(path, signal_alignment=signal_alignment, formats=formats) + record.write( + path, + signal_alignment=signal_alignment, + formats=formats, + adc_gain=adc_gain, + baseline=baseline, + ) return 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 or RecordData") + if adc_gain is not None or baseline is not None: + raise TypeError( + "adc_gain and baseline write options apply only to physical RecordData; " + "edit Record.adc_gain and Record.baseline instead" + ) if formats is not None: raise TypeError("formats applies only to RecordData; edit Record.fmt instead") if kind not in (None, "physical", "digital"): diff --git a/src/wfdb/io/signal_values.py b/src/wfdb/io/signal_values.py index c677a154..5f56db54 100644 --- a/src/wfdb/io/signal_values.py +++ b/src/wfdb/io/signal_values.py @@ -2,6 +2,7 @@ import copy import datetime +import operator import os from dataclasses import dataclass, replace from typing import Literal @@ -453,6 +454,8 @@ def write( *, signal_alignment: str | None = None, formats: str | tuple[str, ...] | list[str] | None = None, + adc_gain: list[float] | tuple[float, ...] | None = None, + baseline: list[int] | tuple[int, ...] | None = None, ) -> None: """Write this selected view under a new record name. @@ -490,9 +493,17 @@ def write( establish one format. Values must fit the target format, excluding its reserved missing-sample marker. Masked values require a target format that has a missing-sample marker. + adc_gain : sequence of float, optional + Positive finite gain for each physical channel. Provide together + with ``baseline``. Digital values already have calibration; use + ``with_calibration`` to change it. + baseline : sequence of int, optional + Signed 32-bit baseline for each physical channel. Provide together + with ``adc_gain``. """ if self.metadata.n_signals == 0: raise ValueError("Cannot write a RecordData with no selected channels") + calibration = _write_calibration(self, adc_gain, baseline) ( destination, directory, @@ -501,7 +512,17 @@ def write( expanded, selected_formats, source, - ) = _prepare_signal_read_write(self, path, formats) + ) = _prepare_signal_read_write( + self, path, formats, calibration_override=calibration is not None + ) + if calibration is not None: + if any(fmt is None for fmt in selected_formats): + raise ValueError( + "physical calibration needs an unambiguous target format " + "for every channel; pass formats=..." + ) + source.adc_gain = list(calibration[0]) + source.baseline = list(calibration[1]) from wfdb.io.record import _WriteModel field = ("e_" if expanded else "") + ( @@ -519,7 +540,11 @@ def write( directory, destination if archive else None, derive_features=False, - refresh_features=getattr(self, "_edited_values", False), + refresh_features=( + getattr(self, "_edited_values", False) + or calibration is not None + or _format_override_recodes_missing(self, selected_formats, formats) + ), ) @@ -528,7 +553,77 @@ def write( SignalRead = RecordData -def _prepare_signal_read_write(read, path, formats): +def _validated_channel_calibration(adc_gain, baseline, count): + """Validate complete gains and baselines shared by RecordData operations.""" + if not isinstance(adc_gain, (list, tuple)) or len(adc_gain) != count: + raise ValueError("adc_gain must contain one value per loaded channel") + if not isinstance(baseline, (list, tuple)) or len(baseline) != count: + raise ValueError("baseline must contain one value per loaded channel") + gains = [] + offsets = [] + for index, (gain, offset) in enumerate(zip(adc_gain, baseline, strict=True)): + if isinstance(gain, (bool, np.bool_)) or not isinstance( + gain, (int, float, np.integer, np.floating) + ): + raise ValueError(f"adc_gain[{index}] must be a positive finite number") + try: + gain = float(gain) + except OverflowError as error: + raise ValueError( + f"adc_gain[{index}] must be a positive finite number" + ) from error + if not np.isfinite(gain) or gain <= 0: + raise ValueError(f"adc_gain[{index}] must be a positive finite number") + if isinstance(offset, (bool, np.bool_)): + raise ValueError(f"baseline[{index}] must be a signed 32-bit integer") + try: + offset = operator.index(offset) + except TypeError as error: + raise ValueError( + f"baseline[{index}] must be a signed 32-bit integer" + ) from error + if not -(2**31) <= offset <= 2**31 - 1: + raise ValueError(f"baseline[{index}] must be a signed 32-bit integer") + gains.append(gain) + offsets.append(int(offset)) + return tuple(gains), tuple(offsets) + + +def _write_calibration(read, adc_gain, baseline): + """Validate paired calibration for a physical RecordData write.""" + if adc_gain is None and baseline is None: + return None + if read.signals.kind != "physical": + raise ValueError( + "adc_gain and baseline write options apply only to physical " + "RecordData; use with_calibration for digital values" + ) + if (adc_gain is None) != (baseline is None): + raise ValueError("adc_gain and baseline must be provided together") + return _validated_channel_calibration(adc_gain, baseline, read.metadata.n_signals) + + +def _format_override_recodes_missing(read, selected_formats, formats): + """Refresh declarations only when a format choice changes gap markers.""" + if formats is None: + return False + expanded = isinstance(read.signals, ExpandedSignals) + channels = read.signals.values if expanded else tuple(read.signals.values.T) + for index, channel in enumerate(channels): + source_format = read._write_formats[index] + if source_format == selected_formats[index]: + continue + missing = ( + np.ma.getmaskarray(channel) + if read.signals.kind == "digital" + else np.isnan(channel) + ) + if np.any(missing): + return True + return False + + +def _prepare_signal_read_write(read, path, formats, *, calibration_override=False): """Prepare the destination, formats, and selected source for writing.""" from wfdb.io._cloud import is_cloud_path from wfdb.io._coreio import _split_path @@ -552,7 +647,7 @@ def _prepare_signal_read_write(read, path, formats): expanded = isinstance(read.signals, ExpandedSignals) selected_formats = _select_write_formats(read, formats) source = copy.copy(read._record) - if formats is not None or read.signals.kind == "digital": + if formats is not None or read.signals.kind == "digital" or calibration_override: source.fmt = list(selected_formats) files = source.file_name or [None] * len(selected_formats) formats_by_file = {} diff --git a/tests/test_physical_recorddata_write_calibration.py b/tests/test_physical_recorddata_write_calibration.py new file mode 100644 index 00000000..de777c64 --- /dev/null +++ b/tests/test_physical_recorddata_write_calibration.py @@ -0,0 +1,285 @@ +"""Explicit calibration when writing physical RecordData.""" + +import pickle +from pathlib import Path + +import numpy as np +import pytest + +import wfdb + + +def _physical_read(tmp_path): + """Read a short physical view with two different storage formats.""" + source = tmp_path / "source" + values = np.array([[0, 0], [0.5, 0.25], [1, 0.5], [np.nan, 0.75]], dtype=np.float64) + wfdb.write_signals( + source, + values, + fs=125, + kind="physical", + formats=["16", "212"], + channel_names=["I", "II"], + units=["mV", "mV"], + adc_gain=[2, 4], + baseline=[0, 1], + ) + return wfdb.read_signals(source, kind="physical", layout="uniform") + + +def _same_written_bytes(tmp_path, data, **options): + """The function and method forms must write identical files.""" + method_dir = tmp_path / "method" + function_dir = tmp_path / "function" + method_dir.mkdir() + function_dir.mkdir() + assert data.write(method_dir / "copy", **options) is None + assert wfdb.write_record(function_dir / "copy", data, **options) is None + expected = {path.name: path.read_bytes() for path in method_dir.iterdir()} + actual = {path.name: path.read_bytes() for path in function_dir.iterdir()} + assert actual == expected + return function_dir / "copy" + + +def test_physical_calibration_override_matches_explicit_adc(tmp_path): + """Both writers use the requested gain and baseline without editing data.""" + read = _physical_read(tmp_path) + original = read.signals.values.copy() + target = _same_written_bytes(tmp_path, read, adc_gain=[4, 8], baseline=[2, 3]) + digital = wfdb.read_signals(target, kind="digital", layout="uniform") + expected = np.ma.array( + [[2, 3], [4, 5], [6, 7], [0, 9]], + mask=[[False, False], [False, False], [False, False], [True, False]], + ) + np.testing.assert_array_equal(digital.signals.values, expected) + np.testing.assert_array_equal( + np.ma.getmaskarray(digital.signals.values), np.ma.getmaskarray(expected) + ) + assert [item.adc_gain for item in digital.metadata.signals] == [4, 8] + assert [item.baseline for item in digital.metadata.signals] == [2, 3] + np.testing.assert_array_equal(read.signals.values, original) + assert [item.adc_gain for item in read.metadata.signals] == [2, 4] + assert digital.metadata.channels[0].storage.init_value == 2 + assert digital.metadata.channels[0].storage.checksum == ( + np.sum(digital.signals.values.data[:, 0]) % 65536 + ) + + +def test_same_calibration_agrees_with_to_digital(tmp_path): + """A physical conversion and an explicit write use the same ADC rule.""" + read = _physical_read(tmp_path) + converted = read.to_digital() + target = tmp_path / "same" + read.write(target, adc_gain=[2, 4], baseline=[0, 1]) + written = wfdb.read_signals(target, kind="digital", layout="uniform") + np.testing.assert_array_equal(written.signals.values, converted.signals.values) + np.testing.assert_array_equal( + np.ma.getmaskarray(written.signals.values), + np.ma.getmaskarray(converted.signals.values), + ) + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +def test_format_override_refreshes_sample_declarations(tmp_path, kind): + """Changing the marker format updates checksum and initial declarations.""" + physical = _physical_read(tmp_path) + read = physical if kind == "physical" else physical.to_digital() + target = tmp_path / f"format_{kind}" + read.write(target, formats="24") + written = wfdb.read_signals(target, kind="digital", layout="uniform") + for index, channel in enumerate(written.metadata.channels): + values = written.signals.values[:, index] + marker = -(2**23) + encoded = values.data.copy() + encoded[np.ma.getmaskarray(values)] = marker + assert channel.storage.init_value == int(encoded[0]) + assert (channel.storage.checksum - int(np.sum(encoded))) % 65536 == 0 + + +def test_expanded_physical_calibration_override(tmp_path): + """Expanded channels retain their sample counts and use new calibration.""" + read = wfdb.read_signals( + "sample-data/test01_00s_frame", kind="physical", layout="expanded", stop=5 + ) + gains = [item.adc_gain for item in read.metadata.signals] + baselines = [item.baseline + 1 for item in read.metadata.signals] + target = _same_written_bytes(tmp_path, read, adc_gain=gains, baseline=baselines) + written = wfdb.read_signals(target, kind="digital", layout="expanded") + for old, new, gain, baseline in zip( + read.signals.values, written.signals.values, gains, baselines + ): + expected = np.rint(old * gain + baseline) + np.testing.assert_array_equal(new, expected) + + +def test_flattened_physical_calibration_is_not_reinferred(tmp_path): + """Explicit values survive the flattened-write preparation path.""" + read = wfdb.read_signals( + "sample-data/multi-segment/041s/041s", + kind="physical", + layout="uniform", + start=10, + stop=20, + ) + gains = [item.adc_gain for item in read.metadata.signals] + baselines = [item.baseline + 1 for item in read.metadata.signals] + target = tmp_path / "flattened" + read.write(target, adc_gain=gains, baseline=baselines) + written = wfdb.read_signals(target, kind="digital", layout="uniform") + assert [item.adc_gain for item in written.metadata.signals] == gains + assert [item.baseline for item in written.metadata.signals] == baselines + + +def test_ambiguous_flattened_formats_need_explicit_choice(tmp_path): + """Calibration cannot be silently replaced by inferred storage fields.""" + read = wfdb.read_signals( + "sample-data/multi-segment/s00001/s00001-2896-10-10-00-31", + kind="physical", + layout="uniform", + start=2225802, + stop=2225810, + ) + destination = tmp_path / "ambiguous" + with pytest.raises(ValueError, match="pass formats"): + read.write( + destination, + adc_gain=[200] * read.metadata.n_signals, + baseline=[0] * read.metadata.n_signals, + ) + assert not destination.with_suffix(".hea").exists() + read.write( + destination, + formats="16", + adc_gain=[200] * read.metadata.n_signals, + baseline=[0] * read.metadata.n_signals, + ) + written = wfdb.read_signals(destination, kind="digital", layout="uniform") + assert all(signal.adc_gain == 200 for signal in written.metadata.signals) + + +@pytest.mark.parametrize( + "options,message", + [ + ({"adc_gain": [2, 4], "baseline": None}, "provided together"), + ({"adc_gain": None, "baseline": [0, 1]}, "provided together"), + ({"adc_gain": [2]}, "adc_gain must contain one"), + ({"baseline": [0]}, "baseline must contain one"), + ({"adc_gain": [0, 4]}, r"adc_gain\[0\]"), + ({"adc_gain": [-2, 4]}, r"adc_gain\[0\]"), + ({"adc_gain": [np.inf, 4]}, r"adc_gain\[0\]"), + ({"adc_gain": [True, 4]}, r"adc_gain\[0\]"), + ({"baseline": [0.5, 1]}, r"baseline\[0\]"), + ({"baseline": [True, 1]}, r"baseline\[0\]"), + ({"baseline": [2**31, 1]}, r"baseline\[0\]"), + ], +) +def test_invalid_calibration_fails_before_files(tmp_path, options, message): + """Incomplete or invalid options cannot leave output behind.""" + read = _physical_read(tmp_path) + values = {"adc_gain": [2, 4], "baseline": [0, 1]} + values.update(options) + destination = tmp_path / "invalid" + with pytest.raises(ValueError, match=message): + wfdb.write_record(destination, read, **values) + assert not destination.with_suffix(".hea").exists() + + +@pytest.mark.parametrize( + "options,message", + [ + ({"adc_gain": [2, 4], "baseline": [-32768, 1]}, "missing marker"), + ({"adc_gain": [100000, 4], "baseline": [0, 1]}, "valid range"), + ], +) +def test_unencodable_physical_values_fail_before_files(tmp_path, options, message): + """The existing physical range checks run with explicit calibration.""" + read = _physical_read(tmp_path) + destination = tmp_path / "unencodable" + with pytest.raises(ValueError, match=message): + read.write(destination, **options) + assert not destination.with_suffix(".hea").exists() + + +def test_digital_and_mutable_record_reject_write_calibration(tmp_path): + """Digital metadata edits and mutable Record fields have their own APIs.""" + physical = _physical_read(tmp_path) + digital = physical.to_digital() + with pytest.raises(ValueError, match="only to physical RecordData"): + digital.write(tmp_path / "digital", adc_gain=[2, 4], baseline=[0, 1]) + with pytest.raises(TypeError, match="only to physical RecordData"): + wfdb.write_record( + tmp_path / "mutable", + physical.to_legacy_record(), + adc_gain=[2, 4], + baseline=[0, 1], + ) + assert not (tmp_path / "digital.hea").exists() + assert not (tmp_path / "mutable.hea").exists() + + +def test_old_physical_pickle_accepts_write_calibration(tmp_path): + """The options also work for a saved read predating the private model.""" + fixture = Path(__file__).parent / "fixtures/signal_read_v5_17/physical_uniform.pkl" + read = pickle.loads(fixture.read_bytes()) + gain = [signal.adc_gain for signal in read.metadata.signals] + baseline = [signal.baseline for signal in read.metadata.signals] + target = tmp_path / "old_pickle" + read.write(target, adc_gain=gain, baseline=baseline) + restored = wfdb.read_signals(target, kind="digital", layout="uniform") + assert [signal.adc_gain for signal in restored.metadata.signals] == gain + + +@pytest.mark.parametrize("edit", ["partial", "select", "values"]) +def test_missing_adc_fields_are_filled_for_derived_declarations(tmp_path, edit): + """The n8 header can be written after selecting or editing its samples.""" + source = "sample-data/n8_evoked_raw_95_F1_R9" + read = wfdb.read_signals(source, kind="physical", layout="uniform", stop=100) + if edit == "select": + read = read.select(start=1, stop=100) + elif edit == "values": + read = read.with_values(read.signals.values.copy()) + destination = tmp_path / edit + read.write(destination) + header = wfdb.rdheader(str(destination)) + assert header.adc_res == [24, 24] + assert header.adc_zero == [0, 0] + assert read.source_header.signals[0].adc_res is None + + +def test_full_n8_write_accepts_explicit_format(tmp_path): + """A full read with formats= can write a header lacking ADC declarations.""" + read = wfdb.read_signals( + "sample-data/n8_evoked_raw_95_F1_R9", kind="physical", layout="uniform" + ) + destination = tmp_path / "full" + read.write(destination, formats="32") + header = wfdb.rdheader(str(destination)) + assert header.adc_res == [32, 32] + assert header.adc_zero == [0, 0] + + +def test_legacy_partial_n8_write_fills_required_adc_fields(tmp_path): + """The shared header writer also repairs a legacy partial write.""" + record = wfdb.rdrecord( + "sample-data/n8_evoked_raw_95_F1_R9", physical=False, sampto=100 + ) + record.record_name = "legacy" + record.file_name = ["legacy.dat"] * record.n_sig + record.wrsamp(write_dir=str(tmp_path)) + header = wfdb.rdheader(str(tmp_path / "legacy")) + assert header.adc_res == [24, 24] + assert header.adc_zero == [0, 0] + + +def test_explicit_source_formats_do_not_change_bytes(tmp_path): + """Repeating the source formats does not refresh otherwise unchanged data.""" + read = wfdb.read_signals("sample-data/100", kind="digital", layout="uniform") + implicit = tmp_path / "implicit" + explicit = tmp_path / "explicit" + implicit.mkdir() + explicit.mkdir() + read.write(implicit / "copy") + read.write(explicit / "copy", formats=["212", "212"]) + assert {file.name: file.read_bytes() for file in implicit.iterdir()} == { + file.name: file.read_bytes() for file in explicit.iterdir() + }