Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AF Classification Backend

This repository contains backend code for ECG signal processing and atrial fibrillation (AF) classification, including signal quality assessment, noise detection, P wave and R peak detection, and AF analysis. It supports the PTB-XL dataset and simulated ECG data.


Table of Contents


Features

  • ECG Record Loading: Load and parse ECG records from PTB-XL or WFDB-compatible files.
  • Signal Quality Assessment: Comprehensive checks for noise, flatline, saturation, and overall signal usability.
  • P Wave and R Peak Detection: Robust detection algorithms for P waves and R peaks.
  • Atrial Fibrillation Detection: Feature extraction and AF classification using RR intervals, P wave presence, Baseline and QRS width.
  • Visualization: Plot ECG signals with detected features.
  • ECG Simulation: Generate synthetic ECG signals (including AF) using NeuroKit2.
  • Extensible: Modular code for easy integration and extension.

Project Structure

af_classification/
│
├── main.py                # Main entry point and workflow
├── p_wave.py              # P wave detection logic
├── af_detector.py         # AF detection and analysis
├── simulate.py            # ECG simulation using NeuroKit2
├── requirements.txt       # Python dependencies
├── .gitignore             # Git ignore rules
├── training2017/          # (Optional) ECG data directory
└── ... (other files)

Installation

  1. Clone the repository:

    git clone https://github.com/yourusername/af_classification.git
    cd af_classification
  2. Create a virtual environment (recommended):

    python3 -m venv venv
    source venv/bin/activate
  3. Install dependencies:

    pip install -r requirements.txt

    If you use NeuroKit2 for simulation, also ensure:

    pip install neurokit2 PyWavelets

Usage

ECG Record Loading

Load an ECG record (e.g., from PTB-XL):

from main import Plotter

plotter = Plotter(data_path='./training2017')
record = plotter.get_record('A00001')
print("ECG shape:", record['signal'].shape)

Signal Quality Assessment

quality = plotter.comprehensive_quality_check(record['signal'][:, 0], record['fs'])
print("Signal quality:", quality['overall_quality'])

P Wave and R Peak Detection

p_wave_results = plotter.detect_p_waves_in_record(record)
plotter.plot_p_wave_detection(record['signal'][:, 0], p_wave_results, record['fs'])

Atrial Fibrillation Detection

from af_detector import AtrialFibrillationDetector

af_detector = AtrialFibrillationDetector(fs=record['fs'])
af_results = af_detector.detect_af_in_record(record)
print("AF Detected:", af_results['af_detected'])
af_detector.plot_af_analysis(record['signal'][:, 0], af_results)

Simulating ECG Data

import neurokit2 as nk
import wfdb
import numpy as np

fs = 300
ecg = nk.ecg_simulate(duration=10, sampling_rate=fs, heart_rate=90, noise=0.01)
ecg_signal = np.array(ecg).reshape(-1, 1)
wfdb.wrsamp('sim_sinus', fs=fs, units=['mV'], sig_name=['I'], p_signal=ecg_signal)

Configuration

  • Data Path: Set the data_path argument in Plotter to your ECG data directory.
  • Lead Selection: By default, lead I ([:, 0]) is used. Change the index for other leads.

Testing

You can add unit tests using pytest or your preferred framework. Example:

pytest tests/

Dependencies

  • Python 3.7+
  • numpy
  • scipy
  • matplotlib
  • wfdb
  • neurokit2 (for simulation)
  • PyWavelets (for neurokit2)

Install all with:

pip install -r requirements.txt

Troubleshooting

  • ModuleNotFoundError: Install missing packages with pip install <package>.
  • ValueError: The length of the input vector x must be greater than padlen: Ensure your ECG signal is long enough (typically >30 samples for filtering).
  • WFDB plotting errors: Pass only WFDB record objects to plot_ecg, not numpy arrays or dicts.

License

This project is licensed under the MIT License.


Acknowledgements

About

An attempt at atrial fibrillation based on 4 principle of proof of Afib

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages