Repository navigation
Choose calibration when writing physical RecordData - #919
Conversation
2d777a7 to
ce4df08
Compare
## 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.
ce4df08 to
1ab4a35
Compare
tompollard
left a comment
There was a problem hiding this comment.
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_valuesor physicalselectresult 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
41885instead of-23651. These are equivalent. - 224 header lines get a different
init_value, and the new one is correct. For03700181in uniform layout, MCL1 (4 samples per frame) becomes56instead of67, because the first written sample is the frame average. RESP becomes-208instead of-304because of aligned skew. - 4 outcomes are the
n8failures 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_valueandchecksumfrom the written values on everyRecordDatawrite. That fixes the stale values everywhere and makesformats=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_valueto 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.
|
Thanks, I agree with the distinction between the new calibration behavior and the older declaration bug. I fixed the 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 I agree that |
Summary
adc_gainandbaselineoptions toRecordData.writeandwrite_record(path, data)for physicalRecordData. The two entry points use the same write path.RecordDatauseswith_calibration; mutableRecordkeeps its existing fields.formats=so the writer cannot silently replace the requested calibration.adc_resandadc_zeroin the outgoing header when derived initial values or checksums require those positional fields. This also repairs partial writes through the legacyRecord.wrsamppath.RecordData.with_calibrationfrom Add validated calibration edits to RecordData #918.This PR is rebased onto main after #918 merged.
Verification
n8_evoked_raw_95_F1_R9writes, edits, and the legacy partial writer.The broader existing issue of stale
init_valueandchecksumon otherwise uneditedRecordDatawrites is tracked separately in #920. That fix will deliberately change more header bytes and deserves its own comparison and review.