Exemple #1
0
    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)
Exemple #2
0
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", " "))
Exemple #3
0
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", " "))
Exemple #4
0
 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
Exemple #5
0
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)
Exemple #6
0
 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"
Exemple #7
0
 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...")
Exemple #8
0
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 read(trains):
    raw = []
    MindwaveData = MindwaveDataPointReader.MindwaveDataPointReader()
    MindwaveData.start()
    while(True):
        dataPoint = MindwaveData.readNextDataPoint()
        if (dataPoint.__class__ is RawDataPoint):
            raw.append(float(dataPoint.rawValue))
            for train in trains: ##把训练样本拉出来准备比较
                fitRate = compare(train.data,raw).fitRate ##实例化并取得fitRate相关系数
                if fitRate > 0.9:
                    print '%s.The fitRate is %s'%(train.name,fitRate)
                    print '\n'
        else:
            raw = []
def attempt_connect(eeg_addr):
    # print('EEG Address in Attempt Connect: {}'.format(eeg_addr))
    connect = False

    # Create Mindwave objects
    eeg_obj = MindwaveDataPointReader(eeg_addr)

    # Attempt connection to EEG Object
    try:
        eeg_obj.start()
    except IOError as e:
        pass
        # print('EEG Not Connected: {}'.format(eeg_addr))
    else:
        connect = True
        print('EEG Connected: {}'.format(eeg_addr))

    # return eeg_obj
    return eeg_obj, connect
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()
Exemple #12
0
    # some X and Y data
    x = np.arange(100)
    y = np.random.rand(100)
    z = np.random.rand(100)
    li1, = ax.plot(x, y, color="b", linewidth=2.0)
    li2, = ax.plot(x, z, color="g")

    # 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
import bluetooth
import numpy as np
from mindwavemobile.MindwaveDataPoints import RawDataPoint
from mindwavemobile.MindwaveDataPointReader import MindwaveDataPointReader
with open("Output.txt", "w") as text_file:  #輸出資料
    if __name__ == '__main__':
        mindwaveDataPointReader = MindwaveDataPointReader(
            address='98:07:2D:7F:40:FF')  #輸入你的腦波儀序號
        mindwaveDataPointReader.start()
        if (mindwaveDataPointReader.isConnected()):
            while (True):
                dataPoint = mindwaveDataPointReader.readNextDataPoint()
                if (dataPoint.__class__.__name__ == 'AttentionDataPoint'):
                    x = np.array(dataPoint)
                    print(dataPoint)
                    print(f"{dataPoint}", file=text_file)
            else:
                pass
        else:
            print(
                'Exiting because the program could not connect to the TGAM device.'
            )
    return dataLabel, deviceAddr


if __name__ == '__main__':
    dataLabel, blueAddr = get_arguments()
    fileName = time.strftime("%Y%m%d%H%M%S_") + dataLabel[0]

    print('File Label:{}'.format(dataLabel))
    print('Device Address:{}'.format(blueAddr))

    with open(fileName + '.csv', mode='w') as logFileName:
        log_writer = csv.writer(logFileName,
                                delimiter='\t',
                                quotechar='"',
                                quoting=csv.QUOTE_MINIMAL)
        mindwaveDataPointReader = MindwaveDataPointReader(blueAddr)
        mindwaveDataPointReader.start()
        if (mindwaveDataPointReader.isConnected()):
            while (True):
                dataPoint = mindwaveDataPointReader.readNextDataPoint()
                if (not dataPoint.__class__ is RawDataPoint):
                    data = str(dataPoint).split(':')
                    if (data[0] == 'delta'):
                        log_writer.writerow([time.strftime("%Y%m%d%H%M%S_")] +
                                            data)
                    else:
                        print(dataPoint)
        else:
            print((textwrap.dedent("""\
                    Exiting because the program could not connect
                    to the Mindwave Mobile device.""").replace("\n", " ")))
import time
import bluetooth
from mindwavemobile.MindwaveDataPoints import RawDataPoint, AttentionDataPoint, MeditationDataPoint, PoorSignalLevelDataPoint
from mindwavemobile.MindwaveDataPointReader import MindwaveDataPointReader
import textwrap

