Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions changelog.d/recorddata-written-declarations.rst
Original file line number Diff line number Diff line change
@@ -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. 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.
5 changes: 5 additions & 0 deletions docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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
channel. Gains must be positive and finite; baselines must be signed 32-bit
Expand Down
11 changes: 10 additions & 1 deletion src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -5753,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
Expand Down Expand Up @@ -5830,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):
Expand Down Expand Up @@ -5861,6 +5869,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."""
Expand Down
27 changes: 2 additions & 25 deletions src/wfdb/io/signal_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,11 +540,8 @@ 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,
signed_checksums=True,
)


Expand Down Expand Up @@ -603,26 +600,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
Expand Down
3 changes: 2 additions & 1 deletion tests/test_physical_recorddata_write_calibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)


Expand Down
134 changes: 134 additions & 0 deletions tests/test_recorddata_written_declarations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
"""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


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):
"""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)
)
10 changes: 5 additions & 5 deletions tests/test_single_read_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,24 +184,24 @@ def test_masked_sample_without_format_marker(tmp_path, layout):
"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 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\n"
"copy.dat 24x1 6.8094e-14(0)/V\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"
"# <SPL>: 95 <Stim Freq (kHz)>: 1 <Ear>: r "
"<Trial Length (samples)>: 2002 <Condition>: 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()
Expand Down
Loading