How deeppsp/torch_ecg works
1. What this repository is
- torch_ecg is a modular PyTorch framework for ECG/physiological-signal research.
- It is organized as a reusable library (torch_ecg/) plus task-specific benchmark projects (benchmarks/) and a large test suite (test/).
2. Top-level architecture
- The core pipeline is: raw database records → database reader / dataset → preprocessing and augmentation → model → task-specific output containers → metrics / logging / training control.
- Configuration is centralized through CFG objects and model config presets, so benchmarks and library code share the same assembly pattern.
3. Data access layer
- torch_ecg/databases/ contains readers for many ECG datasets and challenges, including PhysioNet, CPSC, LUDB, MITDB, and NSRR-derived sources.
- These classes manage record I/O, metadata, record lists, plots, and dataset statistics; they are not training datasets themselves.
- torch_ecg/databases/datasets/ wraps these readers into task-ready PyTorch datasets, e.g. CINC2021Dataset, with train/validation behavior and lazy loading support.
4. Signal preprocessing vs augmentation
- Preprocessing is split into NumPy-oriented preprocessors (torch_ecg/preprocessors/ and older _preprocessors/) for operations like resampling, bandpass filtering, baseline removal, and normalization.
- Augmentations live in torch_ecg/augmenters/ and operate as Torch modules on tensors, including mixup, cutmix, masking, flip, renormalization, stretch/compress, and baseline-wander injection.
- Both are managed through “manager” classes, so a benchmark can describe a whole preprocessing/augmentation stack in config form.
5. Model layer
- torch_ecg/models/ is the model zoo: CRNN, sequence tagging networks, U-Nets, RR-LSTM, and supporting CNN backbones.
- Backbone implementations are separated into torch_ecg/models/cnn/, while task wrappers such as ecg_crnn.py, ecg_seq_lab_net.py, and unets/ compose those backbones into end-task models.
- torch_ecg/model_configs/ holds the canonical configs, which benchmarks customize instead of hardcoding architectures.
6. Task outputs and metrics
- torch_ecg/components/outputs.py defines typed output containers for classification, multilabel classification, sequence tagging, wave delineation, and R-peak detection.
- torch_ecg/components/metrics.py and task-specific scoring modules under benchmarks turn those outputs into challenge metrics.
- This boundary matters because the same model family can feed multiple downstream evaluation styles.
7. Training and experiment orchestration
- torch_ecg/components/trainer.py provides the abstract training workflow: dataloader setup, step execution, evaluation, and other common loop logic.
- torch_ecg/components/loggers.py standardizes CSV, text, and TensorBoard logging.
- Benchmarks subclass or adapt this trainer to implement task-specific losses, batching, and scoring.
8. Benchmark applications
- benchmarks/ contains end-to-end reference projects for challenge tasks such as CinC2020/2021/2022, CPSC2019/2020/2021, and LUDB.
- Each benchmark usually includes its own cfg.py, dataset.py, model.py, trainer.py, and scoring code, showing how to combine the shared library into a working pipeline.
- Some benchmarks are more hybrid: for example, CPSC2021 and CPSC2022 include multiple model heads or multi-task logic, while LUDB focuses on U-Net-style delineation.
9. Data and artifacts
- sample-data/ provides small record sets for several benchmark families, enabling smoke tests and local experimentation without full datasets.
- Benchmark results/ folders store generated CSV/TXT metrics, TensorBoard events, and figures, which act as reproducibility artifacts rather than source code.
- The presence of saved models, PDFs, and notebooks in benchmarks indicates that the repo supports both scripted training and research-style analysis.
10. Utility and algorithmic support
- torch_ecg/utils/ holds cross-cutting helpers: plotting, download utilities, interval/signal math, R-peak detection, and ECG-specific signal processing helpers.
- legacy/ contains older algorithms such as Pan-Tompkins-style code, which likely support backward compatibility or comparison baselines.
- The utils layer is shared broadly by databases, models, and benchmarks, so it is a foundational dependency rather than a standalone subsystem.
11. Quality, documentation, and delivery
- test/ covers databases, models, preprocessors, pipelines, and utilities, mirroring the package boundaries and indicating the intended integration points.
- docs/ is built with Sphinx and documents the same module structure exposed by the package.
- CI workflows run formatting, pytest, database/model/pipeline tests, docs publishing, and CodeQL, which shows the project is maintained as a library with strong regression protection.
12. External dependencies and domain boundaries
- The code is centered on PyTorch, with NumPy-based preprocessing and ECG file formats from PhysioNet/CPSC-style datasets.
- External services and datasets matter architecturally because database readers are tailored to their metadata conventions and record layouts.
- Overall, the repo’s main boundary is between reusable ECG infrastructure in torch_ecg/ and the challenge-specific applications in benchmarks/.
Main entry points: ecg_crnn.py Task models · trainer.py Trainer · cinc2021_dataset.py Task datasets · test_trainer.py Test suite
Components 22
torch_ecg core
Reusable ECG library for data access, signal processing, models, and training components.
- CFG · Central configuration objects shared across datasets, preprocessing, models, and benchmarks.
torch_ecg/cfg.py - DB base · Common reader base for ECG and physiological databases, handling record access and metadata.
torch_ecg/databases/base.py - PhysioNet DBs · Readers for major PhysioNet-style datasets and challenges such as AFDB, MITDB, LUDB, and CINC tasks.
torch_ecg/databases/physionet_databases/cinc2021.py - Task datasets · PyTorch-ready dataset wrappers around database readers, with task-specific sampling and loading behavior.
torch_ecg/databases/datasets/cinc2021/cinc2021_dataset.py - Preprocessors · Signal preprocessing steps such as resampling, filtering, baseline removal, and normalization.
torch_ecg/preprocessors/preproc_manager.py - Augmenters · Tensor-level data augmentation modules such as mixup, cutmix, masking, flipping, and stretch/compress.
torch_ecg/augmenters/augmenter_manager.py - Model configs · Canonical architecture presets used by benchmarks to instantiate and tune models.
torch_ecg/model_configs/ecg_crnn.py - CNN backbones · Reusable convolutional feature extractors shared by higher-level ECG models.
torch_ecg/models/cnn/resnet.py - Task models · End-task model families such as CRNN, sequence labelling nets, U-Nets, and RR-LSTM.
torch_ecg/models/ecg_crnn.py - Outputs · Structured output containers for classification, tagging, delineation, and peak detection tasks.
torch_ecg/components/outputs.py - Metrics · Common metric utilities used to convert model outputs into task scores.
torch_ecg/components/metrics.py - Trainer · Abstract training workflow for dataloading, step execution, evaluation, and experiment control.
torch_ecg/components/trainer.py - Loggers · Standard logging backends for CSV, text, and TensorBoard outputs.
torch_ecg/components/loggers.py
Benchmarks
Task-specific reference projects that assemble the core library into challenge pipelines.
- CinC 2021 · Hybrid benchmark project for the CinC 2021 challenge, combining dataset, model, trainer, and scoring code.
benchmarks/train_hybrid_cpsc2021/trainer.py - CinC 2022 · Multi-task benchmark project for the CinC 2022 challenge with custom models and auxiliary transforms.
benchmarks/train_mtl_cinc2022/trainer.py - CinC 2020 · Challenge benchmark for CRNN-style arrhythmia classification and rhythm detection.
benchmarks/train_crnn_cinc2020/trainer.py - CPSC 2019 · Benchmark project for sequence labelling and U-Net style solutions on CPSC 2019 data.
benchmarks/train_multi_cpsc2019/trainer.py - LUDB · U-Net benchmark for ECG delineation on LUDB.
benchmarks/train_unet_ludb/trainer.py
Support
Documentation, tests, sample data, and legacy code that validate and illustrate the library.
- Sample data · Small record sets used for smoke tests, local experimentation, and benchmark examples.
sample-data/cinc2021/E07500.mat - Test suite · Repository-wide tests spanning databases, preprocessors, models, pipelines, and utilities.
test/test_components/test_trainer.py - Docs · Sphinx documentation reflecting the public package structure and usage patterns.
docs/source/index.rst - Legacy ECG · Back-compat or comparison implementation of classic ECG algorithms such as Pan-Tompkins.
legacy/_pantompkins.py
Connections 34
- CFG → Task datasets: configures · Dataset wrappers are assembled through shared config objects.
- CFG → Preprocessors: configures · Preprocessing stacks are described and composed from configuration.
- CFG → Augmenters: configures · Augmentation pipelines are managed from config-driven setup.
- CFG → Model configs: selects · Model presets provide canonical architecture settings.
- DB base → PhysioNet DBs: specializes · Dataset-specific readers extend the common database reader base.
- DB base → Task datasets: feeds · Readers provide record access for dataset wrappers.
- PhysioNet DBs → Task datasets: wraps into · Raw database readers are turned into task-ready datasets.
- Task datasets → Preprocessors: loads through · Datasets typically apply preprocessing before model input.
- Preprocessors → Augmenters: precedes · Signal preprocessing happens before tensor augmentation in the pipeline.
- Augmenters → Task models: inputs · Augmented tensors are passed to the model stack.
- CNN backbones → Task models: builds · Task models compose reusable CNN backbones into end-task architectures.
- Model configs → Task models: instantiates · Benchmark model assembly uses canonical model configs.
- Task models → Outputs: emits · Models produce typed task outputs rather than raw tensors.
- Outputs → Metrics: evaluates with · Structured outputs feed common and challenge-specific scoring.
- Trainer → Task datasets: consumes · The trainer coordinates dataset and dataloader usage.
- Trainer → Task models: optimizes · Training loop executes forward/backward passes on models.
- Trainer → Metrics: scores · Evaluation uses metrics to summarize predictions.
- Trainer → Loggers: records · Training and evaluation results are written through standard loggers.
- CinC 2021 → Task datasets: uses · Benchmark project uses task datasets and challenge-specific wrappers.
- CinC 2021 → Task models: uses · Benchmark project assembles shared models into a challenge pipeline.
- CinC 2021 → Trainer: adapts · Benchmark-specific training logic subclasses or adapts the shared trainer.
- CinC 2022 → Task models: uses · Multi-task benchmark builds on shared and custom model heads.
- CinC 2022 → Trainer: adapts · Benchmark-specific orchestration extends the common training workflow.
- CinC 2020 → Task models: uses · Challenge benchmark relies on CRNN-style shared models.
- CPSC 2019 → Task models: uses · CPSC 2019 benchmark uses shared sequence tagging and U-Net models.
- LUDB → Task models: uses · LUDB benchmark centers on U-Net style delineation models.
- Sample data → Test suite: supports · Bundled sample data enables smoke tests and local validation.
- Test suite → DB base: covers · Tests mirror the database reader boundary.
- Test suite → Preprocessors: covers · Tests validate preprocessing behavior.
- Test suite → Task models: covers · Tests exercise major model families.
- Test suite → Trainer: covers · Tests validate pipeline and training orchestration.
- Docs → CFG: documents · Docs describe the shared configuration surface.
- Docs → Task models: documents · Docs expose the model zoo and usage patterns.
- Legacy ECG → Metrics: supports · Legacy algorithms provide classic ECG baselines and comparisons.