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
7 changes: 7 additions & 0 deletions changelog.d/record-data-calibration.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
**Edit digital calibration with an explicit meaning**
``RecordData.with_calibration(adc_gain=..., baseline=..., mode=...)`` now
validates a complete per-channel calibration. ``mode="reinterpret"`` keeps
the digital samples; ``mode="rescale"`` adjusts them using the existing ADC
rounding rule to preserve physical values as closely as possible. Rescaling
rejects unknown current calibration and values outside the target format's
valid range. Physical values continue to choose calibration when written.
22 changes: 21 additions & 1 deletion docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -575,7 +575,8 @@ files that either reader accepts.
.. autoclass:: wfdb.io.RecordData
:no-index:
:members: to_physical, to_digital, to_legacy_record, select,
with_values, with_channels, with_comments, shift_time, write
with_values, with_channels, with_calibration, with_comments,
shift_time, write

.. autoclass:: wfdb.io.UniformSignals
:no-index:
Expand Down Expand Up @@ -627,6 +628,20 @@ return independent arrays. They update the selected view and leave
Changing a unit label does not rescale the samples or change gain and
baseline; use it to correct a mislabeled header, not to convert units.

For digital values, ``RecordData.with_calibration(adc_gain=..., baseline=...,
mode=...)`` changes the per-channel calibration. Both sequences must have one
value per loaded channel. Gains must be positive and finite, and baselines
must be signed 32-bit integers. ``mode="reinterpret"`` keeps the integers and
changes the physical values they represent. ``mode="rescale"`` changes the
integers to preserve the physical values as closely as the new calibration
allows. Rescaling requires a known current gain and baseline for each channel.
It uses the existing ADC rule: round to the nearest integer, with exact ties
going to the even integer. Values that hit a known format's missing marker or
exceed its valid range fail at the edit. Rescaling also preserves the loaded
integer dtype and rejects values that would require widening it. Both modes
copy the arrays and masks, and leave the source header unchanged. For physical
values, choose calibration when writing rather than editing the loaded values.

``RecordData.shift_time(timedelta(...))`` changes the selected start date and
time without changing samples. A time-only value wraps within the day, so
whole-day shifts have no visible effect without a date. A date-only value
Expand All @@ -646,6 +661,11 @@ do not share the result's source provenance if it is sensitive.
labeled = edited.with_channels(names=["ECG lead V5", "ECG lead II"])
labeled = labeled.with_comments(["Reviewed for release"])

digital = wfdb.read_signals("sample-data/100", kind="digital", layout="uniform")
corrected = digital.with_calibration(
adc_gain=[200.0, 200.0], baseline=[1024, 1024], mode="reinterpret"
)

Writing a selected signal view
------------------------------

Expand Down
142 changes: 138 additions & 4 deletions src/wfdb/io/_record_data_edits.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,115 @@ 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":
raise ValueError(
"with_calibration applies only to digital values; choose calibration "
"with write options for physical values"
)
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))
if mode == "reinterpret":
return _replace_record_metadata(read, calibration=calibration)

old = read.metadata.signals
missing = [
index
for index, signal in enumerate(old)
if signal.adc_gain is None
or signal.baseline is None
or not np.isfinite(signal.adc_gain)
or signal.adc_gain <= 0
]
if missing:
raise ValueError(
"Cannot rescale channels without current adc_gain and baseline: "
+ ", ".join(map(str, missing))
)
expanded = isinstance(read.signals, ExpandedSignals)
channels = read.signals.values if expanded else tuple(read.signals.values.T)
output = []
for index, channel in enumerate(channels):
mask = np.ma.getmaskarray(channel)
source = np.ma.getdata(channel)
converted = np.zeros(source.shape, dtype=np.int64)
valid = ~mask
if np.any(valid):
physical = (source[valid].astype(np.float64) - old[index].baseline) / old[
index
].adc_gain
rounded = np.rint(physical * gains[index] + offsets[index])
limits = np.iinfo(np.int64)
if (
not np.all(np.isfinite(rounded))
or np.any(rounded < limits.min)
or np.any(rounded >= -float(limits.min))
):
raise ValueError(f"rescaled channel {index} exceeds integer range")
converted[valid] = rounded.astype(np.int64)
output.append(np.ma.array(converted, mask=mask, copy=False))
_validate_digital_ranges(read, output)
casted = []
for index, (source, converted) in enumerate(zip(channels, output, strict=True)):
bounds = np.iinfo(source.dtype)
valid = np.ma.getdata(converted)[~np.ma.getmaskarray(converted)]
if valid.size and (np.min(valid) < bounds.min or np.max(valid) > bounds.max):
raise ValueError(
f"rescaled channel {index} exceeds loaded {source.dtype} "
"resolution; reread with a higher resolution"
)
casted.append(
np.ma.array(
np.ma.getdata(converted).astype(source.dtype),
mask=np.ma.getmaskarray(converted),
copy=False,
)
)
arrays = tuple(casted) if expanded else np.ma.column_stack(casted)
return _replace_record_metadata(
read, calibration=calibration, replacement_values=arrays
)


