class WorkSession: def __init__(self): # Import model self.fs = DEFAULT_FS self.buffer_seconds = DEFAULT_SECONDS self.started = False def start(self): print("started work session :D ") self.timestamp = datetime.now() self.model = torch.load( "../data_analysis/models/model_t_combined_continuous_filtered_3class.pickle" ) self.focus_logger = FocusLogger(fs=self.fs) self.eeg_sampler = EEGSampler(fs=self.fs, buffer_seconds=self.buffer_seconds, update_seconds=DEFAULT_UPDATE_SECONDS, channels=DEFAULT_CHANNELS, binning=DEFAULT_BINNING, live=True, model=self.model, to_clean=True, three_class=True, focus_logger=self.focus_logger) if LIVE_DATA: self.board = OpenBCICyton() self.eeg_thread = threading.Thread( target=self.board.start_stream, args=(self.eeg_sampler.push_data_sample, )) self.eeg_thread.start() self.started = True def end(self): print("ended work session") self.duration = datetime.utcfromtimestamp( (datetime.now() - self.timestamp).total_seconds()).strftime('%H:%M:%S') if LIVE_DATA: self.board.stop_stream() self.started = False def getTotalAvg(self): return self.focus_logger.getTotalAvg() def getTimestamp(self): return self.timestamp def getDuration(self): if self.started: self.duration = datetime.utcfromtimestamp( (datetime.now() - self.timestamp).total_seconds()).strftime('%H:%M:%S') return self.duration def getEEGBufferData(self): return self.eeg_sampler.getBuffer() def getAveragedFocusBufferData(self): return self.eeg_sampler.getAveragedFocus()
class EEGRecorder: def __init__(self, live, output_filename, channels=DEFAULT_CHANNELS): self.fs = DEFAULT_FS self.output_filename = output_filename self.started = False self.live = live self.channels = channels atexit.register(self.end) ############################ ## STREAM CONTROL METHODS ## ############################ def start(self): print("start recording called") if self.live: from pyOpenBCI import OpenBCICyton print("LIVE: started eeg recording") header = ["timestamp"] + self.channels self.csv_writer = CSVWriter(self.output_filename, column_headers=header) self.board = OpenBCICyton() self.eeg_thread = threading.Thread( target=self.board.start_stream, args=(self.record_data_sample, )) self.eeg_thread.start() self.started = True def end(self): print("end recording called") if self.started: print("LIVE: ended eeg recording") if self.live: self.board.stop_stream() self.started = False #################### ## HELPER METHODS ## #################### def record_data_sample(self, sample): # Get timestamp now = time.time() # Get the scaled channel data if self.live: raw_eeg_data = np.array(sample.channels_data) * SCALE_FACTOR_EEG else: raw_eeg_data = np.array(sample) # Record to CSV row_data = [now] row_data.extend(raw_eeg_data[self.channels]) self.csv_writer.writerow(row_data)
class EEGRecorder: def __init__(self): self.__board = None self.__outlet_eeg = None self.__outlet_aux = None self.__createEEGStream() def __createEEGStream(self): info_eeg = StreamInfo(name='OpenBCI EEG', type='EEG', channel_count=8, nominal_srate=250, channel_format='float32', source_id='eeg_thread') info_aux = StreamInfo(name='OpenBCI AUX', type='AUX', channel_count=3, nominal_srate=250, channel_format='float32', source_id='aux_thread') self.__outlet_eeg = StreamOutlet(info_eeg) self.__outlet_aux = StreamOutlet(info_aux) # append some meta-data # info.desc().append_child_value("manufacturer", "OpenBCI") # channels = info.desc().append_child("channels") # for c in ["Fp1", "Fp2", "FPz", "A1"]: # channels.append_child("channel")\ # .append_child_value("name", c)\ # .append_child_value("unit", "microvolts")\ # .append_child_value("type", "EEG") # next make an outlet; we set the transmission chunk size to 32 samples and # the outgoing buffer size to 360 seconds (max.) # outlet = StreamOutlet(info, 32, 360) def __lsl_streamers(self, sample): self.__outlet_eeg.push_sample( np.array(sample.channels_data) * SCALE_FACTOR_EEG) self.__outlet_aux.push_sample( np.array(sample.aux_data) * SCALE_FACTOR_AUX) def runSession(self): self.__createEEGStream() # eeg_thread = threading.Thread(target=self.__board.start_stream, args=(self.__lsl_streamers,)) # eeg_thread.start() try: self.__board = OpenBCICyton() self.__board.start_stream(self.__lsl_streamers) except (KeyboardInterrupt, SystemExit): self.__board.stop_stream() sys.exit()
def main(): TIMEOUT = 60 #Set (daisy = True) to stream 16 ch board = OpenBCICyton(daisy=True) signal.signal(signal.SIGALRM, signal_handler) signal.alarm(TIMEOUT) try: board.start_stream(print_raw) except Exception as e: print("timed out") board.stop_stream() sys.exit(0)
class EEGSampler: """ Holds a buffer of EEG data and accepts a single data sample as input to append to the buffer """ def __init__(self, live, fs=DEFAULT_FS, buffer_seconds=DEFAULT_SECONDS, update_seconds=DEFAULT_UPDATE_SECONDS, prediction_seconds=DEFAULT_PREDICTION_WINDOW_SECONDS, channels=DEFAULT_CHANNELS, model=None, to_clean=True): self.fs = fs self.buffer_seconds = buffer_seconds self.prediction_seconds = prediction_seconds self.timepoints_to_chop = 300 # How many timepoints to disregard from the most recent (this sets back the lag of prediction) if to_clean: if prediction_seconds * fs > (buffer_seconds * fs - self.timepoints_to_chop): print("Warning: prediction window may contain edge artifacts because it is larger than 500 timepoints less than the buffer size") self.timepoints_to_chop = (buffer_seconds * fs - prediction_seconds * fs) // 2 # Take the middle half to reduce edge artifacts self.channels = channels # These are the channels we want self.live = live self.model = model if model is not None: self.classes = list(self.model.model.classes_) self.index_of_left = self.classes.index(1) print("classes", self.classes) # If generating artificial data, this will cap the # of seconds we get artificial data to prevent while(true) runaways self.seconds_to_gather_artificial_data = 600 self.buffer = np.zeros((fs * buffer_seconds, len(channels))) self.raw_buffer = np.zeros((fs * buffer_seconds, len(channels))) self.dc_removed_buffer = np.zeros((fs * buffer_seconds, len(channels))) self.pred_values = np.zeros((fs * buffer_seconds)) self.pred_values_average = np.zeros((fs * buffer_seconds)) self.update_seconds = update_seconds self.last_updated = time.time() self.mean = np.zeros(len(channels)) self.count_samples = 0 self.to_clean = to_clean self.started = False atexit.register(self.end) ############################ ## STREAM CONTROL METHODS ## ############################ def setModel(self, model): ''' Allows for the model to be updated ''' self.model = model self.classes = list(self.model.model.classes_) self.index_of_left = self.classes.index(1) print("classes", self.classes) def startStream(self) : print("start streaming called") if not self.started: self.started = True if self.live: from pyOpenBCI import OpenBCICyton print("LIVE: started eeg streaming") self.board = OpenBCICyton() self.eeg_thread = threading.Thread(target=self.board.start_stream, args=(self.push_data_sample,)) else : print("FAKE DATA: started") self.eeg_thread = threading.Thread(target=self.__generate_artificial_data, args=(self.push_data_sample,)) self.eeg_thread.start() def end(self): print("end stream called") if self.started: self.started = False if self.live: print("LIVE: ended eeg streaming") self.board.stop_stream() else : print("FAKE DATA: ended") ######################## ## BUFFER GET METHODS ## ######################## def getBuffer(self): return self.buffer def getPredictionValue(self): return self.pred_values[0] def getPredictionValues(self): return self.pred_values def getPredictionValueAverage(self): return self.pred_values_average[0] def getPredictionValueAverages(self): return self.pred_values_average ############################ ## PRIVATE HELPER METHODS ## ############################ def __generate_artificial_data(self, callback) : limit_counter = 0 # This will prevent this thread from continuing to produce values on while forever while self.started and (limit_counter < (600 * self.fs)): # TODO: remove fake_sample = np.random.rand(8) * 300 # Cyton has 8 channels by default, so we generate a value for each. callback(fake_sample) time.sleep(0.004) # Sample at 250 Hz limit_counter += 1 def __filter_eeg(self): # Bandpass + 60 Hz Notch for i, chan in enumerate(self.channels): self.buffer[:self.count_samples, i] = filterEEG(self.dc_removed_buffer[:self.count_samples, i], self.fs, (0.5, 50)) def __update_prediction_buffer(self): # Take a 4 second window timepoints_to_chop timepoints away from the end of the buffer to reduce edge effects data = np.transpose(self.buffer[self.timepoints_to_chop : self.prediction_seconds * self.fs + self.timepoints_to_chop]) prediction = self.model.predict_proba(np.array([data]))[0] print("prediction: ", prediction) prediction = prediction[self.index_of_left] self.pred_values[0] = prediction self.pred_values_average = np.roll(self.pred_values_average, 1, 0) # Update average values self.pred_values_average[0] = np.mean(self.pred_values[:self.fs]) ########################### ## CALLBACK FOR NEW DATA ## ########################### def push_data_sample(self, sample): # Count the number of samples up till the full buffer (this is for mean calculation) if self.count_samples < self.fs * self.buffer_seconds: self.count_samples += 1 # Get the scaled channel data if self.live: raw_eeg_data = np.array(sample.channels_data)[self.channels] * SCALE_FACTOR_EEG else : raw_eeg_data = np.array(sample)[self.channels] # Roll and prepend the buffer with the new data self.raw_buffer = np.roll(self.raw_buffer, 1, 0) self.buffer = np.roll(self.buffer, 1, 0) self.dc_removed_buffer = np.roll(self.dc_removed_buffer, 1, 0) self.pred_values = np.roll(self.pred_values, 1, 0) self.pred_values_average = np.roll(self.pred_values_average, 1, 0) for i, chan in enumerate(self.channels): self.raw_buffer[0, i] = raw_eeg_data[i] if self.to_clean: self.dc_removed_buffer[0, i] = self.raw_buffer[0,i] - self.mean[i] self.buffer[0, i] = self.dc_removed_buffer[0, i] else : self.dc_removed_buffer[0, i] = self.raw_buffer[0, i] self.buffer[0, i] = self.raw_buffer[0, i] self.pred_values[0] = self.pred_values[1] self.pred_values_average[0] = np.mean(self.pred_values[:self.fs]) # Calculate the new mean if the update time has passed now = time.time() if (now - self.last_updated) > self.update_seconds : self.last_updated = now # Only predict once we've reached the number of samples we need in the buffer if (self.count_samples > self.prediction_seconds * self.fs + self.timepoints_to_chop): if (self.to_clean): self.__filter_eeg() if (self.model is not None): self.__update_prediction_buffer()
class FrameGesto1(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"Captura de señales para el gesto 1", pos=wx.DefaultPosition, size=wx.Size(1400, 1000), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL) self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize) bSizer4 = wx.BoxSizer(wx.VERTICAL) self.panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) self.panel.SetSizer(sizer) self.m_staticText2 = wx.StaticText( self, wx.ID_ANY, u"Captura de señales para el primer gesto \n", wx.DefaultPosition, wx.Size(700, -1), 0) self.m_staticText2.Wrap(-1) self.m_staticText2.SetFont( wx.Font(34, 70, 90, 90, False, wx.EmptyString)) bSizer4.Add(self.m_staticText2, 0, wx.ALIGN_CENTER_HORIZONTAL, 10) bSizer49 = wx.BoxSizer(wx.VERTICAL) bSizer50 = wx.BoxSizer(wx.HORIZONTAL) bSizer50.SetMinSize(wx.Size(700, 50)) self.m_staticText30 = wx.StaticText( self, wx.ID_ANY, u"Para iniciar el experimento por favor observe \n ", wx.DefaultPosition, wx.Size(1000, -1), 0) self.m_staticText30.Wrap(-1) self.m_staticText30.SetFont( wx.Font(17, 70, 90, 90, False, wx.EmptyString)) bSizer50.Add(self.m_staticText30, 0, wx.ALL, 5) bSizer52 = wx.BoxSizer(wx.VERTICAL) bSizer52.SetMinSize(wx.Size(90, -1)) self.m_button32 = wx.Button(self, wx.ID_ANY, u"Inicio", wx.Point(-1, -1), wx.Size(150, -1), 0) self.m_button32.SetFont(wx.Font(25, 70, 90, 90, False, wx.EmptyString)) bSizer52.Add(self.m_button32, 0, wx.TOP, 10) bSizer50.Add(bSizer52, 1, 0, 5) self.m_animCtrl1 = AnimationCtrl(self, pos=(40, 40), size=(14, 14), name="AnimationCtrl") self.m_animCtrl1.LoadFile( r"C:\Users\crist\OneDrive\Escritorio\Universidad\LASER\Tesis\Open_BCI_and_MYO_UD\GUI_Adquisicion/manos.gif" ) self.m_animCtrl1.Play() self.m_animCtrl1.SetMinSize(wx.Size(200, -1)) bSizer50.Add(self.m_animCtrl1, 0, wx.ALIGN_CENTER, 5) bSizer49.Add(bSizer50, 1, 0, 5) bSizer51 = wx.BoxSizer(wx.VERTICAL) bSizer57 = wx.BoxSizer(wx.HORIZONTAL) # grafica EMG self.figureEMG = plt.figure(figsize=(1, 6), dpi=60) self.axes = [ self.figureEMG.add_subplot('81' + str(i)) for i in range(1, 9) ] self.n = 512 [(ax.set_ylim(ymin=-200, ymax=200)) for ax in self.axes] global graphs self.graphs = [ ax.plot(np.arange(self.n), np.zeros(self.n))[0] for ax in self.axes ] plt.ion() self.canvEMG = FigureCanvas(self, wx.ID_ANY, self.figureEMG) bSizer57.Add(self.canvEMG, 1, wx.TOP | wx.LEFT | wx.EXPAND) # grafica EEG self.figureEEG = plt.figure(figsize=(1, 6), dpi=60) self.axesEEG = [ self.figureEEG.add_subplot('81' + str(i)) for i in range(1, 9) ] [(ax.set_ylim([-150000, 150000])) for ax in self.axesEEG] self.m = 100 self.graphsEEG = [ ax.plot(np.arange(self.m), np.zeros(self.m))[0] for ax in self.axesEEG ] plt.ion() self.canvasEEG = FigureCanvas(self, -1, self.figureEEG) bSizer57.Add(self.canvasEEG, 1, wx.TOP | wx.LEFT | wx.EXPAND) bSizer51.Add(bSizer57, 1, wx.EXPAND, 5) bSizer49.Add(bSizer51, 1, wx.EXPAND, 5) bSizer53 = wx.BoxSizer(wx.HORIZONTAL) self.m_staticText31 = wx.StaticText(self, wx.ID_ANY, u"Señal EMG", wx.DefaultPosition, wx.Size(700, 30), 0) self.m_staticText31.Wrap(-1) self.m_staticText31.SetFont( wx.Font(18, 70, 90, 90, False, wx.EmptyString)) bSizer53.Add(self.m_staticText31, 0, wx.LEFT, 5) self.m_staticText32 = wx.StaticText(self, wx.ID_ANY, u"Señal EEG", wx.DefaultPosition, wx.Size(-1, 30), 0) self.m_staticText32.Wrap(-1) self.m_staticText32.SetFont( wx.Font(18, 70, 90, 90, False, wx.EmptyString)) bSizer53.Add(self.m_staticText32, 0, 0, 5) bSizer49.Add(bSizer53, 1, 0, 5) bSizer8 = wx.BoxSizer(wx.HORIZONTAL) self.m_staticText33 = wx.StaticText(self, wx.ID_ANY, u"Tiempo:", wx.DefaultPosition, wx.Size(550, -1), 0) self.m_staticText33.Wrap(-1) self.m_staticText33.SetFont( wx.Font(18, 70, 90, 90, False, wx.EmptyString)) bSizer8.Add(self.m_staticText33, 0, wx.ALL, 5) pos = wx.DefaultPosition size = wx.Size(1, 11) style = gizmos.LED_ALIGN_CENTER self.led = gizmos.LEDNumberCtrl(self, -1, pos, size, style) self.led.SetBackgroundColour("white") self.led.SetForegroundColour("black") bSizerTimmer = wx.BoxSizer(wx.VERTICAL) bSizerTimmer.Add(self.led, 1, wx.TOP | wx.LEFT | wx.EXPAND) bSizer49.Add(bSizerTimmer, 1, wx.EXPAND, 5) self.button_siguiente = wx.Button(self, wx.ID_ANY, u"Aceptar", wx.DefaultPosition, wx.Size(150, -1), 0) self.button_siguiente.SetFont( wx.Font(18, 70, 90, 90, False, wx.EmptyString)) bSizer8.Add(self.button_siguiente, 0, wx.ALL, 5) self.button_salir = wx.Button(self, wx.ID_ANY, u"Salir", wx.DefaultPosition, wx.Size(150, -1), 0) self.button_salir.SetFont( wx.Font(18, 70, 90, 90, False, wx.EmptyString)) bSizer8.Add(self.button_salir, 0, wx.ALL, 5) bSizer49.Add(bSizer8, 0, wx.TOP, 1) bSizer4.Add(bSizer49, 1, wx.EXPAND, 5) self.SetSizer(bSizer4) self.Layout() self.Centre(wx.BOTH) # Connect Events self.m_button32.Bind(wx.EVT_BUTTON, self.OnClickInicio) self.button_siguiente.Bind(wx.EVT_BUTTON, self.OnClickConcentimiento) self.button_salir.Bind(wx.EVT_BUTTON, self.OnClickSalir) # Arrancar conexion myo self.conexionMYO() def hiloMYOConexion(arg): hiloConexionMYO = threading.currentThread() while getattr(hiloConexionMYO, "do_run", True): print("working on %s" % arg) self.mainMYO() print("Stopping as you wish.") self.hiloConexionMYO = threading.Thread(target=hiloMYOConexion, args=("PLOT_EMG_MYO", )) self.hiloConexionMYO.setDaemon(True) self.hiloConexionMYO.start() # Arranca conexion UltraCortex self.datosEEG = [] self.start_board() def hiloPlotUltracortex(arg): hiloPlotUltracortex = threading.currentThread() while getattr(hiloPlotUltracortex, "do_run", True): print("working on %s" % arg) time.sleep(3) self.mainplotUltracortex() print("Stopping as you wish.") self.hiloPlotUltracortex = threading.Thread( target=hiloPlotUltracortex, args=("PLOT_EEG_ULTRACORTEX", )) self.hiloPlotUltracortex.setDaemon(True) self.hiloPlotUltracortex.start() def __del__(self): pass # Virtual event handlers, overide them in your derived class def OnClickInicio(self, event): self.GetSegundos(None) def OnClickConcentimiento(self, event): event.Skip() def OnClickSalir(self, event): self.Close() sys.exit() def GetSegundos(self, e): global segundos self.board.stop_stream() self.stopconexioUltracortexPlot = True self.hiloPlotUltracortex.do_run = False self.hiloPlotUltracortex.join() self.stopconexion = True self.hiloConexionMYO.do_run = False self.hiloConexionMYO.join() dlg = wx.TextEntryDialog(self.panel, 'Ingrese los segundos a grabar el gesto:', "Captura del gesto", "", style=wx.OK) dlg.ShowModal() segundos = int(dlg.GetValue()) def hiloRunTimmer(arg): hiloRunTimmer = threading.currentThread() while getattr(hiloRunTimmer, "do_run", True): print("working on %s" % arg) self.led.SetValue("00:00") self.OnTimer(None, e=segundos) print("Stopping as you wish.") self.hiloRunTimmer = threading.Thread(target=hiloRunTimmer, args=("RUN_Timmer", )) self.hiloRunTimmer.setDaemon(True) self.hiloRunTimmer.start() def hiloMYOSaved(arg): hiloMYOSaved = threading.currentThread() while getattr(hiloMYOSaved, "do_run", True): print("working on %s" % arg) self.mainSavedMYO() print("Stopping as you wish.") self.hiloMYOSaved = threading.Thread(target=hiloMYOSaved, args=("Saved_EMG_MYO", )) self.hiloMYOSaved.setDaemon(True) self.hiloMYOSaved.start() def hiloUltracortesConexion(arg): hiloUltracortesConexion = threading.currentThread() while getattr(hiloUltracortesConexion, "do_run", True): print("working on %s" % arg) self.mainULTRACORTEX() print("Stopping as you wish.") self.hiloUltracortesConexion = threading.Thread( target=hiloUltracortesConexion, args=("SAVE_EEG_ULTRACORTEX", )) self.hiloUltracortesConexion.setDaemon(True) self.hiloUltracortesConexion.start() dlg.Destroy() def OnTimer(self, event, e): print("OnTimmer Inicia") global i global c c = e if (i < c): i += 1 time.sleep(1) self.TimerGo(None) else: print("Termino Timer") self.board.stop_stream() self.stopconexioUltracortex = True self.hiloUltracortesConexion.do_run = False self.hiloUltracortesConexion.join() self.hiloRunTimmer.do_run = False self.stopsaved = True self.hiloMYOSaved.do_run = False self.hiloMYOSaved.join() def TimerGo(self, event): global s global m global t global c s = int(s) m = int(m) if (s < 59): s += 1 elif (s == 59): s = 0 if (m < 59): m += 1 elif (m == 59): m = 0 if (int(s) < 10): s = str(0) + str(s) if (int(s) > 9): s = str(s) t = str(m) + ":" + str(s) self.led.SetValue(t) self.OnTimer(None, c) def conexionMYO(self): print("Realizando Conexión MYO") myo.init() self.hub = myo.Hub() self.listener = EmgCollector(512) self.stopconexion = False self.stopsaved = False print("Conexión MYO Establecida") self.Crear_carpetaMYO() def mainMYO(self): global data_total data_total = [] with self.hub.run_in_background(self.listener.on_event): while True: self.plotMYO() time.sleep(0.1) if (self.stopconexion == True): break def mainSavedMYO(self): global fila fila = 0 with self.hub.run_in_background(self.listener.on_event): while True: self.SaveMYO() time.sleep(2.56) if (self.stopsaved == True): break def plotMYO(self): global graphs emg_data = self.listener.get_emg_data() emg_data = np.array([x[1] for x in emg_data]).T for g, data in zip(self.graphs, emg_data): if len(data) < self.n: data = np.concatenate([np.zeros(self.n - len(data)), data]) g.set_ydata(data) #plt.draw() def SaveMYO(self): global fila global data_total numMuestras = 512 emg_data = self.listener.get_emg_data() emg_data = [x[1] for x in emg_data] with open(os.path.join(carpetaEMG, "datos %d.csv" % j), 'a') as fp: # Guardar datos en el archivo csv for h in range(0, 512): for i in range(0, 8): fp.write(str(emg_data[h][i]) + ";") fp.write("\n") ########################################################################### # Ultracortex def start_board(self): global fila fila = 0 self.board = OpenBCICyton(port='COM8', daisy=False) self.stopconexioUltracortex = False self.stopconexioUltracortexPlot = False self.Crear_carpetaEEG() def mainULTRACORTEX(self): while (self.stopconexioUltracortex == False): self.board.start_stream(self.save_data) print("entro if") self.board.stop_stream() def mainplotUltracortex(self): while (self.stopconexioUltracortexPlot == False): time.sleep(0.1) self.board.start_stream(self.plot_eeg) print("entro if") self.board.stop_stream() def plot_eeg(self, sample): global datosEEG, bp_a, bp_b global graphsEEG self.datosEEG.append( [i * (SCALE_FACTOR) for i in sample.channels_data]) datosEEGplot = np.array(self.datosEEG).T # for o in range (8): # datosEEGplot[o] = signal.lfilter(bp_b, bp_a, datosEEGplot[o]) for g, data in zip(self.graphsEEG, datosEEGplot): if len(data) < self.m: data = np.concatenate([np.zeros(self.m - len(data)), data]) else: data = np.array(data[(len(data) - self.m):]) # dy = (max(data) - min(data))*0.7 # [(ax.set_ylim([min(data)-dy, max(data)+dy])) for ax in self.axesEEG] g.set_ydata(data) #plt.draw()>:V self.board.stop_stream() def save_data(self, sample): global fila global datosEEG, bp_a, bp_b self.datosEEG.append( [i * (SCALE_FACTOR) for i in sample.channels_data]) datosEEGplot = np.array(self.datosEEG).T with open(os.path.join(carpetaEEG, "datos %d.csv" % j), 'a') as fp: # Guardar datos en el archivo csv for i in range(0, 8): fp.write(str(self.datosEEG[fila][i]) + ";") fp.write("\n") fila += 1 def Crear_carpetaEEG(self): global carpetaEEG global j global fila fila = 0 Archivo = True j = 1 Tipo = "PruebaUltracortex" carpetaEEG = f"Base_Datos_{Tipo}" #Creacion de carpetas para guarda archivos si no existe if not os.path.exists(carpetaEEG): os.mkdir(carpetaEEG) while (Archivo == True ): # Se crea un archivo csv en caso de que no exista if os.path.isfile(carpetaEEG + "/datos %d.csv" % j): print('El archivo existe.') j += 1 else: with open(os.path.join(carpetaEEG, "datos %d.csv" % j), 'w') as fp: [fp.write('CH%d ;' % i) for i in range(1, 9)] fp.write("\n") print("Archivo Creado") Archivo = False def Crear_carpetaMYO(self): global carpetaEMG global j global fila fila = 0 Archivo = True j = 1 Tipo = "PruebaMYO" carpetaEMG = f"Base_Datos_{Tipo}" #Creacion de carpetas para guarda archivos si no existe if not os.path.exists(carpetaEMG): os.mkdir(carpetaEMG) while (Archivo == True ): # Se crea un archivo csv en caso de que no exista if os.path.isfile(carpetaEMG + "/datos %d.csv" % j): print('El archivo existe.') j += 1 else: with open(os.path.join(carpetaEMG, "datos %d.csv" % j), 'w') as fp: [fp.write('CH%d ;' % i) for i in range(1, 9)] fp.write("\n") print("Archivo Creado") Archivo = False
else: sys.exit( 'Currently the Ganglion Python repo only works with Linux OS.') else: board = OpenBCIWiFi() valid_commands = '012345678!@#$%^&*qwertyuiQWERTYUI[]pdbsvnN;-=xXDzZASFGHJKLajbs?c<>' while True: command = input('--> ') if str(command).lower() in ['start', 'stream']: print('Starting Board Stream') stream_thread = threading.Thread(target=board.start_stream, args=(callback, ), daemon=True) stream_thread.start() elif str(command).lower() in ['stop']: board.stop_stream() elif str(command).lower() in ['exit']: sys.exit() elif all(c in valid_commands for c in command): try: board.write_command(command) except: raise else: print('Not a valid command')
class OpenBCI(object): def __init__(self, port=None, daisy=None, chunk_size=250, method=1, path=None, createSession=True): ''' Initialize all the variables ''' self.port = port self.daisy = daisy self.chunk_size = chunk_size self.method = method # Read data continously or in chunks of chunk_size print("Starting creating streamer....") self.streamer = BCI(self.port, self.daisy) self.uVolts_per_count = (4.5) / 24 / ( 2**23 - 1 ) * 1000000 # scalar factor to convert raw data into real world signal data #Saving data and naming conventions self.homeFolder = os.getcwd() self.sessionFolder = self.homeFolder + "/SessionData" self.sessionId = time.strftime("SESSION_%Y%m%d_%H%M%S") if (path == None): self.currentSession = self.sessionFolder + "/" + self.sessionId else: self.currentSession = self.sessionFolder + "/" + path print("Building Session Folders....") if (createSession == True): self.makeSessionFolder() def makeSessionFolder(self): if (os.path.isdir(self.sessionFolder) == False): os.mkdir(self.sessionFolder) if (os.path.isdir(self.currentSession) == False): os.mkdir(self.currentSession) def read_chunk(self, n_chunks=1, verbose=False, data_only=True, exit_after=False, save_data=False): ''' - Each chunk is defined by "chunk_size". - "n_chunks" defines how many chunks of data you want. - "data_only" is to say whether you want only the numeric signal data or you want the entire sample points. - "exit_after" is for if you want to close the stream after reading the data. - "save_data" if you want to save the raw data some where Create a numpy array if the user is requesting for data only Use lists if you entire object of the sample. The output of this function is an array of shape: (n_chunks,chunk_size,n_channels) ''' if (data_only == True): t = 0 data = np.zeros(shape=(1, self.chunk_size, 8)) for i in range(n_chunks): if verbose: print("Reading Chunk: %d " % (i + 1)) sample = self.streamer.start_stream_ext( method=self.method, chunk_size=self.chunk_size, data_only=data_only) sample = np.expand_dims(np.asarray(sample), 0) data = np.append(data, sample, 0) data = data[1:] data = data * self.uVolts_per_count if (exit_after == True): self.streamer.stop_stream() if (save_data == True): t = time.strftime("%Y%m%d_%H%M%S") np.save(self.currentSession + "/RawData_" + t, data) #return (data.transpose(0,2,1),self.currentSession,t) return data.transpose(0, 2, 1) else: data = [] for i in range(n_chunks): print("Reading Chunk: %d " % (i + 1)) sample = self.streamer.start_stream_ext( method=self.method, chunk_size=self.chunk_size, data_only=data_only) data.append(sample) if (exit_after == True): self.streamer.stop_stream() if (save_data == True): t = time.strftime("%Y%m%d_%H%M%D") with open(self.currentSession + "/RawData_" + t + ".pickle", 'w') as f: pickle.dump(data, f) return data