def setup_experiment():
    """
    Intialize the environment for the experiment

    Returns:
    the window
    """
    bufhelp.connect()

    plt.rcParams['toolbar'] = 'None'
    fig = plt.figure()
    fig.patch.set_facecolor('black')
    ax = fig.add_subplot(1, 1, 1)
    ax.set_xlim((-1, 1))
    ax.set_ylim((-1, 1))
    ax.set_axis_off()
    ax.set_facecolor('black')
    text = ax.text(0,
                   0,
                   'STARTING',
                   color='white',
                   fontsize=120,
                   ha='center',
                   va='center')
    drawnow()
    return text
Beispiel #2
0
def signalproxy(fSample=100, nChans=10, blocksize=2):
    from time import sleep, time
    import numpy

    ftc = bufhelp.connect(header=False)

    print "Putting header."

    ftc.putHeader(nChans, fSample, 10)

    print "Starting singal proxy"

    delta = 1.0 / (fSample / blocksize)
    sample = numpy.random.rand(blocksize, nChans)
    n = 0;

    while True:
        sendtime = time()
        ftc.putData(sample)
        n = n + 1
        if n % 100 == 0:
            print str(n) + " data packages sent."
        sample = numpy.random.rand(blocksize, nChans)
        wait = delta - (time() - sendtime)
        if wait > 0:
            sleep(wait)
Beispiel #3
0
def echoClient(timeout=5000):
        		
    ## init connection to the buffer
    ftc,hdr=bufhelp.connect();

    # Now do the echo client
    nEvents=hdr.nEvents;
    endExpt=None;
    while endExpt is None:
        bufhelp.sendEvent('echo',1)
        
        # wait for ackknowledgement from Server
        ack_received = False
        while ack_received is False:
            (curSamp,curEvents)=ftc.wait(-1,nEvents,timeout) # Block until there are new events to process
            if curEvents>nEvents :
                evts=ftc.getEvents([nEvents,curEvents-1]) 
                nEvents=curEvents # update record of which events we've seen
                for evt in evts:
                    if evt.type == "exit": endExpt=1
                    if evt.type == "ack": ack_received = True
                    print(evt)
            else:
                print("Waiting for acknowledgement...")
    
    ftc.disconnect() # disconnect from buffer when done
def echoClient(timeout=5000):

    ## init connection to the buffer
    ftc, hdr = bufhelp.connect()

    # Now do the echo client
    nEvents = hdr.nEvents
    endExpt = None
    while endExpt is None:
        bufhelp.sendEvent('echo', 1)

        # wait for ackknowledgement from Server
        ack_received = False
        while ack_received is False:
            (curSamp, curEvents) = ftc.wait(
                -1, nEvents,
                timeout)  # Block until there are new events to process
            if curEvents > nEvents:
                evts = ftc.getEvents([nEvents, curEvents - 1])
                nEvents = curEvents  # update record of which events we've seen
                for evt in evts:
                    if evt.type == "exit": endExpt = 1
                    if evt.type == "ack": ack_received = True
                    print(evt)
            else:
                print("Waiting for acknowledgement...")

    ftc.disconnect()  # disconnect from buffer when done
 def __init__(self):
     self.si = SOSInterface()
     self.controller = EnvController()
     self.num_of_options = self.si.prepare_main_screen()
     ftc, hdr = bufhelp.connect()
     if (DEBUG):
         self.all_predictions = []
         self.all_targets = []
 def __init__(self):
     self.si = StimulusInterface()
     self.controller = EnvController()
     info = self.si.prepare_main_screen()
     self.num_of_options, self.num_of_groups = info[:2]
     self.row_indices, self.column_indices = info[2:]
     ftc, hdr = bufhelp.connect()
     if (DEBUG):
         self.all_predictions = []
         self.all_targets = []
Beispiel #7
0
    def send_prior_loop(events, timeout=2):

        ## init connection to the buffer
        ftc, hdr = bufhelp.connect()

        ev_list = []

        # Now do the echo client
        nEvents = hdr.nEvents
        endExpt = None
        bufhelp.sendEvent('prior.start', '1')

        priors = calc_priors(ev_list)
        bufhelp.sendEvent('priors', priors.to_csv())
        priors.to_csv('priors.csv')
        # bufhelp.sendEvent('p300preds', priors.to_csv())
        i = 0
        while endExpt is None:
            (curSamp, curEvents) = ftc.wait(
                -1, nEvents,
                timeout)  # Block until there are new events to process
            if curEvents > nEvents:
                evts = ftc.getEvents([nEvents, curEvents - 1])
                nEvents = curEvents  # update record of which events we've seen
                for evt in evts:
                    if evt.type == "exit": endExpt = 1
                    if evt.type == "p300preds":
                        # read classifier predictions
                        preds = pd.read_csv(StringIO(evt.value),
                                            header=None).set_index(0)[1]
                        preds = preds.drop('pause')
                        preds.to_csv('p300pred_wouter' + str(i) + '.csv')
                        i += 1
                        print(priors)
                        print('preds', preds)
                        p = preds * priors
                        print(p)
                        p /= sum(p)
                        print(p)
                        best = p.sort_values().index[-1]
                        best_event, best_value = best.split('.')
                        if best_event == 'sos':
                            bufhelp.sendEvent('sos', 'start')
                        # send actual event to virtual environment
                        bufhelp.sendEvent(best_event, best_value)
                        # send event to MatLab code
                        bufhelp.sendEvent('finalprediction',
                                          best_event + '.' + best_value)
                        ev_list.append(best)
                        priors = calc_priors(ev_list)
                        priors.to_csv('priors.csv')

                    # print(evt)

        ftc.disconnect()  # disconnect from buffer when done
Beispiel #8
0
def echoClient(timeout=5000):
        		
    ## init connection to the buffer
    ftc,hdr=bufhelp.connect();

    # send event to buffer
    bufhelp.sendEvent('echo',1)
        
    # wait for ackknowledgement from Server
       
    ftc.disconnect() # disconnect from buffer when done
Beispiel #9
0
def echoClient(timeout=5000):

    ## init connection to the buffer
    ftc, hdr = bufhelp.connect()

    # send event to buffer
    bufhelp.sendEvent('echo', 1)

    # wait for ackknowledgement from Server

    ftc.disconnect()  # disconnect from buffer when done
Beispiel #10
0
def echoClient(timeout=5000):
        		
    ## init connection to the buffer
    ftc,hdr=bufhelp.connect();

    # send event to buffer
    while True:
        events = bufhelp.buffer_newevents(state=True)

        for event in events:
            if event.type == 'quit':
                ftc.disconnect()
                return
            elif event.type != 'echo':
                bufhelp.sendEvent('echo', event.value)
stimPos=np.stack((np.cos(theta),np.sin(theta))) #[2 x nSymbs]
for hi,pos in enumerate(stimPos):
    rect=patches.Rectangle((pos[0]-stimRadius/2,pos[1]-stimRadius/2),stimRadius/2,stimRadius/2,facecolor=bgColor)
    hhi=ax.add_patch(rect)
    hdls.insert(hi,hhi)
# add symbol for the center of the screen
spos = np.array((0,0)).reshape((-1,1))
stimPos=np.hstack((stimPos,spos)) #[2 x nSymbs+1]
rect = patches.Rectangle((0-stimRadius/4,0-stimRadius/4),stimRadius/2,stimRadius/2,facecolor=bgColor)
hhi  =ax.add_patch(rect)
hdls.insert(nSymbs,hhi)
[ _.set(visible=False) for _ in hdls] # make all invisible


## init connection to the buffer
ftc,hdr=bufhelp.connect();

#wait for key-press to continue
[_.set(facecolor=bgColor) for _ in hdls]
txthdl.set(text='Press key to start')
drawnow()
waitforkey(fig)

bufhelp.sendEvent('stimulus.training','start')
state=None
## STARTING stimulus loop
for si,tgt in enumerate(tgtSeq):
    
    # YOUR CODE HERE #

    #catch the prediction
Beispiel #12
0

# Loading the preproc and bufhelp libraries, preproc provides the processing functions for the signal data
# bufhelp will provide the connection to the buffer, where al programs can pass events

Path_Preproc = "/../python/signalproc"         # This variable contains the path to the folder where the libraries files are
sys.path.append(os.getcwd() + Path_Preproc)    # This allows to load the libraries this way
import preproc                                 # Loading
import bufhelp


Path_FieldTrip = "../dataAcq/buffer/python"    # Variable which contains the path to the Fieldtrip library 
sys.path.append(os.getcwd() + Path_FieldTrip)  
import FieldTrip

ftc,hdr=bufhelp.connect()                     #This functions connects the program to the buffer, and the passing of messages

##### Variables #####

verbose = True                                # For True values, the terminal will detail what it's happening inside the program

im_length = 3000                              # Length of time that the signal will be collected
# This time should be the same as the time used to collect the data to train the classifier, 
#otherwise, the sizes of the classifier training and the processed signal wont match


classifier_right_name =  'classifier_right'   # Name of the file with the classifier for the right hand, must be of pk type
classifier_left_name  =  'classifier_left'    # Name of the file with the classifier for the left hand, must be of pk type


Beispiel #13
0
#!/usr/bin/env python3
import sys,os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),"../../dataAcq/buffer/python"))
sys.path.append("../signalProc")
import preproc
import bufhelp
#import linear
import pickle

bufhelp.connect()

trlen_ms = 600
run = True

print ("Waiting for startPhase.cmd event.")
while run:
    e = bufhelp.waitforevent("startPhase.cmd",1000, True)
    print("Got startPhase event: %s"%e)
    if e is not None:

        if e.value == "calibration":
            print("Calibration phase")
            data, events, stopevents = bufhelp.gatherdata("stimulus.tgtFlash",trlen_ms,("stimulus.training","end"), milliseconds=True)
            pickle.dump({"events":events,"data":data}, open("subject_data", "w"))

        elif e.value == "train":
            print("Training classifier")
            data = preproc.detrend(data)
            data, badch = preproc.badchannelremoval(data)
            data = preproc.spatialfilter(data)
            data = preproc.spectralfilter(data, (0, .1, 10, 12), bufhelp.fSample)
Beispiel #14
0
# Sends a command to BrainRacer.
def send_command(command):
    global br_socket
    print("Send cmd " + str(command))
    cmd = (br_player * 10) + command
    data = struct.pack('B', cmd)

    br_socket.sendto(data, (br_hostname, br_port))


#Connect to BrainRacers
br_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

#Connect to Buffer
(ftc, hdr) = bufhelp.connect(buffer_hostname, buffer_port)
print("Connected to " + buffer_hostname + ":" + str(buffer_port))
print(hdr)


def max2(numbers):
    i1 = i2 = None
    m1 = m2 = float('-inf')
    for i, v in enumerate(numbers):
        if v > m2:
            if v >= m1:
                m1, m2 = v, m1
                i1, i2 = i, i1
            else:
                m2 = v
                i2 = i
Beispiel #15
0
# Sends a command to BrainRacer.
def send_command(command):
    global br_socket
    print("Send cmd " + str(command))
    cmd = (br_player * 10) + command
    data = struct.pack("B", cmd)

    br_socket.sendto(data, (br_hostname, br_port))


# Connect to BrainRacers
br_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Connect to Buffer
(ftc, hdr) = bufhelp.connect(buffer_hostname, buffer_port)
print("Connected to " + buffer_hostname + ":" + str(buffer_port))
print(hdr)


def max2(numbers):
    i1 = i2 = None
    m1 = m2 = float("-inf")
    for i, v in enumerate(numbers):
        if v > m2:
            if v >= m1:
                m1, m2 = v, m1
                i1, i2 = i, i1
            else:
                m2 = v
                i2 = i
Beispiel #16
0
if braincontrol:
    sys.path.append(
        os.path.join(os.path.dirname(os.path.abspath(__file__)), bufferpath))
    import FieldTrip
    import bufhelp
    sys.path.append(
        os.path.join(os.path.dirname(os.path.abspath(__file__)), sigProcPath))

    ## CONFIGURABLE VARIABLES
    # Connection options of fieldtrip, hostname and port of the computer running the fieldtrip buffer.
    hostname = 'localhost'
    port = 1972

    ## init connection to the buffer
    timeout = 5000
    (ftc, hdr) = bufhelp.connect(hostname, port)

    # Wait until the buffer connects correctly and returns a valid header
    hdr = None
    while hdr is None:
        print(('Trying to connect to buffer on %s:%i ...' % (hostname, port)))
        try:
            ftc.connect(hostname, port)
            print('\nConnected - trying to read header...')
            hdr = ftc.getHeader()
        except IOError:
            pass

        if hdr is None:
            print('Invalid Header... waiting')
            sleep(1)
Beispiel #17
0

def draw_enemies(enemies, screen):
    """Draw the enemies and the red line behind them"""
    for enemy in enemies:
        pygame.draw.line(screen, [155, 10, 10], [0, enemy.rect.center[1]], [screen_rect[0], enemy.rect.center[1]], 3)
    enemies.draw(screen)


# Set up the game
screen = pygame.display.set_mode(RESOLUTION, DOUBLEBUF | NOFRAME)
screen_rect = screen.get_rect()
screen_rect = np.array([screen_rect.w, screen_rect.h])
clock = pygame.time.Clock()
keys = defaultdict(bool)
if not SIMULATION: bufhelp.connect()

score = n_shots = n_deaths = n_hits = 0
rect = screen.get_rect()
ship = ShipSprite()
ship_group = pygame.sprite.RenderPlain(ship)
controller = ProbablisticConroller(alpha=0.5*PREDICTION_TIME) if SIMULATION else PlayerController()
enemy_group = pygame.sprite.RenderPlain()
bullet_group = pygame.sprite.RenderPlain()
last_enemy_spawned = -ENEMY_SPAWN_TIME
ship_start_pos = 0
last_pred_time = 0
left = True
pygame.init()
font = pygame.font.Font(pygame.font.get_default_font(), 16)
lasttime = last_bullet_spawned = game_start_time = time.time()
Beispiel #18
0
#!/usr/bin/env python3
import sys, os
sys.path.append(
    os.path.join(os.path.dirname(os.path.abspath(__file__)),
                 "../../dataAcq/buffer/python"))
sys.path.append("../signalProc")
import preproc
import bufhelp
#import linear
import pickle

bufhelp.connect()

trlen_ms = 600
run = True

print("Waiting for startPhase.cmd event.")
while run:
    e = bufhelp.waitforevent("startPhase.cmd", 1000, True)
    print("Got startPhase event: %s" % e)
    if e is not None:

        if e.value == "calibration":
            print("Calibration phase")
            data, events, stopevents = bufhelp.gatherdata(
                "stimulus.tgtFlash",
                trlen_ms, ("stimulus.training", "end"),
                milliseconds=True)
            pickle.dump({
                "events": events,
                "data": data