Ejemplo n.º 1
0
    def update(self):

        if not self.i.ready():
            return

        # set rate from the data if it is not yet given
        if self._rate is None:
            try:
                self._rate = self.i.meta.pop('nominal_rate')
                self.logger.info(f'Nominal rate set to {self._rate}. ')
            except KeyError:
                # If there is no rate in the meta, set rate to 1.0
                self._rate = 1.0
                self.logger.warning(f'Nominal rate not supplied, considering '
                                    f'1.0 Hz instead. ')

        # At this point, we are sure that we have some data to process
        super().update()
        # if the window output is ready, fit the scaler with its values
        if self.o.ready() and not self.o.data.dropna().empty:
            X = self.o.data.dropna().values[:, 0]
            try:
                df = ecg_process(X, sampling_rate=self._rate, hrv_features=None)['df']
                avg_rate = df['Heart_Rate'].dropna().mean()
                if avg_rate == np.NaN:
                    avg_quality = 0.
                else:
                    avg_quality = df['ECG_Signal_Quality'].dropna().median()
            except Exception as e:
                self.logger.debug(e)
                avg_quality = 0.
            self.o.data = pd.DataFrame(columns=['ecg_quality'], data=[avg_quality], index=[self.i.data.index[-1]])
    def extract_ecg(self, data_ecg):
        # try:
        data = nk.ecg_process(ecg=data_ecg, rsp=None, sampling_rate=700)
        # except:
        # return []

        default_features = self.extract_default_features(data_ecg)
        default_features.extend([
            self.select_data_from_array(data['ECG']['HRV'], 'CVSD'),
            self.select_data_from_array(data['ECG']['HRV'], 'HF'),
            self.select_data_from_array(data['ECG']['HRV'], 'HF/P'),
            self.select_data_from_array(data['ECG']['HRV'], 'HFn'),
            self.select_data_from_array(data['ECG']['HRV'], 'LF'),
            self.select_data_from_array(data['ECG']['HRV'], 'LF/HF'),
            self.select_data_from_array(data['ECG']['HRV'], 'LF/P'),
            self.select_data_from_array(data['ECG']['HRV'], 'LFn'),
            self.select_data_from_array(data['ECG']['HRV'], 'RMSSD'),
            self.select_data_from_array(data['ECG']['HRV'], 'Total_Power'),
            self.select_data_from_array(data['ECG']['HRV'], 'Triang'),
            self.select_data_from_array(data['ECG']['HRV'], 'VHF'),
            self.select_data_from_array(data['ECG']['HRV'], 'cvNN'),
            self.select_data_from_array(data['ECG']['HRV'], 'madNN'),
            self.select_data_from_array(data['ECG']['HRV'], 'mcvNN'),
            self.select_data_from_array(data['ECG']['HRV'], 'meanNN'),
            self.select_data_from_array(data['ECG']['HRV'], 'medianNN'),
            self.select_data_from_array(data['ECG']['HRV'], 'pNN20'),
            self.select_data_from_array(data['ECG']['HRV'], 'pNN50'),
            self.select_data_from_array(data['ECG']['HRV'], 'sdNN'),
        ])

        return default_features
Ejemplo n.º 3
0
 def execute(self, sim, model, data, all_deriv = True, T = False, realname = None, noisename = None, output_name = None, output_name_mean = None):
     
     ## model most have a "predict" object
     if(realname != None or noisename != None):
         self.realplt = realname
         self.noiseplt = noisename
     
     signal = [None] * 12
     for i in range(12):
         signal[i] = np.array([x[i] for x in data])
         self.ecg_process[i] = nk.ecg_process(signal[i],
                                         sampling_rate = 400,
                                         hrv_features = None,
                                         filter_type='FIR')
         self.ecg_process[i]['ECG']['R_Peaks'] = [[y, x] for x, y in
                                             enumerate(self.ecg_process[i][
                                                 'ECG']['R_Peaks'])]
     if(T == True):
         aux_signal = deepcopy(np.array([np.transpose(signal)]))
     else:
         aux_signal = signal
     self.true_label = model.predict(aux_signal)
     
     if(output_name == None):
         output_name = 'output_result/means/'
             
     print(self.true_label)
     n = random.randint(0, 20)
     self.compute_score(sim, model, signal, all_deriv, n, output_name_mean, output_name)
     return self.result
Ejemplo n.º 4
0
 def test_ecg_process(self):
     ecg_processed = nk.ecg_process(self.ecg,
                                    rsp=None,
                                    sampling_rate=1000,
                                    quality_model=None)
     self.assertAlmostEqual(ecg_processed["df"]["Heart_Rate"].mean(),
                            60.0,
                            places=1)
Ejemplo n.º 5
0
def get_ecg_features(signal, sample_size, window_size=1, shift=1):
    i = 0
    features = {
        'hr_mean': [], 'hr_std': [], 
        'sum_ulf': [], 'sum_lf':[], 'sum_hf':[], 'sum_uhf':[]#,
        #'hrv_mean': [], 'hrv_std': [],
        #'pNN50': [], 'TINN': [], 'rms': [], 'LFHF': [],
        #'LFn': [], 'HFn': [], 
        #'rel': [], 'e_ulf': [], 'e_lf':[], 'e_hf':[], 'e_uhf':[]
    }
    signal = np.array(signal).flatten()
    s_processed = nk.ecg_process(ecg=signal, sampling_rate=sample_size, filter_type=None)
    # Index(['ECG_Raw', 'ECG_Filtered', 'ECG_R_Peaks', 'Heart_Rate', 'ECG_Systole', 
    #   'ECG_Signal_Quality', 'ECG_RR_Interval', 'ECG_HRV_ULF', 'ECG_HRV_VLF',
    #   'ECG_HRV_LF', 'ECG_HRV_HF', 'ECG_HRV_VHF'],
    #  dtype='object')
    hr = s_processed['df']['Heart_Rate']
    #print(s_processed['ECG']['HRV'].keys())
    #print(s_processed['ECG']['HRV']['RR_Intervals'])
    #hrv = s_processed['ECG']['HRV']['RR_Intervals']
    
    window_size = int(sample_size * window_size)
    shift = int(sample_size * shift)
    
    while i < len(signal):
        temp = hr[i: i + window_size]
        m, s, mn, mx, dr = extract_default_features(temp)
        features['hr_mean'].append(m)
        features['hr_std'].append(s)
        
        temp = s_processed['df']['ECG_HRV_VLF'][i: i + window_size]
        features['sum_ulf'].append(np.sum(temp))
        temp = s_processed['df']['ECG_HRV_LF'][i: i + window_size]
        features['sum_lf'].append(np.sum(temp))
        temp = s_processed['df']['ECG_HRV_HF'][i: i + window_size]
        features['sum_hf'].append(np.sum(temp))
        temp = s_processed['df']['ECG_HRV_VHF'][i: i + window_size]
        features['sum_uhf'].append(np.sum(temp))
        
        """
        features['hrv_mean'].append(hrv['meanNN'])
        features['hrv_std'].append(hrv['sdNN'])
        features['pNN50'].append(hrv['pNN50'])
        features['TINN'].append(hrv['Triang'])
        features['rms'].append(hrv['RMSSD'])
        features['LFHF'].append(hrv['LF/HF'])
        features['LFn'].append(hrv['LFn'])
        features['HFn'].append(hrv['HFn'])
        features['rel'].append(hrv['Total_Power'])
        features['e_ulf'].append(hrv['ULF'])
        features['e_lf'].append(hrv['LF'])
        features['e_hf'].append(hrv['HF'])
        features['e_uhf'].append(hrv['VHF'])
        """
        
        i += shift

    return features
Ejemplo n.º 6
0
    def process(self, signal, label, data, sampling=256):

        # TODO: Process 3 ecg channels to create one clear
        for i, channel in enumerate(signal):
            c = pd.DataFrame(channel)[0]
            features = nk.ecg_process(ecg=c, sampling_rate=256)
            del features['ECG']['HRV'][
                'RR_Intervals']  #exlude because it is seriesd
            f = self.attach_non_zero_values(features['ECG']['HRV'],
                                            label + str(i), data)
def ecg_filling(ecg, sampling_rate, length):
    ecg_II = ecg[1]
    processed_ecg = nk.ecg_process(ecg_II, sampling_rate)
    rpeaks = processed_ecg[1]['ECG_R_Peaks']
    ecg_filled = np.zeros((ecg.shape[0], length))
    sta = rpeaks[-1]
    ecg_filled[:, :sta] = ecg[:, :sta]
    seg = ecg[:, rpeaks[0]:rpeaks[-1]]
    len = seg.shape[1]
    while True:
        if (sta + len) >= length:
            ecg_filled[:, sta: length] = seg[:, : length - sta]
            break
        else:
            ecg_filled[:, sta: sta + len] = seg[:, :]
            sta = sta + len
    return ecg_filled
Ejemplo n.º 8
0
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import neurokit as nk
import nolds



df = pd.read_csv('data.csv')
df = nk.ecg_process(ecg=df["ECG"])


rri = df["ECG"]["RR_Intervals"]

signal=rri
tolerance = "default"
emb_dim=2
chaos = nk.complexity(signal, lyap_r=False, lyap_e=False)


#chaos = pd.Series(chaos)
#chaos.index = ["ECG_Complexity_" + s for s in chaos.index]
#processed_ecg["ECG"]["Complexity"] = chaos.to_dict()
#nolds.sampen(rri, 2, 0.1*np.std(rri), dist="euler")
#sample_entropy(rri,2, 0.1*np.std(rri))[1]
#
#
Ejemplo n.º 9
0
import neurokit as nk

df = nk.read_acqknowledge("abnormal_ECG.acq")

events = nk.find_events(df["Photosensor"], cut="lower")
df = nk.create_epochs(df, events["onsets"], duration=events["durations"])[0]

#df["Photosensor"].plot()
df = nk.ecg_process(df['ECG, X, RSPEC-R'])
ecg = df["ECG"]
df = df["df"]
#rpeaks = nk.ecg_find_peaks(df['ECG_Filtered'])
nk.plot_events_in_signal(df['ECG_Filtered'], ecg["R_Peaks"])
#df['ECG, X, RSPEC-R'].iloc[104000:140000].plot()
Ejemplo n.º 10
0
    st.header("Dataset Summary")
    st.write("The Dataset consisted of ECG 'Heart Signals' with six different abnormalities with the following distributions:  ")
    st.write(c)
    st.write(df)
    st.write('Shape of one sample : (4096,12) where 12 represents each channel of the ECG')
    uploaded_file = st.text_input('Enter file path of test case(s) :')
    if uploaded_file is not None:
        with h5py.File(uploaded_file, "r") as f:
            test_data = np.array(f['tracings'])
        if len(test_data) > 1:
            test = st.selectbox("Select the sample number you want to analyze: ", np.arange(1,len(test_data)+1))
            raw_ecg = np.ravel(test_data[test-1].T[1])
        else:
            raw_ecg = np.ravel(test_data.T[1])

        processed_ecg = nk.ecg_process(raw_ecg, sampling_rate=400, quality_model = None, hrv_features=['time'])

        figure = plot_r_systole(processed_ecg['df'])
        st.write(figure)

        fig, cc = plot_cardiac_cycles(processed_ecg['ECG']['Cardiac_Cycles'])
        st.write(fig)

        hr = round(np.mean(processed_ecg['df']['Heart_Rate']))
        mrr = round(processed_ecg['ECG']['HRV']['meanNN']/400,2)

        prediction, model = diagnose()
        if len(test_data) > 1:
            pred = prediction[test-1]
        else:
            if len(pred)==1:
Ejemplo n.º 11
0
#df = nk.ecg_process(df['ECG, X, RSPEC-R'])
#ecg = df["ECG"]
#df = df["df"]
#rpeaks = nk.ecg_find_peaks(df['ECG_Filtered'])
#nk.plot_events_in_signal(df['ECG_Filtered'], ecg["R_Peaks"])
#df['ECG, X, RSPEC-R'].iloc[104000:140000].plot()



#==============================================================================
# HRV Interpolation
#==============================================================================
df = nk.read_acqknowledge("abnormal_ECG.acq")
df = df[4000:19000]
sampling_rate = 1000
df = nk.ecg_process(df['ECG, X, RSPEC-R'], sampling_rate=sampling_rate)
df["df"]["ECG_Filtered"].plot()


rri = df["ECG"]['RR_Intervals']
rpeaks = df["ECG"]['R_Peaks']

ecg=df["df"]["ECG_Filtered"]


artifacts_treatment="interopolation"