def shift_record_time(read, delta):
"""Shift the selected start date or time without changing its source."""
if not isinstance(delta, datetime.timedelta):
Expand Down Expand Up @@ -406,15 +515,22 @@ def shift_record_time(read, delta):


def _replace_record_metadata(
read, *, names=None, units=None, comments=None, timing=None
read,
*,
names=None,
units=None,
comments=None,
timing=None,
calibration=None,
replacement_values=None,
):
"""Copy arrays and change only the selected view's header metadata."""
model = read._model
expanded = isinstance(read.signals, ExpandedSignals)
current = read.signals.values if replacement_values is None else replacement_values
if read.signals.kind == "digital":
values, mask = _copy_digital(read.signals.values, expanded)
values, mask = _copy_digital(current, expanded)
else:
current = read.signals.values
values = (
tuple(value.copy() for value in current) if expanded else current.copy()
)
Expand All @@ -434,6 +550,12 @@ def _replace_record_metadata(
record.comments = list(comments)
if timing is not None:
record.base_date, record.base_time = timing
if calibration is not None:
record.adc_gain = list(calibration[0])
record.baseline = list(calibration[1])
if replacement_values is not None:
record.init_value = [None] * read.metadata.n_signals
record.checksum = [None] * read.metadata.n_signals
field = ("e_" if expanded else "") + (
"p_signal" if read.signals.kind == "physical" else "d_signal"
)
Expand All @@ -451,9 +573,17 @@ def _replace_record_metadata(
signal,
sig_name=signal.sig_name if names is None else names[index],
units=signal.units if units is None else units[index],
adc_gain=signal.adc_gain
if calibration is None
else calibration[0][index],
baseline=signal.baseline
if calibration is None
else calibration[1][index],
)
for index, signal in enumerate(model.selected_header.signals)
)
if replacement_values is not None:
selected = _clean_signals(selected)
selected_comments = (
model.selected_header.comments if comments is None else comments
)
Expand Down Expand Up @@ -482,7 +612,11 @@ def _replace_record_metadata(
metadata=metadata,
)
)
object.__setattr__(result, "_edited_values", getattr(read, "_edited_values", False))
object.__setattr__(
result,
"_edited_values",
replacement_values is not None or getattr(read, "_edited_values", False),
)
return result


Expand Down
38 changes: 38 additions & 0 deletions src/wfdb/io/signal_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,44 @@ def with_channels(

return replace_record_channel_metadata(self, names, units)

def with_calibration(
self,
*,
adc_gain: list[float] | tuple[float, ...],
baseline: list[int] | tuple[int, ...],
mode: Literal["rescale", "reinterpret"],
) -> "RecordData":
"""Return digital data with a validated per-channel calibration.

``mode="rescale"`` changes the integers to preserve their physical
values under the new gain and baseline. It requires a known current
calibration for every channel. Conversion uses WFDB's existing ADC
rounding rule (nearest integer, with ties to even). Values that do not
fit their known storage formats or the loaded integer dtype are
rejected immediately; the dtype is never silently widened.
``mode="reinterpret"`` keeps the integers and changes the physical
values they represent. Both modes copy the arrays and masks, retain
source provenance, and leave this object unchanged. Use write options
to choose calibration when writing physical data.

Parameters
----------
adc_gain : sequence of float
One positive finite gain per loaded channel.
baseline : sequence of int
One signed 32-bit baseline per loaded channel.
mode : {"rescale", "reinterpret"}
Whether to preserve physical values or digital integers.

Returns
-------
RecordData
An independent result with the requested calibration.
"""
from wfdb.io._record_data_edits import replace_record_calibration

return replace_record_calibration(self, adc_gain, baseline, mode)

def with_comments(self, comments: list[str] | tuple[str, ...]) -> "RecordData":
"""Return a copy with replacement record comments.

Expand Down
Loading
Loading