Skip to content

[BTY-41] Add HeartLang's CSN benchmark on Chapman-Shaoxing - #1571

Merged
solarsys merged 5 commits into
sunlabuiuc:masterfrom
rayrayowo:bty-41-heartlang-chapman
Nov 27, 2026
Merged

solarsys merged 5 commits into
sunlabuiuc:masterfrom
rayrayowo:bty-41-heartlang-chapman

Conversation

@rayrayowo

@rayrayowo rayrayowo commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Part of BTY-41 (HeartLang benchmarks): the Chapman-Shaoxing (CSN) benchmark. CPSC2018 will follow in a separate PR now that #1551 (Cardiology 2.0 port) has landed.

What's added

  • ChapmanShaoxingHeartLangClassification for ChapmanShaoxingDataset, reproducing HeartLang's CSN setup (make_csn_datasets.py, base_csn_linear_prob.sh, HeartLang commit a08afd8):
    raw ADC → min-max to [-3, 3] → 100 Hz (FFT resample) → 0.67–40 Hz order-5 Butterworth (filtfilt) → heartbeat sentences (256 × 96) via ecg_to_heartbeat_sentence.
  • 38-label vocabulary in the column order of HeartLang's chapman_train.csv.
  • split_by_heartlang_csn / load_heartlang_csn_split: HeartLang's train/val/test split (16,546 / 1,860 / 4,620 records), read from the CSVs in a HeartLang checkout.
  • Helpers heartlang_csn_labels, preprocess_heartlang_csn; API docs; tests. The heartlang_csn_labels docstring lists every substring case (ST for STTC/STTU/STE/STDD, AVB and VB for the AV blocks, 2AVB, CR, SA).
  • examples/ecg/chapman_heartlang_csn_linear_probe.py: HeartLang's CSN linear probe (frozen pretrained encoder + linear head, HeartLang's split and hyperparameters); needs the real data and checkpoint, not run here.

Finding: HeartLang's labels are substring matches
A label is positive in HeartLang's table when it is a substring of a diagnosis acronym: AFIB is also AF (atrial flutter), 1AVB is also AVB and VB, STTC is also ST, CCR is also CR, and LVQRSAL (low QRS voltage) is also SA (sinus arrhythmia). This rule reproduces all 23,026 rows of the released table from its diagnose column, so it is the default for comparability; label_match="exact" gives whole-acronym labels. Also, SB is not among the 38 labels.

Shared code (intended)
chapman_heartlang.py imports CHAPMAN_SNOMED_CODES and split_dx_codes from chapman_shaoxing_classification.py on purpose. The SNOMED-CT code → acronym table describes the Chapman-Shaoxing release itself, not one task, and HeartLang's labels are those acronyms. Keeping one table means a fix to it (for example a code added in a later release) reaches both Chapman tasks. A comment above the import says this.

Tests

  • tests/core/test_chapman_heartlang.py (14 tests, synthetic WFDB records; preprocessing checked against a lead-by-lead restatement of the reference steps)
  • test_samples_with_default_qrs_detection runs set_task without mocking the wfdb QRS detector (checks shapes, beats on both leads, time ids, labels).
  • ruff check and tools/check_pr_rules.py pass.
  • Not run on the real dataset or with the pretrained checkpoint here.

Questions

  • Keep label_match="heartlang" as default, or prefer "exact"?
  • Should HeartLang's record lists (MIT) be bundled with the package instead of read from a checkout?

Add ChapmanShaoxingHeartLangClassification, the 38-label CSN linear-probe
setup of HeartLang (Jin et al., ICLR 2025), on ChapmanShaoxingDataset:

- raw ADC values, min-max scaled to [-3, 3], resampled to 100 Hz and
  band-passed at 0.67-40 Hz (order-5 Butterworth, filtfilt), as in
  HeartLang's make_csn_datasets.py; then HeartLang heartbeat sentences
- the 38 labels in the column order of HeartLang's chapman_train.csv
- split_by_heartlang_csn reproduces HeartLang's train/val/test split
  from its record lists (16,546 / 1,860 / 4,620 records)

