Skip to content

Add beat-by-beat comparison of annotations, as WFDB bxb does (development feature) - #679

Merged
tompollard merged 2 commits into
mainfrom
bxb-beat-comparison
Nov 24, 2026
Merged

tompollard merged 2 commits into
mainfrom
bxb-beat-comparison

Conversation

@tompollard

@tompollard tompollard commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Addresses #334.

This adds a beat-by-beat comparison of annotation files, as the bxb program of the WFDB Software Package does for ANSI/AAMI EC57 and EC38, as a development feature: the docs and docstrings say so, that its interface may change, and that results should be checked against bxb before they are used for reporting.

from wfdb.processing import bxb_record, sumstats

result = bxb_record("sample-data/100", "atr", "qrs")  # as bxb -r 100 -a atr qrs
print(result.report())            # the standard report, as bxb -S
result.matrix                     # the comparison matrix, as a DataFrame
result.statistics()               # each statistic as (numerator, denominator)
line, shutdown_line = result.lines()   # the line-format reports, as bxb -L
summary, shutdown_summary = sumstats([result, ...])  # as WFDB sumstats

processing.bxb(reference, test, ...) does the same for Annotation objects, with start, stop and window (as bxb -f, -t and -w; stop=0 is -t 0, which stops at the end of either file).

How it was written

bxb.c is licensed under the GPL, so this was written without reference to its source code (or that of the WFDB library). It is based on:

  • the EC57 beat-by-beat definitions;
  • the bxb, sumstats and evaluation documentation;
  • running the compiled bxb and sumstats (WFDB 10.7.0) as black boxes on many inputs, and adjusting until the results agreed.

Running the programs to compare outputs doesn't make this code derived from them. The module docstring says the same.

Validation

All of these compared every matrix cell, every statistic, the RMS RR interval error and the shutdown time, as well as the full report text and both line-format lines, character for character:

  • About 6000 generated cases, all identical. The cases mixed:

    • jitter across the match window, missed and extra beats, and beats at the same sample;
    • non-beat annotations, and VF episodes in either file;
    • paired and AHA-style shutdowns in either file, and beats near the start and end.

    A third were at 360 Hz with the default options; the rest at 128 to 1000 Hz, with and without a record length, and with random -f, -t (including -t 0) and -w.

  • All 48 MIT-BIH records against five test annotators: sqrs and gqrs from the WFDB tools, xqrs from this package, a perturbed copy of the reference keeping every annotation type and subtype, and the reference itself. The reports, the line-format files and the sumstats output of both files were identical for every annotator.

  • A record of 130,000 beats, to check column widths.

Some of bxb's behaviour that this reproduces:

  • Escape beats are SVEBs: e, j and n beats count as S.
  • Beats missed in shutdown: the total leaves out S beats, but its denominator includes them.
  • Positive predictivity: extra test beats (O and X) count against the VEB and SVEB figures, F beats called V don't count against VEB, and F (but not Q) beats called S do count against SVEB. sumstats' gross figure leaves F out, because its columns combine F with Q.
  • RR intervals: each side forgets its previous beat at a shutdown or VF episode in its own file.
  • The first test beat after the start isn't counted if it is within the match window of the start and the next event also has a test beat.
  • Without a record length, the comparison ends at the last reference beat.
  • Annotation times are converted to the record's sampling frequency when the file has another time resolution, as the WFDB library does. The output of sqrs is stored at 250 Hz.

Not included: the -s, -l, -c and -C report variants, the -o and -O output annotation files, and -v.

Testing

  • tests/test_beat_comparison.py compares four cases with reports made by the C programs (fixtures in tests/target-output/bxb, with the annotation files used): record 100 against 100.qrs; a 360 Hz record with VF and shutdowns in both files; a 250 Hz record compared with start, stop and window, whose test file has 1000 Hz times; and a test file that ends early, compared with stop=0 (bxb -t 0). It also compares both line-format files and both sumstats outputs, and tests the matrix, statistics, stop=0, symbol-only annotations, an undefined RR error and a missing sampling frequency.
  • test_matches_wfdb_bxb compares 200 generated cases with the installed bxb, and is skipped when it isn't installed (as in CI). With WFDB 10.7.0, all 200 match.
  • pytest: all offline and network tests pass, also with --resolution lowest-direct. Ruff and the docs build pass.