if __name__ == '__main__':
    #Try to connect to the predefined device
    mindwaveDataPointReader = MindwaveDataPointReader('20:68:9D:3F:4F:88')
    mindwaveDataPointReader.start()

    #If the predefined device can't be connected, try any on discovery mode
    if(not mindwaveDataPointReader.isConnected()):
        mindwaveDataPointReader = MindwaveDataPointReader()
        mindwaveDataPointReader.start()
    else:
        print('Connected to predefined device')
    count = 0
    if (mindwaveDataPointReader.isConnected()):
        while(True):
            '''dataPoint = mindwaveDataPointReader.readNextDataPoint()
            if (not dataPoint.__class__ is RawDataPoint):
                print count,'-----------------------------------------------'
                print dataPoint
                print 'type', type(dataPoint), dataPoint.__class__
                print '-----------------------------------------------'''
            dataPoint = mindwaveDataPointReader.readNextDataPoint()
            if(dataPoint.__class__ is AttentionDataPoint):
                print dataPoint
            elif(dataPoint.__class__ is MeditationDataPoint):
                print dataPoint
def read(trains):
    raw = []
    MindwaveData = MindwaveDataPointReader.MindwaveDataPointReader()
    MindwaveData.start()
    while(True):
        dataPoint = MindwaveData.readNextDataPoint()
        if (dataPoint.__class__ is RawDataPoint):
            raw.append(float(dataPoint.rawValue))
            for train in trains: ##把训练样本拉出来准备比较
                fitRate = compare(train.data,raw).fitRate ##实例化并取得fitRate相关系数
                if fitRate > 0.9:
                    print '%s.The fitRate is %s'%(train.name,fitRate)
                    print '\n'
        else:
            raw = []

