class RunMWM(threading.Thread): def __init__(self): #self._target = target #self._args = args self.isRunning = True threading.Thread.__init__(self) self._eegpower = deque() self.mindwaveDataPointReader=None #def run(self): # self._target(*self._args) def connectMWM(self, target_address): """ make the MWM connection """ print "Connecting to MWM...", try: self.mindwaveDataPointReader = MindwaveDataPointReader(target_address) self.mindwaveDataPointReader.start() # connect to the mindwave mobile headset except IOError as e: print e print "Couldn't connect to MWM device. Check address? Is it turned on?"; raise e print " connected" def run(self): """ run a while loop to capture data and push it into a queue """ while(self.isRunning): dataPoint = self.mindwaveDataPointReader.readNextDataPoint() if dataPoint.__class__ is PoorSignalLevelDataPoint: count=0 if not dataPoint.headSetHasContactToSkin(): #chek the first one, and if no contact, loop until dies count+=1 dataPoint = mindwaveDataPointReader.readNextDataPoint() print "waiting for signal quality" while(not dataPoint.headSetHasContactToSkin() or count>10000): count+=1 dataPoint = self.mindwaveDataPointReader.readNextDataPoint() if count>10000: print "No contact, quitting" raise ValueError("no EEG contact") else: print "Contact detected" elif (dataPoint.__class__ is EEGPowersDataPoint): eegpower = np.log(dataPoint.asList()) / np.log(float(dataPoint.maxint)) data = {'brain':eegpower, 'timestamp': time.time()} with lock: eegpower_buffer.append(data) #append to global queue print "alphaH {0} --> {1:1.4f} at {2}".format(dataPoint.highAlpha, data['brain'][3], data['timestamp']) print "\n" mindwaveDataPointReader.close() print "Closed MWM session."
def read(queue, mwm_pipeend, display_freq, episode_duration): #used for data acquisition timing counter = 0 record_times = [] #mwm collects data at approximately 512 Hz. Can vary though. That's why we need the trim. trim_size = (episode_duration - .4) * 508 print("episode_duration:", episode_duration) episode_data = [] #creates a new mindwave mobile object mwm_reader = MindwaveDataPointReader() mwm_reader.start() #finds the start signal while True: data_point = mwm_reader.readNextDataPoint() if data_point.__class__ is StartCommand: print("Start sequence received, signaling animation...") #once the start command is received from the mwm, the start signal is sent through the pipe to the animation process mwm_pipeend.send([True]) break epi_type = mwm_pipeend.recv()[0] print("\tCommencing data acquisition at", time.time()) #for as long as the episode is happening, read data from mwm. For some reason, mwm closes too late. Need early stopping #that's why I subtract .4 seconds from the end_time here end_time = (time.time() + episode_duration - .4) - .1 while time.time() < end_time: data_point = mwm_reader.readNextDataPoint() if (data_point.__class__ is RawDataPoint): episode_data.append(data_point._readRawValue()) if (display_freq): current_time = time.time() record_times.append(current_time) counter += 1 if (counter == 240): l = np.average(np.diff(record_times)) print("\t\tmwm:", 1 / l, "Hz") record_times = [] counter = 0 print("\tClosing mwm stream at", time.time()) #get the episode type from the environment # print("trimming ", len(episode_data) - int(trim_size), "readings") # trim the episode data so it's always a constant length print("trimming:", len(episode_data) - trim_size) episode_data = episode_data[:int(trim_size)] episode_data_df = pd.DataFrame().append([episode_data]) episode_data_df['episode_type'] = np.array([epi_type]) #close and delete mwm mwm_reader.end() del mwm_reader #when the episode is finished, the data gathered by the recorder device is accessed and placed in the queue so the parent process can obtain it queue.put(episode_data_df)
def main(): configureLogger("WSO2IOT_RPiStats") UtilsThread() SubscribeToMQTTQueue( ) # connects and subscribes to an MQTT Queue that receives MQTT commands from the server mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() if (mindwaveDataPointReader.isConnected()): counter = 0 signalInfo = [0] * 11 while (True): try: dataPoint = mindwaveDataPointReader.readNextDataPoint() if (not dataPoint.__class__ is RawDataPoint): if (dataPoint.__class__ is EEGPowersDataPoint): signalInfo[2] = float(str(dataPoint.delta)), signalInfo[3] = dataPoint.theta, signalInfo[4] = dataPoint.lowAlpha, signalInfo[5] = dataPoint.highAlpha, signalInfo[6] = dataPoint.lowBeta, signalInfo[7] = dataPoint.highBeta, signalInfo[8] = dataPoint.lowGamma, signalInfo[9] = dataPoint.midGamma if (dataPoint.__class__ is AttentionDataPoint): signalInfo[0] = float(str(dataPoint).split(":")[1]) # TODO send command to virtual fire alarm after checking AttentionDataPointor or signalInfo[0] try: if (dataPoint.__class__ is PoorSignalLevelDataPoint): signalInfo[1] = float(str(dataPoint).split(":")[1]) except ValueError: print "200 - NO CONTACT TO SKIN" signalInfo[1] = 200 pass if (dataPoint.__class__ is MeditationDataPoint): # TODO send command to virtual fire alarm after checking MeditationDataPoint or signalInfo[10] signalInfo[10] = float(str(dataPoint).split(":")[1]) counter = counter + 1 if (counter == 4): counter = 0 currentTime = calendar.timegm(time.gmtime()) PUSH_DATA_BRAIN_WAVE_INFO = iotUtils.BRAIN_WAVE_INFO.format( currentTime, signalInfo[0], signalInfo[1], signalInfo[10], float(signalInfo[2][0]), float(signalInfo[3][0]), float(signalInfo[4][0]), float(signalInfo[5][0]), float(signalInfo[6][0]), float(signalInfo[7][0]), float(signalInfo[8][0]), float(signalInfo[8][0])) print '~~~~~~~~~~~~~~~~~~~~~~~~ Publishing Devic-eData ~~~~~~~~~~~~~~~~~~~~~~~~~' print('PUBLISHED DATA: ' + PUSH_DATA_BRAIN_WAVE_INFO) print('PUBLISHED TOPIC: ' + mqttConnector.TOPIC_TO_PUBLISH_BRAIN_WAVE_INFO) mqttConnector.publish(PUSH_DATA_BRAIN_WAVE_INFO) except AssertionError: print('An error occurred while reading brain signal') pass else: print( textwrap.dedent("""\ Exiting because the program could not connect to the Mindwave Mobile device.""").replace("\n", " "))
def mindwaveArray(self): output = { "delta": deque(maxlen=30), "theta": deque(maxlen=30), "lowAlpha": deque(maxlen=30), "highAlpha": deque(maxlen=30), "lowBeta": deque(maxlen=30), "highBeta": deque(maxlen=30), "lowGamma": deque(maxlen=30), "midGamma": deque(maxlen=30), } while not thread_stop_event.isSet(): mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() if mindwaveDataPointReader.isConnected(): while True: dataPoint = mindwaveDataPointReader.readNextDataPoint() if dataPoint.__class__ is EEGPowersDataPoint: newData = dataPoint.__dict__ for k, v in newData.items(): if k in output.keys(): output[k].appendleft(v) prepData = copy.deepcopy(output) for k, v in prepData.items(): prepData[k] = list(v) socketio.emit( "newnumber", {"output": json.dumps(prepData)}, namespace="/test", ) else: output = "Could not connect to the Mindwave Mobile device, retrying ..." socketio.emit("newnumber", {"output": output}, namespace="/test") sleep(self.delay)
def main(): rospy.init_node('mindwave') pub = rospy.Publisher('neuro', MindwaveValues, queue_size=100) rate = rospy.Rate(100) mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() if (mindwaveDataPointReader.isConnected()): while not rospy.is_shutdown(): dataPoint = mindwaveDataPointReader.readNextDataPoint() if (dataPoint.__class__ is MeditationDataPoint): print(dataPoint.__class__) print(dataPoint) dic = dataPoint.__dict__ meditation = dic['meditationValue'] print(meditation) if (dataPoint.__class__ is AttentionDataPoint): print(dataPoint.__class__) print(dataPoint) dic = dataPoint.__dict__ attention = dic['attentionValue'] print(attention) send_values = MindwaveValues() send_values.meditation = meditation send_values.attention = attention pub.publish(send_values) rate.sleep() else: print( textwrap.dedent("""\ Exiting because the program could not connect to the Mindwave Mobile device.""").replace("\n", " "))
class BrainWaveSource(Source): def __init__(self): Source.__init__(self, self.get_dict().next) self.logger = logging.getLogger('bws') self.mindwaveDataPointReader = MindwaveDataPointReader() self.mindwaveDataPointReader.start() self.finished = False self.initialized = False self.started = False def get_dict(self): "Synchronous (!) method to get the next set of brainwave measurements from the sensor" while True: builder = MeasurementBuilder() self.logger.debug('have builder') self.finished = False while not self.finished: datapoint = self.mindwaveDataPointReader.readNextDataPoint() self.logger.debug('datapoint read') builder.add_measurement(datapoint) self.logger.debug('measurement added') if builder.is_finished(): self.logger.debug('finished building') measurement = builder.get_dict() self.finished = True if not self.initialized: self.logger.debug("Not yet initialized") if not measurement['meta']['noise'] == 25: self.initialized = True else: yield measurement def select(self, selector): return Transformer([self], {self.getName(): 'd'}, lambda d: d and d[selector]) def start(self): self.started = True parent = self def internal(): while parent.started: if parent.finished: parent.push() time.sleep(1) else: time.sleep(0.1) self.t = Thread(target=internal) self.t.daemon = True self.t.start() def stop(self): self.started = False
def read(queue): global results mwm_reader = MindwaveDataPointReader() mwm_reader.start() recorder = rcrdr.Recorder(episode_duration=episode_duration, mwm_reader=mwm_reader) time_out_time = time.time() + 10 while time.time() < time_out_time: data_point = mwm_reader.readNextDataPoint() if data_point.__class__ is StartCommand: print("start sequence received, commencing episode...") break recorder.record_one_episode(1, time.time()) print(recorder.get_episode_data()) queue.put(recorder.get_episode_data())
def main(): mdpr = MindwaveDataPointReader() mdpr.start() eeg_datapoints = [] attention_datapoints = [] index = 0 try: while(True): data = mdpr.readNextDataPoint() if (data.__class__ is AttentionDataPoint): attention_datapoints.append((time.time(),data)) if (data.__class__ is EEGPowersDataPoint): eeg_datapoints.append((time.time(),data)) index+=1 print index except KeyboardInterrupt: pass fmt = 'ddddddddd' dataFormat = [] file_ = open(sys.argv[1], 'wb') file_.write(fmt.ljust(25,' ')) for i in xrange(len(eeg_datapoints)): timestamp = attention_datapoints[i][0] attention = attention_datapoints[i][1] delta = eeg_datapoints[i][1].delta theta = eeg_datapoints[i][1].theta lowalpha = eeg_datapoints[i][1].lowAlpha highalpha = eeg_datapoints[i][1].highAlpha lowbeta = eeg_datapoints[i][1].lowBeta highbeta = eeg_datapoints[i][1].highBeta lowgamma = eeg_datapoints[i][1].lowGamma midgamma = eeg_datapoints[i][1].midGamma s = struct.pack(fmt,timestamp, delta, theta, lowalpha, highalpha, lowbeta, highbeta, lowgamma, midgamma) file_.write(s) file_.close()
def main(): mdpr = MindwaveDataPointReader() mdpr.start() eeg_datapoints = [] attention_datapoints = [] index = 0 try: while (True): data = mdpr.readNextDataPoint() if (data.__class__ is AttentionDataPoint): attention_datapoints.append((time.time(), data)) if (data.__class__ is EEGPowersDataPoint): eeg_datapoints.append((time.time(), data)) index += 1 print index except KeyboardInterrupt: pass fmt = 'ddddddddd' dataFormat = [] file_ = open(sys.argv[1], 'wb') file_.write(fmt.ljust(25, ' ')) for i in xrange(len(eeg_datapoints)): timestamp = attention_datapoints[i][0] attention = attention_datapoints[i][1] delta = eeg_datapoints[i][1].delta theta = eeg_datapoints[i][1].theta lowalpha = eeg_datapoints[i][1].lowAlpha highalpha = eeg_datapoints[i][1].highAlpha lowbeta = eeg_datapoints[i][1].lowBeta highbeta = eeg_datapoints[i][1].highBeta lowgamma = eeg_datapoints[i][1].lowGamma midgamma = eeg_datapoints[i][1].midGamma s = struct.pack(fmt, timestamp, delta, theta, lowalpha, highalpha, lowbeta, highbeta, lowgamma, midgamma) file_.write(s) file_.close()
import time import bluetooth from mindwavemobile.MindwaveDataPoints import RawDataPoint from mindwavemobile.MindwaveDataPointReader import MindwaveDataPointReader import textwrap if __name__ == '__main__': mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() if (mindwaveDataPointReader.isConnected()): while(True): dataPoint = mindwaveDataPointReader.readNextDataPoint() if (not dataPoint.__class__ is RawDataPoint): print dataPoint else: print(textwrap.dedent("""\ Exiting because the program could not connect to the Mindwave Mobile device.""").replace("\n", " "))
# draw and show it fig.canvas.draw() plt.show(block=False) # threshold value threshold = 100 mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() b = generate_bot() if (mindwaveDataPointReader.isConnected()): while (True): dataPoint = mindwaveDataPointReader.readNextDataPoint() if (not dataPoint.__class__ is RawDataPoint): print dataPoint # print(dataPoint.__class__) if dataPoint.__class__.__name__ == "AttentionDataPoint": # print(dataPoint.__class__) if dataPoint.attentionValue > threshol: print('Threshold exceeed!') time.sleep(0.2) ## Wait move_forward(b, 100, 100) else: move_forward(b, 0, 0) y[:-10] = y[10:] y[-10:] = np.random.rand(10) z[:-10] = z[10:]
class SensorMSG(): def __init__(self, EEG=True, IMU=True, HEART=True): self.EEG_addr = EEG_addr self.EEG_queue = queue.Queue(maxsize=EEG_QUEUE_MAXSIZE) self.HEART_queue = queue.Queue(maxsize=HEART_QUEUE_MAXSIZE) self.IMU_queue = queue.Queue(maxsize=IMU_QUEUE_MAXSIZE) if (logmode): self.log_file = open("logfile.log", "a") self.log_file.write( dt.datetime.now().strftime("%m/%d/%Y, %H:%M:%S\n")) '''Enable sensors to work''' self.EEG_enable = EEG self.HEART_enable = HEART self.IMU_enable = IMU '''connection status''' self.EEG_status = False self.HEART_status = False self.IMU_status = False '''control execuion flags''' self.EEG_running = 0 self.HEART_running = 0 self.IMU_running = 0 self.SENDER_running = 0 '''last time update sensor''' self.EEG_t_last = dt.datetime.now() self.HEART_t_last = dt.datetime.now() self.IMU_t_last = dt.datetime.now() if (EEG): self.connect_EEG(self.EEG_addr) if (IMU): self.connect_IMU() if (HEART): self.connect_HEART() def print_log(self, str): print(str) self.log_file.write(dt.datetime.now().strftime("%H:%M:%S: ") + str + "\n") def connect_EEG(self, addr): self.print_log("[+] Try to connect") self.mindwaveDataPointReader = MindwaveDataPointReader(addr) while True: try: self.mindwaveDataPointReader.start() time.sleep(2) if (self.mindwaveDataPointReader.isConnected()): self.print_log("[+] Connected") self.EEG_status = True return self.EEG_status except: self.print_log("[-] Fail Connection") time.sleep(2) self.print_log("[+] retry...") def get_EEG(self): if (self.EEG_status): self.print_log("[+] getting EEG values: Status: " + str(self.EEG_status) + " Running: " + str(self.EEG_running)) dict = { 'Meditation': 0, 'Attention': 0, 'delta': '0', 'theta': '0', 'lowAlpha': '0', 'highAlpha': '0', 'lowBeta': '0', "highBeta": '0', 'lowGamma': '0', 'midGamma': '0', 'PoorSignalLevel': 0 } self.med_value = 0 self.at_value = 0 self.signal = 0 while (self.EEG_running): dataPoint = self.mindwaveDataPointReader.readNextDataPoint() if (dataPoint.__class__ is dp.PoorSignalLevelDataPoint): poorSignalLevel = dataPoint.dict() dict.update(poorSignalLevel) elif (dataPoint.__class__ is dp.AttentionDataPoint): attention = dataPoint.dict() dict.update(attention) elif (dataPoint.__class__ is dp.MeditationDataPoint): meditation = dataPoint.dict() dict.update(meditation) elif (dataPoint.__class__ is dp.EEGPowersDataPoint): eegPowers = dataPoint.dict() dict.update(eegPowers) if (('delta' in dict) and ('PoorSignalLevel' in dict) and ('Meditation' in dict) and ('Attention' in dict)): if (not self.med_value == dict.get('Meditation') or not self.at_value == dict.get('Attention') or not self.signal == dict.get('PoorSignalLevel')): print(dict) self.med_value = int(dict.get('Meditation')) self.at_value = int(dict.get('Attention')) self.signal = int(dict.get('PoorSignalLevel')) self.EEG_queue.put( [self.med_value, self.at_value, self.signal]) self.EEG_t_last = dt.datetime.now() if (self.EEG_running == -1): print("EEG_paused") time.sleep(.5) def start_EEG(self): if (not self.EEG_status): self.print_log('[-] EEG sensor not connected') else: self.EEG_running = 1 threading.Thread(target=self.get_EEG, args=()).start() def pause_EEG(self): self.print_log("[+] Pause EEG") self.EEG_running = -1 def continue_EEG(self): self.print_log("[+] Continue EEG") self.EEG_running = 1 def stop_EEG(self): self.print_log("[+] Stop EEG") self.EEG_running = 0 def connect_IMU(self): self.IMU_status = True if (not debug_mock): mpu9250 = FaBo9Axis_MPU9250.MPU9250() self.print_log("[+]MPU9250 conected") else: self.print_log("[!]MPU9250 mocking mode") def get_IMU(self): while (self.IMU_running): if (self.IMU_running == 1): if (not debug_mock): self.accel = mpu9250.readAccel() self.gyro = mpu9250.readGyro() self.mag = mpu9250.readMagnet() else: self.accel = { 'x': randrange(-2, 2), 'y': randrange(-2, 2), 'z': randrange(-2, 2) } self.gyro = { 'x': randrange(-180, 180, 5), 'y': randrange(-180, 180, 5), 'z': randrange(-180, 180, 5) } self.mag = { 'x': randrange(-180, 180, 5), 'y': randrange(-180, 180, 5), 'z': randrange(-180, 180, 5) } self.IMU_queue.put([ self.accel['x'], self.accel['y'], self.accel['z'], self.gyro['x'], self.gyro['y'], self.gyro['z'], self.mag['x'], self.mag['y'], self.mag['z'] ]) time.sleep(0.2) elif (self.IMU_running == -1): print("IMU_paused") time.sleep(.5) def start_IMU(self): if (not self.IMU_status): self.print_log('[-] IMU sensor not connected') else: self.IMU_running = 1 threading.Thread(target=self.get_IMU, args=()).start() def pause_IMU(self): self.print_log("[+] Pause IMU") self.IMU_running = -1 def continue_IMU(self): self.print_log("[+] Continue IMU") self.IMU_running = 1 def stop_IMU(self): self.print_log("[+] Stop IMU") self.IMU_running = 0 def connect_HEART(self): self.HEART_status = True if (not debug_mock): self.heart_sensor = max30102.MAX30102() self.print_log("[+]MAX30102 conected") else: self.print_log("[!]MPU9250 mocking mode") def display_heartrate(beat, bpm, avg_bpm): pass def start_OSC_sender(self): self.client = udp_client.SimpleUDPClient(IP, PORT) self.SENDER_running = 1 while (self.SENDER_running): if (self.EEG_enable == 1 and not self.EEG_queue.empty()): self.print_log("send_EEG") self.client.send_message("/EEG", self.EEG_queue.get()) if (self.IMU_enable == 1 and not self.IMU_queue.empty()): self.print_log("send_IMU") print(self.IMU_queue.get()) self.client.send_message("/IMU", self.IMU_queue.get()) def stop_OSC_sender(self): self.SENDER_running = 0 pass def end_file(self): if (logmode): self.log_file.close()
def read(queue, mwm_pipeend, display_freq, episode_duration, num_episodes): #num_episodes counter = 0 record_times = [] current_episode = 0 trim_size = (episode_duration - .4) * 508 - 20 trial_data_df = pd.DataFrame() # creates a new mindwave mobile object mwm_reader = MindwaveDataPointReader() mwm_reader.start() # finds the start signal while True: data_point = mwm_reader.readNextDataPoint() if data_point.__class__ is StartCommand: print("Start sequence received.") break start_time = time.time() #idles for 3 seconds to jump past annoying start spike while (time.time() < start_time + 12): mwm_reader.readNextDataPoint() if (display_freq): current_time = time.time() record_times.append(current_time) counter += 1 if (counter == 512): l = np.average(np.diff(record_times)) print("\t\tmwm idling") record_times = [] counter = 0 # once the start command is received from the mwm, the start signal is sent through the pipe to the animation process mwm_pipeend.send(["start_trial"]) print("Startup spike passed. Trial begins.\n") while (current_episode < num_episodes): counter = 0 record_times = [] #used for data acquisition timing episode_data = [] episode_reading_times = [] epi_type = mwm_pipeend.recv()[0] mwm_reader.clearBuffer() # mwm_reader.clearBufferV2() mwm_pipeend.send(["buffer_cleared"]) #for as long as the episode is happening, read data from mwm. For some reason, mwm closes too late. Need early stopping #that's why I subtract .4 seconds from the end_time here end_time = (time.time() + episode_duration - .4) - .15 print("\tCommencing data acquisition at", time.time()) #record data for length of episode while time.time() < end_time: data_point = mwm_reader.readNextDataPoint() if (data_point.__class__ is RawDataPoint): episode_data.append(data_point._readRawValue()) episode_reading_times.append(time.time()) if (display_freq): current_time = time.time() record_times.append(current_time) counter += 1 if (counter == 240): l = np.average(np.diff(record_times)) print("\t\tmwm:", int(1 / l), "Hz") record_times = [] counter = 0 print("\tEnding data acquisition at", time.time()) correct_index = 1024 #this value represents the index at which Pacman initially moves #receives the time at which pacman makes his move from the environment action_time = mwm_pipeend.recv()[0] #finds the index closest in time to pacman's move time action_index = episode_reading_times.index( min(episode_reading_times, key=lambda x: abs(x - action_time))) #adds dummy data to front of episode_data or removes offset number of readings so that the critical points are aligned offset = action_index - correct_index if (offset < 0): dummy = [0] * abs(offset) episode_data = dummy + episode_data elif (offset > 0): episode_data = episode_data[offset:] to_trim = int(len(episode_data) - trim_size) print("\t\ttrimming:", to_trim, "readings") episode_data = episode_data[:int(trim_size)] episode_data_df = pd.DataFrame().append([episode_data]) episode_data_df['episode_type'] = np.array([epi_type]) episode_data_df['episode_num'] = np.array([current_episode]) episode_data_df['action_index'] = np.array([action_index]) episode_data_df['trimmed_data'] = np.array([to_trim]) episode_data_df['win'] = np.array([epi_type in [0, 3]]) print("\tpredicting...") prediction = predict(episode_data_df) mwm_pipeend.send(prediction) print("prediction sent") #predict if episode data df is corrupt if (action_index < 950 or action_index > 1100): episode_data_df['is_corrupt'] = np.array([1]) elif (to_trim > 100 or to_trim < 0): episode_data_df['is_corrupt'] = np.array([1]) else: episode_data_df['is_corrupt'] = np.array([0]) # append to trial data df trial_data_df = pd.concat([trial_data_df, episode_data_df]) print("Episode finished. \n\n") #idle until animation sends finished animation signal # while(not mwm_pipeend.recv()): # mwm_reader.readNextDataPoint() # if (display_freq): # current_time = time.time() # record_times.append(current_time) # counter += 1 # if (counter == 240): # l = np.average(np.diff(record_times)) # print("\t\tmwm:", 1 / l, "Hz") # record_times = [] # counter = 0 current_episode += 1 #close and delete mwm mwm_reader.end() del mwm_reader #when the episode is finished, the data gathered by the recorder device is accessed and placed in the queue so the parent process can obtain it queue.put(trial_data_df)
def main(): mdpr = MindwaveDataPointReader() mdpr.start() eeg_datapoints = [] attention_datapoints = [] try: while(True): data = mdpr.readNextDataPoint() if (data.__class__ is AttentionDataPoint): attention_datapoints.append(data) if (data.__class__ is EEGPowersDataPoint): eeg_datapoints.append(data) except KeyboardInterrupt: pass # plot data print len(eeg_datapoints) print len(attention_datapoints) attention_datapoint_vals = [point.attentionValue for point in attention_datapoints] # will the following give us a good speed increase over using list comprehensions? # or will the readability be better? delta_points = [] theta_points = [] lowAlpha_points = [] highAlpha_points = [] lowBeta_points = [] highBeta_points = [] lowGamma_points = [] midGamma_points = [] for datapoint in eeg_datapoints: # print(datapoint) delta_points.append(datapoint.delta) theta_points.append(datapoint.theta) lowAlpha_points.append(datapoint.lowAlpha) highAlpha_points.append(datapoint.highAlpha) lowBeta_points.append(datapoint.lowBeta) highBeta_points.append(datapoint.highBeta) lowGamma_points.append(datapoint.lowGamma) midGamma_points.append(datapoint.midGamma) # two plots will make the data look more presentable since the scales # of the data vary widely (maybe even more, like a plot per greek letter # or something) # plot the EEG components (scale: 0 - large) pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(delta_points)) for i in delta_points], label="Delta") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(theta_points)) for i in theta_points], label="Theta") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(lowAlpha_points)) for i in lowAlpha_points], label="Low-Alpha") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(highAlpha_points)) for i in highAlpha_points], label="High-Alpha") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(lowBeta_points)) for i in lowBeta_points], label="Low-Beta") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(highBeta_points)) for i in highBeta_points], label="High-Beta") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(lowGamma_points)) for i in lowGamma_points], label="Low-Gamma") pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(midGamma_points)) for i in midGamma_points], label="Mid-Gamma") pl.xlabel("Time Step") pl.ylabel("Reading Value") legend = pl.legend(loc='best', ncol=2, shadow=None) legend.get_frame().set_facecolor('#00FFCC') # pl.yscale('log') pl.show() # plot the attention reading (scale: 1- 1001) pl.plot(range(len(attention_datapoints)), attention_datapoint_vals, label="Attention") pl.xlabel("Time Step") pl.ylabel("Reading Value") legend = pl.legend(loc='best', ncol=2, shadow=None) legend.get_frame().set_facecolor('#00FFCC') pl.show()
def main(): mdpr = MindwaveDataPointReader() mdpr.start() eeg_datapoints = [] attention_datapoints = [] try: while (True): data = mdpr.readNextDataPoint() if (data.__class__ is AttentionDataPoint): attention_datapoints.append(data) if (data.__class__ is EEGPowersDataPoint): eeg_datapoints.append(data) except KeyboardInterrupt: pass # plot data print len(eeg_datapoints) print len(attention_datapoints) attention_datapoint_vals = [ point.attentionValue for point in attention_datapoints ] # will the following give us a good speed increase over using list comprehensions? # or will the readability be better? delta_points = [] theta_points = [] lowAlpha_points = [] highAlpha_points = [] lowBeta_points = [] highBeta_points = [] lowGamma_points = [] midGamma_points = [] for datapoint in eeg_datapoints: # print(datapoint) delta_points.append(datapoint.delta) theta_points.append(datapoint.theta) lowAlpha_points.append(datapoint.lowAlpha) highAlpha_points.append(datapoint.highAlpha) lowBeta_points.append(datapoint.lowBeta) highBeta_points.append(datapoint.highBeta) lowGamma_points.append(datapoint.lowGamma) midGamma_points.append(datapoint.midGamma) # two plots will make the data look more presentable since the scales # of the data vary widely (maybe even more, like a plot per greek letter # or something) # plot the EEG components (scale: 0 - large) pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(delta_points)) for i in delta_points], label="Delta") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(theta_points)) for i in theta_points], label="Theta") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(lowAlpha_points)) for i in lowAlpha_points], label="Low-Alpha") pl.plot( range(len(eeg_datapoints)), [float(i) / float(sum(highAlpha_points)) for i in highAlpha_points], label="High-Alpha") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(lowBeta_points)) for i in lowBeta_points], label="Low-Beta") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(highBeta_points)) for i in highBeta_points], label="High-Beta") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(lowGamma_points)) for i in lowGamma_points], label="Low-Gamma") pl.plot(range(len(eeg_datapoints)), [float(i) / float(sum(midGamma_points)) for i in midGamma_points], label="Mid-Gamma") pl.xlabel("Time Step") pl.ylabel("Reading Value") legend = pl.legend(loc='best', ncol=2, shadow=None) legend.get_frame().set_facecolor('#00FFCC') # pl.yscale('log') pl.show() # plot the attention reading (scale: 1- 1001) pl.plot(range(len(attention_datapoints)), attention_datapoint_vals, label="Attention") pl.xlabel("Time Step") pl.ylabel("Reading Value") legend = pl.legend(loc='best', ncol=2, shadow=None) legend.get_frame().set_facecolor('#00FFCC') pl.show()
import time from mindwavemobile.MindwaveDataPointReader import MindwaveDataPointReader as reader from mindwavemobile.MindwaveDataPoints import * if __name__ == '__main__': data_list = [] temp = 0 med = 0 att = 0 f = open("data.txt", 'w') reader = reader() reader.start() if (reader.isConnected()): while True: data = reader.readNextDataPoint() if (data.__class__ is MeditationDataPoint): med = data.meditationValue temp = time.time() elif(data.__class__ is AttentionDataPoint): att = data.attentionValue unit = [temp, med, att] data_list.append(unit) print(unit) f.write(str(unit) + '\n') f.flush() f.close() else: print("device disconnected")