def detext_xqrs(datas, disp_err=False) -> list: if type(datas) == 'list': xqrs = wfp.XQRS(np.array(datas), fs=250) else: xqrs = wfp.XQRS(datas, fs=250) xqrs.detect(verbose=False) if len(xqrs.qrs_inds) == 0: print("QRS Detect failed. return 75") # index = int(xqrs.qrs_inds[0]) return xqrs.qrs_inds
def extractRpeaks(rdnames, rpeak_lead, samplefrom=0, sampleto='end', verbose=False): allsymbols = [] for rdname in rdnames: print(rdname) sig, fields = wfdb.rdsamp('mitdb/'+rdname, channels='all', sampfrom=samplefrom, sampto=sampleto) ann_ref = wfdb.rdann('mitdb/'+rdname,'atr', sampfrom=samplefrom, sampto=None if sampleto=='end' else sampleto) peak_channel = 0 if rpeak_lead in fields['sig_name']: peak_channel = fields['sig_name'].index(rpeak_lead) else: continue xqrs = processing.XQRS(sig=sig[:,peak_channel], fs=fields['fs']) xqrs.detect() acts = xqrs.qrs_inds comparitor = processing.compare_annotations(ref_sample=ann_ref.sample[1:], test_sample=xqrs.qrs_inds, window_width=int(0.1 * fields['fs']), signal=sig[:,peak_channel]) if verbose: comparitor.print_summary() matched_inds = comparitor.matching_sample_nums outpath = 'mitdb/'+rdname + '.Rpeaks' with open(outpath, 'wb') as handle: pickle.dump({'acts':acts, 'matched_inds':matched_inds, 'anns': ann_ref.symbol[1:]}, handle)
def main(): FILE_DIR = "../../rawData/MIT/" heartbeats_full = [] labels_full = [] for filename in os.listdir(FILE_DIR): if filename.endswith(".dat"): fn = FILE_DIR + filename[:-4] print(fn) sample, metadata = wfdb.rdsamp(fn) annotation = wfdb.rdann(fn, 'atr') lead1, lead2 = zip(*sample) xqrs = wdpc.XQRS(sig=np.asarray(lead1), fs=360) xqrs.detect() heartbeats, labels = split_samples_by_annotation( sample, annotation, xqrs.qrs_inds) heartbeats_full += heartbeats labels_full += labels print(np.shape(heartbeats_full)) print(np.shape(labels_full)) print("Saving Data...") np.save("../../processedData/MIT/heartbeats.npy", heartbeats_full) np.save("../../processedData/MIT/labels.npy", labels_full) print("Saved")
def load_data(data_path): files = glob.glob(os.path.join(data_path, "*/*.dat")) x_total = [] y_total = [] for f_name in tqdm.tqdm(files): p_idx = int(f_name.split("/")[2].split("_")[-1])-1 signals, _ = wfdb.rdsamp(os.path.join(os.path.dirname(f_name), os.path.basename(f_name).split(".")[0])) ecg = sosfiltfilt(sos, signals[:,1]) # R-peak detection xqrs = processing.XQRS(sig=ecg, fs=FS) xqrs.detect(verbose = False) # Amplitude normalization ecg = (ecg - ecg.mean()) / ecg.std() # R-peak based Beat segmentation r_peak_locs = xqrs.qrs_inds seg_start_idx = 0 if not r_peak_locs.size == 0: for idx in range(len(r_peak_locs)-1): if idx != 0: seg_start_idx = seg_end_idx seg_end_idx = int((r_peak_locs[idx] + r_peak_locs[idx+1]) / 2) ecg_segment = resample(ecg[seg_start_idx:seg_end_idx], STEP) x_total.append(ecg_segment) y_total.append(p_idx) return x_total, y_total
def detext_xqrs(datas, disp_err=False) -> int: xqrs = wfp.XQRS(np.array(datas), fs=250) xqrs.detect(verbose=False) if len(xqrs.qrs_inds) == 0: if disp_err: ax: Axes = plt.subplot() ax.plot(datas) plt.show() print("QRS Detect failed. return 75") return 75 index = int(xqrs.qrs_inds[0]) return index
def test_plot(self): record_name = self.mitdb + "100" sig, fields = wfdb.rdsamp(record_name, channels=[0]) print(sig.__class__, sig) print(fields.__class__, fields) ann_ref = wfdb.rdann(record_name, 'atr') xqrs = processing.XQRS(sig=sig[:, 0], fs=fields['fs']) print(xqrs) xqrs.detect() comparitor = processing.compare_annotations(ann_ref.sample[1:], xqrs.qrs_inds, int(0.1 * fields['fs']), sig[:, 0]) comparitor.print_summary() comparitor.plot()
def test_xqrs(self): """ Run xqrs detector on record 100 and compare to reference annotations """ sig, fields = wfdb.rdsamp('sample-data/100', channels=[0]) ann_ref = wfdb.rdann('sample-data/100','atr') xqrs = processing.XQRS(sig=sig[:,0], fs=fields['fs']) xqrs.detect() comparitor = processing.compare_annotations(ann_ref.sample[1:], xqrs.qrs_inds, int(0.1 * fields['fs'])) assert comparitor.sensitivity > 0.99 assert comparitor.positive_predictivity > 0.99
def getXQRS(signal, fields): ''' The qrs detector class for the xqrs algorithm Args: signal (list): y values of signal samples fields (list): properties of signal Returns: xqrs (XQRS object): used to plot signals ''' # QRS Detection xqrs = processing.XQRS(sig=signal[:, 0], fs=fields['fs']) xqrs.detect(verbose=True) return xqrs
def main(): FILE_DIR = "data/" normal_final = [] abnormal_final = [] abnormal_label_final = [] for filename in os.listdir(FILE_DIR): if filename.endswith(".dat"): fn = FILE_DIR + filename[:-4] print(fn) sample, _ = wfdb.rdsamp(fn) annotation = wfdb.rdann(fn, 'atr') sample_array, _ = zip(*sample) xqrs = wdpc.XQRS(sig=np.asarray(sample_array), fs=360) xqrs.detect() n_s, a_s, a_l = split_samples_by_annotation(sample_array, annotation, xqrs.qrs_inds) print(len(n_s)) print(len(a_s)) for sig in n_s: normal_final.append(sig) for asig in a_s: abnormal_final.append(asig) for label in a_l: abnormal_label_final.append(label) print(np.shape(normal_final)) print(np.shape(abnormal_final)) print(np.shape(abnormal_label_final)) with open('normal.pickle', 'wb') as norm_file: pickle.dump(normal_final, norm_file) with open('abnormal.pickle', 'wb') as abnorm_file: pickle.dump(abnormal_final, abnorm_file) with open('abnormal_label.pickle', 'wb') as abnorm_label_file: pickle.dump(abnormal_label_final, abnorm_label_file)
def SC_method_QRS(signal: NDArray[float], conf, fs=100) -> (List, List, List): xqrs = processing.XQRS(sig=signal, fs=fs, conf=conf) xqrs.detect(verbose=False) correct_peaks = xqrs.qrs_inds if len(correct_peaks) > 1: durlist = [ correct_peaks[i + 1] - correct_peaks[i] for i in range(len(correct_peaks) - 1) ] ptplist = [ np.ptp(signal[correct_peaks[i]:correct_peaks[i + 1]]) for i in range(len(correct_peaks) - 1) ] else: ptplist = [0] durlist = [0] return correct_peaks, ptplist, durlist
import matplotlib.pyplot as plt import wfdb from wfdb import processing sig, fields = wfdb.rdsamp('100', channels=[0], sampto=15000, pb_dir='mitdb/') ann_ref = wfdb.rdann('100', 'atr', sampto=15000, pb_dir='mitdb/') #使用XQRS算法 xqrs = processing.XQRS(sig=sig[:, 0], fs=fields['fs']) xqrs.detect() #这里还可以直接使用xqrs_detection #qrs_inds=processing.xqrs_detect(sig=sig[:,0], fs=fields['fs']) #下面进行算法的结果和注释中的结果相对比 #注意:在100.atr中的qrs注释第一个数是18,而18这个位置上并没有峰值,真正的第一个峰值是在第二个数77开始的所以是[1:] comparitor = processing.compare_annotations(ref_sample=ann_ref.sample[1:], test_sample=xqrs.qrs_inds, window_width=int(0.1 * fields['fs']), signal=sig[:, 0]) #输出结果 comparitor.print_summary() fig = comparitor.plot(title='XQRS detected QRS vs reference annotations', return_fig=True) # display(fig[0]) plt.show(fig[0]) #这一步必须加,不然图片会一闪而逝
def test_detect(self): record_name = self.mitdb + "100" sig, fields = wfdb.rdsamp(record_name, channels=[0]) ann_ref = wfdb.rdann(record_name, 'atr') xqrs = processing.XQRS(sig=sig[:, 0], fs=fields['fs']) xqrs.detect()