HeartLang's label table marks a label positive when it is a substring of
a diagnosis acronym (AFIB is also AF, 1AVB also AVB and VB, STTC also ST,
CCR also CR, LVQRSAL also SA). This rule reproduces all 23,026 rows of
the released table from its diagnose column, so it is the default;
label_match="exact" keeps whole acronyms only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UxbiyTdwHAng6T548wdSda
@github-actions github-actions Bot mentioned this pull request Nov 21, 2026
rayrayowo added a commit to rayrayowo/PyHealth that referenced this pull request Nov 22, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UxbiyTdwHAng6T548wdSda
@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 86.75% (48508 / 55914 lines)

Modified file Coverage Lines
pyhealth/tasks/__init__.py 98.18% 108 / 110
pyhealth/tasks/chapman_heartlang.py 96.23% 102 / 106

Workflow run · ab1fcf0

@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Nov 22, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit a262b6a

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for this contribution. It adds HeartLang's 38-label CSN benchmark for Chapman-Shaoxing. It includes the reference preprocessing, the split helpers and a useful finding about the substring-matched labels. The code is well documented, and tests cover it well. Coverage is 96.2% for chapman_heartlang.py, 98% for tasks/init.py and 86% for the whole repository, so it meets the bar. The change is close.

To get this merged:

  • The new task imports CHAPMAN_SNOMED_CODES and split_dx_codes from pyhealth/tasks/chapman_shaoxing_classification.py. That is a link to another concrete component, and the description doesn't mention it. Please either confirm in the description that the sharing is intended and say why (for example, to keep the SNOMED-to-acronym mapping in one place), or keep this task self-contained by copying the mapping and helper into your module.

Optional suggestions:

  • With the default substring rule, ST also fires for STE, STDD and STTU records. The heartlang_csn_labels docstring only partly lists these cases, so please list them all.
  • Consider adding an example script or notebook, like the PTB-XL HeartLang one.
  • On your questions: keeping label_match="heartlang" as the default seems reasonable for comparability with the paper. Reading the record lists from a HeartLang checkout avoids bundling extra data.

Reviewed commit a262b6a

…case

The task reads CHAPMAN_SNOMED_CODES and split_dx_codes from the Chapman
classification module on purpose: the code-to-acronym table describes the
release, so one table serves both tasks. The heartlang_csn_labels
docstring now lists every acronym that also fires another label.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UxbiyTdwHAng6T548wdSda

Copy link
Copy Markdown
Contributor Author

/review


Generated by Claude Code

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 6137414

github-actions[bot]
github-actions Bot previously approved these changes Nov 26, 2026

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: approve
decision: approve

Thank you for this contribution. It adds HeartLang's 38-label CSN benchmark on Chapman-Shaoxing. That includes a task with HeartLang-matching preprocessing, a substring label rule with an exact option, a loader and splitter for HeartLang's record lists, docs, and tests. It looks ready to merge.

  • Self-contained: The change adds a new task module, its export, docs and tests. It doesn't change any existing component's behavior.
  • Shared code: The imports from chapman_shaoxing_classification.py (CHAPMAN_SNOMED_CODES, split_dx_codes) and from pyhealth.models.heartlang (ecg_to_heartbeat_sentence) are named in the description with a clear reason.
  • Coverage: chapman_heartlang.py has 96.23% coverage, above the 80% bar. Total repository coverage is 86.47%, above the 60% bar.
  • Docs: The docs match the code.
  • Dataset: No new dataset is added.

Optional suggestions:

  • preprocess_heartlang_csn returns all zeros for NaN input, because the high > low check is false for NaN. Raising an error, or checking for non-finite values up front, would be clearer.
  • load_heartlang_csn_split silently ignores CSV rows without a JS id. A wrong file format would give empty splits with only an info log. Consider warning, or raising an error, when a split ends up empty.
  • An example script, like the one for the PTB-XL HeartLang task, would help users.
  • On your questions: keeping heartlang as the default is reasonable, since it reproduces the paper's labels and the docstring explains the choice. Reading the record lists from a checkout is fine, and it avoids bundling data.
  • The 23,026-row claim and the pretrained checkpoint weren't checked here, since the real dataset wasn't available.

Reviewed commit 6137414

# Conflicts:
#	pyhealth/tasks/__init__.py
@solarsys

Copy link
Copy Markdown
Collaborator

