Skip to content
Open
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/uncalibrated-modern-metadata.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
**Report uncalibrated gains and default ADC resolution in modern metadata**
``read_header``, ``RecordData.metadata``, and
``SegmentedRecordData.metadata`` now report ``adc_gain=None`` for an
omitted or zero gain, and the WFDB specification's default ADC resolution
for an omitted or zero value. Physical conversion still uses gain 200.
Writing an uncalibrated ``RecordData`` keeps the signal uncalibrated.
Legacy record fields are unchanged.
7 changes: 6 additions & 1 deletion src/wfdb/io/_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ class _ParsedSignalLine:
checksum: int | None
block_size: int | None
sig_name: str | None
uncalibrated: bool = False


@dataclass(frozen=True)
Expand Down Expand Up @@ -1597,6 +1598,7 @@ def _parse_signal_lines(signal_lines):
# Each dictionary field is a list
for field in SIGNAL_SPECS.index:
signal_fields[field] = n_sig * [None]
signal_fields["uncalibrated"] = n_sig * [False]

# Read string fields from signal line
for ch in range(n_sig):
Expand All @@ -1619,6 +1621,8 @@ def _parse_signal_lines(signal_lines):
signal_fields["block_size"][ch],
signal_fields["sig_name"][ch],
) = match.groups()
raw_gain = signal_fields["adc_gain"][ch]
signal_fields["uncalibrated"][ch] = raw_gain == "" or float(raw_gain) == 0

for field in SIGNAL_SPECS.index:
# Replace empty strings with their read defaults (which are mostly None)
Expand Down Expand Up @@ -1671,7 +1675,8 @@ def _parse_header_fields(
signal_fields = _parse_signal_lines(header_lines[1:])
signals = tuple(
_ParsedSignalLine(
**{field: signal_fields[field][ch] for field in SIGNAL_SPECS.index}
**{field: signal_fields[field][ch] for field in SIGNAL_SPECS.index},
uncalibrated=signal_fields["uncalibrated"][ch],
)
for ch in range(len(header_lines) - 1)
)
Expand Down
10 changes: 8 additions & 2 deletions src/wfdb/io/_read_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,15 +266,21 @@ def _metadata_for_view(fields, signals, comments, kind, layout):
logical=LogicalSignalMetadata(
name=signal.sig_name,
units=signal.units,
adc_gain=signal.adc_gain,
adc_gain=(
None if getattr(signal, "uncalibrated", False) else signal.adc_gain
),
baseline=signal.baseline,
),
storage=SignalStorageMetadata(
file_name=signal.file_name,
format=signal.fmt,
samples_per_frame=_plain_int(signal.samps_per_frame),
byte_offset=_plain_int(signal.byte_offset),
adc_res=_plain_int(signal.adc_res),
adc_res=(
_signal._default_adc_res(signal.fmt)
if signal.adc_res in (None, 0)
else _plain_int(signal.adc_res)
),
adc_zero=_plain_int(signal.adc_zero),
init_value=_plain_int(signal.init_value),
checksum=_plain_int(signal.checksum),
Expand Down
5 changes: 5 additions & 0 deletions src/wfdb/io/_record_data_edits.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,11 @@ def _replace_record_metadata(
adc_gain=signal.adc_gain
if calibration is None
else calibration[0][index],
uncalibrated=(
getattr(signal, "uncalibrated", False)
if calibration is None
else False
),
baseline=signal.baseline
if calibration is None
else calibration[1][index],
Expand Down
12 changes: 12 additions & 0 deletions src/wfdb/io/_signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,18 @@
"524": 24,
}


def _default_adc_res(fmt):
"""Return the WFDB specification's default ADC resolution for a format."""
if fmt == "80":
return 8
if fmt == "160":
return 16
if fmt in ("310", "311"):
return 10
return 12


# Numpy dtypes used to load dat files of each format.
DATA_LOAD_TYPES = {
"8": "<i1",
Expand Down
18 changes: 13 additions & 5 deletions src/wfdb/io/headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import datetime
from dataclasses import dataclass

from wfdb.io import _header
from wfdb.io import _header, _signal


@dataclass(frozen=True)
Expand All @@ -13,8 +13,10 @@ class SignalHeader:
The values describe the stored signal, including its file layout and
calibration, not a selected or aligned array returned by ``rdrecord``.
``baseline`` is resolved to ``adc_zero`` when given, or zero otherwise.
Omitted optional fields such as ``adc_zero``, ``adc_res``, and
``init_value`` remain ``None`` even when WFDB defines an effective default.
An omitted or zero gain is reported as ``None`` (uncalibrated); conversion
still uses WFDB's default gain of 200. Omitted or zero ADC resolution is
reported as the format's default. Other omitted optional fields such as
``adc_zero`` and ``init_value`` remain ``None``.
"""

name: str | None
Expand Down Expand Up @@ -135,10 +137,16 @@ def _from_parsed_header(
samples_per_frame=signal.samps_per_frame,
skew=signal.skew,
byte_offset=signal.byte_offset,
adc_gain=signal.adc_gain,
adc_gain=(
None if getattr(signal, "uncalibrated", False) else signal.adc_gain
),
baseline=signal.baseline,
units=signal.units,
adc_res=signal.adc_res,
adc_res=(
_signal._default_adc_res(signal.fmt)
if signal.adc_res in (None, 0)
else signal.adc_res
),
adc_zero=signal.adc_zero,
init_value=signal.init_value,
checksum=signal.checksum,
Expand Down
18 changes: 18 additions & 0 deletions src/wfdb/io/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -5111,8 +5111,25 @@ def _write_model_header(writer, expanded, write_dir, archive):
for field in (*_header.RECORD_SPECS.index, *_header.SIGNAL_SPECS.index)
}
header_fields["comments"] = values["comments"]
if writer.uncalibrated_channels:
header_fields["adc_gain"] = list(header_fields["adc_gain"])
for channel in writer.uncalibrated_channels:
header_fields["adc_gain"][channel] = 0.0

def validate(field, required_channels="all", signal_snapshot=None):
if field == "adc_gain" and writer.uncalibrated_channels:
# Conversion used the effective gain of 200. The outgoing header
# keeps zero to distinguish an uncalibrated source signal.
effective = list(header_fields[field])
for channel in writer.uncalibrated_channels:
effective[channel] = 200.0
_check_field_value(
field,
effective,
required_channels,
lookup=header_fields.__getitem__,
)
return
_check_field_value(
field,
header_fields[field],
Expand Down Expand Up @@ -5572,6 +5589,7 @@ class _WriteModel:
skew: tuple[int | None, ...] | None
from_segments: bool
checksums_from_values: bool = False
uncalibrated_channels: tuple[int, ...] = ()

def _warn_about_replacing_other_files(self, write_dir):
"""Warn from this model's current destination fields."""
Expand Down
38 changes: 38 additions & 0 deletions src/wfdb/io/segment_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@
)
from wfdb.io.archive import WFDBArchive, is_archive_path
from wfdb.io.headers import MultiSegmentHeader, SingleSegmentHeader, _from_parsed_header
from wfdb.io.metadata import (
ChannelMetadata,
LogicalSignalMetadata,
SignalStorageMetadata,
)
from wfdb.io.record import SourceSelection
from wfdb.io.signal_values import ExpandedSignals, RecordData, _from_read_model

Expand All @@ -45,6 +50,7 @@ class SegmentedRecordMetadata:
base_date: datetime.date | None
base_time: datetime.time | None
comments: tuple[str, ...]
channels: tuple[ChannelMetadata, ...] = ()

@property
def n_signals(self) -> int:
Expand Down Expand Up @@ -104,6 +110,29 @@ def _selected_master_metadata(
base_date=selected_date,
base_time=selected_time,
comments=source_header.comments,
channels=tuple(
ChannelMetadata(
logical=LogicalSignalMetadata(
name=signal.name,
units=signal.units,
adc_gain=signal.adc_gain,
baseline=signal.baseline,
),
storage=SignalStorageMetadata(
file_name=signal.file_name,
format=signal.format,
samples_per_frame=signal.samples_per_frame,
byte_offset=signal.byte_offset,
adc_res=signal.adc_res,
adc_zero=signal.adc_zero,
init_value=signal.init_value,
checksum=signal.checksum,
block_size=signal.block_size,
),
)
for channel in selection.channels
for signal in (channel_header.signals[channel],)
),
)


Expand Down Expand Up @@ -148,6 +177,15 @@ class SegmentedRecordData:
def __setstate__(self, state: dict) -> None:
"""Restore selected metadata absent from 5.18 and 6.0 pickles."""
self.__dict__.update(state)
if "metadata" in state and "channels" not in vars(self.metadata):
channels = _selected_master_metadata(
self.source_header,
self.channel_header,
self.source_selection,
self.metadata.kind,
self.metadata.signal_layout,
).channels
object.__setattr__(self.metadata, "channels", channels)
if "metadata" not in state:
first_data = next(
(segment.data for segment in self.segments if segment.data is not None),
Expand Down
6 changes: 6 additions & 0 deletions src/wfdb/io/signal_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,12 @@ def write(
model = _WriteModel.from_record(
source, field, "expanded" if expanded else "uniform", signal_alignment
)
if calibration is None and self._model is not None:
model.uncalibrated_channels = tuple(
index
for index, signal in enumerate(self._model.selected_header.signals)
if getattr(signal, "uncalibrated", False)
)
model.write(
name,
directory,
Expand Down
10 changes: 1 addition & 9 deletions tests/spec_conformance.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
{
"spec_repository": "https://github.com/wfdb/wfdb-spec",
"spec_commit": "ad32e3231a55cf9c8b8fb4da68f64d198bf4884d",
"spec_commit": "cff1af24274d3051a0a43d8d415b216b76e6c690",
"known_gaps": {
"header-partial-signal-fields": {
"status": "differs",
"issue": 937
},
"header-signal-defaults": {
"status": "differs",
"issue": 937
},
"multi-segment-variable-rounding": {
"status": "differs",
"issue": 933
Expand Down
2 changes: 1 addition & 1 deletion tests/test_physical_recorddata_write_calibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def test_missing_adc_fields_are_filled_for_derived_declarations(tmp_path, edit):
header = wfdb.rdheader(str(destination))
assert header.adc_res == [24, 24]
assert header.adc_zero == [0, 0]
assert read.source_header.signals[0].adc_res is None
assert read.source_header.signals[0].adc_res == 12


def test_full_n8_write_accepts_explicit_format(tmp_path):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_read_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,15 @@ def test_read_header_needs_no_signal_file(tmp_path):


def test_omitted_optional_signal_fields_remain_none(tmp_path):
"""Keep omitted fields distinct from effective format defaults."""
"""Resolve ADC resolution while retaining other omitted fields."""
path = Path(tmp_path) / "t.hea"
path.write_text("t 1 100 1\nt.dat 16\n")

signal = wfdb.read_header(path.with_suffix("")).signals[0]

assert signal.baseline == 0
assert signal.adc_zero is None
assert signal.adc_res is None
assert signal.adc_res == 12
assert signal.init_value is None


Expand Down
33 changes: 31 additions & 2 deletions tests/test_read_model_snapshots.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import pytest

import wfdb
from wfdb.io._header import _ParsedSignalLine

CASES = {
"single_basic": ("sample-data/100", {"stop": 8}),
Expand Down Expand Up @@ -124,6 +125,20 @@
FORMAT24_SOURCE_HASH = (
"ed8aa3c182d0a9c3cd328eb666700d85af609a839b65934efbb7c3f5ab87420a"
)
DEFAULT_METADATA_CASES = {
"single_format_24",
"multi_fixed_boundary",
"multi_fixed_later",
"multi_041s_boundary",
"multi_variable_names",
"multi_variable_boundary_one",
"multi_variable_boundary_two",
}
DEFAULT_SOURCE_CASES = {
"single_format_24",
"multi_fixed_boundary",
"multi_fixed_later",
}
EMPTY_SELECTION_ERROR = {
"error_type": "ValueError",
"error": "No selected channels are present in the requested sample range",
Expand All @@ -145,6 +160,9 @@ def _plain(value):
return {
field.name: _plain(getattr(value, field.name))
for field in dataclasses.fields(value)
if not (
isinstance(value, _ParsedSignalLine) and field.name == "uncalibrated"
)
}
if isinstance(value, np.ndarray):
return _array_snapshot(value)
Expand Down Expand Up @@ -268,6 +286,17 @@ def snapshot(case, kind, layout):
return result


def _compare_with_old_defaults(actual, expected, case):
"""Keep old sample checks while allowing the #937 header field changes."""
if case in DEFAULT_METADATA_CASES and "metadata" in actual:
actual["metadata"].pop("all_fields_sha256")
expected["metadata"].pop("all_fields_sha256")
if case in DEFAULT_SOURCE_CASES and "provenance" in actual:
actual["provenance"].pop("all_fields_sha256")
expected["provenance"].pop("all_fields_sha256")
assert actual == expected


@pytest.mark.parametrize(("case", "kind", "layout"), VARIANTS)
def test_read_matches_v5_17_snapshot(case, kind, layout):
"""Selected values, masks, metadata and provenance match the release."""
Expand Down Expand Up @@ -298,7 +327,7 @@ def test_read_matches_v5_17_snapshot(case, kind, layout):
assert expected["error_type"] == "Exception"
assert snapshot(case, kind, layout) == MISMATCHED_DIGITAL_ERROR
return
assert snapshot(case, kind, layout) == expected
_compare_with_old_defaults(snapshot(case, kind, layout), expected, case)


@pytest.mark.parametrize(("case", "kind", "layout"), VARIANTS)
Expand All @@ -312,4 +341,4 @@ def test_read_record_matches_v5_18_read_signals(case, kind, layout):
expected["metadata"]["all_fields_sha256"] = metadata_hash
expected["provenance"]["all_fields_sha256"] = FORMAT24_SOURCE_HASH
expected["legacy_fields_sha256"] = legacy_hash
assert snapshot(case, kind, layout) == expected
_compare_with_old_defaults(snapshot(case, kind, layout), expected, case)
Loading
Loading