def get_all_features_hrva(data_sample, sample_rate=100, rpeak_method=0): """ :param data_sample: :param sample_rate: :param rpeak_method: :return: """ if rpeak_method in [1, 2, 3, 4]: detector = PeakDetector() peak_list = detector.ppg_detector(data_sample, rpeak_method)[0] else: rol_mean = rolling_mean(data_sample, windowsize=0.75, sample_rate=100.0) peaks_wd = detect_peaks(data_sample, rol_mean, ma_perc=20, sample_rate=100.0) peak_list = peaks_wd["peaklist"] rr_list = np.diff(peak_list) * (1000 / sample_rate) #1000 milisecond nn_list = get_nn_intervals(rr_list) nn_list_non_na = np.copy(nn_list) nn_list_non_na[np.where(np.isnan(nn_list_non_na))[0]] = -1 time_domain_features = get_time_domain_features(rr_list) frequency_domain_features = get_frequency_domain_features(rr_list) geometrical_features = get_geometrical_features(rr_list) csi_cvi_features = get_csi_cvi_features(rr_list) return time_domain_features,frequency_domain_features,\ geometrical_features,csi_cvi_features
def get_feature_names(recording): time_domain_features = hrv.get_time_domain_features(recording["Recording"]["RrInterval"]) geometrical_features = hrv.get_geometrical_features(recording["Recording"]["RrInterval"]) frequency_domain_features = hrv.get_frequency_domain_features(recording["Recording"]["RrInterval"]) csi_cvi_features = hrv.get_csi_cvi_features(recording["Recording"]["RrInterval"]) poincare_plot_features = hrv.get_poincare_plot_features(recording["Recording"]["RrInterval"]) feature_dictionary = { **time_domain_features, **geometrical_features, **frequency_domain_features, **csi_cvi_features, **poincare_plot_features } return [key for key in feature_dictionary.keys()]
def get_all_features_hrva(s, sample_rate=100, rpeak_method=0,wave_type='ecg'): """ Parameters ---------- data_sample : Raw signal rpeak_method : return: (Default value = 0) sample_rate : (Default value = 100) Returns ------- """ # if rpeak_method in [1, 2, 3, 4]: # detector = PeakDetector() # peak_list = detector.ppg_detector(data_sample, rpeak_method)[0] # else: # rol_mean = rolling_mean(data_sample, windowsize=0.75, sample_rate=100.0) # peaks_wd = detect_peaks(data_sample, rol_mean, ma_perc=20, # sample_rate=100.0) # peak_list = peaks_wd["peaklist"] if wave_type=='ppg': detector = PeakDetector(wave_type='ppg') peak_list, trough_list = detector.ppg_detector(s, detector_type=rpeak_method) else: detector = PeakDetector(wave_type='ecg') peak_list, trough_list = detector.ecg_detector(s, detector_type=rpeak_method) rr_list = np.diff(peak_list) * (1000 / sample_rate) # 1000 milisecond nn_list = get_nn_intervals(rr_list) nn_list_non_na = np.copy(nn_list) nn_list_non_na[np.where(np.isnan(nn_list_non_na))[0]] = -1 time_domain_features = get_time_domain_features(rr_list) frequency_domain_features = get_frequency_domain_features(rr_list) geometrical_features = get_geometrical_features(rr_list) csi_cvi_features = get_csi_cvi_features(rr_list) return time_domain_features, frequency_domain_features, geometrical_features, csi_cvi_features
def recording_to_x_y_feature_regression(recording): time_domain_features = hrv.get_time_domain_features(recording["Recording"]["RrInterval"]) geometrical_features = hrv.get_geometrical_features(recording["Recording"]["RrInterval"]) frequency_domain_features = hrv.get_frequency_domain_features(recording["Recording"]["RrInterval"]) csi_cvi_features = hrv.get_csi_cvi_features(recording["Recording"]["RrInterval"]) poincare_plot_features = hrv.get_poincare_plot_features(recording["Recording"]["RrInterval"]) feature_dictionary = { **time_domain_features, **geometrical_features, **frequency_domain_features, **csi_cvi_features, **poincare_plot_features } x = [value for value in feature_dictionary.values()] y = decade_to_label(recording["AgeDecade"], False) return [y] + x
def get_geometrical_features(RR_windows): assert isinstance(RR_windows, (list, np.ndarray)) if isinstance(RR_windows, np.ndarray): assert RR_windows.ndim == 2, 'Must be 2D' if any([np.any(wRR > 1000) for wRR in RR_windows if len(wRR) > 0]): log.warn( 'Values seem to be in ms instead of seconds! Algorithm migh fail.') feats = {x: [] for x in ['tinn', 'triangular_index']} for wRR in RR_windows: if len(wRR) < 2: for key, val in feats.items(): feats[key].append(np.nan) else: mRR = hrvanalysis.get_geometrical_features( (wRR * 1000).astype(int)) for key, val in mRR.items(): feats[key].append(val) return feats
def get_bvp_metrics(x, metric, sampling_rate=64): if metric == 'hr_mean': hr = biosppy.signals.bvp.bvp(x, sampling_rate=sampling_rate, show=False)['heart_rate'] return np.mean(hr) if metric == 'hrv_mean': onsets = biosppy.signals.bvp.bvp(x, sampling_rate=sampling_rate, show=False)['onsets'] hrv = tools.nn_intervals(onsets) return np.mean(hrv) if metric == 'hr_std': hr = biosppy.signals.bvp.bvp(x, sampling_rate=sampling_rate, show=False)['heart_rate'] return np.std(hr) if metric == 'hrv_std': onsets = biosppy.signals.bvp.bvp(x, sampling_rate=sampling_rate, show=False)['onsets'] hrv = tools.nn_intervals(onsets) return np.std(hrv) if metric == 'tinn': onsets = biosppy.signals.bvp.bvp(x, sampling_rate=sampling_rate, show=False)['onsets'] hrv = tools.nn_intervals(onsets) return get_geometrical_features(hrv)['triangular_index'] if metric == 'rms': onsets = biosppy.signals.bvp.bvp(x, sampling_rate=sampling_rate, show=False)['onsets'] hrv = tools.nn_intervals(onsets) return np.sqrt((1 / len(hrv)) * sum([i**2 for i in hrv])) return ValueError(f"Unsupported Metric {metric}")
def process_all_files(self, is_test=False): ''' This function will go through every subject overlapped data and extract the intersect set between hr and acc. the dataset quality control will filter out the RRI dataset with lower bound= 300, upper bound with 1000 the output will be in either test output path or the actual output path. :param is_test: true is for test dataset :return: ''' # load Acc, HR and overlap files if is_test: all_acc_files = [] all_hr_files = [] else: all_acc_files = os.listdir(self.acc_path) all_hr_files = os.listdir(self.hr_path) overlap_df = pd.read_csv( self.overlap_path ) # only do experiment if they have overlapped ECG and Actigraphy total_subjects_list = overlap_df['mesaid'].unique() valid_pids = pd.read_csv( self.cfg.TRAIN_TEST_SPLIT)['uids'].values.tolist() # here we set the valid subject IDs according to a snapshot of MESA data on 2019-05-01. In this # snapshot, we manually checked the aligned data making sure the pre-processing yield satisfied quality of data. # ##### The num of total valid subjects should be 1743 total_subjects_list = list( set(total_subjects_list).intersection(set(valid_pids))) total_processed = [] if not os.path.exists(self.processed_records): with open(self.processed_records, "w") as output: writer = csv.writer(output, lineterminator='\n') writer.writerows(total_processed) # tag = datetime.now().strftime("%Y%m%d-%H%M%S") for PID in total_subjects_list: mesa_id = "%04d" % PID # filter Acc and HR based on the overlap records print('*' * 100) print("Processing subject %s dataset" % mesa_id) acc_inlist_idx = [s for s in all_acc_files if mesa_id in s] hr_inlist_idx = [s for s in all_hr_files if mesa_id in s] feature_list = [] if len(acc_inlist_idx) > 0 and len(hr_inlist_idx) > 0: # get the raw dataset file index acc_file_idx = all_acc_files.index(''.join(acc_inlist_idx)) hr_file_idx = all_hr_files.index(''.join(hr_inlist_idx)) # load Acc and HR into Pandas acc_df = pd.read_csv( os.path.join(self.acc_path, all_acc_files[acc_file_idx])) hr_df = pd.read_csv( os.path.join(self.hr_path, all_hr_files[hr_file_idx])) featnames = get_statistic_feature(acc_df, column_name="activity", windows_size=20) acc_start_idx = overlap_df[overlap_df['mesaid'] == PID]['line'].values[0].astype(int) acc_epochs = hr_df['epoch'].max() # cut the dataset frame from the overlapped start index to the HR end index acc_df = acc_df[acc_start_idx - 1:acc_start_idx + acc_epochs - 1] # recalculate the line to the correct index acc_df['line'] = acc_df['line'] - acc_start_idx + 1 acc_df = acc_df.reset_index(drop=True) # calculate the intersect set between HR and acc and cut HR to align the sequence # ################ Data quality control for Acc ######################## # use marker and activity as the indicator column if the shape is different to 2-dim then drop list_size_chk = np.array(acc_df[['marker', 'activity']].values.tolist()) # check whether the activity is empty if len(list_size_chk.shape) < 2: print( "File {f_name} doesn't meet dimension requirement, it's size is {wrong_dim}" .format(f_name=all_acc_files[acc_file_idx], wrong_dim=list_size_chk.shape)) continue # Cut HRV dataset based on length of Actigraphy dataset if (int(hr_df['epoch'].tail(1)) > acc_df.shape[0]): hr_df = hr_df[hr_df['epoch'] <= acc_df.shape[0]] # remove the noise data points if two peaks overlapped or not wear hr_df = hr_df[hr_df['TPoint'] > 0] # Define RR intervals by taking the difference between each one of the measurements in seconds (*1k) hr_df['RR Intervals'] = hr_df['seconds'].diff() * 1000 hr_df['RR Intervals'].fillna( hr_df['RR Intervals'].mean(), inplace=True) # fill mean for first sample # old method for processing of RR intervals which is inappropriate # sampling_df = pd.concat([sampling_df, t1], axis =0 ) # outlier_low = np.mean(hr_df['HR']) - 6 * np.std(hr_df['HR']) # outlier_high = np.mean(hr_df['HR']) + 6 * np.std(hr_df['HR']) # hr_df = hr_df[hr_df['HR'] >= outlier_low] # hr_df = hr_df[hr_df['HR'] <= outlier_high] # apply HRV-Analysis package # filter any hear rate over 60000/300 = 200, 60000/2000 = 30 clean_rri = hr_df['RR Intervals'].values clean_rri = hrvana.remove_outliers(rr_intervals=clean_rri, low_rri=300, high_rri=2000) clean_rri = hrvana.interpolate_nan_values( rr_intervals=clean_rri, interpolation_method="linear") clean_rri = hrvana.remove_ectopic_beats(rr_intervals=clean_rri, method="malik") clean_rri = hrvana.interpolate_nan_values( rr_intervals=clean_rri) hr_df["RR Intervals"] = clean_rri # calculate the Heart Rate hr_df['HR'] = np.round((60000.0 / hr_df['RR Intervals']), 0) # filter ACC acc_df = acc_df[acc_df['interval'] != 'EXCLUDED'] # filter RRI t1 = hr_df.epoch.value_counts().reset_index().rename( { 'index': 'epoch_idx', 'epoch': 'count' }, axis=1) invalid_idx = set(t1[t1['count'] < 3]['epoch_idx'].values) del t1 hr_df = hr_df[~hr_df['epoch'].isin(list(invalid_idx))] # get intersect epochs hr_epoch_set = set(hr_df['epoch'].values) acc_epoch_set = set(acc_df['line']) # get acc epochs # only keep intersect dataset diff_epoch_set_a = acc_epoch_set.difference(hr_epoch_set) diff_epoch_set_b = hr_epoch_set.difference(acc_epoch_set) acc_df = acc_df[~acc_df['line'].isin(diff_epoch_set_a)] hr_df = hr_df[~hr_df['epoch'].isin(diff_epoch_set_b)] # check see if their epochs are equal assert acc_df.shape[0] == len(hr_df['epoch'].unique()) # filter out any epochs with rri less than 3 hr_epoch_set = set(hr_df['epoch'].values) hr_epoch_set = hr_epoch_set.difference(invalid_idx) for _, hr_epoch_idx in enumerate(list(hr_epoch_set)): # sliding window gt_label = hr_df[hr_df['epoch'] == hr_epoch_idx]["stage"].values[0] if self.hrv_win != 0: offset = int(np.floor(self.hrv_win / 2)) tmp_hr_df = hr_df[hr_df['epoch'].isin( np.arange(hr_epoch_idx - offset, hr_epoch_idx + offset))] else: tmp_hr_df = hr_df[hr_df['epoch'] == hr_epoch_idx] try: # check to see if the first time stamp is empty start_sec = float(tmp_hr_df['seconds'].head(1) * 1.0) except Exception as ee: print("Exception %s, source dataset: %s" % (ee, tmp_hr_df['seconds'].head(1))) # calculate each epochs' HRV features rr_epoch = tmp_hr_df['RR Intervals'].values all_hr_features = {} try: all_hr_features.update( hrvana.get_time_domain_features(rr_epoch)) except Exception as ee: self.log_process(ee, PID, hr_epoch_idx) print("processed time domain features: {}".format( str(ee))) try: all_hr_features.update( hrvana.get_frequency_domain_features(rr_epoch)) except Exception as ee: self.log_process(ee, PID, hr_epoch_idx) print("processed frequency domain features: {}".format( str(ee))) try: all_hr_features.update( hrvana.get_poincare_plot_features(rr_epoch)) except Exception as ee: self.log_process(ee, PID, hr_epoch_idx) print("processed poincare features: {}".format( str(ee))) try: all_hr_features.update( hrvana.get_csi_cvi_features(rr_epoch)) except Exception as ee: self.log_process(ee, PID, hr_epoch_idx) print("processed csi cvi domain features: {}".format( str(ee))) try: all_hr_features.update( hrvana.get_geometrical_features(rr_epoch)) except Exception as ee: self.log_process(ee, PID, hr_epoch_idx) print("processed geometrical features: {}".format( str(ee))) all_hr_features.update({ 'stages': gt_label, 'mesaid': acc_df[acc_df['line'] == hr_epoch_idx]['mesaid'].values[0], 'linetime': acc_df[acc_df['line'] == hr_epoch_idx]['linetime'].values[0], 'line': acc_df[acc_df['line'] == hr_epoch_idx]['line'].values[0], 'wake': acc_df[acc_df['line'] == hr_epoch_idx]['wake'].values[0], 'interval': acc_df[acc_df['line'] == hr_epoch_idx]['interval'].values[0], 'activity': acc_df[acc_df['line'] == hr_epoch_idx] ['activity'].values[0] }) feature_list.append(all_hr_features) # If feature list is not empty if len(feature_list) > 0: hrv_acc_df = pd.DataFrame(feature_list) hrv_acc_df = hrv_acc_df.reset_index(drop=True) del hrv_acc_df['tinn'] # tinn is empty featnames = featnames + ["line"] combined_pd = pd.merge(acc_df[featnames], hrv_acc_df, on='line', how='inner') #combined_pd = combined_pd.reset_index(drop=True) combined_pd['timestamp'] = pd.to_datetime( combined_pd['linetime']) combined_pd['base_time'] = pd.to_datetime('00:00:00') combined_pd['seconds'] = (combined_pd['timestamp'] - combined_pd['base_time']) combined_pd['seconds'] = combined_pd['seconds'].dt.seconds combined_pd.drop(['timestamp', 'base_time'], axis=1, inplace=True) combined_pd['two_stages'] = combined_pd["stages"].apply( lambda x: 1.0 if x >= 1.0 else 0.0) combined_pd.loc[combined_pd['stages'] > 4, 'stages'] = 4 # make sure rem sleep label is 4 combined_pd = combined_pd.fillna(combined_pd.median()) combined_pd = combined_pd[ combined_pd['interval'] != 'EXCLUDED'] aligned_data = self.output_path # standardise and normalise the df feature_list = combined_pd.columns.to_list() std_feature = [ x for x in feature_list if x not in [ 'two_stages', 'seconds', 'interval', 'wake', 'linetime', 'mesaid', 'stages', 'line' ] ] if self.standarize: standardize_df_given_feature(combined_pd, std_feature, df_name='combined_df', simple_method=False) combined_pd.to_csv(os.path.join(aligned_data, (mesa_id + '_combined.csv')), index=False) print("ID: {}, successed process".format(mesa_id)) with open(self.processed_records, "a") as text_file: text_file.write( "ID: {}, successed process \n".format(mesa_id)) total_processed.append( "ID: {}, successed process".format(mesa_id)) else: print("Acc is empty or HRV is empty!") total_processed.append( "ID: {}, failed process".format(mesa_id)) with open(self.processed_records, "a") as text_file: text_file.write("ID: {}, failed process".format(mesa_id))
def extract_feature(data, raw_signal): feature = [] ts = np.array(data['ts']) filtered = np.array(data['filtered']) rpeaks = np.array(data['rpeaks']) templates_ts = np.array(data['templates_ts']) templates = np.array(data['templates']) heart_rate_ts = np.array(data['heart_rate_ts']) heart_rate = np.array(data['heart_rate']) s_points = np.array(data['s_points']) q_points = np.array(data['q_points']) feature.append(np.std(raw_signal)) feature.append(np.std(filtered)) # RR interval rr_intervals = rpeaks[1:] - rpeaks[:-1] feature.append(np.min(rr_intervals)) feature.append(np.max(rr_intervals)) feature.append(np.mean(rr_intervals)) feature.append(np.std(rr_intervals)) # R amplitude r_apt = np.abs(filtered[rpeaks]) feature.append(np.min(r_apt)) feature.append(np.max(r_apt)) feature.append(np.mean(r_apt)) feature.append(np.std(r_apt)) # Q amplitude q_apt = np.abs(filtered[q_points]) feature.append(np.min(q_apt)) feature.append(np.max(q_apt)) feature.append(np.mean(q_apt)) feature.append(np.std(q_apt)) # QRS duration qrs_duration = s_points - q_points feature.append(np.min(qrs_duration)) feature.append(np.max(qrs_duration)) feature.append(np.mean(qrs_duration)) feature.append(np.std(qrs_duration)) interpolated_nn_intervals = rr_intervals * 10 / 3 time_domain_feature = hrvanalysis.get_time_domain_features( interpolated_nn_intervals) for f_name in time_domain_feature: feature.append(time_domain_feature[f_name]) # geometrical features geo_feature = hrvanalysis.get_geometrical_features( interpolated_nn_intervals) for f_name in geo_feature: if geo_feature[f_name] is None: feature.append(0) else: feature.append(geo_feature[f_name]) # frequency domain features f_feature = hrvanalysis.get_frequency_domain_features( interpolated_nn_intervals) for f_name in f_feature: if f_feature[f_name] is None: feature.append(0) else: feature.append(f_feature[f_name]) # csi cvi features csi_cvi_feature = hrvanalysis.get_csi_cvi_features( interpolated_nn_intervals) for f_name in csi_cvi_feature: if csi_cvi_feature[f_name] is None: feature.append(0) else: feature.append(csi_cvi_feature[f_name]) # get_poincare_plot_features pp_feature = hrvanalysis.get_poincare_plot_features( interpolated_nn_intervals) for f_name in pp_feature: if pp_feature[f_name] is None: feature.append(0) else: feature.append(pp_feature[f_name]) # wavelet energy coeffs = wavelet_decomposition(filtered) for k, coeff in enumerate(coeffs): b = coeffs[coeff] b = b / np.max(np.abs(b)) feature.append(np.mean(b * b)) # wavelet energy coeffs = wavelet_decomposition(raw_signal) for k, coeff in enumerate(coeffs): b = coeffs[coeff] b = b / np.max(np.abs(b)) feature.append(np.mean(b * b)) # template average templates_ave = np.mean(templates, axis=0) templates_ave = templates_ave / np.max(np.abs(templates_ave)) for p in templates_ave: feature.append(p) # template std ave templates_std = np.std(templates, axis=0) templates_std = templates_std / np.max(np.abs(templates_std)) for p in templates_std: feature.append(p) # wavelet 1 wavelet_1 = coeffs['cA5'] wavelet_1 = wavelet_1[:50] for p in wavelet_1: feature.append(p) return np.array(feature)
def metrics(self): import pyhrv.tools as tools intervalosNN = tools.nn_intervals(self.peaks_fpos) time_domain_features = get_time_domain_features( intervalosNN[intervalosNN != 0]) frecuency_domain_features = get_frequency_domain_features(intervalosNN) geometrical_features = get_geometrical_features(intervalosNN) self.ui.scrollAreaFeatures.setStyleSheet('background-color: white') layout = QHBoxLayout() label = QLabel('<h3>Time Domain Features<h3>') label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label.setStyleSheet("color: rgb(59,59,59)") label.setMaximumWidth(290) layout.addWidget(label) self.ui.verticalLayout_features.addLayout(layout) time_domain_features_to_show = { 'SDNN': time_domain_features['sdnn'], 'SDSD': time_domain_features['sdsd'], 'SDANN': self.sdann, 'RMSSD': time_domain_features['rmssd'] } time_domain_features_to_show2 = { 'NN20 Count': time_domain_features['nni_20'], 'NN50 Count': time_domain_features['nni_50'], 'PNN50 Count': time_domain_features['pnni_50'], 'PNN20 Count': time_domain_features['pnni_20'] } for key, value in time_domain_features_to_show.items(): layout = QVBoxLayout() label = QLabel('<h4>' + str(key) + ':</h4>') label.setStyleSheet("color: rgb(59,59,59)") label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label.setMaximumWidth(122) layout.addWidget(label) label1 = QLabel("{:.4f}".format(value)) label1.setStyleSheet( "padding: 5px; border: 1px solid #cccccc; border-radius: 5px; background-color:#cccccc;" ) label1.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label1.setMaximumWidth(122) layout.addWidget(label1) self.ui.verticalLayout_features1.addLayout(layout) for key, value in time_domain_features_to_show2.items(): layout = QVBoxLayout() label = QLabel('<h4>' + str(key) + ':</h4>') label.setStyleSheet("color: rgb(59,59,59)") label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label.setMaximumWidth(122) layout.addWidget(label) label1 = QLabel("{:.4f}".format(value)) label1.setStyleSheet( "padding: 5px; border: 1px solid #cccccc; border-radius: 5px; background-color:#cccccc;" ) label1.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label1.setMaximumWidth(122) layout.addWidget(label1) self.ui.verticalLayout_features2.addLayout(layout) frecuency_domain_features_to_show = { 'LF': frecuency_domain_features['lf'], 'HF': frecuency_domain_features['hf'], 'VLF': frecuency_domain_features['vlf'] } frecuency_domain_features_to_show2 = { 'LF norm': frecuency_domain_features['vlf'], 'HF norm': frecuency_domain_features['hfnu'], 'Total power': frecuency_domain_features['total_power'] } layout = QHBoxLayout() label = QLabel('<h3>Frecuency Domain Features</h3>') label.setStyleSheet("color: rgb(59,59,59)") label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label.setMaximumWidth(290) layout.addWidget(label) self.ui.verticalLayout_features3.addLayout(layout) for key, value in frecuency_domain_features_to_show.items(): layout = QVBoxLayout() label = QLabel('<h4>' + str(key) + ':</h4>') label.setStyleSheet("color: rgb(59,59,59)") label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label.setMaximumWidth(122) layout.addWidget(label) label1 = QLabel("{:.4f}".format(value)) label1.setStyleSheet( "padding: 5px; border: 1px solid #cccccc; border-radius: 5px; background-color:#cccccc;" ) label1.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label1.setMaximumWidth(122) layout.addWidget(label1) self.ui.verticalLayout_features4.addLayout(layout) for key, value in frecuency_domain_features_to_show2.items(): layout = QVBoxLayout() label = QLabel('<h4>' + str(key) + ':</h4>') label.setStyleSheet("color: rgb(59,59,59)") label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label.setMaximumWidth(122) layout.addWidget(label) label1 = QLabel("{:.4f}".format(value)) label1.setStyleSheet( "padding: 5px; border: 1px solid #cccccc; border-radius: 5px; background-color:#cccccc;" ) label1.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label1.setMaximumWidth(122) layout.addWidget(label1) self.ui.verticalLayout_features5.addLayout(layout) geometrical_features_to_show = {'TINN': geometrical_features['tinn']} geometrical_features_to_show2 = { 'Triangular Index': geometrical_features['triangular_index'] } layout = QHBoxLayout() label = QLabel('<h3>Geometrical Domain Features</h3>') label.setStyleSheet("color: rgb(59,59,59)") label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label.setMaximumWidth(290) layout.addWidget(label) self.ui.verticalLayout_features6.addLayout(layout) for key, value in geometrical_features_to_show2.items(): layout = QVBoxLayout() label = QLabel('<h4>' + str(key) + ':</h4>') label.setStyleSheet("color: rgb(59,59,59)") label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label.setMaximumWidth(122) layout.addWidget(label) label1 = QLabel("{:.4f}".format(value)) label1.setStyleSheet( "padding: 5px; border: 1px solid #cccccc; border-radius: 5px; background-color:#cccccc;" ) label1.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label1.setMaximumWidth(122) layout.addWidget(label1) self.ui.verticalLayout_features7.addLayout(layout) for key, value in geometrical_features_to_show.items(): layout = QVBoxLayout() label = QLabel('<h4>' + str(key) + ':</h4>') label.setStyleSheet("color: rgb(59,59,59)") label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label.setMaximumWidth(122) layout.addWidget(label) label1 = QLabel(str(value)) label1.setStyleSheet( "padding: 5px; border: 1px solid #cccccc; border-radius: 5px; background-color:#cccccc;" ) label1.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) label1.setMaximumWidth(122) layout.addWidget(label1) self.ui.verticalLayout_features8.addLayout(layout) from hrvanalysis import plot_psd
IBI_cleaned = [] outliers = 0 for element in IBI_ts: if element < (meanIBI + (4 * stdIBI)) and (element > meanIBI - (4 * stdIBI)): IBI_cleaned.append(element) else: outliers += 1 percent_removed = (outliers/len(IBI_ts)) * 100; #if we're removing more than 20% of the data then something is wrong and this file should be flagged if percent_removed < 20: time_domain_features = hrv.get_time_domain_features(IBI_cleaned) geometrical_features = hrv.get_geometrical_features(IBI_cleaned) frequency_domain_features = hrv.get_frequency_domain_features(IBI_cleaned) csi_cvi_features = hrv.get_csi_cvi_features(IBI_cleaned) poincare_plot_features = hrv.get_poincare_plot_features(IBI_cleaned) sampen = hrv.get_sampen(IBI_cleaned) td_keys = list(time_domain_features.keys()) geom_keys = list(geometrical_features.keys()) frequency_keys = list(frequency_domain_features.keys()) csi_keys = list(csi_cvi_features.keys()) poincare_keys = list(poincare_plot_features.keys()) samp_keys = list(sampen.keys()) #format header of output header = [] ID = ['ID']