Skip to content

Make WFDB encoders consume explicit model fields #866

Backlog

Description

@tompollard

Problem

#863 showed that modern writes can use a private model and preserve current output, but the model still inherits the legacy Record encoder mixins and copies channel fields into Record-style lists. That does not settle the model boundary in #852 or the dynamic-field dependency in #749.

Baseline and compatibility rule

Use the current main branch at the start of this refactor, commit e3e9729a55ebaad414211dcc0efbc15ae0e6ae89 (after #873), as the pinned output baseline. The 5.15.0 tag and the closed #863 prototype predate the masked-write and array-writer changes and are no longer suitable references. Every refactor PR should preserve the pinned output byte for byte. Any exception must be named, explained, and reviewed as a separate behavior change.

While both encoders exist, keep an offline pytest differential test in the repository. For each supported sample case, write through the old and new paths and compare the complete output files byte for byte. Cover single- and multi-segment sources, uniform and expanded layouts, physical and digital values, skew, selected channels, and missing samples in more than one format. Use bounded reads where needed to keep CI practical; include full-length multi-segment cases in the larger comparison. If a case cannot be written, compare the error outcome as well. When the old encoder is removed, retain representative byte fixtures and run the broader comparison against the pinned baseline before merging that final PR. The benchmark remains a manual, documented check.

Implementation sequence

Keep each PR small and free of intentional behavior changes:

  1. Make header validation and serialization consume explicit record and channel fields, while the old path remains available for comparison.
  2. Make initial-value and checksum calculation consume explicit fields and digital arrays.
  3. Make .dat encoding per format consume explicit channel specifications and arrays.
  4. Switch write_record, SignalRead.write, and write_signals to these functions. Convert a mutable Record from its current fields at one write boundary; modern read results should pass their model directly. Keep the shared checked file-writing step from Share checked file writing and fix overwrite warning location #865 and explicit signal_alignment where skew requires it.
  5. Remove temporary Record adapters, inherited encoder mixins, and copied parallel channel lists once the comparisons pass.

The final writer should not need hidden read history to decide what to write.

Checks and decision

  • Run the existing alignment and edit tests unchanged, including in-place edits, array replacement, channel removal, short raw reads, copy, deepcopy, and pickle.
  • Keep the differential byte test in CI at each step, including masked writes and mixed-format segments. Name and explain any difference.
  • Rerun the recorded 30-run benchmark on the 650,000-frame no-gap record after the final writer switch. Report time and peak memory against the pinned baseline, aiming to stay within roughly 10%.
  • After the refactor is finished, report a written decision for Group per-channel header fields into coherent signal metadata #744 and Decouple I/O internals from dynamic Record fields #749 about the public read result and ownership of channel metadata. Do not settle that public design partway through the encoder work.

The warning-location cleanup is independent and can be handled at any time.

Activity

  1. tompollard commented on Dec 3, 2026

    @tompollard
    MemberAuthor

    Decision for the remaining write-model cleanup, following the review of #888:

    Record.wrsamp, Record.set_defaults, and Record.set_d_features are public
    and must remain callable. I don't plan to route Record.wrsamp wholesale
    through the model: it has legacy selection and mutation behavior that a quiet
    rewrite could change.

    The duplicated default and digital-feature calculations should instead be
    extracted into private helpers that take explicit fields and arrays. The
    write model and the legacy Record methods will call those helpers, while
    the public methods keep their signatures and observable mutation behavior.
    We'll keep the independent parity comparison until that switch is checked;
    the fixed 5.17.0 fixtures from #885 and #886 will then protect output and
    error behavior as the temporary implementations are removed. The cleanup PR
    will map each deleted parity test to a fixed replacement or explain why it is
    no longer needed.

  2. tompollard commented on Dec 3, 2026

    @tompollard
    MemberAuthor

    Writer benchmark after #898

    The completed writer refactor meets the roughly 10% time and memory target. I compared the v5.17.0 tag (9a4bc60) with merged main (aa227d5; the benchmarked #898 branch has the same tree). The machine was macOS 15.7.3 on ARM64, Python 3.11.13, NumPy 2.4.6. Each case had 3 warmups and 30 timed runs, with garbage collection before each run and tracemalloc active. Writes went to a local temporary record stem. The figures below are medians in milliseconds; “read + write” includes a fresh read on each run.

    sample-data/100 has 650,000 frames, two channels, and no missing digital samples:

    Writer Kind Write only, 5.17 → main Read + write, 5.17 → main
    write_record physical 22.22 → 22.21 32.29 → 32.19
    write_record digital 15.58 → 15.80 19.86 → 20.24
    SignalRead.write physical 17.82 → 17.90 27.87 → 27.85
    SignalRead.write digital 11.39 → 11.38 15.58 → 15.75
    write_signals physical 35.14 → 35.36 45.22 → 45.52
    write_signals digital 15.97 → 16.12 20.74 → 21.51

    I also ran the same 12 cases on sample-data/100skew, with 650,000 frames and three masked tail samples after alignment. Its median time changes range from 1.7% faster to 1.6% slower. Across both records the largest slowdown was 3.7% (write_signals, digital, read + write on 100). Median peak traced allocation was effectively unchanged in every case: the largest difference was about 0.01 MiB. On the no-gap record, write-only peaks were about 21.75 MiB for digital and 31.67 MiB for physical; read + write added about 10 MiB. tracemalloc measures traced allocations, not total process RSS, so I am treating this as a regression check rather than a complete memory profile.

    For each writer I used both physical and digital uniform reads. write_signals received the read values and source format, channel names, units, and digital calibration; physical calibration was computed as usual. The 100skew case used signal_alignment="aligned" for write_record and SignalRead.write. The benchmark script and raw 30-run results are retained locally for reruns. This supports finishing the writer portion of #866. The remaining design decision is whether readers should build the same private model, and how channel metadata should be owned (#744/#749). I am deferring removal of _WriteModel's short-lived parallel lists to that decision so the reader and writer channel model can be designed together.

  3. HeywoodGeblomi commented on Dec 3, 2026

    @HeywoodGeblomi
    Contributor

    Suggesting nstdb 118e24 for the comparison set: its baseline and adc_zero differ (1024 vs 0, because nst.c zeroes adczero but keeps baseline), which records where the two match won't exercise. On main 69fbc958, rdrecord(physical=False) followed by Record.wrsamp(expanded=False) writes a .dat that's byte-identical to the PhysioNet file and keeps baseline, adc_zero, init_value and the signed checksums. The .hea isn't byte-identical: it uses LF instead of CRLF, writes the gain as 200.0, and fills in /mV. Record.write makes the same changes and also writes the channel 0 checksum as 52085 instead of -13451 (same 16-bit value).

    Repro:
    r = wfdb.rdrecord("118e24", physical=False); r.wrsamp(expanded=False, write_dir="out")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions