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
6 changes: 6 additions & 0 deletions changelog.d/physical-recorddata-write-calibration.rst
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions changelog.d/write-missing-adc-defaults.rst
Original file line number Diff line number Diff line change
@@ -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.
12 changes: 12 additions & 0 deletions docs/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
40 changes: 40 additions & 0 deletions src/wfdb/io/_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
45 changes: 7 additions & 38 deletions src/wfdb/io/_record_data_edits.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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":
Expand All @@ -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)

Expand Down
26 changes: 23 additions & 3 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``.

Expand Down Expand Up @@ -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
-------
Expand All @@ -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
Expand Down Expand Up @@ -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"):
Expand Down
103 changes: 99 additions & 4 deletions src/wfdb/io/signal_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import copy
import datetime
import operator
import os
from dataclasses import dataclass, replace
from typing import Literal
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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,
Expand All @@ -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 "") + (
Expand All @@ -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)
),
)


Expand All @@ -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
Expand All @@ -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 = {}
Expand Down
Loading
Loading