From a77d32cc707184bbb7050e060d3d17f3ee56065c Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Fri, 4 Dec 2026 13:52:32 -0500 Subject: [PATCH 1/2] Derive RecordData write declarations from encoded samples --- .../recorddata-written-declarations.rst | 8 ++ docs/io.rst | 5 + src/wfdb/io/record.py | 8 +- src/wfdb/io/signal_values.py | 26 +--- tests/test_recorddata_written_declarations.py | 125 ++++++++++++++++++ tests/test_single_read_model.py | 14 +- 6 files changed, 153 insertions(+), 33 deletions(-) create mode 100644 changelog.d/recorddata-written-declarations.rst create mode 100644 tests/test_recorddata_written_declarations.py diff --git a/changelog.d/recorddata-written-declarations.rst b/changelog.d/recorddata-written-declarations.rst new file mode 100644 index 00000000..7dbcb252 --- /dev/null +++ b/changelog.d/recorddata-written-declarations.rst @@ -0,0 +1,8 @@ +**Write accurate initial values and checksums from RecordData** + ``RecordData.write`` and ``write_record(path, RecordData)`` now derive + ``init_value`` and ``checksum`` from the encoded samples on every write. + This corrects stale source declarations after frame smoothing or skew + alignment. Some header bytes change: checksums may use an equivalent + unsigned form, and headers that omitted ADC fields may gain ``adc_res`` and + ``adc_zero`` when the derived declarations require them. Signal data bytes + are unchanged. The mutable ``Record`` writer keeps its existing behavior. diff --git a/docs/io.rst b/docs/io.rst index 84cf2b0e..ec2c2f17 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -697,6 +697,11 @@ 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. +Every ``RecordData`` write derives the output header's initial values and +checksums from the samples actually encoded. They can differ from the source +header after skew alignment, frame smoothing, or a channel selection. +Checksums may be written in an equivalent unsigned form. + 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 diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 96cb5b7e..2c122da9 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -5204,7 +5204,11 @@ def _write_prepared_files(writer, expanded, write_dir, wfdb_archive): "signals with samples is not supported" ) - if writer.checksum is not None and has_signal_files: + if ( + writer.checksum is not None + and has_signal_files + and not (isinstance(writer, _WriteModel) and writer.checksums_from_values) + ): digital = writer.e_d_signal if expanded else writer.d_signal writer.checksum = _signal._resolved_write_checksums( digital, writer.checksum, expanded=expanded @@ -5623,6 +5627,7 @@ class _WriteModel: encoder_signal_fields: tuple[tuple[str, object], ...] skew: tuple[int | None, ...] | None from_segments: bool + checksums_from_values: bool = False def _warn_about_replacing_other_files(self, write_dir): """Warn from this model's current destination fields.""" @@ -5861,6 +5866,7 @@ def _prepare_digital_features( digital, self.samps_per_frame, expanded=expanded ) ) + self.checksums_from_values = True def _prepare_defaults(self) -> None: """Fill the selected header defaults on the model's current fields.""" diff --git a/src/wfdb/io/signal_values.py b/src/wfdb/io/signal_values.py index 5f56db54..f218fe98 100644 --- a/src/wfdb/io/signal_values.py +++ b/src/wfdb/io/signal_values.py @@ -540,11 +540,7 @@ def write( directory, destination if archive else None, derive_features=False, - refresh_features=( - getattr(self, "_edited_values", False) - or calibration is not None - or _format_override_recodes_missing(self, selected_formats, formats) - ), + refresh_features=True, ) @@ -603,26 +599,6 @@ def _write_calibration(read, adc_gain, baseline): 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 diff --git a/tests/test_recorddata_written_declarations.py b/tests/test_recorddata_written_declarations.py new file mode 100644 index 00000000..77a2703b --- /dev/null +++ b/tests/test_recorddata_written_declarations.py @@ -0,0 +1,125 @@ +"""Modern writes declare the samples actually encoded in their files.""" + +import hashlib + +import numpy as np +import pytest + +import wfdb + + +def _encoded_channels(path): + """Read the written integer samples, including missing-value markers.""" + record = wfdb.rdrecord(str(path), physical=False) + return record.d_signal.T + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_full_skewed_multifrequency_write_uses_written_samples(tmp_path, kind, layout): + """Initial values and checksums describe smoothed or aligned output.""" + read = wfdb.read_signals("sample-data/03700181", kind=kind, layout=layout) + destination = tmp_path / "copy" + read.write(destination, signal_alignment="aligned") + header = wfdb.rdheader(str(destination)) + written = wfdb.rdrecord( + str(destination), physical=False, smooth_frames=layout == "uniform" + ) + channels = written.e_d_signal if layout == "expanded" else written.d_signal.T + for index, samples in enumerate(channels): + assert header.init_value[index] == int(samples[0]) + assert (header.checksum[index] - int(np.sum(samples))) % 65536 == 0 + if layout == "uniform": + assert header.init_value == [56, -943, -208] + assert [channel.init_value for channel in read.source_header.signals] == [ + 67, + -943, + -304, + ] + if kind == "digital": + # The data bytes match main before this declaration-only change. + assert hashlib.sha256( + destination.with_suffix(".dat").read_bytes() + ).hexdigest() == ( + "89b9505bf76f1d1ea4b4f798a834867afbe7d53a0e5d355d632b47a321adf68e" + ) + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +def test_explicit_source_formats_match_implicit_write(tmp_path, kind): + """Repeating the source format cannot change modern write declarations.""" + read = wfdb.read_signals( + "sample-data/03700181", kind=kind, layout="uniform", stop=40 + ) + implicit_dir = tmp_path / "implicit" + explicit_dir = tmp_path / "explicit" + implicit_dir.mkdir() + explicit_dir.mkdir() + read.write(implicit_dir / "copy", signal_alignment="aligned") + wfdb.write_record( + explicit_dir / "copy", + read, + signal_alignment="aligned", + formats=["212", "212", "212"], + ) + implicit = {file.name: file.read_bytes() for file in implicit_dir.iterdir()} + explicit = {file.name: file.read_bytes() for file in explicit_dir.iterdir()} + assert explicit == implicit + + +@pytest.mark.parametrize("kind", ["physical", "digital"]) +@pytest.mark.parametrize("layout", ["uniform", "expanded"]) +def test_selected_window_and_mask_declarations(tmp_path, kind, layout): + """Windowed and masked reads declare their first encoded sample and sum.""" + read = wfdb.read_signals( + "sample-data/test01_00s_frame", + kind=kind, + layout=layout, + start=1, + stop=8, + ) + destination = tmp_path / "window" + read.write(destination) + header = wfdb.rdheader(str(destination)) + written = wfdb.rdrecord( + str(destination), physical=False, smooth_frames=layout == "uniform" + ) + channels = written.e_d_signal if layout == "expanded" else written.d_signal.T + for index, samples in enumerate(channels): + assert header.init_value[index] == int(samples[0]) + assert (header.checksum[index] - int(np.sum(samples))) % 65536 == 0 + + +def test_header_without_adc_fields_still_writes(tmp_path): + """Derived declarations can add their required ADC fields.""" + read = wfdb.read_signals( + "sample-data/n8_evoked_raw_95_F1_R9", + kind="physical", + layout="uniform", + stop=100, + ) + destination = tmp_path / "n8" + read.write(destination) + header = wfdb.rdheader(str(destination)) + assert header.adc_res == [24, 24] + assert header.adc_zero == [0, 0] + channels = _encoded_channels(destination) + assert header.init_value == [int(samples[0]) for samples in channels] + + +def test_full_n8_write_adds_derived_declarations(tmp_path): + """A full read also gets truthful declarations without changing its data.""" + read = wfdb.read_signals( + "sample-data/n8_evoked_raw_95_F1_R9", kind="digital", layout="uniform" + ) + destination = tmp_path / "n8_full" + read.write(destination) + header = wfdb.rdheader(str(destination)) + channels = _encoded_channels(destination) + assert header.adc_res == [24, 24] + assert header.adc_zero == [0, 0] + assert header.init_value == [int(samples[0]) for samples in channels] + assert all( + (declared - int(np.sum(samples))) % 65536 == 0 + for declared, samples in zip(header.checksum, channels, strict=True) + ) diff --git a/tests/test_single_read_model.py b/tests/test_single_read_model.py index 0e76587d..4a326bd1 100644 --- a/tests/test_single_read_model.py +++ b/tests/test_single_read_model.py @@ -182,26 +182,26 @@ def test_masked_sample_without_format_marker(tmp_path, layout): ( "sample-data/03700181", "copy 3 125 75000 17:27:45 15/08/1994\n" - "copy.dat 212x4 2963.77(0)/mV 12 0 67 -11266 0 MCL1\n" - "copy.dat 212x1 12.84(-1605)/mmHg 12 0 -943 -23651 0 ABP\n" - "copy.dat 212x1 2000.0(0)/mV 12 0 -304 64723 0 RESP\n", + "copy.dat 212x4 2963.77(0)/mV 12 0 67 54270 0 MCL1\n" + "copy.dat 212x1 12.84(-1605)/mmHg 12 0 -943 41885 0 ABP\n" + "copy.dat 212x1 2000.0(0)/mV 12 0 -208 64723 0 RESP\n", "1d59e406d10292a0f9a913f7a21399fa24c960617982a7f4ea53303994947a00", ), ( "sample-data/n8_evoked_raw_95_F1_R9", "copy 2 48000 2022144\n" - "copy.dat 24x1 2.4011e-11(0)/nV\n" - "copy.dat 24x1 6.8094e-14(0)/V\n" + "copy.dat 24x1 2.4011e-11(0)/nV 24 0 -793009 56979\n" + "copy.dat 24x1 6.8094e-14(0)/V 24 0 -357156 46840\n" "# : 95 : 1 : r " ": 2002 : Normal\n", "60471d87c5945d4b562facb11c5a8d8e708a8b213694f261c1875150f03f86af", ), ], ) -def test_full_expanded_digital_write_matches_v5_17( +def test_full_expanded_digital_write_updates_header_but_keeps_data_bytes( tmp_path, source, header, dat_sha256 ): - """A full expanded read writes the same header and data as v5.17.0.""" + """Full expanded reads update declarations and keep 5.17.0 data bytes.""" read = wfdb.read_signals(source, kind="digital", layout="expanded") read.write(tmp_path / "copy", signal_alignment="aligned") assert (tmp_path / "copy.hea").read_bytes() == header.encode() From 3d45a21e2abc63d1973604eb72a596bd52fbb35d Mon Sep 17 00:00:00 2001 From: Tom Pollard Date: Fri, 4 Dec 2026 13:58:00 -0500 Subject: [PATCH 2/2] Write RecordData checksums in signed WFDB form --- changelog.d/recorddata-written-declarations.rst | 8 ++++---- docs/io.rst | 2 +- src/wfdb/io/record.py | 3 +++ src/wfdb/io/signal_values.py | 1 + tests/test_physical_recorddata_write_calibration.py | 3 ++- tests/test_recorddata_written_declarations.py | 9 +++++++++ tests/test_single_read_model.py | 10 +++++----- 7 files changed, 25 insertions(+), 11 deletions(-) diff --git a/changelog.d/recorddata-written-declarations.rst b/changelog.d/recorddata-written-declarations.rst index 7dbcb252..adbd1b99 100644 --- a/changelog.d/recorddata-written-declarations.rst +++ b/changelog.d/recorddata-written-declarations.rst @@ -2,7 +2,7 @@ ``RecordData.write`` and ``write_record(path, RecordData)`` now derive ``init_value`` and ``checksum`` from the encoded samples on every write. This corrects stale source declarations after frame smoothing or skew - alignment. Some header bytes change: checksums may use an equivalent - unsigned form, and headers that omitted ADC fields may gain ``adc_res`` and - ``adc_zero`` when the derived declarations require them. Signal data bytes - are unchanged. The mutable ``Record`` writer keeps its existing behavior. + alignment. Derived checksums use WFDB's signed 16-bit form. Headers that + omitted ADC fields may gain ``adc_res`` and ``adc_zero`` when the derived + declarations require them. Signal data bytes are unchanged. The mutable + ``Record`` writer keeps its existing behavior. diff --git a/docs/io.rst b/docs/io.rst index ec2c2f17..d517ee22 100644 --- a/docs/io.rst +++ b/docs/io.rst @@ -700,7 +700,7 @@ arrays, so large writes may use substantial memory. Every ``RecordData`` write derives the output header's initial values and checksums from the samples actually encoded. They can differ from the source header after skew alignment, frame smoothing, or a channel selection. -Checksums may be written in an equivalent unsigned form. +Derived checksums use WFDB's signed 16-bit form. For physical values, pass ``adc_gain`` and ``baseline`` together to control the conversion to stored integers. Each must contain one value per selected diff --git a/src/wfdb/io/record.py b/src/wfdb/io/record.py index 2c122da9..7755f13b 100644 --- a/src/wfdb/io/record.py +++ b/src/wfdb/io/record.py @@ -5758,6 +5758,7 @@ def write( *, derive_features: bool = True, refresh_features: bool = False, + signed_checksums: bool = False, ) -> None: """Validate, prepare, and encode this model without a Record adapter.""" self.record_name = name @@ -5835,6 +5836,8 @@ def write( for value in values ], ) + if signed_checksums and self.checksums_from_values: + self.checksum = [(value + 32768) % 65536 - 32768 for value in self.checksum] self._write_files(write_dir, archive_path) def _adc_values_for_write(self, expanded): diff --git a/src/wfdb/io/signal_values.py b/src/wfdb/io/signal_values.py index f218fe98..ac74e4f2 100644 --- a/src/wfdb/io/signal_values.py +++ b/src/wfdb/io/signal_values.py @@ -541,6 +541,7 @@ def write( destination if archive else None, derive_features=False, refresh_features=True, + signed_checksums=True, ) diff --git a/tests/test_physical_recorddata_write_calibration.py b/tests/test_physical_recorddata_write_calibration.py index de777c64..7a7d84c5 100644 --- a/tests/test_physical_recorddata_write_calibration.py +++ b/tests/test_physical_recorddata_write_calibration.py @@ -60,8 +60,9 @@ def test_physical_calibration_override_matches_explicit_adc(tmp_path): 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 + sample_sum = int(np.sum(digital.signals.values.data[:, 0])) assert digital.metadata.channels[0].storage.checksum == ( - np.sum(digital.signals.values.data[:, 0]) % 65536 + (sample_sum + 32768) % 65536 - 32768 ) diff --git a/tests/test_recorddata_written_declarations.py b/tests/test_recorddata_written_declarations.py index 77a2703b..729ff548 100644 --- a/tests/test_recorddata_written_declarations.py +++ b/tests/test_recorddata_written_declarations.py @@ -14,6 +14,15 @@ def _encoded_channels(path): return record.d_signal.T +def test_derived_checksums_use_signed_wfdb_form(tmp_path): + """An unedited full write retains the signed checksums of record 100.""" + read = wfdb.read_signals("sample-data/100", kind="digital", layout="uniform") + destination = tmp_path / "copy" + read.write(destination) + header = wfdb.rdheader(str(destination)) + assert header.checksum == [-22131, 20052] + + @pytest.mark.parametrize("kind", ["physical", "digital"]) @pytest.mark.parametrize("layout", ["uniform", "expanded"]) def test_full_skewed_multifrequency_write_uses_written_samples(tmp_path, kind, layout): diff --git a/tests/test_single_read_model.py b/tests/test_single_read_model.py index 4a326bd1..863fa67f 100644 --- a/tests/test_single_read_model.py +++ b/tests/test_single_read_model.py @@ -182,16 +182,16 @@ def test_masked_sample_without_format_marker(tmp_path, layout): ( "sample-data/03700181", "copy 3 125 75000 17:27:45 15/08/1994\n" - "copy.dat 212x4 2963.77(0)/mV 12 0 67 54270 0 MCL1\n" - "copy.dat 212x1 12.84(-1605)/mmHg 12 0 -943 41885 0 ABP\n" - "copy.dat 212x1 2000.0(0)/mV 12 0 -208 64723 0 RESP\n", + "copy.dat 212x4 2963.77(0)/mV 12 0 67 -11266 0 MCL1\n" + "copy.dat 212x1 12.84(-1605)/mmHg 12 0 -943 -23651 0 ABP\n" + "copy.dat 212x1 2000.0(0)/mV 12 0 -208 -813 0 RESP\n", "1d59e406d10292a0f9a913f7a21399fa24c960617982a7f4ea53303994947a00", ), ( "sample-data/n8_evoked_raw_95_F1_R9", "copy 2 48000 2022144\n" - "copy.dat 24x1 2.4011e-11(0)/nV 24 0 -793009 56979\n" - "copy.dat 24x1 6.8094e-14(0)/V 24 0 -357156 46840\n" + "copy.dat 24x1 2.4011e-11(0)/nV 24 0 -793009 -8557\n" + "copy.dat 24x1 6.8094e-14(0)/V 24 0 -357156 -18696\n" "# : 95 : 1 : r " ": 2002 : Normal\n", "60471d87c5945d4b562facb11c5a8d8e708a8b213694f261c1875150f03f86af",