neuropsychology / NeuroKit

NeuroKit2: The Python Toolbox for Neurophysiological Signal Processing
https://neuropsychology.github.io/NeuroKit
MIT License
1.53k stars 410 forks source link

ecg_delineate rises KeyError #798

Closed HotDog702 closed 1 year ago

HotDog702 commented 1 year ago

Faced this error when R peak is quite close to the end of data (50 points for 1000 Hz sampling) In this case S point is placed beyond the end of the data (actually = len(ecg)), so when further the _signal_from_indices is called, it rises the exception:

_, waves = nk.ecg_delineate(ECG_filtered, ECG_peaks, sampling_rate=fs)

File ~/.local/lib/python3.8/site-packages/neurokit2/ecg/ecg_delineate.py:157 in ecg_delineate instant_peaks = signal_formatpeaks(waves_noNA, desired_length=len(ecg_cleaned))

File ~/.local/lib/python3.8/site-packages/neurokit2/signal/signal_formatpeaks.py:21 in signal_formatpeaks signals[feature] = _signal_from_indices(values, desired_length, 1)

File ~/.local/lib/python3.8/site-packages/neurokit2/signal/signal_formatpeaks.py:75 in _signal_from_indices signal[indices] = value

File ~/.local/lib/python3.8/site-packages/pandas/core/series.py:1088 in setitem self._set_with(key, value)

File ~/.local/lib/python3.8/site-packages/pandas/core/series.py:1123 in _set_with self._set_labels(key, value)

File ~/.local/lib/python3.8/site-packages/pandas/core/series.py:1134 in _set_labels raise KeyError(f"{key[mask]} not in index")

KeyError: '[120000] not in index'

HotDog702 commented 1 year ago

ECG_filtered and ECG_peaks that I've used ECG.zip fs=1000 I tried to figure out, why the last peak is placed outside the data, but failed, sorry

danibene commented 1 year ago

I think this was solved here: https://github.com/neuropsychology/NeuroKit/pull/777

Could you try with the dev version? You could install with: pip install git+https://github.com/neuropsychology/NeuroKit.git@dev

HotDog702 commented 1 year ago

For now I remove last R-peak if it is closer to the end of the signal than 0.2 sec before calling ecg_delineate(). This helps. Looking forward for next release of Neurokit

HotDog702 commented 1 year ago

Another (I think, connected) problem, when P-peak is just removed, not set to nan. So, for the attached file I have got 116 'ECG_P_Onsets' and 'ECG_P_Offsets', but just 115 'ECG_P_Peaks'. The first P-peak corresponds to the second R-peak ECG_1.zip

danibene commented 1 year ago

I actually just ran into the KeyError issue myself while doing my own analysis and switching to the dev version did fix it, I am also looking forward to the next release of NeuroKit :)

Since the original issue you brought up seems to have been resolved in the dev version and you opened a separate issue for your most recent comment (https://github.com/neuropsychology/NeuroKit/issues/804), I'm going to close this for now