Skip to content

Choose calibration when writing physical RecordData - #919

Merged
tompollard merged 2 commits into
mainfrom
feature/physical-recorddata-write-calibration
Dec 4, 2026
Merged

tompollard merged 2 commits into
mainfrom
feature/physical-recorddata-write-calibration

Conversation

@tompollard

@tompollard tompollard commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

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 Add validated calibration edits to RecordData #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.

@tompollard
tompollard force-pushed the feature/physical-recorddata-write-calibration branch from 2d777a7 to ce4df08 Compare December 4, 2026 18:42
tompollard added a commit that referenced this pull request Dec 4, 2026
## 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/record-data-calibration to main December 4, 2026 18:43
@tompollard
tompollard force-pushed the feature/physical-recorddata-write-calibration branch from ce4df08 to 1ab4a35 Compare December 4, 2026 18:43

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

The calibration options work as designed. But tying the refresh of init_value and checksum to formats= makes some writes that work on main fail, and it exposes an older writer bug that needs fixing first. I reviewed only the commit on top of #918 (2d777a7). The offline suite (2,298 passed, 4 skipped) and Ruff pass.

The calibration options: correct

On 100 (uniform), test01_00s_frame (expanded, several samples per frame), s25047 (flattened variable layout) and 03700181 (skewed), I wrote physical reads with a new adc_gain/baseline and formats="16", then read the files back as digital. In every channel, the stored integers equal np.round(physical * gain + baseline), NaNs are masked, and the header has the new calibration. The loaded RecordData is unchanged. A gain that overflows format 16, a gain without a baseline, a zero gain, and the options on digital data each fail with a clear message, and none of them leaves a file behind.

To fix: formats= now breaks writes of headers without adc_res

n8_evoked_raw_95_F1_R9 declares only format, gain and units (24 2.4011e-11/nV). On main it writes with formats=None, "32" or "24". Here, "32" and "24" fail:

TypeError: ('Channel 0 of field `adc_res` must be one of the following types:', (<class 'int'>, <class 'numpy.integer'>))

The cause is older than this PR. Once the writer derives init_value and checksum, it has to write the positional fields before them, so the missing adc_res must be filled in, and validation rejects None. On main and on 5.17.0, the same error already happens for:

  • a partial read of this record: read_signals(..., stop=100).write(...);
  • any select, with_values or physical select result from it, since #908;
  • legacy rdrecord(..., sampto=100).wrsamp().

This PR adds formats= to the conditions that refresh those fields, so a full read with formats= now hits the bug too.

The proper fix belongs in the writer: when later fields are written, fill adc_res from the format's resolution and adc_zero with 0, as the legacy default-setting code does. That would make every one of these writes work, and it's small enough to land first or as part of this PR. Please add n8_evoked_raw_95_F1_R9 to the write tests for a partial read, an edit, and formats= on a full read.

To decide: when the writer derives init_value

I compared 1,836 RecordData.write outcomes between main and this branch: every sample record, both kinds and layouts, full and partial windows, and formats of None, "16" and "32". 388 differ, all with formats= set:

  • 720 header lines write the checksum in its unsigned form, for example 41885 instead of -23651. These are equivalent.
  • 224 header lines get a different init_value, and the new one is correct. For 03700181 in uniform layout, MCL1 (4 samples per frame) becomes 56 instead of 67, because the first written sample is the frame average. RESP becomes -208 instead of -304 because of aligned skew.
  • 4 outcomes are the n8 failures above.

So without formats=, which is the same on main and here, the writer keeps the source header's init_value even when it no longer describes the written data. In my check of unedited writes, 54 of 364 channels had an init_value different from their first written sample. With this PR, passing the source's own format changes the header, while omitting it doesn't.

Two options:

  • Derive init_value and checksum from the written values on every RecordData write. That fixes the stale values everywhere and makes formats= neutral. It changes bytes for those channels compared with 5.17.0, so the change and any fixture updates should be called out.
  • Refresh only when the written integers can change: calibration, or a format change where masked samples get a different marker. Leave the stale init_value to a separate issue.

I'd take the first, but as its own small PR after the adc_res fix, so the byte changes are reviewed on their own.

@tompollard

Copy link
Copy Markdown
Member Author

Thanks, I agree with the distinction between the new calibration behavior and the older declaration bug.

I fixed the n8_evoked_raw_95_F1_R9 failure in ca366ff. The shared header writer now fills omitted adc_res and adc_zero in its outgoing field snapshot when a derived init_value or checksum makes those positional fields necessary. It leaves the caller's Record or RecordData unchanged. I added tests for a partial read, select, with_values, a full read with formats=, and the legacy partial Record.wrsamp path.

I also narrowed the refresh in this PR to cases where the written integers can change: explicit calibration, or a format override that recodes missing samples. Repeating the source format now produces the same bytes as omitting formats=. That keeps the wider header changes out of this calibration PR.

I agree that RecordData.write should ultimately derive init_value and checksum from the values it actually writes on every call. I opened #920 for that separate change, with the byte-comparison and performance checks. The current branch passes 2,307 offline tests, Ruff, and the documentation build.

@tompollard
tompollard merged commit 983407b into main Dec 4, 2026
19 checks passed
@tompollard
tompollard deleted the feature/physical-recorddata-write-calibration branch December 4, 2026 18:48
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