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
103 changes: 45 additions & 58 deletions src/wfdb/io/_signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,38 @@ def _digital_feature_values(values, samps_per_frame=None, *, expanded=False):
)


def _adc_inplace(p_signal, adc_gain, baseline, d_nan):
"""Convert one physical array using the existing WFDB rounding rule."""
nanlocs = np.isnan(p_signal)
p_signal = p_signal.astype("float64", copy=False)
np.multiply(p_signal, adc_gain, p_signal)
np.add(p_signal, baseline, p_signal)
np.round(p_signal, 0, p_signal)
np.copyto(p_signal, d_nan, where=nanlocs)
return p_signal.astype("int64", copy=False)


def _adc_values(values, formats, adc_gain, baseline, *, expanded=False, inplace=False):
"""Convert explicit physical arrays to digital arrays."""
d_nans = _digi_nan(formats)
if expanded:
if inplace:
for ch, channel in enumerate(values):
values[ch] = _adc_inplace(
channel, adc_gain[ch], baseline[ch], d_nans[ch]
)
return values
return [
_adc_inplace(
channel.astype("float64"), adc_gain[ch], baseline[ch], d_nans[ch]
)
for ch, channel in enumerate(values)
]
if not inplace:
values = values.astype("float64")
return _adc_inplace(values, adc_gain, baseline, d_nans)


def _resolved_write_checksums(values, previous, *, expanded=False):
"""Keep omitted or modulo-equivalent declarations when writing samples."""
checksums = _digital_checksums(values, expanded=expanded)
Expand Down Expand Up @@ -623,69 +655,24 @@ def adc(self, expanded=False, inplace=False):
>>> record.dac(inplace=True)

"""
# The digital NAN values for each channel
d_nans = _digi_nan(self.fmt)

# To do: choose the minimum return res needed
intdtype = "int64"

# Convert a physical (1D or 2D) signal array to digital. Note that
# the input array is modified!
def adc_inplace(p_signal, adc_gain, baseline, d_nan):
nanlocs = np.isnan(p_signal)
# Convert to float64 for precise arithmetic to avoid precision loss
# that can occur with float32 input at digital value boundaries
p_signal = p_signal.astype("float64", copy=False)
np.multiply(p_signal, adc_gain, p_signal)
np.add(p_signal, baseline, p_signal)
np.round(p_signal, 0, p_signal)
np.copyto(p_signal, d_nan, where=nanlocs)
d_signal = p_signal.astype(intdtype, copy=False)
return d_signal

# Do inplace conversion and set relevant variables.
values = self.e_p_signal if expanded else self.p_signal
digital = _adc_values(
values,
self.fmt,
self.adc_gain,
self.baseline,
expanded=expanded,
inplace=inplace,
)
if inplace:
if expanded:
for ch, ch_p_signal in enumerate(self.e_p_signal):
ch_d_signal = adc_inplace(
ch_p_signal,
self.adc_gain[ch],
self.baseline[ch],
d_nans[ch],
)
self.e_p_signal[ch] = ch_d_signal
self.e_d_signal = self.e_p_signal
self.e_d_signal = digital
self.e_p_signal = None
else:
self.d_signal = adc_inplace(
self.p_signal,
self.adc_gain,
self.baseline,
d_nans,
)
self.d_signal = digital
self.p_signal = None

# Return the variable
else:
if expanded:
e_d_signal = []
for ch, ch_p_signal in enumerate(self.e_p_signal):
ch_d_signal = adc_inplace(
ch_p_signal.astype("float64"),
self.adc_gain[ch],
self.baseline[ch],
d_nans[ch],
)
e_d_signal.append(ch_d_signal)
return e_d_signal

else:
return adc_inplace(
self.p_signal.astype("float64"),
self.adc_gain,
self.baseline,
d_nans,
)
return None
return digital

def dac(self, expanded=False, return_res=64, inplace=False):
"""Perform the digital to analogue conversion of the signal.
Expand Down
13 changes: 10 additions & 3 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -5744,7 +5744,7 @@ def write(
digital = self.e_d_signal if expanded else self.d_signal
if digital is None:
physical_checked = self._validate_physical_values_if_ready()
converted = self.adc(expanded=expanded)
converted = self._adc_values_for_write(expanded)
if expanded:
self.e_d_signal = converted
else:
Expand All @@ -5753,7 +5753,7 @@ def write(
elif derive_features:
self._prepare_digital_features(expanded=expanded, convert=physical)
elif physical:
converted = self.adc(expanded=expanded)
converted = self._adc_values_for_write(expanded)
if expanded:
self.e_d_signal = converted
else:
Expand All @@ -5774,6 +5774,13 @@ def write(
)
self._write_files(write_dir, archive_path)

def _adc_values_for_write(self, expanded):
"""Convert the selected physical arrays without a Record method."""
values = self.e_p_signal if expanded else self.p_signal
return _signal._adc_values(
values, self.fmt, self.adc_gain, self.baseline, expanded=expanded
)

def _prepare_digital_features(
self, *, expanded: bool, convert: bool = False
) -> None:
Expand All @@ -5782,7 +5789,7 @@ def _prepare_digital_features(
self.check_field("e_p_signal" if expanded else "p_signal")
for field in ("fmt", "adc_gain", "baseline"):
self.check_field(field, "all")
converted = self.adc(expanded=expanded)
converted = self._adc_values_for_write(expanded)
if expanded:
self.e_d_signal = converted
else:
Expand Down
54 changes: 54 additions & 0 deletions tests/test_explicit_adc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""ADC conversion from explicit arrays keeps the public Record behavior."""

import numpy as np
import pytest

import wfdb
from wfdb.io import _signal


@pytest.mark.parametrize("expanded", [False, True])
def test_explicit_adc_keeps_missing_markers_and_input_values(expanded):
"""Each channel uses its format marker without changing caller arrays."""
uniform = np.array([[0.5, -0.5], [np.nan, np.nan]], dtype=np.float32)
values = [uniform[:, 0].copy(), uniform[:, 1].copy()] if expanded else uniform
digital = _signal._adc_values(
values, ["16", "212"], [200.0, 100.0], [0, 0], expanded=expanded
)

expected = [[100, -50], [-32768, -2048]]
actual = np.column_stack(digital) if expanded else digital
np.testing.assert_array_equal(actual, expected)
np.testing.assert_array_equal(
np.column_stack(values) if expanded else values, uniform
)


def test_public_adc_inplace_retains_record_mutation():
"""Record.adc(inplace=True) still moves values to the digital field."""
physical = np.array([[0.5], [np.nan]], dtype=np.float64)
record = wfdb.Record(p_signal=physical, fmt=["16"], adc_gain=[200.0], baseline=[0])

assert record.adc(inplace=True) is None
assert record.p_signal is None
np.testing.assert_array_equal(record.d_signal, [[100], [-32768]])
np.testing.assert_array_equal(physical, [[100], [-32768]])


def test_model_write_does_not_call_record_adc(tmp_path, monkeypatch):
"""Modern physical writes use the explicit array conversion."""

def unexpected_adc(*_args, **_kwargs):
pytest.fail("called SignalMixin.adc")

monkeypatch.setattr(_signal.SignalMixin, "adc", unexpected_adc)
wfdb.write_signals(
tmp_path / "copy",
np.array([[0.0], [0.1], [0.2]]),
fs=125,
kind="physical",
formats="16",
channel_names=["I"],
units=["mV"],
)
assert (tmp_path / "copy.hea").exists()
Loading