def hamilton_single(fields, record, save_path, sig, save=True): detectors = Detectors(fields['fs']) r_peaks = detectors.hamilton_detector(sig[:, 0]) if save: save_prediction(r_peaks, record, save_path) else: return r_peaks
def test_addRepetitionDelay(self): ecg, fecg = self.dataUtils.readData(0) detectors = Detectors(200) # fecgDelayed = self.dataUtils.createDelayRepetition(fecg, 4, 5) # self.assertIsNotNone(fecgDelayed) r_peaks = detectors.hamilton_detector(ecg) pass
def heart_rate_variability(sample, lead, rpeak_method = 'string'): curdir = 'DATA\TrainData_FeatureExtraction' [all_data, header_data, BAD_LABELS] = data_read.data_files_load(curdir) data = all_data[sample][lead] """INITIALIZE DETECTOR CLASS WITH THE SAMPLING RATE:""" detectors = Detectors(500) """FIND RPEAK USING ONE OF THE METHODS BELOW--------------------""" if rpeak_method == 'hamilton' or rpeak_method == 'string': #Hamilton. r_peaks = detectors.hamilton_detector(data) elif rpeak_method == 'christov': #Christov r_peaks = detectors.christov_detector(data) elif rpeak_method == 'engelse': #Engelse and Zeelenberg r_peaks = detectors.engzee_detector(data) elif rpeak_method == 'pan': #Pan and Tompkins r_peaks = detectors.pan_tompkins_detector(data) elif rpeak_method == 'stationary_wavelet': #Stationary Wavelet Transform r_peaks = detectors.swt_detector(data) elif rpeak_method == 'two_moving_average': #Two Moving Average r_peaks = detectors.two_average_detector(data) #elif rpeak_method == 'matched_filter': #Matched Filter #go to pyhrv documentation to find the template file #r_peaks = detectors.matched_filter_detector(data,template_file) """COMPUTE NNI SERIES-------------------------------------------""" nn = nn_intervals(r_peaks) #nni seems to be off by a factor of 3 print("\n\n", nn, "\n\n") """PLOT ECG/TACHOGRAM-------------------------------------------""" #plot_ecg(data, sampling_rate = 500) #tachogram(nn, sampling_rate = 500) """COMPUTE HRV--------------------------------------------------""" results = hrv(nn, None, None, 500) """COMPUTE HR PARAMETERS--(SOMETHING IS WRONG HERE BPM TOO HIGH)""" hr = heart_rate(nn) """COMPUTE FREQUENCY ANALYSIS-----------------------------------""" freq_results = results['fft_bands'] return results, hr, freq_results
def predict_labels(ecg_leads,fs,ecg_names,use_pretrained=False): ''' Parameters ---------- model_name : str Dateiname des Models. In Code-Pfad ecg_leads : list of numpy-Arrays EKG-Signale. fs : float Sampling-Frequenz der Signale. ecg_names : list of str eindeutige Bezeichnung für jedes EKG-Signal. Returns ------- predictions : list of tuples ecg_name und eure Diagnose ''' #------------------------------------------------------------------------------ # Euer Code ab hier # From here add some our code model_name = "model.npy" if use_pretrained: model_name = "model_pretrained.npy" with open(model_name, 'rb') as f: th_opt = np.load(f) # Lade simples Model (1 Parameter) detectors = Detectors(fs) # Initialisierung des QRS-Detektors predictions = list() for idx,ecg_lead in enumerate(ecg_leads): r_peaks = detectors.hamilton_detector(ecg_lead) # Detektion der QRS-Komplexe sdnn = np.std(np.diff(r_peaks)/fs*1000) if sdnn < th_opt: predictions.append((ecg_names[idx], 'N')) else: predictions.append((ecg_names[idx], 'A')) if ((idx+1) % 100)==0: print(str(idx+1) + "\t Dateien wurden verarbeitet.") #------------------------------------------------------------------------------ return predictions # Liste von Tupels im Format (ecg_name,label) - Muss unverändert bleiben!
def std_of_successive_diffs(ecg_signal, sample_rate=1000): hr_analyzer = HRV(sample_rate) detectors = Detectors(sample_rate) r_peaks = detectors.hamilton_detector(ecg_signal) return hr_analyzer.SDSD(r_peaks)
def rms_of_successive_diffs(ecg_signal, sample_rate=1000): hr_analyzer = HRV(sample_rate) detectors = Detectors(sample_rate) r_peaks = detectors.hamilton_detector(ecg_signal) return hr_analyzer.RMSSD(r_peaks, normalise=False)
def rms_diffs(ecg_signal, sample_rate=1000): detectors = Detectors(sample_rate) r_peaks = detectors.hamilton_detector(ecg_signal) return np.sqrt( np.divide(np.sum(np.power(np.diff(r_peaks), 2)), (len(r_peaks) - 1)))
def mean_hr(ecg_signal, sample_rate=1000): hr_analyzer = HRV(sample_rate) detectors = Detectors(sample_rate) r_peaks = detectors.hamilton_detector(ecg_signal) heart_r = hr_analyzer.HR(r_peaks) return np.mean(heart_r)
def mean_rr(signal, sample_rate=1000): detectors = Detectors(sample_rate) # P.S. Hamilton, “Open Source ECG Analysis Software Documentation”, E.P.Limited, 2002 r_peaks = detectors.hamilton_detector(signal) return np.mean(np.diff(r_peaks))
def ecg_peaks(x, sfreq=1000, new_sfreq=1000, method='pan-tompkins', find_local=True, win_size=100): """A simple wrapper for many popular R peaks detectors algorithms. This function calls methods from the py-ecg-detectors [#]_ module. Parameters ---------- x : list or 1d array-like The oxi signal. sfreq : int The sampling frequency. Default is set to 75 Hz. method : str The method used. Can be one of the following: 'hamilton', 'christov', 'engelse-zeelenberg', 'pan-tompkins', 'wavelet-transform', 'moving-average'. find_local : bool If *True*, will use peaks indexs to search for local peaks given the window size (win_size). win_size : int Size of the time window used by :py:func:`systole.utils.to_neighbour()` Returns ------- peaks : 1d array-like Numpy array containing peaks index. resampled_signal : 1d array-like Signal resampled to the `new_sfreq` frequency. Notes ----- This function will call the py-ecg-detectors package to perform R wave detection. .. warning :: This function will resample the signal to 1000 Hz. Examples -------- >>> from systole import import_dataset >>> from systole.detection import ecg_peaks >>> signal_df = import_dataset()[:20*2000] >>> signal, peaks = ecg_peaks(signal_df.ecg.to_numpy(), method='hamilton', >>> sfreq=2000, find_local=True) >>> print(f'{sum(peaks)} peaks detected.') 24 peaks detected. References ---------- .. [#] Howell, L., Porr, B. Popular ECG R peak detectors written in python. DOI: 10.5281/zenodo.3353396 """ if isinstance(x, list): x = np.asarray(x) # Interpolate f = interp1d(np.arange(0, len(x)/sfreq, 1/sfreq), x, fill_value="extrapolate") time = np.arange(0, len(x)/sfreq, 1/new_sfreq) x = f(time) # Copy resampled signal for output resampled_signal = np.copy(x) detectors = Detectors(new_sfreq) if method == 'hamilton': peaks_idx = detectors.hamilton_detector(resampled_signal) elif method == 'christov': peaks_idx = detectors.christov_detector(resampled_signal) elif method == 'engelse-zeelenberg': peaks_idx = detectors.engzee_detector(resampled_signal) elif method == 'pan-tompkins': peaks_idx = detectors.pan_tompkins_detector(resampled_signal) elif method == 'wavelet-transform': peaks_idx = detectors.swt_detector(resampled_signal) elif method == 'moving-average': peaks_idx = detectors.two_average_detector(resampled_signal) else: raise ValueError( 'Invalid method provided, should be: hamilton,', 'christov, engelse-zeelenberg, pan-tompkins, wavelet-transform,', 'moving-average') peaks = np.zeros(len(resampled_signal), dtype=bool) peaks[peaks_idx] = True if find_local is True: peaks = to_neighbour(resampled_signal, peaks, size=win_size) return resampled_signal, peaks
ica_com = ica.get_sources(raw) raw = None gc.collect() ica_times = ica_com.times ica_data = ica_com.get_data() ica_com.close() ica_com = None gc.collect() # https://github.com/berndporr/py-ecg-detectors # variance of the distance between detected R peaks # if the variance is not distinct enough from the 1 percentile, # signal has to be found manually, indicated as 666 in the first item # of the list. r_hr = [ ds.hamilton_detector(ica_data[i]) for i in range(ica_data.shape[0]) ] r_hr = [np.var(np.diff(i)) for i in r_hr] ecg_out[ica_key] = r_hr r_hr = np.array(r_hr) if (np.percentile(r_hr, 1) - np.min(r_hr)) > 500: hr = list(np.where(r_hr < np.percentile(r_hr, 1))[0]) else: hr = [666] samples, events, messages = edf.pread(edf_path) eye = ["left", "right"][events.eye.unique()[0]] del events del messages
def run_algo(algorithm: str, sig: numpy.ndarray, freq_sampling: int) -> List[int]: """ run a qrs detector on a signal :param algorithm: name of the qrs detector to use :type algorithm: str :param sig: values of the sampled signal to study :type sig: ndarray :param freq_sampling: value of sampling frequency of the signal :type freq_sampling: int :return: localisations of qrs detections :rtype: list(int) """ detectors = Detectors(freq_sampling) if algorithm == 'Pan-Tompkins-ecg-detector': qrs_detections = detectors.pan_tompkins_detector(sig) elif algorithm == 'Hamilton-ecg-detector': qrs_detections = detectors.hamilton_detector(sig) elif algorithm == 'Christov-ecg-detector': qrs_detections = detectors.christov_detector(sig) elif algorithm == 'Engelse-Zeelenberg-ecg-detector': qrs_detections = detectors.engzee_detector(sig) elif algorithm == 'SWT-ecg-detector': qrs_detections = detectors.swt_detector(sig) elif algorithm == 'Matched-filter-ecg-detector' and freq_sampling == 360: qrs_detections = detectors.matched_filter_detector( sig, 'templates/template_360hz.csv') elif algorithm == 'Matched-filter-ecg-detector' and freq_sampling == 250: qrs_detections = detectors.matched_filter_detector( sig, 'templates/template_250hz.csv') elif algorithm == 'Two-average-ecg-detector': qrs_detections = detectors.two_average_detector(sig) elif algorithm == 'Hamilton-biosppy': qrs_detections = bsp_ecg.ecg(signal=sig, sampling_rate=freq_sampling, show=False)[2] elif algorithm == 'Christov-biosppy': order = int(0.3 * freq_sampling) filtered, _, _ = bsp_tools.filter_signal(signal=sig, ftype='FIR', band='bandpass', order=order, frequency=[3, 45], sampling_rate=freq_sampling) rpeaks, = bsp_ecg.christov_segmenter(signal=filtered, sampling_rate=freq_sampling) rpeaks, = bsp_ecg.correct_rpeaks(signal=filtered, rpeaks=rpeaks, sampling_rate=freq_sampling, tol=0.05) _, qrs_detections = bsp_ecg.extract_heartbeats( signal=filtered, rpeaks=rpeaks, sampling_rate=freq_sampling, before=0.2, after=0.4) elif algorithm == 'Engelse-Zeelenberg-biosppy': order = int(0.3 * freq_sampling) filtered, _, _ = bsp_tools.filter_signal(signal=sig, ftype='FIR', band='bandpass', order=order, frequency=[3, 45], sampling_rate=freq_sampling) rpeaks, = bsp_ecg.engzee_segmenter(signal=filtered, sampling_rate=freq_sampling) rpeaks, = bsp_ecg.correct_rpeaks(signal=filtered, rpeaks=rpeaks, sampling_rate=freq_sampling, tol=0.05) _, qrs_detections = bsp_ecg.extract_heartbeats( signal=filtered, rpeaks=rpeaks, sampling_rate=freq_sampling, before=0.2, after=0.4) elif algorithm == 'Gamboa-biosppy': order = int(0.3 * freq_sampling) filtered, _, _ = bsp_tools.filter_signal(signal=sig, ftype='FIR', band='bandpass', order=order, frequency=[3, 45], sampling_rate=freq_sampling) rpeaks, = bsp_ecg.gamboa_segmenter(signal=filtered, sampling_rate=freq_sampling) rpeaks, = bsp_ecg.correct_rpeaks(signal=filtered, rpeaks=rpeaks, sampling_rate=freq_sampling, tol=0.05) _, qrs_detections = bsp_ecg.extract_heartbeats( signal=filtered, rpeaks=rpeaks, sampling_rate=freq_sampling, before=0.2, after=0.4) elif algorithm == 'mne-ecg': qrs_detections = mne_ecg.qrs_detector(freq_sampling, sig) elif algorithm == 'heartpy': rol_mean = rolling_mean(sig, windowsize=0.75, sample_rate=100.0) qrs_detections = hp_pkdetection.detect_peaks( sig, rol_mean, ma_perc=20, sample_rate=100.0)['peaklist'] elif algorithm == 'gqrs-wfdb': qrs_detections = processing.qrs.gqrs_detect(sig=sig, fs=freq_sampling) elif algorithm == 'xqrs-wfdb': qrs_detections = processing.xqrs_detect(sig=sig, fs=freq_sampling) else: raise ValueError( f'Sorry... unknown algorithm. Please check the list {algorithms_list}' ) cast_qrs_detections = [int(element) for element in qrs_detections] return cast_qrs_detections
def ecg_detector(self, s, detector_type="pan_tompkins"): """ Expose ECG peak detector from the github https://github.com/berndporr/py-ecg-detectors Parameters ---------- s : Input signal fs: The signal frequency. Default is '256 Hz' detector_type: 'hamilton': Open Source ECG Analysis Software Documentation, E.P.Limited, 2002. 'christov':Real time electrocardiogram QRS detection using combined adaptive threshold 'engzee': A single scan algorithm for QRS detection and feature extraction 'swt': Real-time QRS detector using Stationary Wavelet Transform for Automated ECG Analysis. Uses the Pan and Tompkins thresolding. 'mva': Frequency Bands Effects on QRS Detection. 'mtemp': 'pan_tompkins': A Real-Time QRS Detection Algorithm Default = 'pan_tompkins' Returns ------- type an array of 1-D numpy array represent the peak list """ if self.wave_type == 'ppg': warnings.warn("A ECG detectors is using on PPG waveform. " "Output may produce incorrect result") detector = Detectors(self.fs) if detector_type == 'hamilton': res = detector.hamilton_detector(s) elif detector_type == 'christov': res = detector.christov_detector(s) elif detector_type == 'engzee': res = detector.engzee_detector(s) elif detector_type == 'swt': res = detector.swt_detector(s) elif detector_type == 'mva': res = detector.two_average_detector(s) elif detector_type == 'mtemp': res = self.matched_filter_detector(s) else: res = detector.pan_tompkins_detector(s) return np.array(res)
ecg_leads, ecg_labels, fs, ecg_names = load_references( ) # Importiere EKG-Dateien, zugehörige Diagnose, Sampling-Frequenz (Hz) und Name # Sampling-Frequenz 300 Hz # print('ecg_leads: ', ecg_leads) # print('ecg_names: ', ecg_names) # print('ecg_labels: ', ecg_labels) from ecgdetectors import Detectors detectors = Detectors(fs) # Initialisierung des QRS-Detektors sdnn_normal = np.array([]) # Initialisierung der Feature-Arrays sdnn_afib = np.array([]) sdnn_total = [] ecg_leads_reduced = np.array([]) ecg_labels_reduced = np.array([]) for idx, ecg_lead in enumerate(ecg_leads): r_peaks = detectors.hamilton_detector( ecg_lead) # Detektion der QRS-Komplexe sdnn = np.std( np.diff(r_peaks) / fs * 1000 ) # Berechnung der Standardabweichung der Schlag-zu-Schlag Intervalle (SDNN) in Millisekunden sdnn_total = np.append(sdnn_total, sdnn) # Kombination der beiden SDNN-Listen # if ecg_labels[idx]=='N': # sdnn_normal = np.append(sdnn_normal, sdnn) # Zuordnung zu "Normal" # if ecg_labels[idx]=='A': # sdnn_afib = np.append(sdnn_afib, sdnn) # Zuordnung zu "Vorhofflimmern" # if (ecg_labels[idx] == 'N') | (ecg_labels[idx] =='A'): # ecg_labels_reduced = np.append(ecg_labels_reduced, ecg_labels[idx]) # ecg_leads_reduced = np.append(ecg_leads_reduced, sdnn) print(sdnn_total.shape)