Thanks rayrayowo. This was approved but had picked up a conflict in pyhealth/tasks/__init__.py (master added the PhysioNet 2012 mortality task next to your import), so I merged master and kept both imports. No other changes; test_chapman_heartlang passes. It should merge once the build and a fresh review pass.

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 189463b

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for this contribution. It adds HeartLang's 38-label CSN benchmark for Chapman-Shaoxing, with matching preprocessing, label handling, and a way to reproduce HeartLang's train/val/test split. The docs, the cross-component imports (explained in your description) and the tests are mostly in good shape. Coverage is also well above the bar: chapman_heartlang.py is at 96.2% against 80%, and the whole repository is at 86.6% against 60%.

To get this merged:

  • Add a test of the default path. Every end-to-end test (test_samples, test_drop_empty_labels) patches ecg_to_heartbeat_sentence with fixed R-peaks, so no test runs call with the real QRS detector. Please add one set_task test that doesn't mock it. Your synthetic ADC spikes every 0.8 s are a good start. Check that the sample has the expected shapes, that lead_ids and time_ids are non-empty, and that the labels are right. If the detector can't find peaks in the synthetic signal, make the signal more ECG-like, or assert clearly what happens instead. The PTB-XL HeartLang task has a test like this to use as a model.

Optional suggestions:

  • On your questions: keeping label_match="heartlang" as the default makes sense for comparability with the paper. It is already clearly documented, and the docs could add a short note saying "exact" is the clinically correct choice.
  • Bundling HeartLang's record lists is probably not needed. Reading them from a checkout keeps the package light and makes the source clear.
  • A short example script showing the task, the split and a HeartLang linear probe would help users.

Reviewed commit 189463b

The end-to-end tests patched ecg_to_heartbeat_sentence with fixed
R-peaks, so the default wfdb QRS detection never ran. A new test runs
set_task unmocked on the synthetic record and checks the sentence shape,
that beats are found on both selected leads, that time ids lie in 1..10
on words and 0 on padding, and the labels.

examples/ecg/chapman_heartlang_csn_linear_probe.py runs HeartLang's CSN
linear probe (frozen pretrained encoder, linear head, HeartLang's split
and hyperparameters). It needs the real data and the checkpoint, so it
was not run here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UxbiyTdwHAng6T548wdSda

Copy link
Copy Markdown
Contributor Author

/review


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

/review


Generated by Claude Code

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit ab1fcf0

if x.ndim != 2:
raise ValueError(f"signal must be (leads, samples), got shape {x.shape}")
low, high = x.min(), x.max()
if high > low:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] NaN input is silently turned into an all-zero ECG

When the input contains NaN, x.min() and x.max() are NaN, so high > low is False and the else branch returns zeros. A NaN record therefore becomes an all-zero signal without any error, and the np.isfinite guard in call (line 304) never fires for NaN input. WFDB int16 reads cannot produce NaN, so the task path is not affected today, but the public helper returns wrong data for invalid input. Fix: check np.isfinite(x).all() before scaling and raise ValueError, then keep or drop the guard in call accordingly.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: approve
decision: approve

Thank you for this contribution. It adds HeartLang's 38-label CSN benchmark for Chapman-Shaoxing. That includes the task, HeartLang's preprocessing, the split loader, API docs, an example linear probe and tests. It looks ready to merge.

  • Shared code: Importing CHAPMAN_SNOMED_CODES and split_dx_codes from chapman_shaoxing_classification.py is named in the description with a clear reason. The import of ecg_to_heartbeat_sentence is the sentence-building step and is also documented.
  • Coverage: chapman_heartlang.py is at 96.23%, tasks/__init__.py at 98.18%, and the whole repository at 86.75%. All of these meet the bar.
  • Dataset source: No new dataset is added. The example docstring links to the PhysioNet source.

Optional suggestions:

  • preprocess_heartlang_csn turns a NaN input into an all-zero signal, because x.min() and x.max() are NaN and the high > low check is False. That means the np.isfinite guard in __call__ can never fire. Checking for finite input before scaling would make the guard useful.
  • The example calls split_by_heartlang_csn without record_ids, so it decodes every sample. Passing the record ids would be faster.
  • The preprocessing test compares against your own restatement of the reference steps. A small fixture from HeartLang's actual output would make it stronger, once you can run against the real data.
  • On your questions: keeping heartlang as the default is reasonable for comparability with the paper, since it is documented clearly.

Reviewed commit ab1fcf0

@solarsys
solarsys merged commit 5cf31ab into sunlabuiuc:master Nov 27, 2026
2 checks passed
solarsys added a commit to solarsys/PyHealth that referenced this pull request Nov 27, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: automatic The PR will go through automatic review process.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants