Skip to content

Add opt-in explicit signal values reader - #772

Merged
tompollard merged 4 commits into
mainfrom
explicit-signal-values
Nov 30, 2026
Merged

tompollard merged 4 commits into
mainfrom
explicit-signal-values

Conversation

@tompollard

Copy link
Copy Markdown
Member

Summary

Add read_signal_values as an opt-in reader with a single signals field. The field is UniformSignals for a two-dimensional array with one value per channel per base frame, or ExpandedSignals for one array per channel that preserves every sample. Both state whether values are physical or digital. The result also includes a snapshot of the selected record metadata and source segment references for flattened multi-segment reads.

to_physical and to_digital return another result without changing the original. to_legacy_record returns an independent Record for the existing writer. The new reader delegates file parsing to rdrecord, so plain WFDB files, .wfdb archives, and the current legacy APIs retain their behavior.

This addresses the representation choice in #745. I used read_signal_values as a distinct opt-in name so the broader read_record/read_signals naming discussion in #672 remains open.

Verification

  • New tests cover all four physical/digital and uniform/expanded combinations, conversion in both directions, selected frames and channels, multi-segment provenance, expanded digital write/readback, and .wfdb archive write/readback.
  • Offline suite: 1,015 passed, 4 skipped, 22 network tests deselected (MPLBACKEND=Agg).
  • Ruff check and format pass.
  • Sphinx HTML build passes with warnings treated as errors.

@tompollard tompollard left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading works: all four representations match rdrecord, and conversions leave the original values unchanged. Before merging, I'd fix three API issues, since names and behaviour are hard to change after a release. Follow-ups are listed further down.

Checked:

  • tests/test_signal_values.py (10 passed) and ruff pass.
  • In-place edits to read.signals.values carry through to to_physical() and to_legacy_record().
  • Editing the record from to_legacy_record() leaves read.metadata unchanged.

Should fix before merging:

  1. Converting a variable-layout read to digital fails unhelpfully. wfdb.read_signal_values("sample-data/multi-segment/p000878/p000878-2137-10-26-16-57", stop=7500).to_digital() raises KeyError: None. That record's channels have no single format or calibration across segments, so the conversion can't work, but the error doesn't say so. Checking before converting that each channel has adc_gain, baseline and fmt, and raising a ValueError that names the channels without them, would explain it.
  2. dtype takes a number of bits, not a dtype. dtype=32 works, but dtype=np.float32 and dtype="float32" both raise return_res must be one of the following: 64, 32, 16, 8, which refers to a parameter the caller didn't use. Either accept NumPy dtypes (a floating dtype for physical values, an integer dtype for digital ones), or name the parameter resolution. Both options are listed in #672. to_physical(return_res=...) should then use the same name.
  3. SignalRead can be built without its hidden record. _record is a dataclass field with a default, so wfdb.SignalRead(signals, metadata) is accepted, but to_digital() then raises 'NoneType' object has no attribute 'adc', and to_legacy_record() returns None. Either exclude _record from __init__ and build results only through the reader, or make SignalRead self-contained: conversions could use the calibration in metadata, and the legacy record could be built from the result's own fields.

Follow-ups:

  • A conversion shares lists with the original's record. _converted_read uses copy.copy(read._record), so a converted read's record shares the original's sig_name, units, adc_gain, baseline, fmt and comments lists. Changing adc_gain[0] on a converted read's record also changed the original's record, while the original's metadata still reported the old gain, and later conversions of the original used the new one. Nothing public changes these lists today, since to_legacy_record makes a deep copy, but copying the lists in _converted_read would prevent this. It's also an example of metadata and _record getting out of step. One source of truth for calibration would avoid that.
  • Mark the new APIs as provisional. read_header, Record.metadata, read_multi_segment_headers and now read_signal_values, with its three classes, have all arrived while the naming in #672 is still open. Marking them as provisional in the docs would allow changes without a deprecation cycle.
  • More tests: a conversion that can't be done (point 1), the dtype argument (point 2), and a check that a conversion doesn't share lists with the original.
  • Memory: to_legacy_record copies all the values, about 10 MB for the whole of record 100. It would be worth mentioning in its docstring.

