# deeppsp/torch_ecg architecture

> Architecture diagram of the GitHub repository deeppsp/torch_ecg, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-02). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/deeppsp/torch_ecg
- Repository: https://github.com/deeppsp/torch_ecg

## Overview

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: [`torch_ecg/models/ecg_crnn.py`](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/models/ecg_crnn.py) (Task models), [`torch_ecg/components/trainer.py`](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/components/trainer.py) (Trainer), [`torch_ecg/databases/datasets/cinc2021/cinc2021_dataset.py`](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/databases/datasets/cinc2021/cinc2021_dataset.py) (Task datasets), [`test/test_components/test_trainer.py`](https://github.com/deeppsp/torch_ecg/blob/master/test/test_components/test_trainer.py) (Test suite)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_core["torch_ecg core"]
  node_cfg["CFG<br/>config system<br/>[cfg.py]"]
  node_db_base[("DB base<br/>database API<br/>[base.py]")]
  node_db_physio[("PhysioNet DBs<br/>database readers<br/>[cinc2021.py]")]
  node_db_datasets[("Task datasets<br/>dataset wrappers")]
  node_preproc["Preprocessors<br/>numpy pipeline<br/>[preproc_manager.py]"]
  node_augment["Augmenters<br/>torch transforms"]
  node_model_cfg["Model configs<br/>model presets<br/>[ecg_crnn.py]"]
  node_cnn_backbones["CNN backbones<br/>feature encoders<br/>[resnet.py]"]
  node_task_models["Task models<br/>ECG networks<br/>[ecg_crnn.py]"]
  node_outputs["Outputs<br/>typed containers<br/>[outputs.py]"]
  node_metrics["Metrics<br/>scoring<br/>[metrics.py]"]
  node_trainer["Trainer<br/>training loop<br/>[trainer.py]"]
  node_loggers["Loggers<br/>experiment logging<br/>[loggers.py]"]
end

subgraph group_benchmarks["Benchmarks"]
  node_bench_cinc2021["CinC 2021<br/>benchmark app<br/>[trainer.py]"]
  node_bench_cinc2022["CinC 2022<br/>benchmark app<br/>[trainer.py]"]
  node_bench_cinc2020["CinC 2020<br/>benchmark app<br/>[trainer.py]"]
  node_bench_cpsc2019["CPSC 2019<br/>benchmark app<br/>[trainer.py]"]
  node_bench_ludb["LUDB<br/>benchmark app<br/>[trainer.py]"]
end

subgraph group_support["Support"]
  node_sample_data[("Sample data<br/>artifacts<br/>[E07500.mat]")]
  node_tests["Test suite<br/>validation<br/>[test_trainer.py]"]
  node_docs["Docs<br/>documentation<br/>[index.rst]"]
  node_legacy["Legacy ECG<br/>older algorithms<br/>[_pantompkins.py]"]
end

node_cfg -->|"configures"| node_db_datasets
node_cfg -->|"configures"| node_preproc
node_cfg -->|"configures"| node_augment
node_cfg -->|"selects"| node_model_cfg
node_db_base -->|"specializes"| node_db_physio
node_db_base -->|"feeds"| node_db_datasets
node_db_physio -->|"wraps into"| node_db_datasets
node_db_datasets -->|"loads through"| node_preproc
node_preproc -->|"precedes"| node_augment
node_augment -->|"inputs"| node_task_models
node_cnn_backbones -->|"builds"| node_task_models
node_model_cfg -->|"instantiates"| node_task_models
node_task_models -->|"emits"| node_outputs
node_outputs -->|"evaluates with"| node_metrics
node_trainer -->|"consumes"| node_db_datasets
node_trainer -->|"optimizes"| node_task_models
node_trainer -->|"scores"| node_metrics
node_trainer -->|"records"| node_loggers
node_bench_cinc2021 -->|"uses"| node_db_datasets
node_bench_cinc2021 -->|"uses"| node_task_models
node_bench_cinc2021 -->|"adapts"| node_trainer
node_bench_cinc2022 -->|"uses"| node_task_models
node_bench_cinc2022 -->|"adapts"| node_trainer
node_bench_cinc2020 -->|"uses"| node_task_models
node_bench_cpsc2019 -->|"uses"| node_task_models
node_bench_ludb -->|"uses"| node_task_models
node_sample_data -->|"supports"| node_tests
node_tests -->|"covers"| node_db_base
node_tests -->|"covers"| node_preproc
node_tests -->|"covers"| node_task_models
node_tests -->|"covers"| node_trainer
node_docs -->|"documents"| node_cfg
node_docs -->|"documents"| node_task_models
node_legacy -->|"supports"| node_metrics

click node_cfg "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/cfg.py"
click node_db_base "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/databases/base.py"
click node_db_physio "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/databases/physionet_databases/cinc2021.py"
click node_db_datasets "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/databases/datasets/cinc2021/cinc2021_dataset.py"
click node_preproc "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/preprocessors/preproc_manager.py"
click node_augment "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/augmenters/augmenter_manager.py"
click node_model_cfg "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/model_configs/ecg_crnn.py"
click node_cnn_backbones "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/models/cnn/resnet.py"
click node_task_models "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/models/ecg_crnn.py"
click node_outputs "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/components/outputs.py"
click node_metrics "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/components/metrics.py"
click node_trainer "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/components/trainer.py"
click node_loggers "https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/components/loggers.py"
click node_bench_cinc2021 "https://github.com/deeppsp/torch_ecg/blob/master/benchmarks/train_hybrid_cpsc2021/trainer.py"
click node_bench_cinc2022 "https://github.com/deeppsp/torch_ecg/blob/master/benchmarks/train_mtl_cinc2022/trainer.py"
click node_bench_cinc2020 "https://github.com/deeppsp/torch_ecg/blob/master/benchmarks/train_crnn_cinc2020/trainer.py"
click node_bench_cpsc2019 "https://github.com/deeppsp/torch_ecg/blob/master/benchmarks/train_multi_cpsc2019/trainer.py"
click node_bench_ludb "https://github.com/deeppsp/torch_ecg/blob/master/benchmarks/train_unet_ludb/trainer.py"
click node_sample_data "https://github.com/deeppsp/torch_ecg/blob/master/sample-data/cinc2021/E07500.mat"
click node_tests "https://github.com/deeppsp/torch_ecg/blob/master/test/test_components/test_trainer.py"
click node_docs "https://github.com/deeppsp/torch_ecg/blob/master/docs/source/index.rst"
click node_legacy "https://github.com/deeppsp/torch_ecg/blob/master/legacy/_pantompkins.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_cfg,node_db_base,node_db_physio,node_db_datasets,node_preproc,node_augment,node_model_cfg,node_cnn_backbones,node_task_models,node_outputs,node_metrics,node_trainer,node_loggers toneBlue
class node_bench_cinc2021,node_bench_cinc2022,node_bench_cinc2020,node_bench_cpsc2019,node_bench_ludb toneAmber
class node_sample_data,node_tests,node_docs,node_legacy toneMint
```

## Components

### torch_ecg core

Reusable ECG library for data access, signal processing, models, and training components.

- [CFG](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/cfg.py): config system · Central configuration objects shared across datasets, preprocessing, models, and benchmarks. · `torch_ecg/cfg.py`
- [DB base](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/databases/base.py): database API · Common reader base for ECG and physiological databases, handling record access and metadata. · `torch_ecg/databases/base.py`
- [PhysioNet DBs](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/databases/physionet_databases/cinc2021.py): database readers · 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](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/databases/datasets/cinc2021/cinc2021_dataset.py): dataset wrappers · PyTorch-ready dataset wrappers around database readers, with task-specific sampling and loading behavior. · `torch_ecg/databases/datasets/cinc2021/cinc2021_dataset.py`
- [Preprocessors](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/preprocessors/preproc_manager.py): numpy pipeline · Signal preprocessing steps such as resampling, filtering, baseline removal, and normalization. · `torch_ecg/preprocessors/preproc_manager.py`
- [Augmenters](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/augmenters/augmenter_manager.py): torch transforms · Tensor-level data augmentation modules such as mixup, cutmix, masking, flipping, and stretch/compress. · `torch_ecg/augmenters/augmenter_manager.py`
- [Model configs](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/model_configs/ecg_crnn.py): model presets · Canonical architecture presets used by benchmarks to instantiate and tune models. · `torch_ecg/model_configs/ecg_crnn.py`
- [CNN backbones](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/models/cnn/resnet.py): feature encoders · Reusable convolutional feature extractors shared by higher-level ECG models. · `torch_ecg/models/cnn/resnet.py`
- [Task models](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/models/ecg_crnn.py): ECG networks · End-task model families such as CRNN, sequence labelling nets, U-Nets, and RR-LSTM. · `torch_ecg/models/ecg_crnn.py`
- [Outputs](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/components/outputs.py): typed containers · Structured output containers for classification, tagging, delineation, and peak detection tasks. · `torch_ecg/components/outputs.py`
- [Metrics](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/components/metrics.py): scoring · Common metric utilities used to convert model outputs into task scores. · `torch_ecg/components/metrics.py`
- [Trainer](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/components/trainer.py): training loop · Abstract training workflow for dataloading, step execution, evaluation, and experiment control. · `torch_ecg/components/trainer.py`
- [Loggers](https://github.com/deeppsp/torch_ecg/blob/master/torch_ecg/components/loggers.py): experiment logging · 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](https://github.com/deeppsp/torch_ecg/blob/master/benchmarks/train_hybrid_cpsc2021/trainer.py): benchmark app · Hybrid benchmark project for the CinC 2021 challenge, combining dataset, model, trainer, and scoring code. · `benchmarks/train_hybrid_cpsc2021/trainer.py`
- [CinC 2022](https://github.com/deeppsp/torch_ecg/blob/master/benchmarks/train_mtl_cinc2022/trainer.py): benchmark app · Multi-task benchmark project for the CinC 2022 challenge with custom models and auxiliary transforms. · `benchmarks/train_mtl_cinc2022/trainer.py`
- [CinC 2020](https://github.com/deeppsp/torch_ecg/blob/master/benchmarks/train_crnn_cinc2020/trainer.py): benchmark app · Challenge benchmark for CRNN-style arrhythmia classification and rhythm detection. · `benchmarks/train_crnn_cinc2020/trainer.py`
- [CPSC 2019](https://github.com/deeppsp/torch_ecg/blob/master/benchmarks/train_multi_cpsc2019/trainer.py): benchmark app · Benchmark project for sequence labelling and U-Net style solutions on CPSC 2019 data. · `benchmarks/train_multi_cpsc2019/trainer.py`
- [LUDB](https://github.com/deeppsp/torch_ecg/blob/master/benchmarks/train_unet_ludb/trainer.py): benchmark app · 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](https://github.com/deeppsp/torch_ecg/blob/master/sample-data/cinc2021/E07500.mat): artifacts · Small record sets used for smoke tests, local experimentation, and benchmark examples. · `sample-data/cinc2021/E07500.mat`
- [Test suite](https://github.com/deeppsp/torch_ecg/blob/master/test/test_components/test_trainer.py): validation · Repository-wide tests spanning databases, preprocessors, models, pipelines, and utilities. · `test/test_components/test_trainer.py`
- [Docs](https://github.com/deeppsp/torch_ecg/blob/master/docs/source/index.rst): documentation · Sphinx documentation reflecting the public package structure and usage patterns. · `docs/source/index.rst`
- [Legacy ECG](https://github.com/deeppsp/torch_ecg/blob/master/legacy/_pantompkins.py): older algorithms · Back-compat or comparison implementation of classic ECG algorithms such as Pan-Tompkins. · `legacy/_pantompkins.py`

## Connections

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