if __name__ == '__main__':
    mindwaveDataPointReader = MindwaveDataPointReader(address="AB:90:78:56:40:BD")
    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", " "))
    trains = [train(data[54:56],'Blink1'),train(data[69:71],'Blink2'),train(data[70:73],'Relax')
def main():

    #Default setting
    macaddr = ""
    spi_ch = 0
    sensor_ch = 0
    pNNx = 50
    npNN = 30
    nBPM = 10
    #Load configuration file
    try:
        settingFile = open("setting.txt", "r")
        print('Fond setting file')
        tmp = settingFile.readlines()
        settingFile.close()
        for line in tmp:
            line = line.strip()
            if line[0] == '#' or line[0] == '':
                continue
            else:
                cmd = line.split(':')
                if cmd[0].lower() == 'macaddr':
                    macaddr = cmd[1].strip()
                elif cmd[0].lower() == 'spi-ch':
                    spi_ch = int(cmd[1].strip())
                elif cmd[0].lower() == 'pulse-ch':
                    sensor_ch = int(cmd[1].strip())
                elif cmd[0].lower() == 'pnnx':
                    pNNx = int(cmd[1].strip())
                elif cmd[0].lower() == 'n-pnnx':
                    npNN = int(cmd[1].strip())
                elif cmd[0].lower() == 'n-bpm':
                    nBPM = int(cmd[1].strip())
                else:
                    print('Unknown setting', cmd[0])
    except:
        print('File not found, use default setting')

    newFlag = BOOL(False)
    global threadRun
    IBI = PULSEIBI(size=npNN, pNNx=pNNx)
    queue = QUEUE()
    rawpulse = RAWPULSE(length=3, diff=-0.002)
    rawpulse_size = rawpulse.size()
    ThreadStarted = 0

    raw_emotion = np.zeros(
        (8)
    )  #[happy,excite,surprise,strain,sad,ennui,calm,sleep] -> 'pleasure','excite','arouse','distress','misery','depress','sleep','content'
    percent_emotion = [0] * 8
    percent_min_emotion = [0] * 8

    #Prepare for multiprocessing, plot graph
    global ctype_threadRun
    ctype_percent_emotion = multiprocessing.Array('d', [0] * 8)
    ctype_oneMinEmo = multiprocessing.Array('d', [0] * 8)
    ctype_rawpulse = multiprocessing.Array('i', [0] * rawpulse_size)
    ctype_rawpulse_label = multiprocessing.Array('d', rawpulse.label())
    bpm = IBI.BPM()
    if bpm is None:
        ctype_bpm = multiprocessing.Value('i', 0)
    else:
        ctype_bpm = multiprocessing.Value('i', bpm)
    multi_cond = multiprocessing.Condition()

    bv_condition = threading.Condition()
    #Try to connect to the predefined device
    print("Main program is started on PID", os.getpid())
    try:
        pl = threading.Thread(target=pulse.pulsePNN,
                              name="Pulse sensor reader",
                              args=(spi_ch, sensor_ch, threadRun, IBI,
                                    rawpulse))
        pl.daemon = True
        pl.start()
        ThreadStarted = 1
        print("Reading pulse sensor thread is started")
    except:
        e = sys.exc_info()[0]
        print("Can not start the pulse sensor reader thread", e)
        threadRun.stop()
        ctype_threadRun.value = 0
        return

    try:
        pt = multiprocessing.Process(target=plotGraph,
                                     name="Graph plotter",
                                     args=(ctype_threadRun, multi_cond,
                                           ctype_percent_emotion,
                                           ctype_oneMinEmo, ctype_rawpulse,
                                           ctype_rawpulse_label, ctype_bpm))
        pt.daemon = True
        pt.start()
        ThreadStarted = 2
        print("Plotting process is started")
        #Tflag = True
    except:
        e = sys.exc_info()[0]
        print("Can not start the plotting process", e)
        threadRun.stop()
        ctype_threadRun.value = 0
        return

    if macaddr != '':
        mindwaveDataPointReader = MindwaveDataPointReader("20:68:9D:3F:4F:88")
        mindwaveDataPointReader.start()
        if (not mindwaveDataPointReader.isConnected()):
            print("Find another device...")
            mindwaveDataPointReader = MindwaveDataPointReader()
            mindwaveDataPointReader.start()
    else:
        print("Searching for device")
        mindwaveDataPointReader = MindwaveDataPointReader()
        mindwaveDataPointReader.start()

    if (mindwaveDataPointReader.isConnected()):
        print('Connected to', mindwaveDataPointReader.mac())
        try:
            mv = threading.Thread(target=getSignal,
                                  name="mind wave reader",
                                  args=(mindwaveDataPointReader, bv_condition,
                                        threadRun, newFlag, queue, IBI))
            mv.daemon = True
            mv.start()
            ThreadStarted = 3
            print("Reading mind wave thread is started!")
            #Tflag = True
        except:
            e = sys.exc_info()[0]
            print("Can not start the mind wave reader thread", e)
            threadRun.stop()
            ctype_threadRun.value = 0
            return

        #while threadRun.status():
        start = datetime.now()
        oneMinEmo = CIR_ARRAY(60)
        this_emotion = np.empty((8))

        while threadRun:
            #Critical section
            with bv_condition:
                #bv_condition.acquire()
                while not newFlag:
                    bv_condition.wait()
                    if not threadRun:
                        break
                #print queue.getAll()
                qData = queue.getAll()
                #[poorSignal,meditaton,attention,BPM,pNN50]
                now = datetime.now()
                newFlag.false()
            #print('QLEN:',len(qData))
            #print ('\n\tC-RELE')
            #bv_condition.release()
            #End of Critical section
            #The computation unit starts here!
            updateFlag = False
            for data in qData:
                if data[4] is not None and data[0] < 50:
                    arousal = data[1] - data[
                        2]  #Equivalent to kakusei in Tanaka's work
                    updateFlag = True
                    if data[4] < 0.3:
                        pleasure = -100 * (data[4] / 0.3)
                    else:
                        pleasure = 100 * (data[4] - 0.3) / 0.7
                    angle = math.degrees(math.atan2(arousal, pleasure))

                    if angle < 0:
                        angle += 360
                    elif angle >= 360:
                        angle -= 360

                    if angle < 0 or angle > 360:
                        print(
                            'Unexpected error on angle, stopping for 10 seconds'
                        )
                        time.sleep(10)

                    # OLD 'happy','excite','surprise','strain','sad','ennui','calm','sleep'
                    # NEW 'pleasure','excite','arouse','distress','misery','depress','sleep','content'
                    #emotion classification
                    this_emotion[:] = 0
                    '''
                    if angle < 45:
                        #angle between 0 - 44
                        raw_emotion[0] += 1
                        raw_emotion[1] += 1

                        this_emotion[0] += 1
                        this_emotion[1] += 1
                    elif angle < 90:
                        #angle between 45 - 89
                        raw_emotion[2] += 1
                        raw_emotion[1] += 1

                        this_emotion[2] += 1
                        this_emotion[1] += 1
                    elif angle < 135:
                        #angle between 90 - 134
                        raw_emotion[2] += 1
                        raw_emotion[3] += 1

                        this_emotion[2] += 1
                        this_emotion[3] += 1
                    elif angle < 180:
                        #angle between 135 - 179
                        raw_emotion[4] += 1
                        raw_emotion[3] += 1

                        this_emotion[4] += 1
                        this_emotion[3] += 1
                    elif angle < 225:
                        #angle between 180 - 224
                        raw_emotion[4] += 1
                        raw_emotion[5] += 1

                        this_emotion[4] += 1
                        this_emotion[5] += 1
                    elif angle < 270:
                        #angle between 225 - 269
                        raw_emotion[7] += 1
                        raw_emotion[5] += 1

                        this_emotion[7] += 1
                        this_emotion[5] += 1
                    elif angle < 315:
                        #angle between 270 - 314
                        raw_emotion[7] += 1
                        raw_emotion[6] += 1

                        this_emotion[7] += 1
                        this_emotion[6] += 1
                    else:
                        #angle between 315 - 359
                        raw_emotion[0] += 1
                        raw_emotion[6] += 1

                        this_emotion[0] += 1
                        this_emotion[6] += 1
                    '''
                    if angle < 45:
                        #pleasure - excite
                        #angle between 0 - 44
                        emotionB = angle / 45.0
                        emotionA = 1 - emotionB

                        raw_emotion[0] += emotionA
                        raw_emotion[1] += emotionB

                        this_emotion[0] += emotionA
                        this_emotion[1] += emotionB
                    elif angle < 90:
                        #excite - arouse
                        #angle between 45 - 89
                        emotionB = (angle - 45.0) / 45.0
                        emotionA = 1 - emotionB

                        raw_emotion[1] += emotionA
                        raw_emotion[2] += emotionB

                        this_emotion[1] += emotionA
                        this_emotion[2] += emotionB
                    elif angle < 135:
                        #arouse - distress
                        #angle between 90 - 134
                        emotionB = (angle - 90.0) / 45.0
                        emotionA = 1 - emotionB

                        raw_emotion[2] += emotionA
                        raw_emotion[3] += emotionB

                        this_emotion[2] += emotionA
                        this_emotion[3] += emotionB
                    elif angle < 180:
                        #distress - misery
                        #angle between 135 - 179
                        emotionB = (angle - 135.0) / 45.0
                        emotionA = 1 - emotionB

                        raw_emotion[3] += emotionA
                        raw_emotion[4] += emotionB

                        this_emotion[3] += emotionA
                        this_emotion[4] += emotionB
                    elif angle < 225:
                        #misery - depress
                        #angle between 180 - 224
                        emotionB = (angle - 180.0) / 45.0
                        emotionA = 1 - emotionB

                        raw_emotion[4] += emotionA
                        raw_emotion[5] += emotionB

                        this_emotion[4] += emotionA
                        this_emotion[5] += emotionB
                    elif angle < 270:
                        #depress - sleep
                        #angle between 225 - 269
                        emotionB = (angle - 225.0) / 45.0
                        emotionA = 1 - emotionB

                        raw_emotion[5] += emotionA
                        raw_emotion[6] += emotionB

                        this_emotion[5] += emotionA
                        this_emotion[6] += emotionB
                    elif angle < 315:
                        #sleep - content
                        #angle between 270 - 314
                        emotionB = (angle - 270.0) / 45.0
                        emotionA = 1 - emotionB

                        raw_emotion[6] += emotionA
                        raw_emotion[7] += emotionB

                        this_emotion[6] += emotionA
                        this_emotion[7] += emotionB
                    else:
                        #content - pleasure
                        #angle between 315 - 360
                        emotionB = (angle - 315.0) / 45.0
                        emotionA = 1 - emotionB

                        raw_emotion[7] += emotionA
                        raw_emotion[0] += emotionB

                        this_emotion[7] += emotionA
                        this_emotion[0] += emotionB
                    print('emotion: ', raw_emotion, round(data[4], 2), angle)
                    oneMinEmo.put(this_emotion)
                else:
                    oneMinEmo.put([0, 0, 0, 0, 0, 0, 0, 0])

            #Updating the graph
            if updateFlag:
                #Calculate the graph
                raw_sum = raw_emotion.sum()
                if raw_sum != 0:
                    percent_emotion[:] = raw_emotion * (100 /
                                                        raw_emotion.sum())
                else:
                    percent_emotion[:] = [0] * 8

            #Calculate the one min graph
            oneMin = oneMinEmo.get()
            oneMin_raw = np.array([sum(x) for x in zip(*oneMin)])
            oneMin_sum = sum(oneMin_raw)
            if oneMin_sum != 0:
                factor = 100.0 / oneMin_sum
                percent_min_emotion[:] = oneMin_raw * (100.0 / oneMin_sum)
            else:
                percent_min_emotion[:] = [0] * 8

            with multi_cond:
                ctype_percent_emotion[:] = percent_emotion
                ctype_oneMinEmo[:] = percent_min_emotion
                ctype_rawpulse[:] = rawpulse.get()
                bpm = IBI.BPM(nBPM)
                if bpm is None:
                    ctype_bpm.value = 0
                else:
                    ctype_bpm.value = int(round(bpm))
                multi_cond.notify()

    with multi_cond:
        multi_cond.notify()
    mindwaveDataPointReader.close()
    if ThreadStarted == 1:
        if pl.is_alive():
            pl.join(5)
        print("1 Child thread are successfully closed")
    elif ThreadStarted == 2:
        if pl.is_alive():
            pl.join(5)
        if pt.is_alive():
            pt.join(5)
        print("2 Child thread are successfully closed")
    elif ThreadStarted == 3:
        if pl.is_alive():
            pl.join(5)
        if mv.is_alive():
            mv.join(5)
        if pt.is_alive():
            pt.join(10)
        print("3 Child thread are successfully closed")
    sys.exit(0)
Exemple #18
0
import time
import bluetooth
from mindwavemobile.MindwaveDataPoints import RawDataPoint
from mindwavemobile.MindwaveDataPointReader import MindwaveDataPointReader
import textwrap

if __name__ == '__main__':
    #    mindwaveDataPointReader = MindwaveDataPointReader()
    mindwaveDataPointReader = MindwaveDataPointReader("CC:78:AB:15:40:93")
    mindwaveDataPointReader.start()
    if (mindwaveDataPointReader.isConnected()):
        while (True):
            try:
                dataPoint = mindwaveDataPointReader.readNextDataPoint()
                if (not dataPoint.__class__ is RawDataPoint):
                    print dataPoint
            except IndexError:
                pass
    else:
        print(
            textwrap.dedent("""\
            Exiting because the program could not connect
            to the Mindwave Mobile device.""").replace("\n", " "))
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)
Exemple #20
0
def init():
    global mindwaveDataPointReader
    mindwaveDataPointReader = MindwaveDataPointReader()
    mindwaveDataPointReader.start()
Exemple #21
0
     if playername == 'player1_val':
         print "Player 1"
         target_address = '/dev/tty.MindWaveMobile-DevA'
     elif playername == 'player2_val':
         target_address = '/dev/tty.MindWaveMobile-DevA-2'
         #target_address = "/dev/tty.MindWaveMobile-DevA"
 
 if not target_address:
     raise IOError("No valid serial port address")
     #return
     
 print "Serial port address: " + target_address
 print "Running " + playername
 print "Connecting to MWM...",
 try:
     mindwaveDataPointReader = MindwaveDataPointReader(target_address)
     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
     #return
     
 print " connected"
 
 # datastream = collections.deque;
 rawdatastream = deque()
 attentiondata = deque()
 meditationdata = deque()
 bwdata = deque()
 # Delta (0.5 - 2.75Hz), theta (3.5 - 6.75Hz), low-alpha (7.5 - 9.25Hz), 
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()