Skip to content

Declare replacement signal alignment per write - #849

Merged
tompollard merged 5 commits into
mainfrom
fix/explicit-skew-alignment
Dec 2, 2026
Merged

tompollard merged 5 commits into
mainfrom
fix/explicit-skew-alignment

Conversation

@tompollard

@tompollard tompollard commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Add a per-write signal_alignment="aligned" | "raw" option to write_record and Record.write for replacement values whose skew alignment differs from the original read. The option never shifts samples or persists on the caller's record. Deprecated Record.wrsamp points callers to Record.write for this case.
  • Retain the source read's original skew as the reference. A changed skew remains invalid even when the caller supplies an alignment option.
  • Check whether a raw replacement is missing tail samples using the replacement array's frame count, including expanded arrays. If read selection details were lost through pickling, a raw alignment override fails safely.
  • Document and test both replacement directions, both new write APIs, changed skew, shortened replacements, pickling, the no-skew case, and the fact that an option applies only to one write.

This addresses the explicit-alignment path in #843. Direct assignments without signal_alignment continue to follow the documented assumption that replacement values retain the loaded array's alignment. #843 remains open for the broader question of whether direct assignments should require an explicit declaration.

Validation

  • Offline suite: 1,676 passed, 4 skipped, 23 network tests deselected.
  • Ruff lint and format checks passed.
  • Strict Sphinx docs build passed.

@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 main case works: an aligned read whose array is replaced with raw values, declared "raw", writes back the source skew and reads back with the original aligned values, through both write and wrsamp. Tests, Ruff, the strict docs build and CI all pass. Before merging, I think the declaration needs to stop overriding two existing safety checks. Without it, those checks reject these writes; with it, the writes succeed and produce wrong data.

1. Declaring "raw" accepts a changed skew (record.py, declare_signal_alignment, the "raw" branch)

self._read_skew = tuple(self.skew) takes the current skew as the source skew. So if the skew was changed before the declaration, _skew_for_write sees nothing to reject:

a = wfdb.read_record("sample-data/100skew", start=649000, kind="digital")
a.d_signal = wfdb.read_record(
    "sample-data/100skew", start=649000, kind="digital", ignore_skew=True
).d_signal
a.skew = [0, 7]
a.declare_signal_alignment("raw")
a.write(out)   # succeeds: header says 212:7, but the values have skew 3

Without the declaration, the same steps raise "Cannot write new skew for already aligned channel(s) 1". The same happens on an ignore_skew=True read: changing its skew and then declaring "raw" also bypasses the "Cannot write new skew after an ignore_skew=True read" error. In both cases the written record's aligned view no longer matches the source.

Suggested fix: take the source skew from the read's history rather than from self.skew. For example, use self._applied_skew when it is set, otherwise the existing self._read_skew, and fall back to self.skew only for a record that was not read with skew. _skew_for_write then rejects a changed skew as it does today. The "aligned" branch could do the same in reverse.

2. The missing-tail check uses the original read, not the replacement values (the _incomplete_skew_tail calculation)

The tail check compares source.stop with the source length. But the values being declared may come from a different read than the record's own:

a = wfdb.read_record("sample-data/100skew", start=649000, kind="digital")      # to end
a.d_signal = wfdb.read_record(
    "sample-data/100skew", start=649000, stop=649500, kind="digital", ignore_skew=True
).d_signal
a.sig_len = 500
a.declare_signal_alignment("raw")
a.write(out)   # succeeds; the last 3 samples of V5 read back as -2048

The source has real samples in those 3 frames, so this is the tail loss that the existing check is meant to prevent. Calculating the flag from the values actually loaded would catch it: the record is incomplete when source.start + <frames in the loaded array> < source_length.

There is a related gap when the read history is missing. __getstate__ drops _read_source, so after a pickle round trip the if source is not None branch is skipped and _incomplete_skew_tail keeps whatever value it had. A short aligned read (stop=100) that is pickled and then declared "raw" writes successfully. Without the pickle round trip it is rejected, as in the third test. It would be safer to reject "raw" when the record was aligned on read and its read history is no longer available, rather than leave the flag unchanged.

Smaller points

  • test_short_selection_declared_raw_still_rejects_missing_tail declares "raw" on the aligned values themselves, which is not a real use of the method. Replacing them with values from a short ignore_skew=True read would test the actual case. A test for each of the two cases above would also be worth adding.
  • On the API: the declaration is stored on the record, so it still applies after a later replacement and carries over to copies. A write-time option, for example write_record(..., signal_alignment="raw"), would apply to just that write and wouldn't leave state behind. I'm not asking for that change in this PR. But #843 is still open on whether direct assignments should require a declaration, and a public method is harder to change after release, so it may be worth settling the shape there first.

