Skip to content

Add validated calibration edits to RecordData - #918

Merged
tompollard merged 2 commits into
mainfrom
feature/record-data-calibration
Dec 4, 2026
Merged

tompollard merged 2 commits into
mainfrom
feature/record-data-calibration

Conversation

@tompollard

@tompollard tompollard commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Add RecordData.with_calibration(adc_gain=..., baseline=..., mode=...) for digital reads.
  • mode="reinterpret" keeps the stored integers and changes their physical interpretation. mode="rescale" adjusts the integers to preserve physical values as closely as the new calibration permits.
  • Require one gain and baseline per loaded channel. Reject missing current calibration for rescaling, invalid gains or baselines, reserved marker collisions, values outside known target formats, and values that would widen the loaded integer dtype when the edit is made.
  • Copy values and masks, retain source provenance, and clear sample-dependent declarations after rescaling. Physical reads direct callers to write options instead.

This is based on main after #917 merged. The physical write-option change is in the stacked #919 PR.

Rounding detail

The existing ADC implementation uses NumPy rounding, so exact halves go to the even integer. This PR uses that same rule. The proposed “half up” wording does not match the current code.

WFDB's existing writer requires positive gains, so this edit uses positive finite gains rather than allowing negative ones.

Verification

  • 2,279 offline tests passed; 4 skipped and 23 network tests deselected.
  • Ruff check and format passed; Sphinx docs built with warnings treated as errors.
  • New tests cover masked and expanded values, both calibration meanings, round-trip writes, format limits, unknown source gain, input validation, and a 5.17.0 pickle.

Base automatically changed from feature/write-record-data to main December 4, 2026 18:34
@tompollard
tompollard force-pushed the feature/record-data-calibration branch from 96b6898 to 8cfe663 Compare December 4, 2026 18:34

@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.

This implements the calibration contract, and the arithmetic is right. One small fix is needed: rescale changes the dtype. Thanks for correcting the rounding rule. _adc_inplace uses np.round, which rounds halves to even, and I had mixed it up with the round-half-up rule in frame smoothing. The offline suite (2,276 passed, 4 skipped) and Ruff pass.

What I checked

  • rescale equals converting to physical and back through the ADC. For every sample record with known calibration, in both layouts, I chose a random new gain (0.1× to 2× the current one) and a baseline offset of up to ±5. I compared with_calibration(..., mode="rescale") with np.round(to_physical() * new_gain + new_baseline). All 68 accepted edits match exactly, masks included. The other 18 were rejected when the edit was made, because the rescaled values didn't fit the channel's format.
  • Round trips. Rescaled data for 100 (uniform) and test01_00s_frame (expanded, with several samples per frame) writes and reads back unchanged, and its physical values stay within one new quantisation step of the originals. Gains of 1/3, 200.123456789, 1e-07 and 123456789.5 all reach the header and read back exactly.
  • Unknown calibration. The s25047 variable-layout read, whose channels have adc_gain=None after combining, is rejected for rescale with a message listing the channels. reinterpret can still set it.

To fix: rescale changes the dtype

A read with resolution=16 returns int16 values. After with_calibration(..., mode="rescale") they're int64, because the converted arrays are created as int64 and kept. with_values keeps the dtype (int16 stays int16), and the other edits do too. resolution is the caller's choice and shouldn't change through an edit.

Casting back to the original dtype after the range check would fix it. If a rescaled value doesn't fit that dtype, even though it fits the storage format, raise a clear error rather than widen silently. A test with resolution=16 would pin it.

@tompollard

Copy link
Copy Markdown
Member Author

Thanks, agreed. I fixed this in 10ecb1e. rescale now checks the values against the channel's storage format and the loaded integer dtype, then casts back to that dtype. A value that fits the storage format but not the loaded dtype raises a ValueError suggesting a read at higher resolution.

I added uniform and expanded resolution=16 tests, plus a case where a value fits format 24 but would widen an int16 array. The offline suite passes (2,279 passed, 4 skipped), as do Ruff and the documentation build. I also rebased the stacked #919 branch onto this fix.

@tompollard
tompollard merged commit 2cd73e9 into main Dec 4, 2026
19 checks passed
@tompollard
tompollard deleted the feature/record-data-calibration branch December 4, 2026 18:43
tompollard added a commit that referenced this pull request Dec 4, 2026
## Summary

- Add paired `adc_gain` and `baseline` options to `RecordData.write` and
`write_record(path, data)` for physical `RecordData`. The two entry
points use the same write path.
- Validate one positive finite gain and one signed 32-bit baseline per
channel before creating files. Digital `RecordData` uses
`with_calibration`; mutable `Record` keeps its existing fields.
- Apply the calibration to a private write copy, leaving loaded values
and source metadata unchanged. For flattened reads with ambiguous
formats, require `formats=` so the writer cannot silently replace the
requested calibration.
- Refresh initial values and checksums when calibration changes the
integers or a target format recodes missing markers. Repeating the
source format leaves an otherwise unchanged write byte-identical.
- Fill omitted `adc_res` and `adc_zero` in the outgoing header when
derived initial values or checksums require those positional fields.
This also repairs partial writes through the legacy `Record.wrsamp`
path.
- Both paths use the existing format range and missing-marker checks
before writing.
- Share gain/baseline validation with `RecordData.with_calibration` from
#918.

This PR is rebased onto main after #918 merged.

## Verification

- 2,307 offline tests passed; 4 skipped and 23 network tests deselected.
- Ruff check and the warning-as-error Sphinx build passed.
- New tests cover both writer forms producing identical bytes, uniform
and expanded values, flattened records, mixed formats, old pickles,
valid and invalid calibration, marker and range failures before files
exist, and checksum refresh after missing-marker recoding. They also
cover full and partial `n8_evoked_raw_95_F1_R9` writes, edits, and the
legacy partial writer.

The broader existing issue of stale `init_value` and `checksum` on
otherwise unedited `RecordData` writes is tracked separately in #920.
That fix will deliberately change more header bytes and deserves its own
comparison and review.
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