Beispiel #1
0
def main():
    try:
        duration = int(sys.argv[1])
    except:
        print "Usage: %s <duration> [ch1,ch2,..,chN]" % sys.argv[0]
        return 1

    channels = None
    try:
        channels = sys.argv[2].split(",")
    except:
        pass

    # Setup headset
    headset = epoc.EPOC(enable_gyro=False)
    if channels:
        headset.set_channel_mask(channels)

    # Acquire
    idx, data = headset.acquire_data_fast(duration)

    print "Battery: %d %%" % headset.battery
    print "Contact qualities"
    print headset.quality

    utils.save_as_matlab(data, headset.channel_mask)

    try:
        headset.disconnect()
    except e:
        print e
def main():

    try:
        ssvepd_pid = int(open(SSVEPD_PID, "r").read())
    except:
        print "SSVEP service is not running."
        return 1

    try:
        sock = socket.socket(socket.AF_UNIX)
        sock.connect(DSPD_SOCK)
    except:
        print "Can't connect to DSP block."
        return 1

    # Setup headset
    headset = epoc.EPOC(enable_gyro=False)
    headset.set_channel_mask(["O1", "O2", "P7", "P8"])

    # Experiment duration
    duration = 4
    try:
        duration = int(sys.argv[1])
    except:
        pass

    # Experiment data (7 bytes)
    experiment = get_subject_information()
    sock.send("%7s" % experiment)

    # Send 4 bytes of data for duration
    sock.send("%4d" % duration)

    # Send comma separated list of enabled channels (49 bytes max.)
    channel_conf = "CTR," + ",".join(headset.channel_mask)
    sock.send("%49s" % channel_conf)

    os.kill(ssvepd_pid, signal.SIGUSR1)
    for i in range(duration):
        # Fetch 1 second of data each time
        data = headset.acquire_data(1)

        # Send the data to DSP block
        sock.sendall(data.tostring())

    os.kill(ssvepd_pid, signal.SIGUSR1)

    # Close devices
    try:
        headset.disconnect()
        sock.close()
    except e:
        print e
Beispiel #3
0
def main():
    # Setup headset
    headset = epoc.EPOC()

    try:
        d = headset.get_sample()
        prev_ctr = headset.counter
        while 1:
            d = headset.get_sample()
            ctr = headset.counter
            if (prev_ctr + 1) % 129 != ctr:
                print "Dropped packets between %d and %d" % (prev_ctr, ctr)
            prev_ctr = ctr
    except:
        headset.disconnect()
        return 0
def main():
    print "Running Data Aquisition: Press any key to terminate at the end of the block."

    channels = None
    try:
        channels = sys.argv[1].split(",")
    except:
        pass

    # Setup headset
    headset = epoc.EPOC(enable_gyro=False)
    if channels:
        headset.set_channel_mask(channels)

    # Acquire
    dataAcquisitionLoop(headset)
    #print "Data Acquisition Terminated."
    try:
        headset.disconnect()
    except e:
        print e
Beispiel #5
0
def main():
    duration = float(WL/fs)

    
    channels = col_list
    print(channels)
    
    # Setup headset
    headset = epoc.EPOC(enable_gyro=False)
    if channels:
        headset.set_channel_mask(channels)

    # Acquire
    idx, data = headset.acquire_data_fast(duration)
    print(np.shape(data))
    #data = data[:, cols]
    data = np.transpose(data)
    data = data.reshape(1, data.shape[0], data.shape[1], 1)
    train_mean = np.load('train_mean.npy')
    train_std = np.load('train_std.npy')

    img_arr = (img_arr -train_mean.reshape((-1,D,WL,1)))/train_std.reshape((-1,D,WL,1))

    filepath = "./models/WL=150_labels_5_electrodes_['F8', 'F3', 'FC5', 'AF3']_lr_0.001_filter_no._[50, 50, 20]_filt_frac_img_[0.25, 0.25]_drop_0.1_one_d_200_epochs_200.h5"
    model = load_model(filepath)
    pred = model.predict(img_arr)
    print(pred)

    print ("Battery: %d %%" % headset.battery)
    print ("Contact qualities")
    print (headset.quality)

    #utils.save_as_matlab(data, headset.channel_mask)

    try:
        headset.disconnect()
    except e:
        print (e)
        print "Error: Can't launch SSVEP/DSP subprocesses: %s" % e
        sys.exit(2)

    # Open socket to DSP process if any
    if dspd:
        sock = socket.socket(socket.AF_UNIX)
        sock_connected = False
        for i in range(10):
            try:
                sock.connect(DSPD_SOCK)
                sock_connected = True
            except:
                time.sleep(0.5)

    # Setup headset
    headset = epoc.EPOC(enable_gyro=False)
    headset.set_channel_mask(["O1", "O2", "P7", "P8"])

    # Collect experiment information
    experiment = get_subject_information()
    experiment['channel_mask'] = headset.channel_mask
    experiment['n_trials'] = n_trials
    experiment['trial_duration'] = duration

    # Equal amount of trials for each LED will be randomized
    cues = ["Left" for i in range(n_trials / 2)
            ] + ["Right" for i in range(n_trials / 2)]
    random.shuffle(cues)
    random.shuffle(cues)
    experiment['cues'] = cues
#!/usr/bin/env python

import pylsl
import time

try:
    from emotiv import epoc
except ImportError:
    sys.path.insert(0, "..")
    from emotiv import epoc

if __name__ == '__main__':

    headset = epoc.EPOC()
    print "Found headset with serial number: ", headset.serial_number

    info = pylsl.stream_info('Emotiv EEG', 'EEG', len(headset.channel_mask),
                             headset.sampling_rate, pylsl.cf_int16,
                             str(headset.serial_number))

    info_desc = info.desc()
    info_desc.append_child_value("manufacturer", "Emotiv")
    channels = info_desc.append_child("channels")

    for ch in headset.channel_mask:
        channels.append_child("channel").append_child_value(
            "label", ch).append_child_value("unit",
                                            "microvolts").append_child_value(
                                                "type", "EEG")

    # Outgoing buffer size = 360 seconds, transmission chunk size = 32 samples
Beispiel #8
0
#!/usr/bin/env python

import emotiv.epoc as ep
import time
import numpy as np
from socketIO_client import SocketIO

# e = ep.EPOC("dummy")
e = ep.EPOC()

import logging
logging.basicConfig(level=logging.DEBUG)

with SocketIO('localhost', 8080) as socketIO:
    while 1:
        try:
            data = e.get_sample()
            if data:
                for i, channel in enumerate(e.channel_mask):
                    print "%10s: %.2f %20s: %.2f" % (
                        channel, data[i], "Quality", e.quality[channel])
                zipdata = dict((i, x) for i, x in zip(e.channel_mask, data))
                socketIO.emit('aaa', zipdata)
                # time.sleep(0.01)
        except EPOCTurnedOffError, ete:
            print ete
        except KeyboardInterrupt, ki:
            e.disconnect()
def data_collector(state_queue, file_name, dummy):
    import tables, time, numpy
    from matplotlib.dates import date2num
    from emotiv import epoc
    from path import path
    from itertools import izip
    from datetime import datetime
    from lockfile import FileLock

    #    lock = FileLock(file_name)
    if path(file_name).exists():
        raise Exception('Recording "{}" already exists'.format(file_name))
#         h5file = tables.open_file(file_name, mode="a", title='[Title] EEG Signal')
#         h5table = h5file.root.eeg.signal
    else:
        h5file = tables.open_file(file_name,
                                  mode="w",
                                  title='[Title] EEG Signal')
        h5group = h5file.create_group("/", 'eeg', '[Group] EEG signal')
        h5table = h5file.create_table(h5group, 'signal', EEGTick,
                                      "[Table] EEG Signal")
    row = h5table.row

    e = epoc.EPOC(method='dummy' if dummy else 'libusb')
    try:
        cycle, last_tick, last_packet = -1, -1, 0
        current_state = 'neutral'
        while True:
            if dummy:
                time.sleep(0.0077)
            sample, tick, tick_time = e.get_sample(
            ), e.counter, numpy.datetime64(datetime.utcnow()).astype(
                numpy.uint64)
            if not state_queue.empty():
                current_state = state_queue.get_nowait()
            if current_state == 'quit':
                break
            if tick < last_tick and last_tick != -1:
                cycle += 1
            last_tick = tick
            packet = cycle * (SAMPLING_RATE + 1) + tick
            packets_skipped = packet - last_packet - 1
            last_packet = packet
            if tick == 128 or cycle == -1:
                continue
#             with lock:
            row['state'], row['packet'], row['tick'], row[
                'tick_time'] = current_state, packet, tick, tick_time
            row['packets_skipped'], row['battery'] = packets_skipped, e.battery
            row['gyroX'], row['gyroY'] = e.gyroX, e.gyroY
            for channel, value in izip(CHANNELS, sample):
                row[channel], row[channel +
                                  '_QUAL'] = value, e.quality[channel]
            row.append()
            h5table.flush()
    except KeyboardInterrupt:
        pass
    finally:
        e.disconnect()
        #         with lock:
        h5table.flush()
def main():

    # Setup headset
    headset = epoc.EPOC(method="direct")
    headset.set_channel_mask(["O1", "O2"])

    # Setup pins
    GPIO.setmode(GPIO.BOARD)

    # Experiment duration
    duration = 4
    try:
        duration = int(sys.argv[1])
    except:
        pass

    # Process pool
    pool = []

    # Stimuli and experiment information
    stimuli = {
        PIN_LEFT_ARM: 10.8,
        PIN_RIGHT_ARM: 15,
    }

    experiment = {
        "SSVEP": stimuli.values(),
        "Duration": duration,
        "LED": "Green",
        "Subject": "OC",
        "Age": 28,
        "Date": time.strftime("%d-%h-%Y %H:%M"),
    }

    # Spawn processes
    for pin, frequency in stimuli.items():
        if frequency > 0:
            process = Process(target=blinkLed, args=(pin, frequency))
            process.daemon = True
            pool.append(process)

    # Resting EEG
    eeg_rest = headset.acquire_data(duration)

    # Start flickering
    for process in pool:
        process.start()

    # SSVEP EEG
    eeg_ssvep = headset.acquire_data(duration)

    # Stop LED's
    for p in pool:
        p.terminate()

    # Close devices
    try:
        headset.disconnect()
        GPIO.cleanup()
    except e:
        print e

    # Finally, save the data as matlab files
    headset.save_as_matlab(eeg_ssvep, "eeg-ssvep", experiment)
    headset.save_as_matlab(eeg_rest, "eeg-resting", experiment)