@tompollard 🟥 red 🦥 sloth · aspen

processing.bxb and processing.bxb_record compare a test annotation file
with a reference one beat by beat, as the bxb program of the WFDB Software
Package does for ANSI/AAMI EC57 and EC38: the comparison matrix of AAMI
beat classes, QRS, VEB and SVEB sensitivity and positive predictivity, the
RMS RR interval error and shutdown statistics, and bxb's standard (-S) and
line-format (-L) reports. processing.sumstats combines several records'
results as WFDB sumstats does.

This is a development feature. It was written from the descriptions in
EC57 and the bxb documentation, and by comparing its results with those of
the bxb and sumstats programs of WFDB 10.7.0, without reference to their
source code, which is licensed under the GPL. The tests compare its reports
with ones made by those programs.

Addresses #334.

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

Expert review of commit 54c900c, using correctness, performance, and test coverage lenses:

Correctness — address before merging (src/wfdb/processing/beat_comparison.py:525). bxb(stop=0) treats zero as an immediate cutoff. With two matching beats at samples 360 and 720, I got zero counted matches; stop=720 counted both. The WFDB bxb manual gives -t 0 a special meaning: stop when the end of either annotation file is reached (https://physionet.org/physiotools/wag/bxb-1.htm). Since this PR presents stop as the equivalent of -t, please implement that case or document the difference explicitly.

Performance — follow-up (src/wfdb/processing/beat_comparison.py:111). Each _in call scans every interval. A stress case with 500 shutdowns and unmatched beats took 0.008 seconds; 4,000 took 0.423 seconds. Profiling the 4,000 case showed 16 million interval checks, accounting for nearly all runtime. An indexed lookup would avoid quadratic growth when recordings contain many shutdown or VF intervals.

Tests. All 9 committed beat-comparison tests pass. Please add a stop=0 regression case. The larger differential run described in the PR is useful evidence, but it is not reproducible from the committed tests.

I would fix the stop=0 mismatch before merging. The performance work can follow for this development feature. All CI checks now pass.

…lled

As with bxb -t 0, stop=0 now ends the comparison at the last beat of the
file that ends first, counting every test shutdown. It used to stop at
sample 0, so that nothing was counted.

Comparing with bxb -t 0 and more generated cases also showed that, without
a record length, bxb stops at the last reference beat (not annotation);
that an AHA-style shutdown with no annotation before it starts one window
after sample 0; that a shutdown with no annotation after it adds time only
if the end of the comparison is known; and that the first test beat after
the start is dropped only if the next test beat is closer to the reference
beat it was compared with.

Look up times in shutdown and VF intervals with an index (sorted starts and
the running maximum of ends), instead of scanning every interval, so that
records with many intervals take linear rather than quadratic time.

Add a regression test for stop=0 (with a test file that ends early, and its
report from bxb -t 0), and test_matches_wfdb_bxb, which compares 200
generated cases with the installed bxb, and is skipped if bxb is not
installed.
@tompollard

Copy link
Copy Markdown
Member Author

Thanks, all three addressed in 1939664.

stop=0: implemented as bxb -t 0. Probing bxb showed that the comparison ends when either file has no more beats; annotations that aren't beats don't extend it. So stop=0 now stops at the last beat of whichever file ends first, and counts every test shutdown (bxb reads the test file to its end). Your example now counts both matches. The docstrings of bxb and bxb_record describe this.

Checking -t 0 against bxb on more generated cases also turned up four rules I had wrong, all now fixed:

  • No record length: the comparison ends at the last reference beat, not at the last reference annotation.
  • An AHA-style shutdown with no annotation before it starts one match window after sample 0, rather than at 0.
  • A shutdown with no annotation after it adds time only if the end of the comparison is known, from the record length or stop.
  • The first test beat after the start is dropped only if the next test beat is closer than it to the reference beat it was compared with. That's the same test as in normal matching, and it replaces my rule about the next event.

Performance: shutdown and VF lookups now use an index: the starts sorted, with the running maximum of the ends, which stays exact for overlapping intervals. Your stress case with 4,000 shutdowns now takes about 0.012 s, and 32,000 take 0.135 s.

Tests:

  • stop-0: a new case uses a test file (bxb360.qrs) that ends before the reference file, compared with the report from bxb -t 0. A unit test covers your example, and checks that an explicit stop at the last reference beat does count it as missed. Both fail on the previous commit.
  • test_matches_wfdb_bxb: this makes the differential comparison reproducible. It generates 200 cases (beat classes, jitter, missed and extra beats, VF episodes, both kinds of shutdown, 128 to 1000 Hz, and random -f, -t including -t 0, and -w), runs the installed bxb on each, and compares the reports. It's skipped when bxb isn't on the path, so CI skips it. With WFDB 10.7.0 installed, all 200 match.

My larger runs also pass with these changes: about 6,000 generated cases (comparing the reports and both line-format lines), and all 48 MIT-BIH records with sqrs, gqrs, xqrs, a perturbed reference and the reference itself (reports, line-format files and sumstats). All offline and network tests pass, also with --resolution lowest-direct; ruff and the docs build pass too.

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

Re-reviewed at 1939664. The previous stop=0 mismatch is fixed and covered by both a focused regression test and a reference report fixture. The interval index agrees with direct interval scans in randomized checks and removes the earlier quadratic lookup path. I ran the committed beat-comparison tests locally (11 passed); all PR checks are green. I found no merge blocker for the documented development feature.

Follow-up: the four differential tests against the installed WFDB bxb program are skipped in CI because that program is not installed there. A dedicated CI job running them would help catch future divergence from the reference implementation.

@tompollard
tompollard merged commit 9475b8a into main Nov 24, 2026
18 checks passed
@tompollard
tompollard deleted the bxb-beat-comparison branch November 24, 2026 05:19
tompollard added a commit that referenced this pull request Nov 24, 2026
## Summary

Bump the version from 5.1.0 to 5.2.0, and collect the 19 entries in
`changelog.d/` into `docs/changes.rst` with `towncrier build --date "Nov
2026"`, with a short summary at the top of the new section.

This is a minor release. The one change that existing code may notice is
that `rdann` and `Annotation.apply_range` now stop before `sampto`, as
`rdrecord` and `rdsamp` do, so an annotation exactly at `sampto` is no
longer included (#667). The summary calls it out, with how to get the
old result.

The release also includes:
- **Fixes for PhysioNet:** `get_dbs`, which PhysioNet's API change had
broken (#665), record names with folders in `pn_dir` (#666), and
`physionet://` and other URIs in `read_edf`, `rdedfann` and `read_wav`
(#674).
- **Robustness:**
  - headers whose base time or date is in another form (#668);
- multi-segment writes that leave no partial record after an error
(#673);
- a warning before `wrsamp` replaces another record's signal files
(#675).
- **New:** a beat-by-beat comparison of annotation files, as WFDB `bxb`
does, as a development feature (#679), and axis labels in `plot_wfdb`
(#670).
- **Smaller fixes:**
- integer overflow and precision in `find_peaks` and `normalize_bound`;
  - constant signals in `normalize_bound`;
  - multi-character custom annotation symbols;
  - format 61 signals read with `smooth_frames=False`;
  - skew written twice when rewriting records;
  - docstring examples, and more.

This will be the first release published by
`.github/workflows/publish.yml`, from the GitHub release, with
provenance.

## Checks

- `pytest -m "not network"`: 679 passed (4 skipped, the `bxb` comparison
that needs WFDB installed), also with `--python 3.11 --resolution
lowest-direct`. `pytest -m network`: 20 passed.
- Ruff and the Sphinx HTML build with warnings as errors pass.
- The wheel and source distribution build and pass `twine check`. They
have `Version: 5.2.0` and include `wfdb/processing/beat_comparison.py`.
- PyPI has no 5.2.0 release yet.

<sub>@tompollard 🟥 red 🦥 sloth · aspen</sub>
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