@tompollard tompollard changed the title Allow declaring replacement signal alignment Declare replacement signal alignment per write Dec 2, 2026
@tompollard

Copy link
Copy Markdown
Member Author

Thanks for catching both safety gaps. I fixed them in 36c5a9f and then changed the API in 81275ef to address the state concern as well.

The alignment choice is now a signal_alignment option on write_record, Record.write, and Record.wrsamp. It applies to one write, so replacing the array later cannot inherit an old declaration. The writer keeps the skew from the original read as its reference, which makes both changed-skew examples fail as they did before. For raw replacement values, the tail check uses the replacement array's frame count in uniform and expanded layouts. If pickling removed the source selection needed for that check, the raw override raises before writing.

I changed the short-read test to use actual raw replacement values and added tests for changed skew, a shorter replacement taken from a different read, pickling, multiple loaded forms, and a later write without the option. The offline suite passes (1,673 passed, 4 skipped), as do Ruff and the strict docs build. I updated the PR description and documentation to match the write-time API.

@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, the write-time option is a better shape, and both safety gaps are closed. I reran my earlier examples against 81275ef with signal_alignment="raw":

  • A changed skew ([0, 7]) after an aligned read, and after an ignore_skew=True read, is now rejected before any file is written.
  • A shorter raw replacement on a full read is rejected by the tail check. The expanded layout is rejected too, and no files are created.
  • After a pickle round trip, "raw" raises with the reread hint.
  • The main case still round-trips through write_record, Record.write and wrsamp, uniform and expanded. The record's skew state is unchanged after the write, and wrsamp emits one deprecation warning, not two, despite the recursive call.
  • "aligned" on an ignore_skew=True read whose array was replaced with aligned values writes the aligned view with no skew.

The offline suite (1,673 passed, 4 skipped), Ruff and the strict docs build pass locally.

One thing I'd change before merging:

  • signal_alignment raises on records without skew. write_record(path, wfdb.read_record("sample-data/100"), signal_alignment="aligned") fails with "A nonzero skew is required to declare alignment", and so does "raw". When no channel has skew, both answers are trivially true. A caller writing many records with the same option would have to check skew first. It would be friendlier to validate the value and then ignore the option when skew is absent or all zero. Because this is a new parameter, it's easier to get right now than to relax later.

Optional:

  • The changed-skew error after an aligned read with "raw" says "Cannot write new skew after an ignore_skew=True read", which the caller didn't do. Something like "Cannot write a skew that differs from the source read" would cover both paths.
  • wrsamp is deprecated in favour of Record.write, so adding a new keyword there grows the legacy surface. Keeping the option on write_record and Record.write only, with the wrsamp docstring pointing to Record.write for replacement alignment, would be enough.

@tompollard

Copy link
Copy Markdown
Member Author

Agreed. I updated the PR in af3ec5d:

  • signal_alignment is now only on write_record and Record.write. The deprecated wrsamp signature is unchanged, and its docstring points to Record.write for replacement values with different alignment.
  • "aligned" and "raw" are both harmless when the selected record has no skew. Invalid option values still raise before any files are created.
  • The changed-skew error now says the requested skew differs from the source read, so it applies to both aligned and raw read paths.

I added the no-skew and invalid-value tests and updated the existing error-message assertions. The offline suite passes (1,676 passed, 4 skipped), as do Ruff and the strict docs build. The PR description now reflects the narrower API.

@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, af3ec5d covers all three. Checked against the new head:

  • signal_alignment="aligned" and "raw" now write sample-data/100 normally, with no skew. An invalid value such as "Raw" or "bogus" still raises before any files are created, with or without skew.
  • wrsamp is back to its original signature, and passing signal_alignment to it gives a TypeError.
  • The earlier cases still behave correctly. A changed skew is rejected with the new message on both read paths. A shorter raw replacement and a pickled record are rejected. The main raw and aligned replacements write correctly and leave the record unchanged.
  • The offline suite (1,676 passed, 4 skipped), Ruff and the strict docs build pass locally.

Tiny optional nit: a shorter raw replacement on an aligned read still gets "Cannot write a selected ignore_skew=True read with nonzero skew…", which names a read the caller didn't do. A wording like the new changed-skew message would fit both paths.

Ready to merge once CI is green.

@tompollard

Copy link
Copy Markdown
Member Author

Thanks, that wording was misleading for a raw replacement supplied through signal_alignment. I changed it in 978fd8e to say "Cannot write raw signal values with nonzero skew" and kept the explanation about missing tail samples. The focused record and signal tests pass (196 passed), as do Ruff format and lint.

@tompollard
tompollard merged commit 6acfa8f into main Dec 2, 2026
19 checks passed
@tompollard
tompollard deleted the fix/explicit-skew-alignment branch December 2, 2026 14:53
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