@tompollard

Copy link
Copy Markdown
Member Author

Thanks for the careful review. I pushed aab176b with the three changes you identified:

  • Conversion now checks fmt, adc_gain, and baseline for every channel before calling the existing converter. For the variable-layout example, it raises a ValueError naming channels 2 (V) and 3 (ABP) and their missing fields.
  • I renamed dtype and to_physical(return_res=...) to resolution, since both take a bit count. Invalid resolutions now raise errors using that name.
  • SignalRead can only be created by the reader, which supplies the record needed for conversion and writing. Calling its constructor directly raises a clear TypeError.

I also copied the mutable record lists when making a converted view, marked this new API as provisional in the docs while #672 is open, and documented that to_legacy_record() copies the signal arrays. I added tests for these cases. The full offline suite passes (1,019 passed, 4 skipped), as do Ruff and the strict docs build.

@tompollard tompollard left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, aab176b addresses all three points and the follow-ups. Looks good to merge.

Checked:

  • The variable-layout conversion now fails with a clear message: Cannot convert signal values; missing channel fields: 2 (V): fmt, adc_gain, baseline; 3 (ABP): fmt, adc_gain, baseline.
  • resolution is used in both places. np.float32, and 8 for physical values, are rejected with errors that name it.
  • SignalRead(...) raises a clear TypeError. Pickling and copy.deepcopy still work, and the copies can still be converted.
  • A converted read no longer shares lists with the original's record.
  • Tests: tests/test_signal_values.py (13 passed) and ruff pass.

Minor, not blocking:

  • dataclasses.replace(read, ...) now raises the same TypeError, which is consistent, but worth a mention in the docstring since it's a common way to adjust frozen dataclasses.
  • dataclasses.asdict(read) includes _record and recursively copies the whole Record, including its arrays. Storing _record as a plain attribute set in _create, rather than as a dataclass field, would keep it out of asdict, fields() and comparisons.

@tompollard

Copy link
Copy Markdown
Member Author

Thanks for checking again. I addressed both minor points in a16ac5d. The conversion record is now a plain internal attribute rather than a dataclass field, so fields(read) and asdict(read) exclude it. I also noted in the SignalRead docstring that dataclasses.replace() cannot construct a result because it does not supply the record needed for conversions.

I added regression tests for introspection, replace, deep copying, and pickling. The full offline suite passes (1,020 passed, 4 skipped), as do Ruff and the strict docs build.

@tompollard

Copy link
Copy Markdown
Member Author

Good catch. I fixed this in 01c12e5. Both methods now return a distinct result with independent signal arrays when the values already have the requested kind. to_physical() validates resolution before checking the kind and casts already physical values to the requested width.

I added tests for physical and digital values in both uniform and expanded layouts, array independence, changing physical resolution, and rejecting an invalid resolution. The full offline suite passes (1,025 passed, 4 skipped), as do Ruff and the strict docs build.

@tompollard
tompollard merged commit e91b1c9 into main Nov 30, 2026
19 checks passed
@tompollard
tompollard deleted the explicit-signal-values branch November 30, 2026 00:47
tompollard added a commit that referenced this pull request Nov 30, 2026
## Summary

Require `layout` as a keyword argument to `read_signal_values`. Callers
choose `layout="uniform"` to average multi-frequency channels to one
value per base frame, or `layout="expanded"` to retain every channel
sample. Omitting it now raises a `TypeError` before any file is read.

This is a small follow-up to #772 while the opt-in API is still
unreleased. It addresses the default-layout concern in #745 and #376
without changing `rdrecord`, `rdsamp`, or the WFDB file reader.

The docs explain the choice, and all examples and tests now pass a
layout. A regression test covers the omitted argument.

## Verification

- Offline suite: 1,032 passed, 4 skipped, 22 network tests deselected
(`MPLBACKEND=Agg`).
- Ruff check and format pass.
- Sphinx HTML build passes with warnings treated as errors.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant