-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.py
199 lines (174 loc) · 7.42 KB
/
dataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import numpy as np
import torch
import neurokit2 as nk
from operator import itemgetter
import matplotlib.pyplot as plt
from qrs import QRS
class ECGDataset:
def __init__(self, ecg=None, annotations=None):
self.ecg = ecg
self.annotations = annotations
self.fs = 360
if ecg is not None:
self.split_ecg = self._split_by_r_peaks()
if annotations is not None:
self.fs = annotations.fs
self.annotations.symbol = [symbol.upper() for symbol in self.annotations.symbol]
self.labels = np.array([peak.label for peak in self.split_ecg])
@staticmethod
def get_peaks(ecg: np.ndarray, sampling_rate: int = 250):
_, r_peaks = nk.ecg_peaks(ecg, sampling_rate=sampling_rate)
_, waves_peak = nk.ecg_delineate(ecg, r_peaks, sampling_rate=sampling_rate, method="peak", show_type='peaks')
waves_peak['ECG_R_Peaks'] = r_peaks['ECG_R_Peaks'][:-1]
# delete offsets and onsets
del waves_peak['ECG_P_Onsets'], waves_peak['ECG_T_Offsets']
return {key: np.array(waves_peak[key])[~np.isnan(waves_peak[key])].astype(int) for key in waves_peak}
def _split_by_r_peaks(self, start_from=-1, delta=60):
split_ecg = []
if self.annotations is None:
# find r peaks by nk.ecg_peaks
r_peaks = nk.ecg_peaks(self.ecg, sampling_rate=self.fs)[1]['ECG_R_Peaks']
else:
r_peaks = self.annotations.sample
for i in range(len(r_peaks) - 1):
if start_from > i:
continue
if (not (r_peaks[i] - delta < 0 or r_peaks[i] + delta > len(self.ecg)) and
(self.annotations is None or self.annotations.symbol[i].upper() in QRS.LABELS)):
split_ecg.append(
QRS(
self.ecg[r_peaks[i] - delta: r_peaks[i] + delta],
None if self.annotations is None else self.annotations.symbol[i],
self.fs,
start=r_peaks[i] - delta,
)
)
else:
print(f'QRS {i} is too close to the edge')
print(f'r_peaks[i] - delta: {r_peaks[i] - delta}, r_peaks[i] + delta: {r_peaks[i] + delta}')
return split_ecg
@staticmethod
def draw_ecg(ecg):
plt.plot(ecg)
plt.show()
def extract_images(self, methods=None, split_ecg=None) -> torch.Tensor:
if split_ecg is None:
split_ecg = self.split_ecg
images = [itemgetter(*methods)(split_ecg[i].get_images(methods)) for i in range(len(split_ecg))]
if isinstance(images[0], tuple):
images = [torch.cat(im).reshape(len(methods), *QRS.IMG_SIZE) for im in images]
return torch.cat(images).reshape(-1, len(methods), *QRS.IMG_SIZE)
def __getitem__(self, item):
return [qrs for qrs in self.split_ecg if qrs.label == item]
def append(self, ecg, annotations):
annotations.sample += len(self.ecg)
self.annotations.sample = np.append(self.annotations.sample, annotations.sample)
self.annotations.symbol = np.append(self.annotations.symbol, annotations.symbol)
self.annotations.symbol = [symbol.upper() for symbol in self.annotations.symbol]
self.ecg = np.append(self.ecg, ecg)
self.split_ecg.extend(self._split_by_r_peaks(start_from=len(self.split_ecg) - 1))
self.labels = [peak.label for peak in self.split_ecg]
def __len__(self):
return len(self.split_ecg)
def plot_ecg(self, start=0, end=1000):
s = self.split_ecg[start].start
plt.plot(self.ecg[self.split_ecg[start].start: self.split_ecg[end].start + len(self.split_ecg[end].ecg)],
label='Normal')
for i in range(start, end):
qrs = self.split_ecg[i]
conf = qrs.labels[max(qrs.labels, key=qrs.labels.get)]
if qrs.label == "A" and conf > 0.9:
color = 'r'
label = 'Atrial'
elif qrs.label == "V" and conf > 0.9:
color = 'g'
label = 'Ventricular'
else:
color = 'b'
label = 'Normal'
if color != 'b':
# set plot different color from i.start to i.start + len(i.ecg)
plt.plot(range(qrs.start - s, qrs.start - s + len(qrs.ecg)),
self.ecg[qrs.start: qrs.start + len(qrs.ecg)], color, label=label)
# add legend
plt.legend()
# remove axis
plt.axis('off')
plt.show()
if __name__ == '__main__':
data_path = 'mitbit'
import os
from utils import load_ecg
from transformer import ECGDETR
# ecg = load_ecg('/home/oleksandr/ECG_diplom/mitbit/201')[0][:2000]
# model = ECGDETR(['cwt'])
# pred = model.predict(ecg)
"100, 101, 103, 113, 115 109, 111, 207, 214 118, 124, 212, 231 209, 220, 222, 223, 232 106, 119, 200, 208, 233"
numbers = ['100', '101', '103', '113', '115', '109', '111', '207', '214', '118', '124', '212', '231', '209', '220',
'222', '223', '232', '106', '119', '200', '208', '233']
# numbers = ['201']
ecg_dataset = ECGDataset(*load_ecg(os.path.join(data_path, numbers[0])))
#
for number in numbers:
ecg, annotations = load_ecg(os.path.join(data_path, number))
ecg_dataset.append(ecg, annotations)
print(f'{number} done')
# for i, qrs in enumerate(ecg_dataset.split_ecg):
# qrs.images = qrs.get_images()
# if i % 10 == 0:
# print(f'{i}/{len(ecg_dataset.split_ecg)}')
# if i % 1000 == 0 and i != 0:
# joblib.dump(ecg_dataset.split_ecg, f'dump_images/qrs_{i}.pkl')
#
# import joblib
# joblib.dump(ecg_dataset, 'ecg_dataset1.pkl')
n_data = ecg_dataset['N']
v_data = ecg_dataset['V']
a_data = ecg_dataset['A']
l_data = ecg_dataset['L']
r_data = ecg_dataset['R']
min_len = min(len(n_data), len(v_data), len(a_data), len(l_data), len(r_data))
print(f"Min len: {min_len}")
n_data = n_data[2000:min_len]
v_data = v_data[2000:min_len]
a_data = a_data[2000:min_len]
l_data = l_data[2000:min_len]
r_data = r_data[2000:min_len]
import pickle
with open('test_ecg_dataset1.pkl', 'wb') as f:
pickle.dump([n_data, v_data, a_data, l_data, r_data], f)
# with open('ecg_dataset.pkl', 'rb') as f:
# n_data, v_data, a_data = pickle.load(f)
#
# methods = ['fft', 'stft', 'cwt', 'spectrogram', 'welch']
# for data in [n_data, a_data, v_data]:
# if not data:
# continue
# images = []
# for i, qrs in enumerate(data):
# image = []
# for method in methods:
# image.append(qrs.convert_to_image(method))
# images.append(image)
# # qrs.plot_spectrum()
# print(f"{i}/{len(data)}")
# images = np.array(images)
#
# # save images
# import pickle
#
# name = data[0].label
# folder = os.path.join('images', name)
# if not os.path.exists(folder):
# os.makedirs(folder)
#
# for i, qrs in enumerate(data):
# image = qrs.image((640, 480))
# cv2.imwrite(os.path.join(folder, f'{i}.jpg'), image)
# print(f"{i}/{len(data)}")
#
# # with open(f'{name}_images.pkl', 'wb') as f:
# # pickle.dump(images, f)
#
# print(f'{name} done')
# print(f'done')