def test_1c(self): """ Format 16, byte offset, selected duration, selected channels, digital. Target file created with: rdsamp -r sample-data/a103l -f 80 -s 0 1 | cut -f 2- > record-1c """ record = wfdb.rdrecord('sample-data/a103l', sampfrom=20000, channels=[0, 1], physical=False) sig = record.d_signal sig_target = np.genfromtxt('tests/target-output/record-1c') # Compare data streaming from physiobank record_pb = wfdb.rdrecord('a103l', pb_dir='challenge/2015/training', sampfrom=20000, channels=[0, 1], physical=False) # Test file writing record.wrsamp() record_write = wfdb.rdrecord('a103l', physical=False) assert np.array_equal(sig, sig_target) assert record.__eq__(record_pb) assert record.__eq__(record_write)
def test_2b(self): """ Format 212, selected duration, selected channel, digital. Target file created with: rdsamp -r sample-data/100 -f 0.002 -t 30 -s 1 | cut -f 2- > record-2b """ record = wfdb.rdrecord('sample-data/100', sampfrom=1, sampto=10800, channels=[1], physical=False) sig = record.d_signal sig_target = np.genfromtxt('tests/target-output/record-2b') sig_target = sig_target.reshape(len(sig_target), 1) # Compare data streaming from physiobank record_pb = wfdb.rdrecord('100', sampfrom=1, sampto=10800, channels=[1], physical=False, pb_dir='mitdb') # This comment line was manually added and is not present in the # original physiobank record del(record.comments[0]) # Option of selecting channels by name record_named = wfdb.rdrecord('sample-data/100', sampfrom=1, sampto=10800, channel_names=['V5'], physical=False) del(record_named.comments[0]) # Test file writing record.wrsamp() record_write = wfdb.rdrecord('100', physical=False) assert np.array_equal(sig, sig_target) assert record.__eq__(record_pb) assert record.__eq__(record_named) assert record.__eq__(record_write)
def get_ecg_db(): data = [] max_R = 2.0 min_S = -1.3 for k in range(1, 91): if k in [5, 6, 11, 14, 20, 21, 22, 40, 48, 49, 71, 74, 79, 84, 88, 90]: continue #Получение данных с сайта if k < 10: record = wfdb.rdrecord('rec_1', pb_dir='ecgiddb/Person_0{0}/'.format(k), sampto=SAMPTO, channels=[0]) record2 = wfdb.rdrecord('rec_2', pb_dir='ecgiddb/Person_0{0}/'.format(k), sampto=SAMPTO, channels=[0]) else: record = wfdb.rdrecord('rec_1', pb_dir='ecgiddb/Person_{0}/'.format(k), sampto=SAMPTO, channels=[0]) record2 = wfdb.rdrecord('rec_2', pb_dir='ecgiddb/Person_{0}/'.format(k), sampto=SAMPTO, channels=[0]) #Преобразование данных к списку sig = [record.p_signal[i][0] for i in range(len(record.p_signal))] sig2 = [record2.p_signal[i][0] for i in range(len(record2.p_signal))] #обработка сигнала out = ecg.ecg(signal=sig, sampling_rate=500., show=False) out2 = ecg.ecg(signal=sig2, sampling_rate=500., show=False) #Обработанный сигнал filtered = list(out[1]) filtered.extend(list(out2[1])) i = 0 P = [] Q = [] R = list(out[2]) R.extend([list(out2[2])[i] + 10000 for i in range(len(list(out2[2])))]) S = [] T = [] ''' plt.plot([i for i in range(20000)], filtered) plt.plot(R, [filtered[i] for i in R], 'ro') plt.show() ''' for r in R: if i == len(R) - 1: break dx = (R[i+1] - r) / 2 min_x = int(r - dx) if (r-dx > 0) else 0 max_x = int(r + dx) q_ = indexOfMinElement(filtered[min_x:r]) + min_x Q.append(q_) s_ = indexOfMinElement(filtered[r:max_x]) + r S.append(s_) P.append(indexOfMaxElement(filtered[min_x:q_]) + min_x) T.append(indexOfMaxElement(filtered[s_:max_x]) + s_) i += 1 del R[-1] max_R = max([filtered[j] for j in R]) if max([filtered[j] for j in R]) > max_R else max_R min_S = min([filtered[j] for j in S]) if min([filtered[j] for j in S]) < min_S else min_S print("max R -> {0:.4f}, min_S -> {1:.4f}".format(max_R, min_S)) person_data = QRS(P, [filtered[j] for j in P], Q, [filtered[j] for j in Q], R, [filtered[j] for j in R], S, [filtered[j] for j in S], T, [filtered[j] for j in T]) data.append(person_data) print("Info with QRS of {0} person added".format(k)) return data
def load_waveforms(data_dir, infant_index, verbose=True): """ load ECG/RESP waveforms, return as arrays, return sampling freqs """ file_ecg = f"infant{infant_index:d}_ecg" file_resp = f"infant{infant_index:d}_resp" record_ecg = wfdb.rdrecord(os.path.join(data_dir, file_ecg)) record_resp = wfdb.rdrecord(os.path.join(data_dir, file_resp)) d_ecg = record_ecg.__dict__ d_resp = record_resp.__dict__ fs_ecg = d_ecg['fs'] # ECG sampling rate in Hz fs_resp = d_resp['fs'] # RESP sampling rate in Hz x_ecg = d_ecg['p_signal'].ravel() x_resp = d_resp['p_signal'].ravel() if verbose: print("Loading ECG file: ", file_ecg) print("Loading RESP file: ", file_resp) #print("ECG record: ", d_ecg['record_name']) #print("number of signals: ", d_ecg['n_sig']) #print("sampling frequency: ", d_ecg['fs'], "Hz") #print("Number of samples: ", d_ecg['sig_len']) #print("Signal name: ", d_ecg['sig_name']) #print("RESP record: ", d_resp['record_name']) #print("number of signals: ", d_resp['n_sig']) #print("sampling frequency: ", d_resp['fs'], "Hz") #print("Number of samples: ", d_resp['sig_len']) #print("Signal name: ", d_resp['sig_name']) print("ECG sampling frequency: ", fs_ecg, " Hz") print("RESP sampling frequency: ", fs_resp, " Hz") return x_ecg, x_resp, fs_ecg, fs_resp
def test_4b(self): """ Format 12, multi-samples per frame, skew, entire signal, digital. Target file created with: rdsamp -r sample-data/03700181 | cut -f 2- > record-4b """ record = wfdb.rdrecord('sample-data/03700181', physical=False) sig = record.d_signal # The WFDB library rdsamp does not return the final N samples for all # channels due to the skew. sig = sig[:-4, :] # The WFDB python rdsamp does return the final N samples, filling in # NANs for end of skewed channels only. sig_target = np.genfromtxt('tests/target-output/record-4b') # Compare data streaming from physiobank record_pb = wfdb.rdrecord('03700181', physical=False, pb_dir='mimicdb/037') # Test file writing. Multiple samples per frame and skew. # Have to read all the samples in the record, ignoring skew record_no_skew = wfdb.rdrecord('sample-data/03700181', physical=False, smooth_frames=False, ignore_skew=True) record_no_skew.wrsamp(expanded=True) # Read the written record record_write = wfdb.rdrecord('03700181', physical=False) assert np.array_equal(sig, sig_target) assert record.__eq__(record_pb) assert record.__eq__(record_write)
def save_data(file_path): samples = load_samples() patient = 0 validation_segment = 0 for i in range(len(samples)): if (i % 15 == 0 and i != 0 and validation_segment < 5): validation_segment += 1 # load up the sample to be looped over s = samples[i] # set the filename for the baseline ECG baseline_record = str(s[0]).zfill(3) + 'a' # and the balloon inflation ECG (referred to elsewhere as the ischaemic ECG) balloon_record = str(s[0]).zfill(3) + s[4] # all baseline ECGs were 300 seconds baseline_seconds = 300 # the first 60 seconds of balloon inflation were discarded balloon_start = int(s[1]) + 60 balloon_seconds = int(s[2]) - 60 # write baseline record: record = wfdb.rdrecord(baseline_record, pb_dir='staffiii/data/') ecg = record.p_signal filename = file_path + '0\\' + str(patient).zfill(2) + '.npy' np.save(filename, ecg) record = wfdb.rdrecord(balloon_record, pb_dir='staffiii/data/') ecg = record.p_signal # write balloon record: filename = file_path + '1\\' + str(patient).zfill(2) + '.npy' np.save( filename, ecg[(balloon_start * 1000):(balloon_start * 1000) + (balloon_seconds * 1000)]) print('Written ' + str(patient + 1) + ' patient files of ' + str(len(samples))) patient += 1
def test_4a(self): """ Format 16, multi-samples per frame, skew, digital. Target file created with: rdsamp -r sample-data/test01_00s_skewframe | cut -f 2- > record-4a """ record = wfdb.rdrecord('sample-data/test01_00s_skewframe', physical=False) sig = record.d_signal # The WFDB library rdsamp does not return the final N samples for all # channels due to the skew. The WFDB python rdsamp does return the final # N samples, filling in NANs for end of skewed channels only. sig = sig[:-3, :] sig_target = np.genfromtxt('tests/target-output/record-4a') # Test file writing. Multiple samples per frame and skew. # Have to read all the samples in the record, ignoring skew record_no_skew = wfdb.rdrecord('sample-data/test01_00s_skewframe', physical=False, smooth_frames=False, ignore_skew=True) record_no_skew.wrsamp(expanded=True) # Read the written record record_write = wfdb.rdrecord('test01_00s_skewframe', physical=False) assert np.array_equal(sig, sig_target) assert record.__eq__(record_write)
def test_multi_variable_d(self): """ Multi-segment, variable layout, selected duration, selected channels, digital. There are two channels: PLETH, and II. Their fmt, adc_gain, and baseline do not change between the segments. Target file created with: rdsamp -r sample-data/multi-segment/p000878/p000878-2137-10-26-16-57 -f s3550 -t s7500 -s 0 1 | cut -f 2- | perl -p -e 's/-32768/ -128/g;' > record-multi-variable-d """ record = wfdb.rdrecord('sample-data/multi-segment/p000878/p000878-2137-10-26-16-57', sampfrom=3550, sampto=7500, channels=[0, 1], physical=False) sig = record.d_signal # Compare data streaming from physiobank record_pb = wfdb.rdrecord('p000878-2137-10-26-16-57', pb_dir='mimic3wdb/matched/p00/p000878/', sampfrom=3550, sampto=7500, channels=[0, 1], physical=False) sig_target = np.genfromtxt('tests/target-output/record-multi-variable-d') # Option of selecting channels by name record_named = wfdb.rdrecord('sample-data/multi-segment/p000878/p000878-2137-10-26-16-57', sampfrom=3550, sampto=7500, physical=False, channel_names=['PLETH', 'II']) np.testing.assert_equal(sig, sig_target) assert record.__eq__(record_pb) assert record.__eq__(record_named)
def test_2b(self): record = wfdb.rdrecord('sample-data/100', sampfrom=1, sampto=10800, channels=[1], physical=False) sig = record.d_signal sig_target = np.genfromtxt('tests/target-output/io-2b') sig_target = sig_target.reshape(len(sig_target), 1) # Compare data streaming from physiobank record_pb = wfdb.rdrecord('100', sampfrom=1, sampto=10800, channels=[1], physical=False, pb_dir='mitdb') # This comment line was manually added and is not present in the # original physiobank record del (record.comments[0]) # Test file writing record.wrsamp() record_write = wfdb.rdrecord('100', physical=False) assert np.array_equal(sig, sig_target) assert record.__eq__(record_pb) assert record.__eq__(record_write)
def test_infer_sig_len(self): """ Infer the signal length of a record without the sig_len header Read two headers. The records should be the same. """ record = wfdb.rdrecord('sample-data/100') record_2 = wfdb.rdrecord('sample-data/100-no-len') record_2.record_name = '100' assert record_2.__eq__(record)
def preprocess(self, channels, name, path): if name == '114': if channels == [[0]]: record = wfdb.rdrecord(path, channels=[1]) elif channels == [[1]]: record = wfdb.rdrecord(path, channels=[0]) else: record = wfdb.rdrecord(path, channels=channels) else: record = wfdb.rdrecord(path, channels=channels) record = np.transpose(record.p_signal) return record
def classify(): # POST request body data = request.get_json() # Import record and find Peaks. file_path = '../DemoApp/Backend/uploads/' + data['filename'] start = 0 stop = 65000 record = wfdb.rdrecord(file_path, sampfrom=start, sampto=stop, channels=[0]) ecg = record.p_signal # rqrs = processing.xqrs_detect(record.p_signal[:,0], record.fs) rqrs = ecg_peak_detection(ecg, 30, 0.03, (stop - start) / record.fs, record.fs) # Image Generation # Conversion of Digital signals to Matplotlib Figures to Numpy Arrays test_data = [] for i in range(1, 100): start = rqrs[i] stop = rqrs[i] + 200 if start < 0: start = 0 temp_rec = wfdb.rdrecord(file_path, sampfrom=start, sampto=stop, channels=[0]) image = plt.figure() plt.plot(range(200), temp_rec.p_signal) image.canvas.draw() data = np.frombuffer(image.canvas.tostring_rgb(), dtype=np.uint8) data = data.reshape((image.canvas.get_width_height()[::-1] + (3, ))) data = cv2.cvtColor(data, cv2.COLOR_RGB2BGR) data = cv2.resize(data, (432, 288), cv2.INTER_LINEAR) data = data[288 - 250:288 - 35, 55:390] data = cv2.resize(data, (int(215 / 5), int(215 / 5)), cv2.INTER_LINEAR) test_data.append(data) del image plt.close() test_data = np.array(test_data) # Convert List to Numpy Array test_data = np.array(test_data) with graph.as_default(): predictions = loaded_model.predict_classes(test_data).tolist() return jsonify({'classes': predictions})
def test_4c(self): """ Format 12, multi-samples per frame, skew, selected suration, selected channels, physical. Target file created with: rdsamp -r sample-data/03700181 -f 8 -t 128 -s 0 2 -P | cut -f 2- > record-4c """ sig, fields = wfdb.rdsamp('sample-data/03700181', channels=[0, 2], sampfrom=1000, sampto=16000) sig_round = np.round(sig, decimals=8) sig_target = np.genfromtxt('tests/target-output/record-4c') # Compare data streaming from physiobank sig_pb, fields_pb = wfdb.rdsamp('03700181', pb_dir='mimicdb/037', channels=[0, 2], sampfrom=1000, sampto=16000) # Test file writing. Multiple samples per frame and skew. # Have to read all the samples in the record, ignoring skew record_no_skew = wfdb.rdrecord('sample-data/03700181', physical=False, smooth_frames=False, ignore_skew=True) record_no_skew.wrsamp(expanded=True) # Read the written record writesig, writefields = wfdb.rdsamp('03700181', channels=[0, 2], sampfrom=1000, sampto=16000) assert np.array_equal(sig_round, sig_target) assert np.array_equal(sig, sig_pb) and fields == fields_pb assert np.array_equal(sig, writesig) and fields == writefields
def test_2c(self): """ Format 212, entire signal, physical, odd sampled record. Target file created with: rdsamp -r sample-data/100_3chan -P | cut -f 2- > record-2c """ record = wfdb.rdrecord('sample-data/100_3chan') sig_round = np.round(record.p_signal, decimals=8) sig_target = np.genfromtxt('tests/target-output/record-2c') # Test file writing record.d_signal = record.adc() record.wrsamp() record_write = wfdb.rdrecord('100_3chan') record.d_signal = None assert np.array_equal(sig_round, sig_target) assert record.__eq__(record_write)
def test_multi_fixed_c(self): """ Multi-segment, fixed layout, selected duration and channels, samples read from multiple segments Target file created with: rdsamp -r sample-data/multi-segment/fixed1/v102s -f s70000 -t s80000 -s 1 0 3 -P | cut -f 2- > record-multi-fixed-c """ record = wfdb.rdrecord('sample-data/multi-segment/fixed1/v102s', sampfrom=70000, sampto=80000, channels=[1, 0, 3]) sig_round = np.round(record.p_signal, decimals=8) sig_target = np.genfromtxt('tests/target-output/record-multi-fixed-c') # Option of selecting channels by name record_named = wfdb.rdrecord('sample-data/multi-segment/fixed1/v102s', sampfrom=70000, sampto=80000, channel_names=['V', 'II', 'RESP']) np.testing.assert_equal(sig_round, sig_target) assert record.__eq__(record_named)
def test_2d(self): """ Format 310, selected duration, digital Target file created with: rdsamp -r sample-data/3000003_0003 -f 0 -t 8.21 | cut -f 2- | wrsamp -o 310derive -O 310 rdsamp -r 310derive -f 0.007 | cut -f 2- > record-2d """ record = wfdb.rdrecord('sample-data/310derive', sampfrom=2, physical=False) sig = record.d_signal sig_target = np.genfromtxt('tests/target-output/record-2d') assert np.array_equal(sig, sig_target)
def test_3a(self): """ Multi-dat, entire signal, digital Target file created with: rdsamp -r sample-data/s0010_re | cut -f 2- > record-3a """ record= wfdb.rdrecord('sample-data/s0010_re', physical=False) sig = record.d_signal sig_target = np.genfromtxt('tests/target-output/record-3a') # Compare data streaming from physiobank record_pb= wfdb.rdrecord('s0010_re', physical=False, pb_dir='ptbdb/patient001') # Test file writing record.wrsamp() record_write = wfdb.rdrecord('s0010_re', physical=False) assert np.array_equal(sig, sig_target) assert record.__eq__(record_pb) assert record.__eq__(record_write)
def test_multi_fixed_a(self): """ Multi-segment, fixed layout, read entire signal. Target file created with: rdsamp -r sample-data/multi-segment/fixed1/v102s -P | cut -f 2- > record-multi-fixed-a """ record = wfdb.rdrecord('sample-data/multi-segment/fixed1/v102s') sig_round = np.round(record.p_signal, decimals=8) sig_target = np.genfromtxt('tests/target-output/record-multi-fixed-a') np.testing.assert_equal(sig_round, sig_target)
def test_multi_fixed_b(self): """ Multi-segment, fixed layout, selected duration, samples read from one segment. Target file created with: rdsamp -r sample-data/multi-segment/fixed1/v102s -t s75000 -P | cut -f 2- > record-multi-fixed-b """ record = wfdb.rdrecord('sample-data/multi-segment/fixed1/v102s', sampto=75000) sig_round = np.round(record.p_signal, decimals=8) sig_target = np.genfromtxt('tests/target-output/record-multi-fixed-b') np.testing.assert_equal(sig_round, sig_target)
def test_multi_variable_b(self): """ Multi-segment, variable layout, selected duration, samples read from several segments. Target file created with: rdsamp -r sample-data/multi-segment/s00001/s00001-2896-10-10-00-31 -f s14428364 -t s14428375 -P | cut -f 2- > record-multi-variable-b """ record = wfdb.rdrecord('sample-data/multi-segment/s00001/s00001-2896-10-10-00-31', sampfrom=14428364, sampto=14428375) sig_round = np.round(record.p_signal, decimals=8) sig_target = np.genfromtxt('tests/target-output/record-multi-variable-b') np.testing.assert_equal(sig_round, sig_target)
def test_1a(self): """ Format 16, entire signal, digital. Target file created with: rdsamp -r sample-data/test01_00s | cut -f 2- > record-1a """ record = wfdb.rdrecord('sample-data/test01_00s', physical=False) sig = record.d_signal sig_target = np.genfromtxt('tests/target-output/record-1a') # Compare data streaming from physiobank record_pb = wfdb.rdrecord('test01_00s', physical=False, pb_dir='macecgdb') # Test file writing record_2 = wfdb.rdrecord('sample-data/test01_00s', physical=False) record_2.sig_name = ['ECG_1', 'ECG_2', 'ECG_3', 'ECG_4'] record_2.wrsamp() record_write = wfdb.rdrecord('test01_00s', physical=False) assert np.array_equal(sig, sig_target) assert record.__eq__(record_pb) assert record_2.__eq__(record_write)
def test_gqrs(self): record = wfdb.rdrecord('sample-data/100', channels=[0], sampfrom=9998, sampto=19998, physical=False) expected_peaks = [271, 580, 884, 1181, 1469, 1770, 2055, 2339, 2634, 2939, 3255, 3551, 3831, 4120, 4412, 4700, 5000, 5299, 5596, 5889, 6172, 6454, 6744, 7047, 7347, 7646, 7936, 8216, 8503, 8785, 9070, 9377, 9682] peaks = processing.gqrs_detect(d_sig=record.d_signal[:,0], fs=record.fs, adc_gain=record.adc_gain[0], adc_zero=record.adc_zero[0], threshold=1.0) assert np.array_equal(peaks, expected_peaks)
def test_4d(self): """ Format 16, multi-samples per frame, skew, read expanded signals Target file created with: rdsamp -r sample-data/test01_00s_skewframe -P -H | cut -f 2- > record-4d """ record = wfdb.rdrecord('sample-data/test01_00s_skewframe', smooth_frames=False) # Upsample the channels with lower samples/frame expandsig = np.zeros((7994, 3)) expandsig[:,0] = np.repeat(record.e_p_signal[0][:-3],2) expandsig[:,1] = record.e_p_signal[1][:-6] expandsig[:,2] = np.repeat(record.e_p_signal[2][:-3],2) sig_round = np.round(expandsig, decimals=8) sig_target = np.genfromtxt('tests/target-output/record-4d') assert np.array_equal(sig_round, sig_target)
def test_multi_variable_c(self): """ Multi-segment, variable layout, entire signal, physical The reference signal creation cannot be made with rdsamp directly because the wfdb c package (10.5.24) applies the single adcgain and baseline values from the layout specification header, which is undesired in multi-segment signals with different adcgain/baseline values across segments. Target file created with: ``` for i in {01..18} do rdsamp -r sample-data/multi-segment/s25047/3234460_00$i -P | cut -f 2- >> record-multi-variable-c done ``` Entire signal has 543240 samples. - 25740 length empty segment. - First 16 segments have same 2 channels, length 420000 - Last 2 segments have same 3 channels, length 97500 """ record = wfdb.rdrecord('sample-data/multi-segment/s25047/s25047-2704-05-04-10-44') sig_round = np.round(record.p_signal, decimals=8) sig_target_a = np.full((25740,3), np.nan) sig_target_b = np.concatenate( (np.genfromtxt('tests/target-output/record-multi-variable-c', skip_footer=97500), np.full((420000, 1), np.nan)), axis=1) sig_target_c = np.genfromtxt('tests/target-output/record-multi-variable-c', skip_header=420000) sig_target = np.concatenate((sig_target_a, sig_target_b, sig_target_c)) np.testing.assert_equal(sig_round, sig_target)