Reusable ECG R-peak detection and HRV analysis code, cleaned up from older analysis scripts.
The default pipeline:
- Reads an EDF file with MNE.
- Extracts one ECG channel.
- Cleans the ECG with NeuroKit's BioSPPy-style cleaner.
- Checks whether the ECG polarity should be flipped.
- Detects R-peaks with NeuroKit.
- Removes implausible peaks using RR interval, relative interval, amplitude, and low-beat-count window checks.
- Exports R-peaks, RR intervals, NeuroKit HRV metrics, optional resampled NN series, run metadata, and a diagnostic ECG/R-peak plot.
Create an environment and install the package:
python -m pip install -e ".[dev]"With conda:
conda env create -f environment.yml
conda activate hrv-toolsRun the included SHHS example:
hrv-tools analyze examples/data/shhs1-205804.edf --channel ECG --output-dir outputs/shhs1Or, without installing the command:
PYTHONPATH=src python -m hrv_tools analyze examples/data/shhs1-205804.edf --channel ECG --output-dir outputs/shhs1List EDF channels:
hrv-tools list-channels examples/data/shhs1-205804.edfThe analyze command writes:
rpeaks_rr_intervals.csv: retained R-peaks, RR intervals, instantaneous heart rate, amplitudes, and a validity flag for intervals crossing large gaps.hrv_time.csv,hrv_frequency.csv,hrv_nonlinear.csv,hrv_all.csv: NeuroKit HRV metrics for the analysis window.nn_linear_4hz.csv: linearly resampled NN intervals.nn_berger_4hz.csv: Berger-style fractional-beat resampled heart rate and NN intervals.ecg_rpeaks_segment.png: diagnostic ECG segment with retained R-peaks.run_metadata.json: parameters, package versions, channel metadata, and peak counts.
By default HRV metrics are computed on the first hour, matching the old demonstration script:
hrv-tools analyze examples/data/shhs1-205804.edf --analysis-start 0 --analysis-duration 3600Use --analysis-duration 0 to use all retained peaks. If large gaps are present,
the command computes metrics on the longest continuous retained segment in the
selected window.
from hrv_tools import compute_neurokit_hrv, create_rr_table, detect_rpeaks, read_ecg_from_edf
record = read_ecg_from_edf("examples/data/shhs1-205804.edf", channel="ECG")
detection = detect_rpeaks(record.signal, record.sampling_rate)
rr_table = create_rr_table(detection.rpeaks, record.sampling_rate, detection.ecg_cleaned)
hrv = compute_neurokit_hrv(detection.rpeaks[:4000], record.sampling_rate)- NeuroKit2: ECG cleaning, R-peak detection, and HRV metrics.
- MNE-Python: EDF reading.
- Berger RD, Akselrod S, Gordon D, Cohen RJ. An efficient algorithm for spectral analysis of heart rate variability. IEEE Transactions on Biomedical Engineering. 1986;33(9):900-904.