def __init__(self): self.value = 0 self.counter = 0 self.skip_value = 0 self.data_array = [0.000] * 1024 self.neuro_object = NeuroPy("COM15") self.caller()
def mindWave(duration): mind = NeuroPy("/dev/tty.MindWaveMobile-DevA", 57600) mind.start() cur_time = time() while time() < cur_time + duration: cur.execute("INSERT INTO Waves VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (time(), mind.delta, mind.theta, mind.lowAlpha, mind.highAlpha, mind.lowBeta, mind.highBeta, mind.lowGamma, mind.midGamma, mind.attention, mind.meditation)) sleep(0.5)
def start_data_collection(serial_port, num_seconds=-1): headset_obj = NP.NeuroPy(serial_port, 9600, log=False) headset_obj.setCallBack("attention", generic_callback) headset_obj.setCallBack("meditation", generic_callback) headset_obj.setCallBack("rawValue", generic_callback) headset_obj.setCallBack("delta", generic_callback) headset_obj.setCallBack("theta", generic_callback) headset_obj.setCallBack("lowAlpha", generic_callback) headset_obj.setCallBack("highAlpha", generic_callback) headset_obj.setCallBack("lowBeta", generic_callback) headset_obj.setCallBack("highBeta", generic_callback) headset_obj.setCallBack("lowGamma", generic_callback) headset_obj.setCallBack("midGamma", generic_callback) headset_obj.setCallBack("poorSignal", generic_callback) headset_obj.setCallBack("blinkStrength", generic_callback) headset_obj.start() if num_seconds != -1: time.sleep(num_seconds) headset_obj.stop() if num_seconds != -1: time.sleep(num_seconds) headset_obj.stop()
def main(): print("hallo hallo") object1 = NeuroPy("/dev/rfcomm0") object1.setCallBack("attention", attention_callback) object1.start() while True: if (object1.meditation > 70): object1.stop()
def collect(port, user_id): """Collect attention and meditation values from NeuroSky headset & store to database""" print "You have reached the beginning of this function!" port = str(port) headset_data = NeuroPy("/dev/cu.MindWaveMobile-DevA-" + port, 57600) headset_data.start() current_time = time.time() start_time = time.time() elapsed_time = current_time + 30 # Collect data from headset for an elapsed time of a minute. new_session = Session(utc=datetime.datetime.utcnow(), user_id=user_id) # TODO: figure out how to get current_user # current_user.sessions.append(new_session) # db.session.add(current_user) # db.session.add(new_session) # db.session.commit() print new_session.id # Add session to database first. # In the while loop, save attention and meditation data to database. while current_time < elapsed_time: attention = headset_data.attention # print attention current_time = time.time() # print current_time, elapsed_time meditation = headset_data.meditation new_state = State(utc=datetime.datetime.utcnow(), attention=attention, meditation=meditation, session_id=new_session.id) # db.session.add(new_state) # db.session.commit() new_session.states.append(new_state) time.sleep(3) # Collect data every 3 seconds. new_session.generate_high_score() db.session.add(new_session) db.session.commit() # headset_data.stop() # print attention return
def startBCI(): object1=NeuroPy("COM6") #set call back: object1.setCallBack("attention",attention_callback) #start method object1.start() return None
def main(): neuropy = NeuroPy("/dev/rfcomm0") #instantiate NeuroPy class neuropy.start() #start thread start_time = 0 blinked = False #if blink is detected last_blink_time = 0 double_blink = False triple_blink = False i = 100 j = 100 try: while i < 20000: i = i + 1 value = neuropy.rawValue #gets the raw brain activity level print value, " ", i if value > 100: #if the raw level gets above 200, which indicates a spike, start the clock start_time = time.clock() #print value if start_time: if value < -100: #if the spike in brain activity is over total_time = time.clock() - start_time #how long the spike was start_time = 0 if 0.01 < total_time < 0.050: #if the spike was a certain length if last_blink_time and time.clock() - last_blink_time < .6: #if the blink occured right after the previous blink if double_blink: triple_blink = True else : double_blink = True last_blink_time = time.clock() #reset the clock i+=1 blinked = True if blinked and time.clock()-last_blink_time > .61: #if a certain amount of time has passed since the last blink if triple_blink: print "Triple blink detected .......... turning left" motor.forward_left() time.sleep(3) motor.forward() break elif double_blink: print "Double blink detected ........... turning right" motor.forward_right() time.sleep(3) motor.forward() break double_blink = blinked = triple_blink = False time.sleep(2) return finally: neuropy.stop()
class Nsky(): def __init__(self): self.value = 0 self.counter = 0 self.skip_value = 0 self.data_array = [0.000] * 1024 self.neuro_object = NeuroPy("COM15") self.caller() def attention_callback(self, attention_value): if (self.neuro_object.attention >= 15 and self.neuro_object.meditation >= 15 and self.neuro_object.poorSignal == 0): self.counter += 1 for i in range(len(self.data_array) - 1): self.data_array[i] = self.data_array[i + 1] self.data_array[1023] = attention_value if (self.counter == 1024): if (self.skip_value == 0): self.skip_value = 1 self.value = input( "(0 for left and 1 for right and 2 for ntg)") self.counter = 0 if self.value == 3: self.neuro_object.stop() return None with open('traindata.csv', 'ab') as datafile: writer = csv.writer(datafile) writer.writerow([ self.neuro_object.attention, self.neuro_object.meditation, self.neuro_object.poorSignal, self.data_array, self.value ]) self.value = input( "(0 for left and 1 for right and 2 for ntg)") self.counter = 0 return None def caller(self): #set call back: self.neuro_object.setCallBack("rawValue", self.attention_callback) #call start method self.value = input("(0 for left and 1 for right and 2 for ntg)") self.neuro_object.start() while True: if ( self.neuro_object.meditation > 100 ): #another way of accessing data provided by headset (1st being call backs) print("geda meditationg too much")
class MyWin(QtWidgets.QMainWindow): started = False ncolors = 256 colors_by_att = False MindWave_obj = NeuroPy("COM3") cam = cv2.VideoCapture() pwidth, pheight = 0, 0 pil_img = Image.init() pixmap = QtGui.QPixmap def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle("Color levels | PyQt | OpenCV | NeuroSky MindWave") self.setGeometry(400, 100, 1241, 820) self.ui.pushButton_3.clicked.connect(self.Ext) self.ui.pushButton_4.clicked.connect(self.loadImage) self.ui.pushButton_5.clicked.connect(self.saveImage) self.ui.horizontalSlider.setValue(self.ncolors) self.ui.horizontalSlider.valueChanged.connect(self.colorsChanged) self.ui.checkBox.stateChanged.connect(self.colorsModeChanged) self.ui.checkBox_2.stateChanged.connect(self.cameraModeChanged) self.pwidth = self.ui.label.width() self.pheight = self.ui.label.height() self.pil_img = Image.open("eye.jpg") self.pixmap = QtGui.QPixmap.fromImage( self.pilImgToQImg_resized(self.pil_img)) self.ui.label.setPixmap(self.pixmap) if not self.MindWave_obj.threadRun: try: self.MindWave_obj.start() self.statusBar().showMessage(" === MindWave connected! === ") except: self.statusBar().showMessage( " === Connection to MindWave failed! === ") def pilImgToQImg_resized(self, pilimg): """ convert Pillow Image to QImage and resize choosen image to window area """ ocvimg = cv2.cvtColor(np.array(pilimg), cv2.COLOR_RGB2BGR) dim = (self.pwidth, self.pheight) resized = cv2.resize(ocvimg, dim, interpolation=cv2.INTER_AREA) self.pil_img = Image.fromarray(cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)) return QtGui.QImage(resized, resized.shape[1], resized.shape[0], resized.shape[1] * 3, QtGui.QImage.Format_RGB888).rgbSwapped() def saveImage(self): """ save current transformation of image to file """ fileName, _ = QFileDialog.getSaveFileName( self, "QFileDialog.getSaveeFileName()", "", "Image Files (*.jpg *.png *.bmp)") if fileName: self.pixmap.save(fileName) def loadImage(self): """ load image from file """ fileName, _ = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", "", "Image Files (*.jpg *.png *.bmp)") if fileName: self.pil_img = Image.open(fileName) self.pixmap = QtGui.QPixmap.fromImage( self.pilImgToQImg_resized(self.pil_img)) self.ui.label.setPixmap(self.pixmap) def cameraModeChanged(self): """ turn on / off camera input """ if not self.cam.isOpened(): self.cam.open(0) self.started = True else: self.started = False self.cam.release() def colorsModeChanged(self): """ turn on / off color levels dependency on attention level (obtained from EEG device) """ self.colors_by_att = not self.colors_by_att def colorsChanged(self): """ processing change of color levels """ self.ncolors = self.ui.horizontalSlider.value() self.ui.progressBar.setValue(self.MindWave_obj.attention) self.ui.label_3.setText("COLOR LEVELS: " + str(self.ncolors)) if not self.started: t_pil_img = self.pil_img.convert( 'P', palette=Image.ADAPTIVE, colors=self.ncolors).convert('RGB') im = t_pil_img.convert("RGBA") data = im.tobytes("raw", "RGBA") qim = QtGui.QImage(data, im.size[0], im.size[1], QtGui.QImage.Format_RGBA8888) self.pixmap = QtGui.QPixmap.fromImage(qim) self.ui.label.setPixmap(self.pixmap) def update_flow(self): """ update attention value and processing camera input for transformation """ self.ui.progressBar.setValue(self.MindWave_obj.attention) if self.started: ret, frame = self.cam.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) t_pil_img = Image.fromarray(frame) t_pil_img = t_pil_img.convert('P', palette=Image.ADAPTIVE, colors=self.ncolors).convert('RGB') im = t_pil_img.convert("RGBA") data = im.tobytes("raw", "RGBA") qim = QtGui.QImage(data, im.size[0], im.size[1], QtGui.QImage.Format_RGBA8888) self.pixmap = QtGui.QPixmap.fromImage(qim).scaled( self.pwidth, self.pheight, QtCore.Qt.IgnoreAspectRatio) self.ui.label.setPixmap(self.pixmap) if self.MindWave_obj.attention > 0: if self.colors_by_att: self.ncolors = self.MindWave_obj.attention self.ui.horizontalSlider.setValue(self.ncolors) def Ext(self): """ exit the application """ sys.exit()
from NeuroPy import NeuroPy import threading def stoppa(a): a.stop() a.save() #Rilassamento 438 secs a 1min #Musica metal 200 secs da 25sec #Logica 200 da 0 #Memoria 200 da 0 person_name = input('Nome dell\'utente: ') task_name = input('Nome del task: ') task_duration = input('Durata del task(sec):') record = NeuroPy("COM3", person_name=person_name, task_name=task_name, task_duration=task_duration) threading.Timer(int(task_duration), stoppa, [record]).start() record.start()
# -*- coding: utf-8 -*- from NeuroPy import NeuroPy from time import sleep import threading from api_service import * neuropy = NeuroPy("COM4") # type: NeuroPy #neuropy = NeuroPy("/dev/rfcomm0",57600) # type: NeuroPy def attention_callback(attention_value): """this function will be called everytime NeuroPy has a new value for attention""" print("Value of attention is: ", attention_value) return 0 def meditation_callback(meditation_value): """this function will be called everytime NeuroPy has a new value for attention""" print("Value of meditation is: ", meditation_value) return 1 def rawValue_callback(rawValue_value): """this function will be called everytime NeuroPy has a new value for attention""" # print ("Value of rawValue is: ", rawValue_value) return 2 def delta_callback(delta_value): """this function will be called everytime NeuroPy has a new value for attention""" print("Value of delta is: ", delta_value)
def __init__(self, parent=None, sensorNUmber=0): #sensorNUmber - rfcomm port number - 0 for rfcomm0 etc super(BrainWindow, self).__init__(parent) self.sensorNUmber = sensorNUmber self.setWindowTitle(u"Mindwave"+str(self.sensorNUmber)) layout = QGridLayout() layout.addWidget(QLabel("Value"),0,1) layout.addWidget(QLabel("Min"),0,2) layout.addWidget(QLabel("Max"),0,3) layout.addWidget(QLabel("Relative"),0,4) layout.addWidget(QLabel("Attention:"),1,0) layout.addWidget(QLabel("Poor signal:"),1,2) layout.addWidget(QLabel("Low beta"),2,0) layout.addWidget(QLabel("High beta"),3,0) layout.addWidget(QLabel("Low gamma"),4,0) layout.addWidget(QLabel("Mid gamma"),5,0) layout.addWidget(QLabel("Raw data:"),6,0) self.attentionLabel = QLabel() layout.addWidget(self.attentionLabel,1,1) self.poorSignalLabel = QLabel() layout.addWidget(self.poorSignalLabel,1,3) self.lBetaLabel = QLabel() self.lBetaMinLabel = QLabel() self.lBetaMaxLabel = QLabel() self.lBetaRelLabel = QLabel() layout.addWidget(self.lBetaLabel,2,1) layout.addWidget(self.lBetaMinLabel,2,2) layout.addWidget(self.lBetaMaxLabel,2,3) layout.addWidget(self.lBetaRelLabel,2,4) self.hBetaLabel = QLabel() self.hBetaMinLabel = QLabel() self.hBetaMaxLabel = QLabel() self.hBetaRelLabel = QLabel() layout.addWidget(self.hBetaLabel,3,1) layout.addWidget(self.hBetaMinLabel,3,2) layout.addWidget(self.hBetaMaxLabel,3,3) layout.addWidget(self.hBetaRelLabel,3,4) self.lGammaLabel = QLabel() self.lGammaMinLabel = QLabel() self.lGammaMaxLabel = QLabel() self.lGammaRelLabel = QLabel() layout.addWidget(self.lGammaLabel,4,1) layout.addWidget(self.lGammaMinLabel,4,2) layout.addWidget(self.lGammaMaxLabel,4,3) layout.addWidget(self.lGammaRelLabel,4,4) self.mGammaLabel = QLabel() self.mGammaMinLabel = QLabel() self.mGammaMaxLabel = QLabel() self.mGammaRelLabel = QLabel() layout.addWidget(self.mGammaLabel,5,1) layout.addWidget(self.mGammaMinLabel,5,2) layout.addWidget(self.mGammaMaxLabel,5,3) layout.addWidget(self.mGammaRelLabel,5,4) #stop stopButton = QPushButton("Stop") stopButton.clicked.connect(self.stop) layout.addWidget(stopButton,7,0) self.setLayout(layout) self.headSet = NeuroPy("/dev/rfcomm"+str(sensorNUmber),57600) self.headSet.setCallBack("attention",self.attention_callback) self.headSet.setCallBack("lowBeta",self.lowBeta_callback) self.headSet.setCallBack("highBeta",self.highBeta_callback) self.headSet.setCallBack("lowGamma",self.lowGamma_callback) self.headSet.setCallBack("midGamma",self.midGamma_callback) self.headSet.setCallBack("rawValue",self.rawValue_callback) self.headSet.setCallBack("poorSignal",self.poorSignal_callback) self.headSet.start() self.highLimit = 100000 # ignore occasional higher values from EEG data self.lowLimit = 100 self.lBetamin = 10000 self.lBetamax = 0.1 self.lBetarelative = 0 self.hBetamin = 10000 self.hBetamax = 0.1 self.hBetarelative = 0 self.lGammamin = 10000 self.lGammamax = 0.1 self.lGammarelative = 0 self.mGammamin = 10000 self.mGammamax = 0.1 self.mGammarelative = 0
''' attention, meditation, rawValue, delta, theta, lowAlpha, highAlpha, lowBeta, highBeta, lowGamma, midGamma, poorSignal, blinkStrength $ pip install pyserial $ pip install NeuroPy $ pip install pyosc ''' from NeuroPy import NeuroPy import OSC import time neuroPy = NeuroPy("/dev/rfcomm0", 57600) neuroPy.start() oscClient = OSC.OSCClient() oscClient.connect(('127.0.0.1', 57120)) while True: attention = neuroPy.attention meditation = neuroPy.meditation oscMsg = OSC.OSCMessage() oscMsg.setAddress("/neuro") oscMsg.append([attention, meditation]) oscClient.send(oscMsg) print "attention: " + str(attention) + " - " + "meditation: " + str( meditation)
def PostRequest(request_body): # 构造服务接口地址 url = 'http://localhost:{0}/'.format(6000) r0 = requests.post(url=url, json=request_body) # print(r0.json()) pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True) r = redis.Redis(connection_pool=pool) serport = FindSerialDevice("Select the Serial port: ") ser = serial.Serial(serport, 9600, timeout=1) mindwaveport = FindSerialDevice("Select the Mindwave port: ") bluetooth_baund_rate = input( 'bluetooth baund rate (default: 57600) >') or 57600 mindwave = NeuroPy(mindwaveport, bluetooth_baund_rate) jsonlist = [] jsonlist1 = [] list = [] if ser.is_open: ser.flushOutput() ser.flushInput() try: mindwave.start() while 1: ser.flushOutput() now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') response = ser.readline().decode().strip() low_alpha = mindwave.low_alpha
def __init__(self, aantal_avg, interval, com_port_mindwave): self.aantal_avg = aantal_avg self.interval = interval self.com = com_port_mindwave self.mindwave_instance = NeuroPy(self.com) self.mindwave_instance.start()
# Connect to Mindwave to computer first # Call neuropy.start() to get data. # Neuropy.stop() to stop from NeuroPy import NeuroPy import numpy as np import matplotlib.pyplot as plt import mindwave, time neuropy = NeuroPy() neuropy.start() then = time.time() now = time.time() plt.axis([-2000, 2000, 0, 50]) plt.ion() #connects the path(usb) and the specific serial number of your mindwave headset = mindwave.Headset('COM5', 'CC0E') time.sleep(2) #connecting the mindwave headset.connect() print("Pairing...") while mindwave.status != "Paired!": time.sleep(2) if mindwave.status == "Standing by...": mindwave.connect() print("Retrying...") print("Paired!")
def predict(model, scl, inpt): inpt = inpt.reshape(1, -1) inpt = scl.transform(inpt) inpt = torch.FloatTensor(inpt) out = model(inpt) y_test_pred = torch.sigmoid(out) y_pred_tag = torch.round(y_test_pred) return y_pred_tag.item() model, scaler = load_model('model_no_jump_hist40.pth', 'scaler_no_jump_hist40.scl') neuropy = mp.NeuroPy(port='COM4') results = Attrdict() def set_callback(neuropy, name, print_result=False, function=None): def default_function(value): results[name] = value if print_result: print(name, value) results[name] = 0 selected_function = function if function else default_function neuropy.setCallBack(name, selected_function) is_pressed_manually = False
#code to obtain data from NeuroPy import NeuroPy import time datafile = open("testdata.txt", "w+") object = NeuroPy("COM11", 57600) #Start communication object.start() f = 200 #set sampling frequency t = 2 #set sampling time N = f * 2 #no of sample points datafile.write('%d\n' % f) datafile.write('%d\n' % N) i = 0 while i < N: datafile.write('%d\n' % object.rawValue) time.sleep(1 / f) i = i + 1 datafile.close()
''' Created on 6 Jan 2014 @author: Maged ''' from NeuroPy import NeuroPy import serial object1=NeuroPy("COM14") # Port connecting to Neurosky bluetooth ser = serial.Serial(41) # Port to send data on (to serial DUE USB = 12, serial UNO = 42 / Bluetooth shield = variable) max = 2 idx = max sum = 0 def blink_callBack(blink_rate): print "Blink rate is", blink_rate return None def attention_callback(attention_value): "this function will be called everytime NeuroPy has a new value for attention" global idx, sum if idx > 0: idx= idx -1 sum = sum + attention_value return None else: idx = max print "Average value of attention is", sum/max #do other stuff (fire a rocket), based on the obtained value of attention_value #do some more stuff
from NeuroPy import NeuroPy import time import socket import sys eyesOption = ['eyes_open', 'eyes_closed'] alphaOption = ['lowAlpha', 'highAlpha'] object1 = NeuroPy("COM3") #If port not given 57600 is automatically assumed #object1=NeuroPy("/dev/rfcomm0") for linux ''' def attention_callback(attention_value): "this function will be called everytime NeuroPy has a new value for attention" print "Value of attention is",attention_value #do other stuff (fire a rocket), based on the obtained value of attention_value #do some more stuff return None ''' #for each callback, store value into textfile def highalpha_callback(highAlpha_value): print "Value of highAlpha is ", highAlpha_value file_name = str(eyesOption[0]) + '-' + str(alphaOption[1]) with open(file_name, 'a') as f: f.write(str(highAlpha_value) + '\n') def lowalpha_callback(lowAlpha_value): print "Value of lowAlpha is ", lowAlpha_value
class MindwaveTracker: com = "COM16" time_last_notified = time.clock() MAX_ZERO_VALUES_BEFORE_WARNING = 10 attention_value = 0 meditation_value = 0 poorSignal = 0 blinkStrength = 0 index = 0 aantal_avg = 0 interval = 0 teller_duration_iteration_sec = 0.0 datetime_from = datetime.datetime.today() teller_zero_values = 0 mindwave_instance = None def __init__(self, aantal_avg, interval, com_port_mindwave): self.aantal_avg = aantal_avg self.interval = interval self.com = com_port_mindwave self.mindwave_instance = NeuroPy(self.com) self.mindwave_instance.start() def notify(self): time_now = time.clock() duration_iteration_sec = time_now - self.time_last_notified self.time_last_notified = time.clock() self.teller_duration_iteration_sec += duration_iteration_sec if self.teller_duration_iteration_sec >= self.interval: self.teller_duration_iteration_sec = 0.0 self.record_measurement() def record_measurement(self): print str( str('attention: ' + str(self.mindwave_instance.attention)) + '\t' + str('meditation: ' + str(self.mindwave_instance.meditation))) if (self.index == self.aantal_avg): print str('avg attention: ' + str(float(self.attention_value / self.aantal_avg))) average_attention = float( self.attention_value / self.aantal_avg) / 100 average_meditation = float( self.meditation_value / self.aantal_avg) / 100 average_poorSignal = float(self.poorSignal / self.aantal_avg) average_blinkStrength = float(self.blinkStrength / self.aantal_avg) datetime_to = datetime.datetime.today() DAMindwave_SQLite.insert_row_mindwave( self.datetime_from, datetime_to, average_attention, average_meditation, average_poorSignal, average_blinkStrength) self.attention_value = self.mindwave_instance.attention self.meditation_value = self.mindwave_instance.meditation self.poorSignal = self.mindwave_instance.poorSignal self.blinkStrength = self.mindwave_instance.blinkStrength self.index = 1 self.datetime_from = datetime.datetime.today() else: if self.mindwave_instance.attention != 0 and self.mindwave_instance.meditation != 0: self.attention_value += self.mindwave_instance.attention self.meditation_value += self.mindwave_instance.meditation self.poorSignal += self.mindwave_instance.poorSignal self.blinkStrength += self.mindwave_instance.blinkStrength self.index += 1 else: self.teller_zero_values += 1 if self.teller_zero_values == self.MAX_ZERO_VALUES_BEFORE_WARNING: tkMessageBox.showinfo( title="Warning", message= "The attention and meditation values are 0 for a long time. Possible problem with the device" ) self.teller_zero_values = 0 def stop_device(self): try: self.mindwave_instance.stop() except Exception, e: raise Exception(e)
from NeuroPy import NeuroPy from time import sleep from threading import Timer def end_reading(): file_at.close() # file_me.close() # file_bl.close() neuropy.stop() neuropy = NeuroPy('COM4') neuropy.start() t = Timer(10.0, end_reading) file_at = open('data-bl.txt', 'w') t.start() while True: file_at.write(str(neuropy.blink)) file_at.write('\n') sleep(0.2)
import serial import time from NeuroPy import NeuroPy ser = serial.Serial(port='COM5', baudrate=9600) #set the Arduino port connection object1 = NeuroPy("COM4", 57600) #set the MindWave headset portconnection #change ports if needed object1.start() #start reading from the MindWave headset #t_end = time.time() + 60 * 1 to define time for the while-loop if needed print 'Are you ready to break a spoon bitch !!!' a = input('Shall we continue sucker ?') #request a keyboard input, which is '' to continue with the script #this is done to allow time for the servo to go to the initial position try: while True: if object1.attention > 40: #this statement tells the arduino to start moving the motor if #attention level is over 40 (attention level varies 0-100) ser.write('5') time.sleep(0.5) #0.5s time delay to make consistent and smooth movement of the motor print object1.attention else: #this statement tells the arduino to stop moving the motor if # attention level is bellow the threshold time.sleep(0.5) # another time delay for consistency
import time import json import socket from NeuroPy import NeuroPy s = socket.socket() host = 'localhost' port = 6969 # print ("Host", host) s.connect((host, port)) object1=NeuroPy("/dev/rfcomm0", 57600) def attention_callback(attention_value): print ("Value of attention is", attention_value) data = {} data['type'] = 'attention' data['value'] = str(attention_value) json_data = json.dumps(data) s.send(json_data) return None def meditation_callback(meditation_value): print ("Value of meditation is", meditation_value) data = {} data['type'] = 'meditation' data['value'] = str(meditation_value) json_data = json.dumps(data)
from NeuroPy import NeuroPy from time import sleep import serial neuropy = NeuroPy(port='/dev/tty.MindWaveMobile-SerialPo') def attention_callback(attention_value): """this function will be called everytime NeuroPy has a new value for attention""" print "Value of attention is: ", attention_value return None neuropy.setCallBack("attention", attention_callback) # neuropy.__srl = serial.Serial( # '/dev/tty.MindWaveMobile-SerialPo', 57600) #neuropy.__srl.flushInput() neuropy.start() print('Sleeping for 10 seconds') sleep(10) try: while True: sleep(1) finally: neuropy.stop()
class BrainWindow(QWidget): def __init__(self, parent=None, sensorNUmber=0): #sensorNUmber - rfcomm port number - 0 for rfcomm0 etc super(BrainWindow, self).__init__(parent) self.sensorNUmber = sensorNUmber self.setWindowTitle(u"Mindwave"+str(self.sensorNUmber)) layout = QGridLayout() layout.addWidget(QLabel("Value"),0,1) layout.addWidget(QLabel("Min"),0,2) layout.addWidget(QLabel("Max"),0,3) layout.addWidget(QLabel("Relative"),0,4) layout.addWidget(QLabel("Attention:"),1,0) layout.addWidget(QLabel("Poor signal:"),1,2) layout.addWidget(QLabel("Low beta"),2,0) layout.addWidget(QLabel("High beta"),3,0) layout.addWidget(QLabel("Low gamma"),4,0) layout.addWidget(QLabel("Mid gamma"),5,0) layout.addWidget(QLabel("Raw data:"),6,0) self.attentionLabel = QLabel() layout.addWidget(self.attentionLabel,1,1) self.poorSignalLabel = QLabel() layout.addWidget(self.poorSignalLabel,1,3) self.lBetaLabel = QLabel() self.lBetaMinLabel = QLabel() self.lBetaMaxLabel = QLabel() self.lBetaRelLabel = QLabel() layout.addWidget(self.lBetaLabel,2,1) layout.addWidget(self.lBetaMinLabel,2,2) layout.addWidget(self.lBetaMaxLabel,2,3) layout.addWidget(self.lBetaRelLabel,2,4) self.hBetaLabel = QLabel() self.hBetaMinLabel = QLabel() self.hBetaMaxLabel = QLabel() self.hBetaRelLabel = QLabel() layout.addWidget(self.hBetaLabel,3,1) layout.addWidget(self.hBetaMinLabel,3,2) layout.addWidget(self.hBetaMaxLabel,3,3) layout.addWidget(self.hBetaRelLabel,3,4) self.lGammaLabel = QLabel() self.lGammaMinLabel = QLabel() self.lGammaMaxLabel = QLabel() self.lGammaRelLabel = QLabel() layout.addWidget(self.lGammaLabel,4,1) layout.addWidget(self.lGammaMinLabel,4,2) layout.addWidget(self.lGammaMaxLabel,4,3) layout.addWidget(self.lGammaRelLabel,4,4) self.mGammaLabel = QLabel() self.mGammaMinLabel = QLabel() self.mGammaMaxLabel = QLabel() self.mGammaRelLabel = QLabel() layout.addWidget(self.mGammaLabel,5,1) layout.addWidget(self.mGammaMinLabel,5,2) layout.addWidget(self.mGammaMaxLabel,5,3) layout.addWidget(self.mGammaRelLabel,5,4) #stop stopButton = QPushButton("Stop") stopButton.clicked.connect(self.stop) layout.addWidget(stopButton,7,0) self.setLayout(layout) self.headSet = NeuroPy("/dev/rfcomm"+str(sensorNUmber),57600) self.headSet.setCallBack("attention",self.attention_callback) self.headSet.setCallBack("lowBeta",self.lowBeta_callback) self.headSet.setCallBack("highBeta",self.highBeta_callback) self.headSet.setCallBack("lowGamma",self.lowGamma_callback) self.headSet.setCallBack("midGamma",self.midGamma_callback) self.headSet.setCallBack("rawValue",self.rawValue_callback) self.headSet.setCallBack("poorSignal",self.poorSignal_callback) self.headSet.start() self.highLimit = 100000 # ignore occasional higher values from EEG data self.lowLimit = 100 self.lBetamin = 10000 self.lBetamax = 0.1 self.lBetarelative = 0 self.hBetamin = 10000 self.hBetamax = 0.1 self.hBetarelative = 0 self.lGammamin = 10000 self.lGammamax = 0.1 self.lGammarelative = 0 self.mGammamin = 10000 self.mGammamax = 0.1 self.mGammarelative = 0 def __del__(self): self.stop() def stop(self): self.headSet.stop() #self.perf.Stop() #self.perf.Join() #self.cs.Stop() #TEMPORARY -delete later def lowBeta_callback(self, value): #print "Low beta: ", value if (value>self.highLimit or value<self.lowLimit): # don't handle occasional high values return self.lBetaLabel.setText(str(value)) if (value<self.lBetamin and value!=0): self.lBetamin = value self.lBetaMinLabel.setText(str(value)) if (value>self.lBetamax): self.lBetamax = value self.lBetaMaxLabel.setText(str(value)) self.lBetarelative = float(value-self.lBetamin)/(self.lBetamax-self.lBetamin+1) self.lBetaRelLabel.setText(str(self.lBetarelative)) sendUdpMessage("sensor,lb"+str(self.sensorNUmber+1)+","+str(self.lBetarelative)) #self.cs.SetChannel("lowBetaRelative",self.lBetarelative) return None def highBeta_callback(self, value): #print "high beta: ", value if (value>self.highLimit or value<self.lowLimit): # don't handle occasional high values return self.hBetaLabel.setText(str(value)) if (value<self.hBetamin and value!=0): self.hBetamin = value self.hBetaMinLabel.setText(str(value)) if (value>self.hBetamax): self.hBetamax = value self.hBetaMaxLabel.setText(str(value)) self.hBetarelative = float(value-self.hBetamin)/(self.hBetamax-self.hBetamin+1) self.hBetaRelLabel.setText(str(self.hBetarelative)) sendUdpMessage("sensor,hb"+str(self.sensorNUmber+1)+","+str(self.hBetarelative)) #self.cs.SetChannel("highBetaRelative",self.hBetarelative) return None def lowGamma_callback(self, value): #print "Low gamma: ", value if (value>self.highLimit or value<self.lowLimit): # don't handle occasional high values return self.lGammaLabel.setText(str(value)) if (value<self.lGammamin and value!=0): self.lGammamin = value self.lGammaMinLabel.setText(str(value)) if (value>self.lGammamax): self.lGammamax = value self.lGammaMaxLabel.setText(str(value)) self.lGammarelative = float(value-self.lGammamin)/(self.lGammamax-self.lGammamin+1) self.lGammaRelLabel.setText(str(self.lGammarelative)) #self.cs.SetChannel("lowBetaRelative",self.lGammarelative) return None def midGamma_callback(self, value): #print "mid gamma: ", value if (value>self.highLimit or value<self.lowLimit): # don't handle occasional high values return self.mGammaLabel.setText(str(value)) if (value<self.mGammamin and value!=0): self.mGammamin = value self.mGammaMinLabel.setText(str(value)) if (value>self.mGammamax): self.mGammamax = value self.mGammaMaxLabel.setText(str(value)) self.mGammarelative = float(value-self.mGammamin)/(self.mGammamax-self.mGammamin+1) self.mGammaRelLabel.setText(str(self.mGammarelative)) #self.cs.SetChannel("midmGammaRelative",self.mGammarelative) return None def attention_callback(self, value): #print "Attention: ",value self.attentionLabel.setText(str(value)) sendUdpMessage("sensor,attention"+str(self.sensorNUmber+1)+","+str(float(value)/100)) #self.cs.SetChannel("attention",value) return None def rawValue_callback(self, value): #this is very fast don't print this #print "rawValue: ", value #self.cs.SetChannel("rawValue",value) if (abs(value)<1000): sendUdpMessage("sensor,raw"+str(self.sensorNUmber+1)+","+str(value)) return None def poorSignal_callback(self,value): print "headset: ",self.sensorNUmber,"poor signal: ",value self.poorSignalLabel.setText(str(value))
from NeuroPy import NeuroPy import time eyesOption = ['eyes_open','eyes_closed'] alphaOption = ['lowAlpha','highAlpha'] object1=NeuroPy("COM3") #If port not given 57600 is automatically assumed #object1=NeuroPy("/dev/rfcomm0") for linux ''' def attention_callback(attention_value): "this function will be called everytime NeuroPy has a new value for attention" print "Value of attention is",attention_value #do other stuff (fire a rocket), based on the obtained value of attention_value #do some more stuff return None ''' #for each callback, store value into textfile def highalpha_callback(highAlpha_value): print "Value of highAlpha is ", highAlpha_value file_name = str(eyesOption[0]) + '-' + str(alphaOption[1]) with open (file_name,'a') as f: f.write(str(highAlpha_value)+ '\n') def lowalpha_callback(lowAlpha_value): print "Value of lowAlpha is ", lowAlpha_value file_name = str(eyesOption[0]) + '-' + str(alphaOption[0])
from NeuroPy import NeuroPy import time import matplotlib.pyplot as plt import matplotlib.animation as animation neuropy = NeuroPy("COM3") # Specify COM Port neuropy.start() fig = plt.figure() t = 0 meditation = [] x_time = [] print("=============================") def animate(i): global t global meditation if t == 300: # preset: 300(sec) con = input("Continue (Y/N)? ") if con == 'N': with open('BrainWave/BrainWave.csv', 'w') as w: meditation = str(meditation) meditation = meditation.split() for i in range(len(meditation)):
class neural(): data2 = pd.read_csv('dataset4.csv', names=['att', 'med', 'poo', 'rawValue', 'label']) X_test = data2.rawValue.tolist() # plot 4 images as gray scale tsts2 = [] for i in range(len(X_test)): temp = literal_eval(X_test[i]) temp2 = np.array(temp) tsts2.append(temp2) X_test = np.array(tsts2) X_test = X_test.reshape(len(X_test), 1, 8) json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model loaded_model.load_weights("model.h5") print("Loaded model from disk") # evaluate loaded model on test data loaded_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) sleep(1) print("taking input started") object1 = NeuroPy("COM11") def attention_callback(attention_value): win = GraphWin('Face', 200, 150) # give title and dimensions win.yUp() # make right side up coordinates! head = Circle(Point(40, 100), 25) # set center and radius head.setFill("yellow") head.draw(win) if (object1.attention >= 5 and object1.meditation >= 5): print(object1.poorSignal) temp = [ object1.delta, object1.theta, object1.lowAlpha, object1.highAlpha, object1.lowBeta, object1.highBeta, object1.lowGamma, object1.midGamma ] #with open('dataset3.csv', 'ab') as f: #writer = csv.writer(f) #writer.writerow([object1.attention, object1.meditation, object1.poorSignal, temp, 0]) temp2 = [temp] temp2 = np.array(temp2) temp2 = temp2.reshape(len(temp2), 1, 8) ynew = loaded_model.predict_proba(temp2) print("X=%s, Predicted=%s" % (temp2, ynew)) if (ynew[0][0] > 0.69): print("left") eye1 = Circle(Point(30, 105), 5) eye1.setFill('blue') eye1.draw(win) if (ynew[0][1] > 0.69): print("right") eye2 = Line(Point(45, 105), Point(55, 105)) # set endpoints eye2.setWidth(3) eye2.draw(win) return None #set call back: object1.setCallBack("delta", attention_callback) #call start method object1.start() while True: if ( object1.meditation > 100 ): #another way of accessing data provided by headset (1st being call backs) print("geda meditationg too much") #object1.stop() #if meditation level reaches above 70, stop fetching data from the headset
from NeuroPy import NeuroPy object1=NeuroPy("/dev/rfcomm0") #If port not given 57600 is automatically assumed #object1=NeuroPy("/dev/rfcomm0") for linux def attention_callback(attention_value): "this function will be called everytime NeuroPy has a new value for attention" print ("Value of attention is",attention_value) #do other stuff (fire a rocket), based on the obtained value of attention_value #do some more stuff return None def blink_callback(blink_value): "this function will be called everytime NeuroPy has a new value for blink" print ("Value of blinks is",blink_value) #do other stuff (fire a rocket), based on the obtained value of attention_value #do some more stuff return None #set call back: object1.setCallBack("attention",attention_callback) object1.setCallBack("blink", blink_callback) #set call back: object1.setCallBack("meditation",attention_callback) #call start method object1.start() while True: if(object1.meditation>70): #another way of accessing data provided by headset (1st being call backs) object1.stop() #if meditation level reaches above 70, stop fetching data from the headset
json_file = open('model4.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model loaded_model.load_weights("model4.h5") print("Loaded model from disk") # evaluate loaded model on test data loaded_model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) sleep(1) print("taking input started") object1=NeuroPy("COM15") count=0 count0=0 count1=0 val=0 cnter=0 qwe=0 arrdelta=[0.000]*8 arrtheta=[0.000]*8 arrloalpha=[0.000]*8 arrhialpha=[0.000]*8 arrlobeta=[0.000]*8 arrhibeta=[0.000]*8 arrlogamma=[0.000]*8 arrmidgamma=[0.000]*8 def attention_callback(attention_value):
import csv from subprocess import call import sys import time ts = time.strftime("%I%M%S") val = 0 val2 = 0 val3 = 0 cnter = 0 cnter2 = 0 cnter3 = 0 qwe = 0 arr = [0.000] * 512 arr2 = [0.000] * 1024 arr3 = [0.000] * 2048 object1 = NeuroPy("COM5") # with open('dataset5.csv', 'wb') as f: # writer = csv.writer(f) def attention_callback(attention_value): if (object1.attention >= 10 and object1.meditation >= 10 and object1.poorSignal == 0 and attention_value < 30000): global cnter global cnter2 global cnter3 cnter += 1 cnter2 += 1 cnter3 += 1 for i in range(len(arr) - 1): arr[i] = arr[i + 1]
rowdata.append(hset.rawValue) rowdata.append(hset.attention) rowdata.append(hset.meditation) rowdata.append(hset.delta) rowdata.append(hset.theta) rowdata.append(hset.lowAlpha) rowdata.append(hset.highAlpha) rowdata.append(hset.lowBeta) rowdata.append(hset.highBeta) rowdata.append(hset.lowGamma) rowdata.append(hset.midGamma) queue.append(rowdata) # NeuroSky Setup hset = NeuroPy('COM4') hset.start() time.sleep(8) print('Ready...') results = [] queue = [] while True: # Terminating data collection if keyboard.is_pressed('q'): print('Quitting - Results outputted to output.csv') #storing into csv with open("output.csv", "wb") as f: writer = csv.writer(f) writer.writerows(results)
from NeuroPy import NeuroPy from time import sleep neuropy = NeuroPy("COM4") neuropy.start() while True: if neuropy.meditation > 70: # Access data through object neuropy.stop() sleep(0.2) # Don't eat the CPU cycles
__author__ = 'sitin' from NeuroPy import NeuroPy from time import sleep import mp3play import os __dir__ = os.path.dirname(os.path.realpath(__file__)) devices = { 'OS X': '/dev/cu.MindWaveMobile-DevA' } headset = NeuroPy('/dev/cu.MindWaveMobile-DevA') def cb(name): def a_cb(value): print(name, value) return a_cb #call start method headset.start() #set call back: for attr in ('attention', 'delta', 'highAlpha', 'highBeta', 'lowAlpha', 'lowBeta', 'lowGamma', 'meditation', 'midGamma', 'theta'): headset.setCallBack(attr, cb(attr)) mp3 = mp3play.load('../6.mp3') mp3.play()
from NeuroPy import NeuroPy from time import sleep from time import time import csv neuropy = NeuroPy("/dev/rfcomm1") neuropy.start() sleep(3) with open('_jamanna blink.csv', 'w') as csvfile: fieldnames = ['attention', 'delta', 'meditation', 'rawValue', 'theta', 'lowAlpha', 'highAlpha', 'lowBeta', 'highBeta', 'lowGamma', 'midGamma', 'poorSignal', 'blinkStrength' ,'label'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() i = time() j = time() print "Action 1 = truth" while(j-i<140): writer.writerow({'attention': neuropy.attention, 'delta': neuropy.delta, 'meditation': neuropy.meditation, 'rawValue': neuropy.rawValue, 'theta': neuropy.theta, 'lowAlpha': neuropy.lowAlpha, 'highAlpha': neuropy.highAlpha, 'lowBeta': neuropy.lowBeta, 'highBeta': neuropy.highBeta, 'lowGamma' : neuropy.lowGamma, 'midGamma' : neuropy.midGamma, 'poorSignal' : neuropy.poorSignal, 'blinkStrength': neuropy.blinkStrength, 'label': '1'}) sleep(0.1) j = time() csvfile.close() neuropy.stop()
# by using the Neurosky MindWave EEG headband. # Author: Jacob Stein # Created: 7/30/2013 # Copyright: (c) Jacob 2013 #------------------------------------------------------------------------------- #TODO: make a way so instead of detecting when it first hits 150 or -150, ir waits until it reaches the peak by waiting until it starts going down/up. from NeuroPy import NeuroPy import time import serial #import sys #import pygame #from pygame.locals import * object1=NeuroPy("COM4") #If port not given 57600 is automatically assumed #Serial = serial.Serial(2,9600) #On port 4 at 9600 baud #Serial.close() '''def attention_callback(attention_value): "this function will be called everytime NeuroPy has a new value for attention" print "Value of attention is",attention_value #do other stuff (fire a rocket), based on the obtained value of attention_value #do some more stuff return None''' #set call back: #object1.setCallBack("attention",attention_callback) #call start method
##Sample Program## from NeuroPy import NeuroPy object1=NeuroPy("COM6",57600) #If port not given 57600 is automatically assumed #object1=NeuroPy("/dev/rfcomm0") for linux def attention_callback(attention_value): "this function will be called everytime NeuroPy has a new value for attention" print ("Value of attention is",attention_value) #do other stuff (fire a rocket), based on the obtained value of attention_value #do some more stuff return None #set call back: object1.setCallBack("attention",attention_callback) #call start method object1.start() while True: if(object1.meditation>70): #another way of accessing data provided by headset (1st being call backs) object1.stop() #if meditation level reaches above 70, stop fetching data from the headset
from NeuroPy import NeuroPy import serial try: neuro = NeuroPy("COM3", 57600) neuro.start() print ("Neuropy found on COM5") except: print "Not found" value = 0 while True: value = neuro.rawValue print value
__author__ = "Shivam Shekhar, edited by COGS 189 Group!" import os import sys import pygame import random from pygame import * from time import sleep from NeuroPy import NeuroPy neuropy = NeuroPy("COM3") data = [] pygame.init() scr_size = (width, height) = (600, 150) FPS = 60 gravity = 0.6 black = (0, 0, 0) white = (255, 255, 255) background_col = (235, 235, 235) high_score = 0 screen = pygame.display.set_mode(scr_size) clock = pygame.time.Clock() pygame.display.set_caption("T-Rex Rush") jump_sound = pygame.mixer.Sound('sprites/jump.wav') die_sound = pygame.mixer.Sound('sprites/die.wav')
from NeuroPy import NeuroPy import time from pac import transform as pt from pac import sel as ps object1=NeuroPy("/dev/tty.MindWaveMobile-DevA",57600) object1.start() import Orange iris = Orange.data.Table("chosen.csv") #import training data ann = Orange.classification.neural.NeuralNetworkLearner(iris, n_mid=10, reg_fact=1, max_iter=300, rand=None) #def return_wave(): # delta = object1.delta # high_alpha = object1.highAlpha # high_beta = object1.highBeta # low_alpha = object1.lowAlpha # low_beta = object1.lowBeta # low_gamma = object1.lowGamma # mid_gamma = object1.midGamma # theta = object1.theta # return [delta,high_alpha,high_beta,low_alpha,low_beta,low_gamma,mid_gamma,theta] #queue = [] while True: print object1.poorSignal print object1.delta # if len(queue) == 3:
import pyautogui as pi from win32api import GetSystemMetrics import pytweening import time import win32gui def map(x, oFrom, oTo, nFrom, nTo): return x * ((nTo - nFrom) / (oTo - oFrom)) pass print("Width =", GetSystemMetrics(0)) print("Height =", GetSystemMetrics(1)) ob = NeuroPy("COM6") ob.start() count = 0 flag = 1 lastAttention = 0 while (True): # print(ob.attention, "blink",ob.blinkStrength) # pi.moveTo(map(ob.attention+1, 1, 100, 1, GetSystemMetrics(0)), # map(ob.meditation+1, 1, 100, 1, GetSystemMetrics(1)), pytweening.easeInQuad(0.75)) # pi.moveTo(map(ob.highBeta+1, 1, 100, 1, GetSystemMetrics(0)), # 100, pytweening.easeInQuad(0.75)) # print(ob.blinkStrength) # time.sleep(0.1) # print("alpha ",ob.highAlpha," ",ob.lowAlpha," Beta ",ob.highBeta," ",ob.lowBeta) flags, hcursor, (x, y) = win32gui.GetCursorInfo() if (ob.attention == 0):
from NeuroPy import NeuroPy #import winsound import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from pyo import * s = Server().boot() npo=NeuroPy('/dev/rfcomm0',57600) npo.start() def npacb(sigval): print sigval return None #npo.setCallBack("rawValue",npacb) npo.setCallBack("attention",npacb) freqeeg = 512 def crtfrearray(feeg): eegcoll = [] cnteeg=0 while cnteeg<feeg: eegcoll.append(npo.rawValue) cnteeg+=1 freqs = np.fft.fftfreq(len(eegcoll)) idx=np.argmax(np.abs(np.array(eegcoll))**2) freq=freqs[idx] freqhz=abs(freq*freqeeg) if freqhz>40 and freqhz<freqeeg: