-
Notifications
You must be signed in to change notification settings - Fork 0
/
eeg.py
246 lines (196 loc) · 9.09 KB
/
eeg.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#bibliotecas necessarias
import csv
import numpy as np
from scipy import signal
#funcoes uteis
from re import search
from os import get_terminal_size
from time import sleep
from copy import deepcopy
from sklearn.preprocessing import minmax_scale
from pylsl import StreamInfo, StreamOutlet, resolve_stream, StreamInlet
from concurrent.futures import ThreadPoolExecutor
#debug
# import matplotlib.pyplot as plt
class Eletroencefalograma:
def __init__(self, freq, electrodes):
self.electrodes = electrodes
self.freq = freq
self.data = None
#end init/open
def processSample(self, electrodes=[], sample=None, notch=0, lowcut=0, highcut=0):
data = np.array(sample)
#dominio do tempo
data = data.swapaxes(1, 0)
#remove colunas que nao serao usadas
if electrodes:
delete = [i for i in range(self.electrodes) if i not in electrodes]
data = np.delete(data, delete, 0)
# Aplica esses filtros lá no buffer size processing
#filtros
# if notch:
# # aplica o filtro notch no valor determinado e nos harmonicos
# while notch <= (self.freq/2):
# data = self.__butterNotch(data, notch)
# notch = notch*2
# if lowcut:
# #Remove o que estiver abaixo de Lowcut
# data = self.__butterHighpass(data, lowcut)
# if highcut:
# #Remove o que estiver acima de Highcut
# data = self.__butterLowpass(data, highcut)
if(self.data is None):
self.data = data
else:
self.data = np.concatenate((self.data, data), axis=1)
#end configure
def execute(self, output, bufferSize, refresh, scale=0, start=0, simulate=False, stream=False, invertScale=False):
seconds = start
info = StreamInfo('Processed Data', 'Markers', 1, 0, 'float32', 'myuidw43536')
outlet = StreamOutlet(info)
print("looking for a OpenBCI EEG stream...")
streams = resolve_stream('type', 'EEG')
inlet = StreamInlet(streams[0])
print("EEG Stream Found...")
initSample = inlet.pull_sample()
# After waiting for the buffer size it pulls a chunk of data
# This should return the bufferSize * freq, in this case, 4 x 256 = 1024.
# But it doesn't always happen, sometimes it returns less data.
sleep(bufferSize)
chunk = inlet.pull_chunk()
eeg.processSample(electrodes=[1,2,3,4,5,6,7,8], sample=list(chunk[0]) + list([initSample[0]]), notch=60, lowcut=5, highcut=35)
with open(output + '.csv', mode='w') as file:
print('open')
writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['Janela', 'Delta', 'Theta', 'Alpha', 'Beta', 'Gamma'])
while True:
# 1-2-3s x 256Hz + 4s x 256Hz (bufferSize)
end = int((seconds * self.freq) + (bufferSize * self.freq))
# 1-2-3s x 256Hz
begin = int(seconds * self.freq)
sleep(refresh)
chunk = inlet.pull_chunk()
eeg.processSample(electrodes=[1,2,3,4,5,6,7,8], sample=chunk[0], notch=0, lowcut=0, highcut=0)
# This ensures there always are enough data in the buffer, if not, wait for the refresh time and try again
# It makes sure the program won't crash due to data stream inconsistencies.
# The drawback is that it could affect response time of the game as it's basically just waiting for new data to come in
# Without adding the "seconds" variable. After there are enough data the loop comes back from where it stopped (seconds + refresh)
if(self.data.shape[1] < end):
continue
#welch
f, psdWelch = signal.welch(self.data[:,begin:end])
psdWelch = np.average(psdWelch, axis=0)
features = list()
for mi, ma in [(0, 4),(4, 8),(8, 12),(12, 30),(30, 100)]:
features.append(psdWelch[mi:ma])
features = [np.average(f) for f in features]
# plot
if simulate:
self.__consolePlot(bufferSize, seconds, minmax_scale(features, feature_range=(0, 100)))
if scale:
if(invertScale):
features = scale - minmax_scale(features, feature_range=(0, scale))
else:
features = minmax_scale(features, feature_range=(0, scale))
# Stream data to the network
if stream:
outlet.push_sample([int(features[3])])
#escreve no csv
writer.writerow(np.insert(features, 0, seconds))
seconds += refresh
#end while
#end csv
#end execute
# ===============================================================================
def __open(self, filename):
data = list()
with open(filename) as file:
linhas = file.readlines()
for linha in linhas:
res = search('^\d{1,3},(?P<dado>(\ -?.+?,){%d})'%self.electrodes, linha)
if res:
cols = res.group(1)
data.append([float(d[1:]) for d in cols.split(',') if d])
return np.array(data[1:])
#end open
def __consolePlot(self, bufferSize, second, features):
terminal = get_terminal_size()
r = int(terminal.columns/2) #range
feat = minmax_scale(features, feature_range=(0, r))
delta = '[' + ('=' * int(feat[0])) + (' ' * (r-int(feat[0]))) + ']'
theta = '[' + ('=' * int(feat[1])) + (' ' * (r-int(feat[1]))) + ']'
alpha = '[' + ('=' * int(feat[2])) + (' ' * (r-int(feat[2]))) + ']'
beta = '[' + ('=' * int(feat[3])) + (' ' * (r-int(feat[3]))) + ']'
gamma = '[' + ('=' * int(feat[4])) + (' ' * (r-int(feat[4]))) + ']'
#minutos xd
m = int(second / 60)
m = m if m > 10 else f'0{m}'
s = second % 60
s = f'{s:.2f}' if s > 10 else f'0{s:.2f}'
for i in range(terminal.lines):
clear = '\x1b[F' + (' ' * terminal.columns) + '\x1b[A'
print(clear)
# print(f'Arquivo: {self.filename}')
print(f'Simulação / Buffer {bufferSize}s / Segundo {second:.2f} ({m}:{s}):')
print(f' DELTA:\t{delta}\n THETA:\t{theta}\n ALPHA:\t{alpha}\n BETA: \t{beta}\n GAMMA:\t{gamma}')
#end consoleplot
# ===============================================================================
#filters
def __butterNotch(self, data, cutoff, var=1, order=4):
nyq = self.freq * 0.5
low = (cutoff - var) / nyq
high = (cutoff + var) / nyq
b, a = signal.iirfilter(order, [low, high], btype='bandstop', ftype="butter")
return signal.filtfilt(b, a, data)
def __butterLowpass(self, data, lowcut, order=4):
nyq = self.freq * 0.5
low = lowcut / nyq
b, a = signal.butter(order, low, btype='lowpass')
return signal.filtfilt(b, a, data)
def __butterHighpass(self, data, highcut, order=4):
nyq = self.freq * 0.5
high = highcut / nyq
b, a = signal.butter(order, high, btype='highpass')
return signal.filtfilt(b, a, data)
# def __butterBandpass(self, lowcut, highcut, order=4):
# nyq = self.freq * 0.5
# low = lowcut / nyq
# high = highcut / nyq
# b, a = signal.butter(order, [low, high], btype='bandpass')
# return signal.filtfilt(b, a, self.data)
#end filters
# ===============================================================================
# #debug
# def welchPlot(self, data):
# if len(data.shape) == 1:
# plt.plot(data[:55])
# else:
# for ch in range(data.shape[0]):
# plt.plot(data[ch,:55])
# plt.axvline(x=4, linestyle='--', color='red')
# plt.axvline(x=8, linestyle='--', color='blue')
# plt.axvline(x=12, linestyle='--', color='orange')
# plt.axvline(x=30, linestyle='--', color='purple')
# plt.show()
# #end myplot
# def matplotGraphs(self):
# for i in range(self.data.shape[0]):
# plt.plot(self.data[i,:])
# plt.title('Domínio do tempo')
# plt.show()
# for i in range(self.data.shape[0]):
# plt.psd(self.data[i,:], Fs=self.freq)
# plt.title('Domínio da frequência')
# plt.show()
# for i in range(self.data.shape[0]):
# plt.specgram(self.data[i,:], Fs=self.freq)
# plt.title('Espectrograma')
# plt.show()
# #end matplotgraphs
#end class eeg
# =========================================================
if __name__ == "__main__":
eeg = Eletroencefalograma(256, 8)
# Scale is height of screen minus object height
eeg.execute(output="teste", bufferSize=4, refresh=0.3, scale=1030, start=0, simulate=True, stream=True, invertScale=True)
# eeg.matplotGraphs()