Skip to content

Add write_annotations API - #784

Merged
tompollard merged 3 commits into
mainfrom
write-annotations-api
Nov 30, 2026
Merged

tompollard merged 3 commits into
mainfrom
write-annotations-api

Conversation

@tompollard

@tompollard tompollard commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Summary

Add write_annotations(path, annotation, *, write_fs=True) as the write counterpart to read_annotations. The path is a complete annotation filename such as 100.atr; local and supported cloud destinations use the existing annotation writer. The new function writes from a copy, so preparing labels and changing the output name do not mutate the caller's Annotation. It stores fs when available by default, so an annotation read from a record can be written and read again without needing a header beside the output file.

Allow digit-prefixed annotator extensions such as 16a in the existing writer, matching what read_annotations accepts. Filename validation is shared by the new reader and writer. The legacy wrann function and Annotation.wrann method remain available. Writing annotations into .wfdb archives and to physionet:// is still unsupported.

Also fix a pre-existing round-trip failure for annotation files with numeric label codes that have no symbol in the standard table. rdann now retains the raw label_store values when a requested symbol or description is unknown; the writers encode each annotation from its available symbol, then description, and fall back to the raw code only when its label is unknown. This preserves user edits to known labels even when another annotation has an unknown code. Label summaries include unknown codes. These cases are covered with sample-data/12726.wabp, which contains code 42.

Verification

  • Tests cover local and memory:// round trips, fs handling, source object preservation (including custom labels), .16a writing through both new and legacy interfaces, invalid destinations, unknown label codes, and edits to known symbols and descriptions alongside unknown codes.
  • Offline suite: 1,123 passed, 4 skipped, 22 network tests deselected.
  • Ruff check and format pass; Sphinx HTML docs build passes with warnings treated as errors.

Related: #672 and #783.

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

This looks ready to merge.

Checked locally:

  • The caller's object is unchanged. I compared every attribute of the annotation before and after write_annotations for seven kinds of annotation: read from files, built with symbols only, built with label_store only, and built with custom labels as a DataFrame and as a list. Nothing changed: wrann replaces attributes on the copy rather than editing shared values, and custom_labels is deep-copied.
  • Destinations.
    • bare.atr in the current folder works, as do x.atr_1, x.ATR and memory://…/r.16a.
    • x.v1.atr, my rec.atr and a+b.atr are rejected with the record-name error.
    • A missing parent folder raises FileNotFoundError.
  • write_fs=True without fs writes no frequency and reads back fs=None, as the docstring says.
  • Round trips. Every annotation file in sample-data gives the same samples, symbols and notes when read back, except the one below.
  • The offline suite and ruff pass.

An older bug, outside this PR: wfdb.rdann("sample-data/12726", "wabp") can't be written back by either write_annotations or Annotation.wrann. Its label codes aren't in the standard table, so rdann returns nan symbols, and the writer then raises TypeError: Subelements of the symbol field must be strings. The cause is in rdann, so this is probably worth its own issue.

Optional: test_local_round_trip_preserves_source checks record_name, extension and label_store. A case built with symbols only and custom labels, checking that the arrays and custom_labels are unchanged after writing, would test the full guarantee.

Taking the path first matches read_annotations and numpy.save. It would be good for the planned write_record to use the same order.

@tompollard

Copy link
Copy Markdown
Member Author

Thanks for the thorough check. I fixed the older 12726.wabp bug in 03ccc1d as part of this PR. When a label code has no known symbol or description, rdann now retains its raw label_store values. Both write_annotations and Annotation.wrann can write those codes directly, and summarize_labels=True includes them instead of raising. The tests cover code 42 from 12726.wabp through both writers and all three label field selections.

I also added the suggested source-preservation test using custom labels. The full offline suite passes (1,119 passed, 4 skipped), as do Ruff and the strict docs build. I agree that a future write_record should take the path first as well.

@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 for fixing the unknown-code bug here.

  • The 12726.wabp round trips pass in all three label modes and through the legacy writer.
  • summarize_labels=True counts code 42.
  • Normal files are unaffected: rdann("sample-data/100", "atr").label_store is still None.

There's one remaining problem: while any nan symbol is present, edits to symbol are silently discarded.

ann = wfdb.rdann("sample-data/12726", "wabp")
ann.symbol[4] = "V"            # was "N"
ann.record_name = "edit"
ann.wrann(write_dir=out)
wfdb.rdann(f"{out}/edit", "wabp").symbol[4]   # "N"

On main, this raised TypeError: Subelements of the symbol field must be strings. Now it writes without warning and drops the edit, because the nan path in Annotation.wrann sets symbol to None and writes every code from label_store.

It goes the other way too. If every nan is replaced (for example with "Q"), the writer uses symbol and ignores label_store. So which field wins depends on whether a single nan is left anywhere.

Building each code from symbol where it's a string, and falling back to label_store only where it's nan, would keep both the unknown codes and the user's edits. A test that edits one known symbol in 12726.wabp and checks the written value would cover it.

Not blocking, just noting:

  • rdann now returns a label_store array for files with unknown codes, even with the default return_label_elements=["symbol"]. The changelog covers this.
  • Code that filters only sample and symbol now fails with "The lengths of the 'sample' and 'label_store' fields do not match". It already failed on main for these files, so this isn't a regression.

@tompollard

Copy link
Copy Markdown
Member Author

You're right; the previous fallback could silently discard an edit. I fixed that in e78dace. When an annotation has an unmapped label, the writer now resolves each position separately: an available symbol takes precedence, then an available description, and only a missing label uses its stored numeric code.

I added regression tests that change symbol[4] from N to V while the same file still contains code 42. The edit survives through both write_annotations and Annotation.wrann, and the 45 unknown codes remain intact. There are also tests for a description edit and for replacing every unknown symbol. The full offline suite passes (1,123 passed, 4 skipped), as do Ruff and the strict docs build.

The extra label_store on reads with unknown codes is documented in the changelog and reader docstrings. Filtering still requires the annotation fields to have matching lengths, as you noted.

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

  • Edits now survive. Each position now resolves to its symbol, then its description, then the raw code, and the new tests cover symbol and description edits through both writers.
  • No codes change. I wrote one annotation for every code from 1 to 49 in the label table, plus the unknown code 42, and read it back first with symbols and then with descriptions. Writing it again changed no codes. No symbol or description appears twice in the table, so the lookups can't map a label to a different code.
  • Custom labels. Adding a custom label for 42 after reading still writes 42.
  • The offline suite and ruff pass.

One limitation to be aware of, not blocking: because symbols take precedence, editing label_store where a symbol is known has no effect. Setting label_store[4] from 1 to 5 in 12726.wabp still writes 1. That matches the documented precedence, and editing symbols is the normal workflow.

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