Skip to content

Add write_record for single-segment records - #785

Merged
tompollard merged 2 commits into
mainfrom
write-record-api
Nov 30, 2026
Merged

tompollard merged 2 commits into
mainfrom
write-record-api

Conversation

@tompollard

@tompollard tompollard commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Summary

Add write_record(path, record, *, kind=None, layout=None) as the path-first counterpart to read_record. This first version accepts a single-segment Record and writes its current in-memory view through the existing Record.wrsamp implementation. A selected or flattened read is written as one record; the function does not claim to reconstruct the source files or their segment layout. MultiRecord is explicitly rejected for now, while MultiRecord.wrsamp remains available.

The function accepts a local record stem, supported cloud URI, or local .wfdb archive path. It renames signal file groups under the destination stem, clears source byte offsets, and writes from a metadata copy so the caller's record is unchanged. If more than one signal array is loaded, kind and/or layout must select one; no representation is chosen silently. Physical values may be quantized by the existing writer, while digital samples are written directly. For records built in code, it calculates missing physical calibration and header defaults. Digital records require fmt, adc_gain, and baseline.

The legacy wrsamp APIs are unchanged. This is a focused first step toward #500 and the naming plan in #672.

Verification

  • Tests cover digital, physical, and expanded round trips; records built in code; source byte offsets; selected and flattened records; file grouping; local archives and memory:// paths; ambiguous signal arrays; unsupported inputs; and preservation of the caller's metadata and values.
  • Full offline suite: 1,138 passed, 4 skipped, 22 network tests deselected.
  • Ruff check and format pass; Sphinx HTML docs build passes with warnings treated as errors.

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

Round trips from records read from files work well. Two things should be fixed before merge, plus a duplication worth removing.

Checked locally:

  • The caller's record is unchanged. I compared every attribute, including the arrays, before and after writing these records:

    • 100, read as physical and as digital;
    • mixedsignals, expanded;
    • a103l;
    • 041s, flattened from multiple segments;
    • a record with an edited physical value.

    Nothing changed, and check_record reports no issues for any output.

  • Skew is handled correctly. Read with skew applied, the output header has no skew; read with ignore_skew=True, it keeps skew=3. The values match either way.

  • Multiple signal forms. A record with both p_signal and d_signal raises "Multiple signal forms are loaded", and kind="digital" then writes it.

  • Destinations. Archives and memory:// work. x.hea, my rec, dir/ and physionet:// are rejected.

  • The offline suite and ruff pass.

Should fix: a record built in code can't be written.

record = wfdb.Record(record_name="x", fs=100, n_sig=1, sig_len=3, sig_name=["I"],
                     units=["mV"], p_signal=np.array([[0.0], [0.1], [0.2]]))
wfdb.write_record("out/x", record)   # KeyError: None, in _digi_nan

Adding fmt, adc_gain and baseline only gets as far as "Missing field required: block_size".

  • Record.wrsamp fails the same way, so this isn't new.
  • The wrsamp() function handles this case with set_d_features(do_adc=1) and set_defaults(), and #672 lists write_record as its replacement.

When only physical values are loaded and the format or gain fields are missing, filling them in the same way would make write_record cover that workflow. If that's out of scope for now, a clear error naming the missing fields would be much better than the KeyError.

Should fix: the byte offset is carried over. Writing a103l produces a103l.dat 16+24 and prints "Writing file … with 24 empty leading bytes". #776 cleared byte_offset in SignalRead.write for this reason, so the two writers currently give different files for the same data.

Duplication: the renaming code here repeats _destination_file_names in signal_values.py almost line for line. The byte-offset difference shows how two copies drift apart.

  • Suggestion: move one helper into record.py that copies the record, renames its signal files and clears the byte offset.
  • write_record could use that helper, and SignalRead.write could simply call write_record(path, self.to_legacy_record()).

Tests: cases for a record built in code and for a source with a byte offset (a103l) would cover both fixes.

@tompollard

Copy link
Copy Markdown
Member Author

Thanks for checking these cases. I pushed 1d6c76a to address them.

write_record now runs the existing feature calculation and header defaults on a copy of the record. Your Record(...) example writes and reads back, including when fmt, adc_gain, and baseline are supplied but fields such as block_size are omitted. Digital values without the calibration needed for a valid header now give a clear error naming the missing fields.

Both write_record and SignalRead.write use the same preparation helper for destination file names and clearing byte_offset. Writing a103l now starts the new data file at byte zero. I kept SignalRead.write's existing path handling and conversion flow, with the shared helper covering the duplicated logic.

I added regression tests for the built records, missing digital calibration, and a103l. The full offline suite passes (1,138 passed, 4 skipped), as do Ruff and the strict Sphinx build. I also updated the PR description.

@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, this looks ready to merge.

  • Records built in code. They now write and read back:

    • physical with no calibration: 80 1270.0(-127)/mV, the same as wrsamp();
    • physical with fmt, adc_gain and baseline;
    • digital with calibration.

    check_record reports no issues, and the caller's record is unchanged. Digital values without calibration, and adc_gain without fmt, give clear errors.

  • Calibration for records read from files is unchanged. I compared output headers from the previous and current heads for:

    • 100, physical and digital;
    • a103l;
    • mixedsignals, expanded;
    • 03700181;
    • s0010_re;
    • 041s, flattened.

    Formats, gains and baselines are identical, and values round-trip exactly, so the new set_d_features call keeps existing calibration.

  • Byte offsets are cleared, and SignalRead.write now uses the same helper.

  • The offline suite and ruff pass.

Two older failures in the calibration step, which the legacy wrsamp() function shares, are now tracked in #786: physical signals that contain NaN, and expanded physical signals without calibration.

@tompollard
tompollard merged commit b9e0618 into main Nov 30, 2026
19 checks passed
@tompollard
tompollard deleted the write-record-api branch November 30, 2026 06:16
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