biosppy.signals.ecg¶
biosppy.signals.ecg¶
This module provides methods to process Electrocardiographic (ECG) signals. Implemented code assumes a single-channel Lead I like ECG signal.
- copyright:
2015-2026 by Instituto de Telecomunicacoes
- license:
BSD 3-clause, see LICENSE for more details.
Functions
|
ECG R-peak segmentation algorithm. |
|
ECG QRS-Peak Detection Algorithm |
|
Signal quality estimator. Designed for signal with a lenght of 10 seconds. |
|
Comparison of the output of two detectors. |
|
Checks **kwargs against valid optional parameters for the selected segmenter and calls it with the valid arguments. |
|
ECG R-peak segmentation algorithm. |
|
Compare the segmentation performance of a list of R-peak positions against a reference list. |
|
correct_artifacts: correct artifacts according to its type. |
|
correct_extra: correct extra beat by deleting it. |
|
correct_misaligned: correct misaligned beat (long or short) by interpolating new values to the RR time series. |
|
correct_missed: correct missed beat by adding new R-wave occurrence time so that it divides the detected long RR interval into two equal halves and RR interval series is then recalculated. |
|
Correct R-peak locations to the maximum within a tolerance. |
|
Process a raw ECG signal and extract relevant signal features using default parameters. |
|
ECG R-peak segmentation algorithm. |
|
estimate_th: estimate threshold |
|
Extract heartbeat templates from an ECG signal, given a list of R-peak locations. |
|
Returns the ration between two frequency power bands. |
|
find_artifacts: find and classify artifacts |
|
FIXPEAKS: HRV time series artifact correction. |
|
ECG R-peak segmentation algorithm. |
|
Different ECG Waves (Q, R, S, ...) are not present or are not so clear to identify in all ECG signals (I II III V1 V2 V3, ...) |
|
Different ECG Waves (Q, R, S, ...) are not present or are not so clear to identify in all ECG signals (I II III V1 V2 V3, ...) For Q wave we suggest to use signals I, aVL . |
|
Different ECG Waves (Q, R, S, ...) are not present or are not so clear to identify in all ECG signals (I II III V1 V2 V3, ...) |
|
Different ECG Waves (Q, R, S, ...) are not present or are not so clear to identify in all ECG signals (I II III V1 V2 V3, ...) For T wave we suggest to use signals V4, v5 (II, V3 have good results, but in less accuracy) . |
|
ECG R-peak segmentation algorithm. |
|
Return the kurtosis of the signal |
|
Return the flatline percentage of the signal |
|
plot_artifacts: plot artifacts according to its type. |
|
Return the skewness of the signal |
|
ECG R-peak segmentation based on the Slope Sum Function (SSF). |
|
update_indices: updates the indices in update_indices based on the values in source_indices and update. |
- biosppy.signals.ecg.ASI_segmenter(signal=None, sampling_rate=1000.0, Pth=5.0)[source]¶
ECG R-peak segmentation algorithm.
- Parameters:
signal (array) – Input ECG signal.
sampling_rate (int, float, optional) – Sampling frequency (Hz).
Pth (int, float, optional) – Free parameter used in exponential decay
- Returns:
rpeaks (array) – R-peak location indices.
References
Modification by Tiago Rodrigues, based on: [R. Gutiérrez-rivas 2015] Novel Real-Time Low-Complexity QRS Complex Detector
Based on Adaptive Thresholding. Vol. 15,no. 10, pp. 6036–6043, 2015.
- [D. Sadhukhan] R-Peak Detection Algorithm for Ecg using Double Difference
And RRInterval Processing. Procedia Technology, vol. 4, pp. 873–877, 2012.
- biosppy.signals.ecg.Pan_Tompkins_Plus_Plus_segmenter(signal=None, sampling_rate=1000.0)[source]¶
ECG QRS-Peak Detection Algorithm
Follows the approach by Md Niaz and Naimul [MdNiNai22].
- Parameters:
signal (array) – Input raw ECG signal.
sampling_rate (int, float, optional) – Sampling frequency (Hz).
- Returns:
qrs_i_raw (array) – R-peak location indices.
References
[MdNiNai22]Khan, Naimul and Imtiaz, Md Niaz, “Pan-Tompkins++: A Robust Approach to Detect R-peaks in ECG Signals”, arXiv preprint arXiv:2211.03171, 2022
- biosppy.signals.ecg.ZZ2018(signal, detector_1, detector_2, fs=1000, search_window=100, nseg=1024, mode='simple')[source]¶
- Signal quality estimator. Designed for signal with a lenght of 10 seconds.
Follows the approach by Zhao et la. [Zhao18].
- Parameters:
signal (array) – Input ECG signal in mV.
detector_1 (array) – Input of the first R peak detector.
detector_2 (array) – Input of the second R peak detector.
fs (int, float, optional) – Sampling frequency (Hz).
search_window (int, optional) – Search window around each peak, in ms.
nseg (int, optional) – Frequency axis resolution.
mode (str, optional) – If ‘simple’, simple heurisitc. If ‘fuzzy’, employ a fuzzy classifier.
- Returns:
noise (str) – Quality classification.
References
[Zhao18]Zhao, Z., & Zhang, Y. (2018).
SQI quality evaluation mechanism of single-lead ECG signal based on simple heuristic fusion and fuzzy comprehensive evaluation. Frontiers in Physiology, 9, 727.
- biosppy.signals.ecg.bSQI(detector_1, detector_2, fs=1000.0, mode='simple', search_window=150)[source]¶
Comparison of the output of two detectors.
- Parameters:
detector_1 (array) – Output of the first detector.
detector_2 (array) – Output of the second detector.
fs (int, optional) – Sampling rate, in Hz.
mode (str, optional) – If ‘simple’, return only the percentage of beats detected by both. If ‘matching’, return the peak matching degree. If ‘n_double’ returns the number of matches divided by the sum of all minus the matches.
search_window (int, optional) – Search window around each peak, in ms.
- Returns:
bSQI (float) – Performance of both detectors.
- biosppy.signals.ecg.call_segmenter(segmenter, filtered_signal, sampling_rate, verbose=False, **kwargs)[source]¶
Checks **kwargs against valid optional parameters for the selected segmenter and calls it with the valid arguments.
- Parameters:
segmenter (Callable) – The segmentation function to call.
filtered_signal (array_like) – Filtered ECG signal.
sampling_rate (int or float) – Sampling frequency in Hz.
verbose (bool, optional) – If True, prints which valid parameters were passed to the segmenter.
**kwargs (dict) – Additional optional keyword arguments to pass to the segmenter.
- Returns:
rpeaks (array) – Indices of detected R-peaks.
- biosppy.signals.ecg.christov_segmenter(signal=None, sampling_rate=1000.0)[source]¶
ECG R-peak segmentation algorithm.
Follows the approach by Christov [Chri04].
- Parameters:
signal (array) – Input filtered ECG signal.
sampling_rate (int, float, optional) – Sampling frequency (Hz).
- Returns:
rpeaks (array) – R-peak location indices.
References
[Chri04]Ivaylo I. Christov, “Real time electrocardiogram QRS detection using combined adaptive threshold”, BioMedical Engineering OnLine 2004, vol. 3:28, 2004
- biosppy.signals.ecg.compare_segmentation(reference=None, test=None, sampling_rate=1000.0, offset=0, minRR=None, tol=0.05)[source]¶
Compare the segmentation performance of a list of R-peak positions against a reference list.
- Parameters:
reference (array) – Reference R-peak location indices.
test (array) – Test R-peak location indices.
sampling_rate (int, float, optional) – Sampling frequency (Hz).
offset (int, optional) – Constant a priori offset (number of samples) between reference and test R-peak locations.
minRR (float, optional) – Minimum admissible RR interval (seconds).
tol (float, optional) – Tolerance between corresponding reference and test R-peak locations (seconds).
- Returns:
TP (int) – Number of true positive R-peaks.
FP (int) – Number of false positive R-peaks.
performance (float) – Test performance; TP / len(reference).
acc (float) – Accuracy rate; TP / (TP + FP).
err (float) – Error rate; FP / (TP + FP).
match (list) – Indices of the elements of ‘test’ that match to an R-peak from ‘reference’.
deviation (array) – Absolute errors of the matched R-peaks (seconds).
mean_deviation (float) – Mean error (seconds).
std_deviation (float) – Standard deviation of error (seconds).
mean_ref_ibi (float) – Mean of the reference interbeat intervals (seconds).
std_ref_ibi (float) – Standard deviation of the reference interbeat intervals (seconds).
mean_test_ibi (float) – Mean of the test interbeat intervals (seconds).
std_test_ibi (float) – Standard deviation of the test interbeat intervals (seconds).
- biosppy.signals.ecg.correct_artifacts(artifacts, peaks)[source]¶
correct_artifacts: correct artifacts according to its type.
- Parameters:
artifacts (dictionary) – Struct containing indices of detected artifacts.
peaks (array) – Vector containing indices of detected peaks (R waves locations)
- Returns:
peaks (array) – Vector containing indices of corrected R peaks.
- biosppy.signals.ecg.correct_extra(extra_indices, peaks)[source]¶
correct_extra: correct extra beat by deleting it.
- Parameters:
extra_indices (array) – Vector containing indices of extra beats.
peaks (array) – Vector containing indices of detected peaks (R waves locations).
- Returns:
corrected_peaks (array) – Vector containing indices of corrected peaks.
- biosppy.signals.ecg.correct_misaligned(misaligned_indices, peaks)[source]¶
correct_misaligned: correct misaligned beat (long or short) by interpolating new values to the RR time series.
- Parameters:
misaligned_indices (array) – Vector containing indices of misaligned beats.
peaks (array) – Vector containing indices of detected peaks (R waves locations).
- Returns:
corrected_peaks (array) – Vector containing indices of corrected peaks.
- biosppy.signals.ecg.correct_missed(missed_indices, peaks)[source]¶
correct_missed: correct missed beat by adding new R-wave occurrence time so that it divides the detected long RR interval into two equal halves and RR interval series is then recalculated.
- Parameters:
missed_indices (array) – Vector containing indices of missed beats.
peaks (array) – Vector containing indices of detected peaks (R waves locations).
- Returns:
corrected_peaks (array) – Vector containing indices of corrected peaks.
- biosppy.signals.ecg.correct_rpeaks(signal=None, rpeaks=None, sampling_rate=1000.0, tol=0.05)[source]¶
Correct R-peak locations to the maximum within a tolerance.
- Parameters:
signal (array) – ECG signal.
rpeaks (array) – R-peak location indices.
sampling_rate (int, float, optional) – Sampling frequency (Hz).
tol (int, float, optional) – Correction tolerance (seconds).
- Returns:
rpeaks (array) – Cerrected R-peak location indices.
Notes
The tolerance is defined as the time interval
.
- biosppy.signals.ecg.ecg(signal=None, sampling_rate=1000.0, units=None, path=None, show=True, interactive=False, segmenter='hamilton', verbose_segmenting=False, **kwargs)[source]¶
Process a raw ECG signal and extract relevant signal features using default parameters.
- Parameters:
signal (array) – Raw ECG signal.
sampling_rate (int, float, optional) – Sampling frequency (Hz).
units (str, optional) – The units of the input signal. If specified, the plot will have the y-axis labeled with the corresponding units.
path (str, optional) – If provided, the plot will be saved to the specified file.
show (bool, optional) – If True, show a summary plot.
interactive (bool, optional) – If True, shows an interactive plot.
segmenter (string, optional) –
Name of the segmenting algorithm. Available options:
”hamilton” → hamilton_segmenter
”ASI” → ASI_segmenter
”gamboa” → gamboa_segmenter
”engzee” → engzee_segmenter
”ssf” → ssf_segmenter
”pan-tompkins” → Pan_Tompkins_Plus_Plus_segmenter
If a different name is passed hamilton will be used.
verbose_segmenting (bool, optional) – If True, prints which valid parameters (for the chosen segmenter) were passed.
**kwargs (dict) – Additional optional keyword arguments (currently only viable for segmenter parameters).
- Returns:
ts (array) – Signal time axis reference (seconds).
filtered (array) – Filtered ECG signal.
rpeaks (array) – R-peak location indices.
templates_ts (array) – Templates time axis reference (seconds).
templates (array) – Extracted heartbeat templates.
heart_rate_ts (array) – Heart rate time axis reference (seconds).
heart_rate (array) – Instantaneous heart rate (bpm).
- biosppy.signals.ecg.engzee_segmenter(signal=None, sampling_rate=1000.0, threshold=0.48)[source]¶
ECG R-peak segmentation algorithm.
Follows the approach by Engelse and Zeelenberg [EnZe79] with the modifications by Lourenco et al. [LSLL12].
- Parameters:
signal (array) – Input filtered ECG signal.
sampling_rate (int, float, optional) – Sampling frequency (Hz).
threshold (float, optional) – Detection threshold.
- Returns:
rpeaks (array) – R-peak location indices.
References
[EnZe79]W. Engelse and C. Zeelenberg, “A single scan algorithm for QRS detection and feature extraction”, IEEE Comp. in Cardiology, vol. 6, pp. 37-42, 1979
[LSLL12]A. Lourenco, H. Silva, P. Leite, R. Lourenco and A. Fred, “Real Time Electrocardiogram Segmentation for Finger Based ECG Biometrics”, BIOSIGNALS 2012, pp. 49-54, 2012
- biosppy.signals.ecg.estimate_th(x, alpha, ww)[source]¶
estimate_th: estimate threshold
- Parameters:
x (array) – Vector containing drrs or mrrs.
alpha (float) – Empirically obtaind constant used in threshold calculation.
ww (int) – Window width in ms.
- Returns:
th (float) – Threshold.
- biosppy.signals.ecg.extract_heartbeats(signal=None, rpeaks=None, sampling_rate=1000.0, before=0.2, after=0.4)[source]¶
Extract heartbeat templates from an ECG signal, given a list of R-peak locations.
- Parameters:
signal (array) – Input ECG signal.
rpeaks (array) – R-peak location indices.
sampling_rate (int, float, optional) – Sampling frequency (Hz).
before (float, optional) – Window size to include before the R peak (seconds).
after (int, optional) – Window size to include after the R peak (seconds).
- Returns:
templates (array) – Extracted heartbeat templates.
rpeaks (array) – Corresponding R-peak location indices of the extracted heartbeat templates.
- biosppy.signals.ecg.fSQI(ecg_signal, fs=1000.0, nseg=1024, num_spectrum=[5, 20], dem_spectrum=None, mode='simple')[source]¶
Returns the ration between two frequency power bands.
- Parameters:
ecg_signal (array) – ECG signal.
fs (float, optional) – ECG sampling frequency, in Hz.
nseg (int, optional) – Frequency axis resolution.
num_spectrum (array, optional) – Frequency bandwidth for the ratio’s numerator, in Hz.
dem_spectrum (array, optional) – Frequency bandwidth for the ratio’s denominator, in Hz. If None, then the whole spectrum is used.
mode (str, optional) – If ‘simple’ just do the ration, if is ‘bas’, then do 1 - num_power.
- Returns:
Ratio (float) – Ratio between two powerbands.
- biosppy.signals.ecg.find_artifacts(peaks, sampling_rate)[source]¶
find_artifacts: find and classify artifacts
- Parameters:
peaks (array) – Vector containing indices of detected peaks (R waves locations)
sampling_rate (float) – ECG sampling frequency, in Hz.
- Returns:
artifacts (dictionary) – Struct containing indices of detected artifacts.
subspaces (dictionary) – Subspaces containing rr, drrs, mrrs, s12, s22, c1, c2 used to classify artifacts.
- biosppy.signals.ecg.fixpeaks(peaks, sampling_rate=1000, iterative=True, show=False)[source]¶
FIXPEAKS: HRV time series artifact correction.
Follows the approach by Lipponen et. al, 2019 [Lipp19]. Matlab implementation by Marek Sokol, 2022.
- Parameters:
peaks (array) – Vector containing indices of detected peaks (R waves locations)
sampling_rate (int, float, optional) – ECG sampling frequency, in Hz.
iterative (boolean, optional) – Repeatedly apply the artifact correction (default = true).
show (boolean, optional) – Visualize artifacts and artifact thresholds (default = false).
- Returns:
artifacts (dictionary) – Struct containing indices of detected artifacts.
peaks_clean (array) – Vector of corrected peak values (indices)
References
[Lipp19]Jukka A. Lipponen & Mika P. Tarvainen (2019): A robust algorithm for heart rate variability time series artefact correction using novel beat classification, Journal of Medical Engineering & Technology
- biosppy.signals.ecg.gamboa_segmenter(signal=None, sampling_rate=1000.0, tol=0.002)[source]¶
ECG R-peak segmentation algorithm.
Follows the approach by Gamboa.
- Parameters:
signal (array) – Input filtered ECG signal.
sampling_rate (int, float, optional) – Sampling frequency (Hz).
tol (float, optional) – Tolerance parameter.
- Returns:
rpeaks (array) – R-peak location indices.
- biosppy.signals.ecg.getPPositions(ecg_proc=None, show=False)[source]¶
- Different ECG Waves (Q, R, S, …) are not present or are not so clear to identify in all ECG signals (I II III V1 V2 V3, …)
For P wave we suggest to use signals II, V1, aVF . Avoid I, III, V1, V2, V3, V4, V5, AVL
- Parameters:
ecg_proc (object) – object return by the function ecg.
show (bool, optional) – If True, show a plot of the P Positions on every signal sample/template.
- Returns:
P_positions (array) – Array with all P positions on the signal
P_start_ positions (array) – Array with all P start positions on the signal
P_end_ positions (array) – Array with all P end positions on the signal
- biosppy.signals.ecg.getQPositions(ecg_proc=None, show=False)[source]¶
Different ECG Waves (Q, R, S, …) are not present or are not so clear to identify in all ECG signals (I II III V1 V2 V3, …) For Q wave we suggest to use signals I, aVL . Avoid II, III, V1, V2, V3, V4, aVR, aVF
- Parameters:
ecg_proc (object) – object return by the function ecg.
show (bool, optional) – If True, show a plot of the Q Positions on every signal sample/template.
- Returns:
Q_positions (array) – Array with all Q positions on the signal
Q_start_ positions (array) – Array with all Q start positions on the signal
- biosppy.signals.ecg.getSPositions(ecg_proc=None, show=False)[source]¶
- Different ECG Waves (Q, R, S, …) are not present or are not so clear to identify in all ECG signals (I II III V1 V2 V3, …)
For S wave we suggest to use signals V1, V2, V3. Avoid I, V5, V6, aVR, aVL
- Parameters:
ecg_proc (object) – object return by the function ecg.
show (bool, optional) – If True, show a plot of the S Positions on every signal sample/template.
- Returns:
S_positions (array) – Array with all S positions on the signal
S_end_ positions (array) – Array with all S end positions on the signal
- biosppy.signals.ecg.getTPositions(ecg_proc=None, show=False)[source]¶
Different ECG Waves (Q, R, S, …) are not present or are not so clear to identify in all ECG signals (I II III V1 V2 V3, …) For T wave we suggest to use signals V4, v5 (II, V3 have good results, but in less accuracy) . Avoid I, V1, V2, aVR, aVL
- Parameters:
ecg_proc (object) – object return by the function ecg.
show (bool, optional) – If True, show a plot of the T Positions on every signal sample/template.
- Returns:
T_positions (array) – Array with all T positions on the signal
T_start_ positions (array) – Array with all T start positions on the signal
T_end_ positions (array) – Array with all T end positions on the signal
- biosppy.signals.ecg.hamilton_segmenter(signal=None, sampling_rate=1000.0)[source]¶
ECG R-peak segmentation algorithm.
Follows the approach by Hamilton [Hami02].
- Parameters:
signal (array) – Input filtered ECG signal.
sampling_rate (int, float, optional) – Sampling frequency (Hz).
- Returns:
rpeaks (array) – R-peak location indices.
References
[Hami02]P.S. Hamilton, “Open Source ECG Analysis Software Documentation”, E.P.Limited, 2002
- biosppy.signals.ecg.kSQI(signal, fisher=True)[source]¶
Return the kurtosis of the signal
- Parameters:
signal (array) – ECG signal.
fisher (bool, optional) – If True,Fisher’s definition is used (normal ==> 0.0). If False, Pearson’s definition is used (normal ==> 3.0).
- Returns:
kurtosis (float) – Kurtosis value.
- biosppy.signals.ecg.pSQI(signal, f_thr=0.01)[source]¶
Return the flatline percentage of the signal
- Parameters:
signal (array) – ECG signal.
f_thr (float, optional) – Flatline threshold, in mV / sample
- Returns:
flatline_percentage (float) – Percentage of signal where the absolute value of the derivative is lower then the threshold.
- biosppy.signals.ecg.plot_artifacts(artifacts, subspaces)[source]¶
plot_artifacts: plot artifacts according to its type.
- Parameters:
artifacts (dictionary) – Struct containing indices of detected artifacts.
subspaces (dictionary) – Subspaces containing rr, drrs, mrrs, s12, s22, c1, c2 used to classify artifacts.
- Returns:
None
- biosppy.signals.ecg.sSQI(signal)[source]¶
Return the skewness of the signal
- Parameters:
signal (array) – ECG signal.
- Returns:
skewness (float) – Skewness value.
- biosppy.signals.ecg.ssf_segmenter(signal=None, sampling_rate=1000.0, threshold=20, before=0.03, after=0.01)[source]¶
ECG R-peak segmentation based on the Slope Sum Function (SSF).
- Parameters:
signal (array) – Input filtered ECG signal.
sampling_rate (int, float, optional) – Sampling frequency (Hz).
threshold (float, optional) – SSF threshold.
before (float, optional) – Search window size before R-peak candidate (seconds).
after (float, optional) – Search window size after R-peak candidate (seconds).
- Returns:
rpeaks (array) – R-peak location indices.
- biosppy.signals.ecg.update_indices(source_indices, update_indices, update)[source]¶
update_indices: updates the indices in update_indices based on the values in source_indices and update.
- Parameters:
source_indices (array) – Vector containing original indices.
update_indices (array) – Vector containing update_indices.
update (int) – Update index
- Returns:
list(np.unique(update_indices)) (array) – Vector containing unique updated indices.