def GetResponse():
    global currentRule, currentTgt, ruleCount, rightAnswers, gameScore

    event.clearEvents()

    retVal = 0 #if not modified, breaks the task
    answerPressed = -1 # which card was selected?

    keylist = { 'down': ['down', '2'], 'left': ['left', '4'], 'up': ['up', '8'], 'right': ['right', '6']}

    keys = event.waitKeys(keyList=['f10', 'escape', 'up', 'right', 'down', 'left', '2', '4', '6', '8'])

    if keys[0] == 'f10':
        triggerAndLog(portCodes['stop'], "STP", 0, 0, "STOP: aborted by F10")
        win.close()
        core.quit()

    if keys[0] == 'escape':
        retVal = 0
    #elif keys[0] == 'up':
    elif keys[0] in keylist['up']:
        if CheckCard( 0, currentRule, currentTgt ):
            rightAnswers += 1
            retVal = 1
        else:
            retVal = -1
    #elif keys[0] == 'right':
    elif keys[0] in keylist['right']:
        if CheckCard( 1, currentRule, currentTgt ):
            rightAnswers += 1
            retVal = 2
        else:
            retVal = -2
    #elif keys[0] == 'down':
    elif keys[0] in keylist['down']:
        if CheckCard( 2, currentRule, currentTgt ):
            rightAnswers += 1
            retVal = 3
        else:
            retVal = -3
    #elif keys[0] == 'left':
    elif keys[0] in keylist['left']:
        if CheckCard( 3, currentRule, currentTgt ):
            rightAnswers += 1
            retVal = 4
        else:
            retVal = -4

    idx=str(rules.index(currentRule)+1)

    if retVal > 0:
        gameScore += 1
        triggerAndLog( portCodes['respRight'] + portCodes['rule'+idx],\
        "RSP", currentBlock, currentTrial, 'RESPONSE 1 ' + currentRule + ' ANSWER ' + str(retVal) )
    elif retVal < 0:
        gameScore -= 1
        triggerAndLog( portCodes['respWrong'] + portCodes['rule'+idx],\
        "RSP", currentBlock, currentTrial, 'RESPONSE 0 ' + currentRule + ' ANSWER ' + str(retVal) )
    
    return retVal
Exemplo n.º 2
0
    def run_preferential_gaze(self):
        cont=True
        for i in range(self.preferential_gaze_trials):
            self.distractor_set.show_video()

            # clear any keystrokes before starting
            event.clearEvents()

            self.preferential_gaze.run(self.ns, self.eye_tracker, self.mouse, self.gaze_debug, self.debug_sq)

            # Check user input
            all_keys = event.getKeys()
            if len(all_keys):
                # Quit experiment
                if all_keys[0].upper() in ['Q', 'ESCAPE']:
                    cont = False
                    break
                # Pause block
                elif all_keys[0].upper() == 'P':
                    self.pause()
                # End block
                elif all_keys[0].upper() == 'E':
                    break
                event.clearEvents()

        return cont
Exemplo n.º 3
0
def textInput():
    #until return pressed, listen for letter keys & add to text string
    text = ''
    while event.getKeys(keyList=['escape'])==[]:
        letterlist=event.getKeys()
        letterDict = {'space': ' '}
#        letterlist=event.getKeys(keyList=['0','1','2','3','4','5','6','7','8','9','backspace'])

        for l in letterlist:
            if l == 'space':
                text += ' '
            elif l == 'return':
                text += '\n'
            #if key isn't backspace, add key pressed to the string
            elif l != 'backspace':
                text += l
            #otherwise, take the last letter off the string
            elif len(text)>0:
                text = text[:-1]
        #continually redraw text onscreen until return pressed

        textObject = visual.TextStim(win=win, ori=0, name='pause', text=text, font=u'Arial', pos=[0, 0],
                                     height=1.0, wrapWidth=None, color=u'white', colorSpace=u'rgb', opacity=1, depth=-1.0)

        # textReport.draw()
        textObject.draw()
        win.flip()
    text = str(text)
    event.clearEvents()
    print text
    return text
Exemplo n.º 4
0
def practicerounds(r):
        already = True#why is this here again?
        bet = 999
        #load words
        words = ["one","two","three"]
        #show words
        event.clearEvents()
        if r == 0:
            while event.getKeys(keyList=['return'])==[]:#wait till ready
                instructions2[3].draw()
                mywin.flip()
        questions.draw()#draw blank
        w = visual.TextStim(mywin, height=55,text= words[rq],color="white",pos=(0,0))
        if already == True:
            w.draw()
            mywin.flip()#show word
            core.wait(2)#wait 2 seconds
            #THIS IS WHERE THE TIMING STUFF WILL GO
        while bet > 10:
            print type(bet)
            print bet
            betAsk.draw()#ask how much they want to bet
            mywin.flip()
            trialtime = core.Clock()
            trialtime.reset()
            bet = WaitForKeyInput() #recieve bet input
            try:
                bet = int(bet)
            except ValueError:
                bet = 999
                continue
            RT = trialtime.getTime()
def RunTrial(goForward, nKeys):

    # get trial start time
    tTrial = globalClock.getTime() * 1000
    # reset trial clock
    trialClock.reset()
    # clear event buffer
    event.clearEvents()

    # display response direction
    line.draw()
    if goForward:
        rightArrow.draw()
        win.logOnFlip(level=logging.EXP, msg="Right Arrow")
    else:
        leftArrow.draw()
        win.logOnFlip(level=logging.EXP, msg="Left Arrow")
    win.flip()
    # wait for responses
    #    core.wait(respDur)

    # get responses
    allKeys = []
    while len(allKeys) < nKeys and trialClock.getTime() < respDur:
        newKeys = event.getKeys(timeStamped=trialClock)
        for thisKey in newKeys:
            allKeys.append(thisKey)  # ,keyList=['1','2','3','4','q','Escape']

    #    allKeys = event.getKeys(timeStamped=trialClock)
    return (tTrial, allKeys)
Exemplo n.º 6
0
def display_practice(graphics):
    """
    Display the practice phase
    :param graphics: graphics object which holds all visuals.
    """

    # num of trials in left must be equal to num of trials in right.
    if len(Constants.PRACTICE_LEFT_STIMS) != len(Constants.RIGHT_STIM_KEYS):
        return

    num_of_practice_trials = 2
    practice_stim_val = [Constants.VIS_PRACTICE_LEFT_STIM, Constants.VIS_PRACTICE_RIGHT_STIM]
    practice_stim = [Constants.PRACTICE_LEFT_STIMS, Constants.PRACTICE_RIGHT_STIMS]
    routine_timer = core.CountdownTimer()

    for trial in range(num_of_practice_trials):  # 2 practice trials
        for i in range(2):  # Left stim then right stim
            for stim in range(3):  # Go through each triplet

                # Set timer for each stim
                routine_timer.reset()
                routine_timer.add(Constants.DISPLAY_VISUAL_TIME)

                # Set and display current stim.
                graphics.set_text(practice_stim_val[i], practice_stim[i][trial][stim])
                graphics.draw(practice_stim_val[i])
                graphics.refresh()

                # Display for the given length
                while routine_timer.getTime() > 0:
                    if event.getKeys(keyList=Constants.ESCAPE_KEYS):
                        core.quit()
                    elif event.getKeys(keyList=Constants.SKIP_KEYS):
                        return

                graphics.refresh()
                routine_timer.add(Constants.NO_VISUAL_TIME)

                # Remove visuals for the given length (transition from one stim to another)
                while routine_timer.getTime() > 0:
                    if event.getKeys(keyList=Constants.ESCAPE_KEYS):
                        core.quit()
                    elif event.getKeys(keyList=Constants.SKIP_KEYS):
                        return

        # After stims have been displayed, draw a question mark and wait for response.
        graphics.draw(Constants.VIS_QUESTION_MARK)
        graphics.refresh()
        event.clearEvents()

        # Wait until response given or escape key is pressed.
        while True:
            if event.getKeys(keyList=Constants.ESCAPE_KEYS):
                core.quit()
            elif event.getKeys(keyList=Constants.PRACTICE_RESP_KEYS):
                break

        # Clear screen and wait for the given length before starting next trial.
        graphics.refresh()
        time.sleep(Constants.NO_VISUAL_TIME)
Exemplo n.º 7
0
 def pause(self):
     """
     Pause block
     """
     event.clearEvents()
     self.win.flip()
     event.waitKeys()
Exemplo n.º 8
0
def new_block(input):
    im = Image.new("RGB", (2048, 500), bg)

    font = ImageFont.truetype("arial.ttf", 50)
    draw = ImageDraw.Draw(im)
    draw.text((580, 100), input, fill=(0,0,0), font=font)
    # Attention: input can only be one line!
    draw.text((580, 200), 'Weiter mit linker Maustaste.', fill=(0,0,0), font=font)
    im.save("instructions/new_block.png")

    eizoGS320.convert_to_eizo_picture("instructions/new_block.png", "instructions/block_eizo.png")

    im_draw = visual.SimpleImageStim(mywin, "instructions/block_eizo.png", units="pix")

    event.clearEvents()
    run = True
    while run:
        for key in event.getKeys():
            if key in ['escape','q']:
                core.quit()

        mouse1, mouse2, mouse3 = mymouse.getPressed()

        if (mouse1):
            run = False

        event.clearEvents()

        im_draw.draw()
        mywin.flip()

    mywin.flip()
    core.wait(0.1)
 def showUntilKeyPressed(self, text, keyList=[]):
     """
     Show text until a key is pressed.
     If keyList is empty, it will listen for all keys.
     """
     
     self._display(text)
     
     
     instructionClock = core.Clock()
     instructionClock.reset()
     
     keyPressed = False
     eventCheckStarted = False
     while not keyPressed:
         t = instructionClock.getTime()
         
         if t >= 0.5:
             # Do not check for events immediatelly, such that people do not accidentally
             # skip the message.
             
             if eventCheckStarted == False:
                 # Remove keyboard events that were sent before the "grace" period had elapsed
                 event.clearEvents(eventType='keyboard')
                 eventCheckStarted = True
                 
             # Check for keys
             if keyList == []:
                 theseKeys = event.getKeys()
             else:
                 theseKeys = event.getKeys(keyList=keyList)
             
             if len(theseKeys) > 0:
                 # A key was pressed, return it
                 return theseKeys[0]
def ask(text='', keyList=[]):
    """
    Ask subject something. Shows question and returns answer (keypress)
    and reaction time. Defaults to no text and all keys.
    """
    # Draw the TextStims to visual buffer, then show it and reset timing immediately (at stimulus onset)
    stimText.setText(codecs.decode(text,"utf-8"))
    spaceText.setText(codecs.decode(spaceLookup[language],"utf-8"))
    # Set the text height
    stimText.setHeight(1)
    spaceText.setHeight(1)
    # set the text color
    stimText.setColor('white')
    spaceText.setColor('white')
    stimText.draw()
    spaceText.draw()
    win.flip()
    event.clearEvents('keyboard')

    # Halt everything and wait for (first) responses matching the keys given in the Q object.
    response = event.waitKeys(keyList=['space','q','r'])
    if response[0] in keysQuit:  # Look at first reponse [0]. Quit everything if quit-key was pressed
        core.quit()
    if response[0] in keysBreak:
        event.clearEvents('keyboard')
        win.flip()
    if event.getKeys(keyList=['escape', 'q']):
        core.quit()
    if event.getKeys(keyList=['s']):
        print "Skipped experiment"
        quit()
    return response # When answer given, return it.
Exemplo n.º 11
0
	def flush(self):
	
		"""See openexp._mouse.legacy"""
	
		event.mouseButtons = [0,0,0]
		event.clearEvents()
		return False
Exemplo n.º 12
0
    def showResponseOptions(self):
        
        self.responseObj.updateVariants()
        
        self.win.setColor(self.responseBgnd)
        self.win.flip()

        t=self.clock.getTime()
        self.responseDur=-1
        resp=None

        while resp==None:

            pos=self.mouse.getPos()
            choice=self.responseObj.variantForPoint(pos)
            
            self.mouse.setVisible(1)

            self.responseObj.draw()
            self.win.flip()

            btn=self.mouse.getPressed()
            if btn[0]==True and choice != -1:

                resp=True
                self.responseDur=self.clock.getTime()-t
                self.responseObj.blinkSelected()
                self.win.flip()
                
            event.clearEvents()        
        return choice
Exemplo n.º 13
0
def wait_get_response(p, clock, oddball, wait_time):
    """Get response info specific to this experiment."""
    check_clock = core.Clock()
    good_resp = False
    corr, response, resp_rt = 0, 0, -1
    while not good_resp:
        keys = event.getKeys(timeStamped=clock)
        for key, stamp in keys:
            if key in p.quit_keys:
                print "Subject quit execution"
                core.quit()
            elif key in p.match_keys:
                corr = 0 if oddball else 1
                response = 1
                resp_rt = stamp
                good_resp = True
                break
            elif key in p.nonmatch_keys:
                corr = 1 if oddball else 0
                response = 2
                resp_rt = stamp
                good_resp = True
                break
            event.clearEvents()
        # Possibly exit with nothing
        if check_clock.getTime() >= wait_time:
            return corr, response, resp_rt
    # Wait the rest of the time
    core.wait(wait_time - resp_rt)
    return corr, response, resp_rt
Exemplo n.º 14
0
def WaitForKeyInput():
    text='...'
    #until return pressed, listen for letter keys & add to text string
    while event.getKeys(keyList=['return'])==[]:
        letterlist=event.getKeys(keyList=['0', '1', '2', '3', '4',  '5' , '6', '7', '8', '9','backspace','q'])
        for l in letterlist:
            if l == 'q':
                core.quit()
            #if key isn't backspace, add key pressed to the string
            if l !='backspace':
                if text =="...":
                    text=l
                    pressedkeys=l
                else:
                    text+=l
                    pressedkeys+=(";" + l)
            #otherwise, take the last letter off the string
            elif len(text)>0:
                text=text[:-1]
                pressedkeys+=(";backspace")
            #continually redraw text onscreen until return pressed
            text = unicode(text)
            print "UNICODE"
            print text
            response = visual.TextStim(mywin, height=36,text=text,color="white",pos=(0,-100))
            betAsk.draw()
            response.draw()
            mywin.flip()
            core.wait(0.1)
    RT = trialClock.getTime()
    event.clearEvents()
    return text,RT
def run_calibration():
    # display instructions
    set_msg('SET SOUND LEVEL','TITLE')
    set_msg('press up and down to increase/decrease sound level and press enter when level is confortable','MAIN')
    set_msg('Press return to continue','KEY')

    win.flip()
    # prepare calibration sound
    s = sound_build.make_lp_noise(100000,3000,Exp.rate)
    vol = 0.5
    playsound(s,vol,200)
    pressEnter = False
    while pressEnter==False:
        allKeys=event.waitKeys()
        for thisKey in allKeys:
            if thisKey=='up':
                pygame.mixer.music.set_volume(pygame.mixer.music.get_volume()+0.03)
                print(pygame.mixer.music.get_volume())
            elif thisKey=='down':
                pygame.mixer.music.set_volume(pygame.mixer.music.get_volume()-0.03)
                print(pygame.mixer.music.get_volume())
            elif thisKey in ['return']:
                pressEnter = True
            elif thisKey in ['q', 'escape']:
                core.quit() #abort experiment
        event.clearEvents() #must clear other (eg mouse) events - they clog the buffer
    vol = pygame.mixer.music.get_volume()
    
    pygame.mixer.music.stop()
    return vol
def RunAttentionTrial(cue,stim,cueDur,preStimDur,stimDur):
    # --- SET UP
    #Flush the key buffer and mouse movements
    event.clearEvents()
    #Reset our clock to zero  - I think this call should take less time than window.flip, so resetting after the flip should be slightly more accurate.
    clock.reset()
    
    # --- DISPLAY
    # display cue
    textStim.setText(cue)
    textStim.draw()
    win.flip() #Put the image on the screen
    core.wait(cueDur,cueDur) # tie up the CPU for cueDur seconds.
    # display blank
    textStim.setText('')
    textStim.draw()
    win.flip()
    core.wait(preStimDur,preStimDur) # tie up the CPU for preStimDur seconds.
    # display stimulus
    textStim.setText(stim)
    textStim.draw()
    win.flip() #Put the image on the screen
    #Wait stimDur seconds.  Tie up the CPU the entire time (this is more accurate than letting other processes go)
    core.wait(stimDur,stimDur)
    
    # --- CLEAN UP
    #Get a list of all keys that were pressed during our wait.  Tell it to give also give us the amount of time since our clock was reset when the key was pressed (reaction time).
    keypresses = event.getKeys(None,clock)
    return keypresses
Exemplo n.º 17
0
def fScore():
    global score
    wordsToScore = wordsTheyRecalled
    wordList = './words/words%i.txt' %(round-1)
    throwAwayWords = list(cor for cor in open(wordList).read().split("\n") if cor)
    print "WORDS THEY RECALLED"
    print wordsTheyRecalled
    print "ORIGINAL"
    print throwAwayWords
    for w in wordsToScore:
        instructions2[2].draw()
        mywin.flip()
        core.wait(0.1)
        if w in throwAwayWords:
            risk = int(findBet(w))
            throwAwayWords.remove(w)
            score += risk
            writeToDataFile(scorefileName,w,risk,score)
            print score
        correctedWord = correct(w)
        if correctedWord != w:
            while event.getKeys(keyList=['return'])==[]:
                global corrects
                misspelled = visual.TextStim(mywin, height=30,text=w,color="white",pos=(-300,0))
                didYouMean = visual.TextStim(mywin, height=30,text=correctedWord,color="white",pos=(300, 0))
                ask = visual.TextStim(mywin, height=45,text='Did you mean:',color="white",pos=(0, 0))
                how = visual.TextStim(mywin, height=30,text='press y for Yes or n for No',color="white",pos=(0, -200))
                instructions[2].draw()
                misspelled.draw()
                didYouMean.draw()
                ask.draw()
                how.draw()
                mywin.flip()
                event.clearEvents()
                corrects = WaitForMouseInput()
                print "DID THEY CHANGE?"
                print corrects + "in loop"
                if corrects == "yes":
                    if correctedWord in throwAwayWords:
                        risk = int(findBet(correctedWord))
                        throwAwayWords.remove(correctedWord)
                        score += risk
                        writeToDataFile(scorefileName,correctedWord,risk,score)
                        print score
                    else:
                        continue
    for w in throwAwayWords:
        risk = int(findBet(w))
        score -= risk
        writeToDataFile(scorefileName,w,risk,score)
        print score
    questions.draw()
    #THIS IS WHERE THE FEEDBACK GOES
    t = visual.TextStim(mywin, height=36,text="Your current score: ",color="white",pos=(-150,-100))
    doing = visual.TextStim(mywin, height=36,text=score,color="white",pos=(150,-100))
    t.draw()
    doing.draw()
    mywin.flip()
    core.wait(4)
    return score
Exemplo n.º 18
0
def RunTrial(sequence):
    
    # check for going over session time
    if globalClock.getTime()-tStartSession > tSessionMax:
        CoolDown() #exit experiment gracefully
    
    # get deadline for response
    respDur = tRespPerItem*(len(sequence))
    respDur = int(tRespRoundOff * np.ceil(float(respDur)/tRespRoundOff)) # round up to next tRespRoundOff multiple
#    print("length = %d, respDur = %1.1f"%(len(sequence), respDur))
    logging.log(level=logging.EXP, msg='Start Sequence %d'%len(sequence))
    # play sequence
    for iStim in sequence:
        DisplayButtons([iStim],stimDur)
        beeps[iStim].play()
        core.wait(stimDur,stimDur) # wait so sound plays properly
        DisplayButtons([],pauseDur)
#        core.wait(pauseDur,pauseDur)
    
    logging.log(level=logging.EXP, msg='End Sequence %d'%len(sequence))
    #draw fixation dot and wait for response
    event.clearEvents() # ignore any keypresses before now
#    win.logOnFlip(level=logging.EXP, msg='Display Fixation')
#    fixation.draw()
    DisplayButtons([],0,True)
#    tResp = trialClock.getTime() # IMPORTANT REFERENCE POINT
    tResp = tNextFlip[0] # IMPORTANT REFERENCE POINT
    iSeq = 0
    # Response loop
    while globalClock.getTime() < (tResp + respDur) and iSeq < len(sequence):
        iStim = sequence[iSeq]
        thisKey = event.getKeys(timeStamped=globalClock)
        if len(thisKey)>0 and thisKey[0][0] == respKeys[iStim]:
            #tResp = trialClock.getTime(); # reset the shot clock
#            fixation.draw()
            DisplayButtons([iStim],0,True) # DON'T INCREMENT CLOCK
            beepsShort[iStim].play()
            core.wait(shortDur,shortDur) # USE CORE.WAIT HERE SO CLOCK DOESN'T INCREMENT
#            fixation.draw()
            DisplayButtons([],0,True)
            iSeq += 1
        elif len(thisKey)>0 and thisKey[0][0] in ['q','escape']:
            core.quit()
        elif len(thisKey)>0:
            print('this: %s'%str(thisKey[0][0]))
            print('correct: %s'%str(respKeys[iStim]))
            buzz.play()
            core.wait(buzzDur,buzzDur) # USE CORE.WAIT HERE SO CLOCK DOESN'T INCREMENT
            return (WRONG)
            
    #get response
    if iSeq == len(sequence): # finished sequence
        DisplayButtons([],respDur,False) # increment next-frame clock
        return(RIGHT)
    else: # ran out of time
        buzz.play()
        core.wait(buzzDur,buzzDur) # USE CORE.WAIT HERE SO CLOCK DOESN'T INCREMENT
        DisplayButtons([],respDur,False) # increment next-frame clock
        return (TOOSLOW)
Exemplo n.º 19
0
def RunTrial(targetDir, flankerDir, tStartTrial):

    # display fixation cross
    fixation.draw()
    win.logOnFlip(level=logging.EXP, msg="Display Fixation")
    win.flip()

    # wait until it's time to start the new trial
    while globalClock.getTime() < tStartTrial:
        pass  # do nothing

    # get trial time
    tTrial = globalClock.getTime()
    # reset clock
    trialClock.reset()

    # display flankers
    for flanker in flankers:
        flanker.text = arrowChars[flankerDir]
        flanker.draw()
    win.logOnFlip(level=logging.EXP, msg="Display %sFlankers" % arrowNames[flankerDir])
    win.flip()
    core.wait(flankerDur, flankerDur)

    # display flankers AND target arrow
    for flanker in flankers:
        flanker.draw()
    target.text = arrowChars[targetDir]
    target.draw()
    win.logOnFlip(level=logging.EXP, msg="Display %sTarget" % arrowNames[targetDir])
    win.flip()
    tStim = trialClock.getTime()  # get time when stim was displayed
    event.clearEvents()  # flush buffer
    core.wait(targetDur, targetDur)

    # draw blank screen
    win.logOnFlip(level=logging.EXP, msg="Display Blank")
    win.flip()
    core.wait(
        respDur - targetDur, respDur - targetDur
    )  # wait for specified ms (use a loop of x frames for more accurate timing)

    # get responses
    allKeys = event.getKeys(timeStamped=trialClock)
    # find RT
    RT = float("Inf")
    for thisKey in allKeys:
        if thisKey[0] in respKeys:
            RT = thisKey[1] - tStim
            break

    if RT >= rtDeadline:
        tooSlowStim.draw()
        win.logOnFlip(level=logging.EXP, msg="Display TooSlow")
        win.flip()
        core.wait(rtTooSlowDur, rtTooSlowDur)

    # return trial time, response(s)
    return (tTrial, allKeys)
def doUserInteraction(stim, expectedKeys, timeout, soundFile):
    global paused
    if timeout == None or timeout == 0:
        timeout = sys.maxint
    startTime = trialClock.getTime()
    endTime = startTime + timeout

    response = {
        "keys": [],
        "firstKey": None,
        "lastKey": None,
        "startTime": startTime,
        "endTime": endTime,
        "duration": 0,
        "timedOut": False,
        }

    if soundFile != None:
        soundFile.play()

    while(True):
        stim.setAutoDraw(True) #continuously draws the stimulus to the buffer
        win.flip() # exposes the stimulus to the screen
        keys = [] # initializes an empty array to hold the keys that were pressed.

        # this IF checks 2 things in order to determine which keys are allowed to be pressed:

        if expectedKeys != None: # Have I specified a list of allowed keys?
            if len(expectedKeys) != 0: # Have I specified any particular keys (rather than just [] which means All keys?
                keys = event.getKeys(expectedKeys) # Listen for key presses from a particular subset
            else:
                keys = event.getKeys() # Listen for Any key presses.
        if len(keys) > 0: # If a key was pressed store some values in the object "response" defined above.
            response["keys"] = keys # put all the responses in here.
            response["firstKey"] = keys[0] # put the first keypress here
            response["lastKey"] = keys[len(keys)-1] # put the last keypress here.
            break #break out of this function

        elif trialClock.getTime() > endTime: # If the response time window has run out
            response["timedOut"] = True # indicate that we timed out
            response["firstKey"] = 'NA' # put 'NA' as the first key pressed
            break

        if event.getKeys(['f5']): # This is a "pause" button for the experiment
            textStim.text = 'Press any key to continue'
            textStim.pos = (0,-10)
            paused = 1
            stimUntilAnyKey(textStim)
            textStim.pos = (0,0)

        #check for quit (the [Esc] key)
        if event.getKeys(["escape"]):
            core.quit() #quits the entire experiment - will dump you to the desktop or whatever.

    stim.setAutoDraw(False) # stop drawing the stimulus to the buffer
    win.flip() # expose the now blank buffer to the screen
    response["duration"] = trialClock.getTime() - startTime # keeps track of how long since the stim was drawn to the screen
    event.clearEvents(eventType=None) # clear the key buffer.
    return response # ends the function and returns the object "response". Without this return - we would not be able to access any of this data.
Exemplo n.º 21
0
def GetResponse():
    global currentRule, currentTgt, ruleCount, rightAnswers, gameScore

    event.clearEvents()

    retVal = 0 #if not modified, breaks the task
    answerPressed = -1 # which card was selected?

    keys = event.waitKeys()

    if keys[0]=='escape':
        retVal = 0
    elif keys[0] == 'up':
        if CheckCard( 0, currentRule, currentTgt ):
            rightAnswers += 1
            retVal = 1
        else:
            retVal = -1
    elif keys[0] == 'right':
        if CheckCard( 1, currentRule, currentTgt ):
            rightAnswers += 1
            retVal = 2
        else:
            retVal = -2
    elif keys[0] == 'down':
        if CheckCard( 2, currentRule, currentTgt ):
            rightAnswers += 1
            retVal = 3
        else:
            retVal = -3
    elif keys[0] == 'left':
        if CheckCard( 3, currentRule, currentTgt ):
            rightAnswers += 1
            retVal = 4
        else:
            retVal = -4
            
    if retVal > 0:
        gameScore += 1
        if currentRule == 'G1':
           triggerAndLog( portCodes['respRight'] | portCodes['rule1'], 'RESP   1 ' + currentRule + ' ANSWER ' + str(retVal) )
        if currentRule == 'G2':
            triggerAndLog( portCodes['respRight'] | portCodes['rule2'], 'RESP   1 ' + currentRule + ' ANSWER ' + str(retVal) )
        if currentRule == 'L1':
            triggerAndLog( portCodes['respRight'] | portCodes['rule3'], 'RESP   1 ' + currentRule + ' ANSWER ' + str(retVal) )
        if currentRule == 'L2':
            triggerAndLog( portCodes['respRight'] | portCodes['rule4'], 'RESP   1 ' + currentRule + ' ANSWER ' + str(retVal) )
    elif retVal < 0:
        gameScore -= 1
        if currentRule == 'G1':
            triggerAndLog( portCodes['respWrong'] | portCodes['rule1'], 'RESP   0 ' + currentRule + ' ANSWER ' + str(retVal) )
        if currentRule == 'G2':
            triggerAndLog( portCodes['respWrong'] | portCodes['rule2'], 'RESP   0 ' + currentRule + ' ANSWER ' + str(retVal) )
        if currentRule == 'L1':
            triggerAndLog( portCodes['respWrong'] | portCodes['rule3'], 'RESP   0 ' + currentRule + ' ANSWER ' + str(retVal) )
        if currentRule == 'L2':
            triggerAndLog( portCodes['respWrong'] | portCodes['rule4'], 'RESP   0 ' + currentRule + ' ANSWER ' + str(retVal) )
    
    return retVal
Exemplo n.º 22
0
def WaitForIt( keys=['x'], duration=-1 ):
    if duration < 0:
        keys = event.waitKeys(keys)
        core.wait(keyWait)
        event.clearEvents()
    else:
        core.wait(duration)
    return keys
Exemplo n.º 23
0
 def clearEvents(self, eventType=None):
     if havePTB:
         for buffer in self._buffers.values():
             buffer._evts.clear()
             buffer._keys.clear()
             buffer._keysStillDown.clear()
     else:
         event.clearEvents(eventType)
Exemplo n.º 24
0
def click_to_continue(cursor):
    event.clearEvents()
    cursor.clickReset() 
    while cursor.getPressed()==[False,False,False]:
        cursor.getPressed()
        if event.getKeys(keyList = 'q'):
            print 'User Terminated'
            core.quit()
Exemplo n.º 25
0
def show_instruction(instrStim):
    # shows an instruction until a key is hit.
    while True:
        instrStim.draw()
        win.flip()
        if len(event.getKeys()) > 0:
            break
        event.clearEvents()
Exemplo n.º 26
0
def runBlock(loop = object, saveData = True):
    """Runs a loop for an experimental block and saves reposnes if requested"""
    for thisTrial in loop:
        
        resp = None
        rt = None
        
        probe.setPos( [thisTrial['probeX'], 0] )
        cue.setOri( thisTrial['cueOri'] )
        
        fixation.setAutoDraw(True)
        for frameN in range(info['fixFrames']):
            win.flip()
    
        cue.setAutoDraw(True)
        for frameN in range(info['cueFrames']):
            win.flip()
        cue.setAutoDraw(False)
        
        probe.setAutoDraw(True)
        win.callOnFlip(respClock.reset)
        event.clearEvents()
        for frameN in range(info['probeFrames']):
            if frameN == 0:
                respClock.reset()
            keys = event.getKeys(keyList = ['left','right','escape'])
            if len(keys) > 0:
                resp = keys[0]
                rt = respClock.getTime()
                break
            win.flip()
        probe.setAutoDraw(False)
        fixation.setAutoDraw(False)
    
        #clear screen
        win.flip()
    
        if resp == None:
            
            keys = event.waitKeys(keyList = ['left','right','escape'])
            resp = keys[0]
            rt = respClock.getTime()
        
        if saveData == True:
            if thisTrial['probeX']>0 and resp=='right':
                corr = 1
            elif thisTrial['probeX']<0 and resp=='left':
                corr = 1
            elif resp=='escape':
                corr = None
                trials.finished = True
            else:
                corr = 0
        
            trials.addData('resp', resp)
            trials.addData('rt', rt)
            trials.addData('corr', corr)
            thisExp.nextEntry()
def picture_task(pictures, text_elem, patch_elem, choice_keys_dict, sheet_name, extra_info, side_info_dict, data_file, append):
    pictures_len = len(pictures)
    pictures_permutation = RandomPermutation(pictures_len)
    
    trial_clock = core.Clock()
    trials_list = [ { 'Trial': '%d' %(i+1) } for i in xrange(0, 2*pictures_len) ]
    trials = data.TrialHandler(trialList = trials_list, nReps=1, method=u'sequential', extraInfo=extra_info)
    trial_count = 0
    
    for thisTrial in trials:
        which_picture = pictures_permutation.select()
        picture_info = pictures[which_picture]
        patch_elem['face']['obj'].setTex(patch_elem['face']['dir'] + picture_info['Face'])
        
        #run the trial
        keys_to_press = choice_keys_dict['input'].keys()
        timestamps = []
        register_time = False
        continue_trial=True
        event.clearEvents()
        t=0; trial_clock.reset()
    
        while continue_trial and (t<1000000.0000):
            t = trial_clock.getTime()
            rt_k, keys = key_pressed(trial_clock, keys_to_press)
            
            if t >= 0:

                if len(keys) == 0:
                    patch_elem['face']['obj'].draw()
                    text_elem['choice_face']['obj'].draw()
                    register_time = True
                elif len(timestamps) > 0:
                    rt_picture = rt_k - timestamps[0]
                    key_picture = choice_keys_dict['input'][keys[0]]
                    continue_trial = False
                    if trial_count < 2*pictures_len - 1:
                        text_elem['choice_face']['obj'].draw()
                    
            win.flip()
            
            if register_time:
                timestamps.append(trial_clock.getTime())
                register_time = False
                
        for k,v in picture_info.items():
            trials.addData(k, v)
                    
        trials.addData('Key', key_picture)
        trials.addData('Response', side_info_dict['CHOICE'][key_picture])
        trials.addData('RT', rt_picture)
        trial_count += 1
        core.wait(0.5)

    trials.saveAsExcel(data_file, sheetName = sheet_name,
                       stimOut=[],
                       dataOut=['all_raw'],
                       appendFile = append)
Exemplo n.º 28
0
def fScore():
    global score
    wordsToScore = wordsTheyRecalled
    wordList = './words/%s/words%s.txt' %(version, round-1)
    throwAwayWords = list(cor for cor in open(wordList).read().split("\n") if cor)
    #print "WORDS THEY RECALLED"
    #print wordsTheyRecalled
    for w in wordsToScore:
        instructions2[2].draw()
        core.wait(0.1)
        if w in throwAwayWords:
            risk = int(findBet(w))
            throwAwayWords.remove(w)
            if practice == False:
                score += risk
            writeToDataFile(scorefileName,w,risk,score)
            print score
        correctedWord = correct(w)
        if correctedWord == w:#still show them scoring screen if there's no questions
            mywin.flip()
            core.wait(0.5)
        elif correctedWord != w: #ask them if they made a spelling error
            global corrects
            misspelled = visual.TextStim(mywin, height=30,text=w,color="white",pos=(-300,0))
            didYouMean = visual.TextStim(mywin, height=30,text=correctedWord,color="white",pos=(300, 0))
            ask = visual.TextStim(mywin, height=45,text='Did you mean:',color="white",pos=(0, 0))
            how = visual.TextStim(mywin, height=30,text='press Yes or No',color="white",pos=(0, -200))
            yes = visual.TextStim(mywin, height=50,text='Yes',color="white",pos=(-100, -150))
            no = visual.TextStim(mywin, height=50,text='No',color="white",pos=(100, -150))
            instructions2[2].draw()
            misspelled.draw()
            didYouMean.draw()
            ask.draw()
            how.draw()
            yes.draw()
            no.draw()
            mywin.flip()
            event.clearEvents()
            corrects = WaitForMouseInput()
            print "DID THEY CHANGE?"
            print corrects
            if corrects == "yes":
                if correctedWord in throwAwayWords:
                    risk = int(findBet(correctedWord))
                    throwAwayWords.remove(correctedWord)
                    if practice == False:
                        score += risk
                    writeToDataFile(scorefileName,correctedWord,risk,score)
                    print score
                else:
                    break
    for w in throwAwayWords:
        risk = int(findBet(w))
        if practice == False:
            score -= risk
        writeToDataFile(scorefileName,w,risk,score)
        print score
    return score
Exemplo n.º 29
0
def wait_for_key(keys):
    '''Wait for a key that is in a set of keys
    to be pressed before proceeding.

    Args:
    keys - A list or tuple of keys.
    '''
    event.clearEvents()
    event.waitKeys(keyList=keys)
Exemplo n.º 30
0
 def test_no_mode(self):
     #pytest.skip()
     event.clearEvents()
     ResponseEmulator(simResponses=[(0.5, 'escape')]).run()
     vol = launchScan(self.win, BASE_MR_SETTINGS.copy(), globalClock=self.globalClock,
                      wait_timeout=1, log=False)
     # no mode, so a RatingScale will be displayed; return to select value
     # the key event is not being detected here
     core.wait(1, 0)
Exemplo n.º 31
0
 def test_clearEvents_keyboard(self):
     event._onPygletKey(symbol='x', modifiers=0, emulated=True)
     event.clearEvents('keyboard')
     assert not event._keyBuffer
Exemplo n.º 32
0
    # *instr1* updates
    if t >= 0.0 and instr1.status == NOT_STARTED:
        # keep track of start time/frame for later
        instr1.tStart = t
        instr1.frameNStart = frameN  # exact frame index
        instr1.setAutoDraw(True)

    # *ready1* updates
    if t >= 0.0 and ready1.status == NOT_STARTED:
        # keep track of start time/frame for later
        ready1.tStart = t
        ready1.frameNStart = frameN  # exact frame index
        ready1.status = STARTED
        # keyboard checking is just starting
        event.clearEvents(eventType='keyboard')
    if ready1.status == STARTED:
        theseKeys = event.getKeys()

        # check for quit:
        if "escape" in theseKeys:
            endExpNow = True
        if len(theseKeys) > 0:  # at least one key was pressed
            # a response ends the routine
            continueRoutine = False
        if useButtonBox:
            if totalTrials > 0:
                continueRoutine = False

    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
Exemplo n.º 33
0
 def test_clearEvents_joystick(self):
     """Keyboard buffer should not be affected.
     """
     event._onPygletKey(symbol='x', modifiers=0, emulated=True)
     event.clearEvents('joystick')
     assert event._keyBuffer
Exemplo n.º 34
0
    def run(self):
        self.checkParameterValues()

        self.prepareRun()

        # create checkerboard background
        self._squareSizePix = round(self.squareSize * self.pixelsPerDeg)
        leftOffset = rightOffset = topOffset = bottomOffset = self._squareSizePix
        bckgnd = self.makeCheckerboard(
            (math.ceil(self.imageSize[1] / self._squareSizePix),
             math.ceil(self.imageSize[0] / self._squareSizePix)))
        if self.moveLikeOpticFlow:
            centerOffset = (self.imageSize[0] / 2) % self._squareSizePix
            if centerOffset > 0:
                self.shiftBckgnd(bckgnd[:, ::-1], centerOffset, centerOffset)
                rightOffset = centerOffset
        checkerboardImage = np.copy(
            bckgnd[:self.imageSize[1], :self.imageSize[0]])
        checkerboardStim = ImageStimNumpyuByte(self._win,
                                               image=checkerboardImage,
                                               size=self.imageSize,
                                               pos=self.imagePosition)

        # get trialTypes
        laserPwr = self.laserPower if self.laserRandom else [
            self.laserPower[0]
        ]
        trialTypes = list(
            itertools.product(
                self.bckgndSpeed,
                [dir for dir in self.bckgndDir if dir in (0, 180)],
                self.patchSize, self.patchSpeed,
                [dir for dir in self.patchDir if dir in (0, 180)],
                self.patchElevation, laserPwr))
        trialTypes.extend(
            itertools.product(
                self.bckgndSpeed,
                [dir for dir in self.bckgndDir if dir in (90, 270)],
                self.patchSize, self.patchSpeed,
                [dir for dir in self.patchDir if dir in (90, 270)],
                self.patchAzimuth, laserPwr))
        for params in copy.copy(trialTypes):
            # don't need all bckgnd directions for bckgndSpeed=0
            # or all patch sizes, directions, and positions for patchSpeed=0
            # or patch speed and direction = bckgnd speed and direction when both speeds > 0
            if ((params[0] == 0 and params[1] != self.bckgndDir[0])
                    or (params[3] == 0 and
                        (params[2] != self.patchSize[0]
                         or params[3] != self.patchSpeed[0]
                         or params[4] != self.patchDir[0] or
                         (params[5] != self.patchElevation[0] if params[4] in
                          (0, 180) else params[5] != self.patchAzimuth[0]))) or
                (params[0] > 0 and params[3] > 0 and params[0] == params[3]
                 and params[1] == params[4])):
                if params in trialTypes:
                    trialTypes.remove(params)
        trialsPerLoop = len(trialTypes) * len(self.laserPower)
        if len(self.laserPower) > 1 and not self.laserRandom:
            trialTypes = [trialTypes]
            for pwr in self.laserPower[1:]:
                trials = [list(params) for params in trialTypes[0]]
                for params in trials:
                    params[-1] = pwr
                trialTypes.append(trials)

        # run
        frame = 0
        loop = -1
        trial = -1
        trialFrame = 0
        trialInterval = self.getInterTrialInterval()
        self.trialStartFrame = []
        self.trialNumFrames = []
        self.trialBckgndSpeed = []
        self.trialBckgndDir = []
        self.trialPatchSize = []
        self.trialPatchSpeed = []
        self.trialPatchDir = []
        self.trialPatchPos = []
        self.trialLaserPower = []
        while True:
            if trialFrame == trialInterval - 1:
                if loop == -1 or trial == trialsPerLoop - 1:
                    if loop == self.numLoops - 1:
                        break
                    loop += 1
                    print('starting loop ' + str(loop + 1))
                    shuffledTrials = np.array(
                        self.setTrialLaserPower(trialTypes))
                    if len(self.laserPower) > 1 and not self.laserRandom:
                        self.spaceLaserTrials(shuffledTrials)
                    trial = 0
                else:
                    trial += 1
                trialFrame = -1
                self.trialBckgndSpeed.append(shuffledTrials[trial, 0])
                self.trialBckgndDir.append(shuffledTrials[trial, 1])
                self.trialPatchSize.append(shuffledTrials[trial, 2])
                self.trialPatchSpeed.append(shuffledTrials[trial, 3])
                self.trialPatchDir.append(shuffledTrials[trial, 4])
                self.trialPatchPos.append(shuffledTrials[trial, 5])
                self.trialLaserPower.append(shuffledTrials[trial, 6])
                if self.trialBckgndDir[-1] == 0:
                    bckgndOffset = leftOffset
                elif self.trialBckgndDir[-1] == 180:
                    bckgndOffset = rightOffset
                elif self.trialBckgndDir[-1] == 90:
                    bckgndOffset = bottomOffset
                else:
                    bckgndOffset = topOffset
                bckgndMovPerFrame = round(self.trialBckgndSpeed[-1] *
                                          self.pixelsPerDeg / self.frameRate)
                patchMovPerFrame = round(self.trialPatchSpeed[-1] *
                                         self.pixelsPerDeg / self.frameRate)
                patchSizePix = round(self.trialPatchSize[-1] *
                                     self.pixelsPerDeg)
                if patchMovPerFrame > 0:
                    patch = self.makeCheckerboard(
                        (round(self.trialPatchSize[-1] / self.squareSize), ) *
                        2)
                    if self.trialPatchDir[-1] in [0, 180]:
                        y = self._squareSizePix * round(
                            (self.imageSize[1] / 2 - self.imagePosition[1] +
                             self.trialPatchPos[-1] * self.pixelsPerDeg) /
                            self._squareSizePix) - int(patchSizePix / 2)
                        if topOffset < self._squareSizePix:
                            y -= topOffset
                        if self.trialPatchDir[-1] == 0:
                            patchPos = [
                                self.imageSize[0] / 2 - patchSizePix, y
                            ]
                        else:
                            patchPos = [self.imageSize[0], y]
                        self.trialNumFrames.append(
                            int(
                                round((self.imageSize[0] / 2 + patchSizePix) /
                                      patchMovPerFrame)))
                    else:
                        x = self._squareSizePix * round(
                            (self.imageSize[0] / 2 - self.imagePosition[0] +
                             self.trialPatchPos[-1] * self.pixelsPerDeg) /
                            self._squareSizePix) - int(patchSizePix / 2)
                        if leftOffset < self._squareSizePix:
                            x -= leftOffset
                        if self.trialPatchDir[-1] == 90:
                            patchPos = [x, self.imageSize[1]]
                        else:
                            patchPos = [x, -patchSizePix]
                        self.trialNumFrames.append(
                            int(
                                round((self.imageSize[1] + patchSizePix) /
                                      patchMovPerFrame)))
                else:
                    if bckgndMovPerFrame > 0:
                        if self.trialBckgndDir[-1] in [0, 180]:
                            self.trialNumFrames.append(
                                int(
                                    round(self.imageSize[0] / 2 /
                                          bckgndMovPerFrame)))
                        else:
                            self.trialNumFrames.append(
                                int(
                                    round(self.imageSize[1] /
                                          bckgndMovPerFrame)))
                    else:
                        self.trialNumFrames.append(
                            int(round(2 * self.frameRate)))
                trialInterval = self.laserPreFrames + self.trialNumFrames[
                    -1] + self.laserPostFrames + self.getInterTrialInterval()
            elif trial > -1:
                if trialFrame == 0:
                    self.setLaserOn(self.trialLaserPower[-1])
                if self.laserPreFrames <= trialFrame < self.laserPreFrames + self.trialNumFrames[
                        -1]:
                    if trialFrame == self.laserPreFrames:
                        self.trialStartFrame.append(frame)
                    if bckgndMovPerFrame > 0:
                        if bckgndOffset == 0:
                            bckgndOffset = self._squareSizePix
                        bckgndOffset += bckgndMovPerFrame
                        if bckgndOffset > self._squareSizePix:
                            newSqOffset = bckgndOffset - self._squareSizePix
                            bckgndOffset %= self._squareSizePix
                        else:
                            newSqOffset = 0
                        if self.trialBckgndDir[-1] == 0:
                            if self.moveLikeOpticFlow:
                                self.shiftBckgnd(
                                    bckgnd[:, self.imageSize[0] / 2 + 1:],
                                    bckgndMovPerFrame, newSqOffset)
                                self.shiftBckgnd(
                                    bckgnd[:, self.imageSize[0] / 2::-1],
                                    bckgndMovPerFrame, newSqOffset)
                            else:
                                self.shiftBckgnd(bckgnd, bckgndMovPerFrame,
                                                 newSqOffset)
                        elif self.trialBckgndDir[-1] == 180:
                            if self.moveLikeOpticFlow:
                                self.shiftBckgnd(
                                    bckgnd[:, -1:self.imageSize[0] / 2:-1],
                                    bckgndMovPerFrame, newSqOffset)
                                self.shiftBckgnd(
                                    bckgnd[:, :self.imageSize[0] / 2 + 1],
                                    bckgndMovPerFrame, newSqOffset)
                            else:
                                self.shiftBckgnd(bckgnd[:, ::-1],
                                                 bckgndMovPerFrame,
                                                 newSqOffset)
                        elif self.trialBckgndDir[-1] == 90:
                            self.shiftBckgnd(bckgnd[:, ::-1].T,
                                             bckgndMovPerFrame, newSqOffset)
                        else:
                            self.shiftBckgnd(bckgnd.T, bckgndMovPerFrame,
                                             newSqOffset)
                    checkerboardImage = np.copy(
                        bckgnd[:self.imageSize[1], :self.imageSize[0]])
                    if patchMovPerFrame > 0:
                        if self.trialPatchDir[-1] == 0:
                            patchPos[0] += patchMovPerFrame
                        elif self.trialPatchDir[-1] == 180:
                            patchPos[0] -= patchMovPerFrame
                        elif self.trialPatchDir[-1] == 90:
                            patchPos[1] -= patchMovPerFrame
                        else:
                            patchPos[1] += patchMovPerFrame
                        if patchPos[0] <= self.imageSize[0] and patchPos[
                                1] <= self.imageSize[1]:
                            patchImagePos = copy.copy(patchPos)
                            patchImage = patch
                            if patchPos[0] < self.imageSize[0] / 2:
                                patchImage = patch[:,
                                                   int(self.imageSize[0] / 2 -
                                                       patchPos[0]):]
                                patchImagePos[0] = self.imageSize[0] / 2
                            if patchPos[1] < 0:
                                patchImage = patch[-patchPos[1]:, :]
                                patchImagePos[1] = 0
                            if patchPos[0] + patch.shape[1] > self.imageSize[0]:
                                patchImage = patch[:, :int(self.imageSize[0] -
                                                           patchPos[0])]
                            if patchPos[1] + patch.shape[0] > self.imageSize[1]:
                                patchImage = patch[:self.imageSize[1] -
                                                   patchPos[1], :]
                            checkerboardImage[
                                int(patchImagePos[1]):int(patchImagePos[1] +
                                                          patchImage.shape[0]),
                                int(patchImagePos[0]
                                    ):int(patchImagePos[0] +
                                          patchImage.shape[1])] = patchImage
                    if trialFrame == self.laserPreFrames + self.trialNumFrames[
                            -1] - 1:
                        if self.trialBckgndDir[-1] == 0:
                            leftOffset = bckgndOffset
                            rightOffset = self._squareSizePix - bckgndOffset
                            if self.moveLikeOpticFlow:
                                rightOffset += centerOffset
                                if rightOffset > self._squareSizePix:
                                    rightOffset -= self._squareSizePix
                        elif self.trialBckgndDir[-1] == 180:
                            rightOffset = bckgndOffset
                            leftOffset = self._squareSizePix - bckgndOffset
                            if self.moveLikeOpticFlow:
                                leftOffset -= centerOffset
                                if leftOffset < 0:
                                    leftOffset += self._squareSizePix
                        elif self.trialBckgndDir[-1] == 90:
                            bottomOffset = bckgndOffset
                            topOffset = self._squareSizePix - bckgndOffset
                        else:
                            topOffset = bckgndOffset
                            bottomOffset = self._squareSizePix - bckgndOffset
                if trialFrame == self.laserPreFrames + self.trialNumFrames[
                        -1] + self.laserPostFrames:
                    self.setLaserOff()
            checkerboardStim.setReplaceImage(checkerboardImage)
            checkerboardStim.draw()
            self.visStimFlip()
            frame += 1
            trialFrame += 1
            if len(event.getKeys()) > 0:
                event.clearEvents()
                break
        self.completeRun()
Exemplo n.º 35
0
def VWFAlocImages(scanDict,screenSize=[1024,768]):
    #objects from
    #http://stims.cnbc.cmu.edu/Image%20Databases/TarrLab/Objects/
    #faces from
    #http://www.cl.cam.ac.uk/research/dtg/attarchive/facedatabase.html
#
#more faces
#http://tarrlab.cnbc.cmu.edu/newsite/index.php?option=com_content&view=article&id=51&Itemid=61
#more objects
#http://stims.cnbc.cmu.edu/Image%20Databases/BOSS/

    #scenes
    #http://pirsquared.org/research/vhatdb/full/
    #houses
    #http://groups.csail.mit.edu/vision/SUN/

#    USING IN THE END:
    #houses
    #http://groups.csail.mit.edu/vision/SUN/
    #objects & chairs  from
    #http://stims.cnbc.cmu.edu/Image%20Databases/TarrLab/Objects/
    #faces from
    #http://www.cl.cam.ac.uk/research/dtg/attarchive/facedatabase.html
     #more chairs from
     #????
    white=[1.0,1.0,1.0]
    gray=[0.0,0.0,0.0]
    black=[-1.0,-1.0,-1.0]

    fixPercentage =scanDict['fixFraction']
    fixDuration=0.25
    respDuration=1.0
    IR=scanDict['innerRadius']
    screenSize=scanDict['screenSize']

    #create a designmatrix
    #there are 4 categories of things to show
    #faces, places (houses), chairs (objects), and letters (words?)
    #also need rest in there
    #so need 4 columns in design matrix

    numTrials=210
    numImages=40*4
    designMatrix=numpy.zeros((numTrials,4))
    designMatrixX=numpy.zeros((numTrials,1))

    #first N Trs are already zero--rest
    #figure out when each stim should be on
    #for now, just get the frame working
    #hard code this as restABCDrestBADCrestCBDArestDCABrest
    #rests are 10s of gray, blocks are 10s of images
    #within each block, show 10 examples drawn randomly from a big list
    stimDur=0.75
    ISIdur=0.25
    trialLength=stimDur+ISIdur
    trialsPerBlock=10
    blockLength=trialLength*trialsPerBlock
    IBIdur=10
    #A: 10-20,70-80,140-150,180-190
    designMatrix[10:20,0]=1
    designMatrix[70:80,0]=1
    designMatrix[140:150,0]=1
    designMatrix[180:190,0]=1
    #B: 20-30,60-70,120-130,190-200
    designMatrix[20:30,1]=1
    designMatrix[60:70,1]=1
    designMatrix[120:130,1]=1
    designMatrix[190:200,1]=1

    #C: 30-40,90-100,110-120,170-180
    designMatrix[30:40,2]=1
    designMatrix[90:100,2]=1
    designMatrix[110:120,2]=1
    designMatrix[170:180,2]=1

    #D: 40-50,80-90, 130-140, 160-170
    designMatrix[40:50,3]=1
    designMatrix[80:90,3]=1
    designMatrix[130:140,3]=1
    designMatrix[160:170,3]=1

    #UGH i need to hack a new design matrix for the images without the rest spots in it
    designMatrixX[10:20,0]=1
    designMatrixX[70:80,0]=1
    designMatrixX[140:150,0]=1
    designMatrixX[180:190,0]=1
    #B: 20-30,60-70,120-130,190-200
    designMatrixX[20:30,0]=1
    designMatrixX[60:70,0]=1
    designMatrixX[120:130,0]=1
    designMatrixX[190:200,0]=1

    #C: 30-40,90-100,110-120,170-180
    designMatrixX[30:40,0]=1
    designMatrixX[90:100,0]=1
    designMatrixX[110:120,0]=1
    designMatrixX[170:180,0]=1

    #D: 40-50,80-90, 130-140, 160-170
    designMatrixX[40:50,0]=1
    designMatrixX[80:90,0]=1
    designMatrixX[130:140,0]=1
    designMatrixX[160:170,0]=1


    #length of scan in s
    scanLength=numTrials*trialLength
    # msgScanLength=visual.TextStim(winOp,pos=[0,2],text='Scan length (s): %.1f' %scanLength)
    # msgScanTr=visual.TextStim(winOp,pos=[0,1],text='No. of Volumes (at Tr=%.2f): %.0f' %(scanDict['Tr'],scanLength/scanDict['Tr']) )
    # msgScanLength.draw()
    # msgScanTr.draw()
    # winOp.flip()
    #pop up the Tr info and wait for "ok"
    winOp = visual.Window([500,500],monitor='testMonitor',units='norm',screen=scanDict['operatorScreen'],
                              color=[0.0,0.0,0.0],colorSpace='rgb')
    msgScanLength=visual.TextStim(winOp,pos=[0,0.5],units='norm',height=0.1,text='Scan length (s): %.1f' %scanLength)
    msgScanTr=visual.TextStim(winOp,pos=[0,0],units='norm',height=0.1,text='No. of Volumes (at Tr=%.2f): %.1f' %(scanDict['Tr'],scanLength/scanDict['Tr']) )
    msgOK=visual.TextStim(winOp,pos=[0,-0.5],units='norm',height=0.1,text='Operator, press any key to proceed')
    msgScanLength.draw()
    msgScanTr.draw()
    msgOK.draw()
    winOp.flip()
    #wait for keypress
    thisKey=None
    while thisKey==None:
        thisKey = event.waitKeys()
    if thisKey in ['q','escape']:
        core.quit() #abort
    else:
        event.clearEvents()
    #close the winOp
    winOp.close()

    #open subject window
    winSub = visual.Window(screenSize,monitor=scanDict['monCalFile'],units="deg",screen=scanDict['subjectScreen'],
                       color=gray,colorSpace='rgb',fullscr=False,allowGUI=False)
    subjectResponse=numpy.zeros((numTrials+1,1))
    subRespArray=numpy.zeros((numTrials+1,3))
    subjectResponse[:]=numpy.nan


   #prep display objects
    #get the list of files for each
    myPath=os.path.dirname(os.path.realpath(__file__))
    Aimages=glob.glob(os.path.join(myPath,'vwfaProcImages','faces256','*.png'))
    if len(Aimages)==0:
        Aimages=glob.glob(os.path.join(myPath,'vwfaProcImages','faces256','*.PNG'))
    if len(Aimages)==0:
        print('No face images found')
        core.quit()
    Bimages=glob.glob(os.path.join(myPath,'vwfaProcImages','houses256','*.jpg'))
    if len(Bimages)==0:
        Bimages=glob.glob(os.path.join(myPath,'vwfaProcImages','houses256','*.JPG'))
    if len(Bimages)==0:
        print('No house images found')
        core.quit()
    Cimages=glob.glob(os.path.join(myPath,'vwfaProcImages','chairs256','*.png'))
    if len(Cimages)==0:
        Cimages=glob.glob(os.path.join(myPath,'vwfaProcImages','chairs256','*.PNG'))
    if len(Cimages)==0:
        print('No chair images found')
        core.quit()
    Dimages=glob.glob(os.path.join(myPath,'vwfaProcImages','letters256','*.png'))
    if len(Dimages)==0:
        Dimages=glob.glob(os.path.join(myPath,'vwfaProcImages','letters256','*.PNG'))
    if len(Dimages)==0:
        print('No letter images found')
        core.quit()
    #print Aimages
    #print Bimages
    ##print Cimages
    #print Dimages
    numInList=numpy.zeros((4,1))
    numInList[0]=len(Aimages)
    numInList[1]=len(Bimages)
    numInList[2]=len(Cimages)
    numInList[3]=len(Dimages)
    #print numInList
    #generate my random sequence --need 40 of each list
    Asequence=numpy.random.randint(0,high=numInList[0],size=40)
    Bsequence=numpy.random.randint(0,high=numInList[1],size=40)
    Csequence=numpy.random.randint(0,high=numInList[2],size=40)
    Dsequence=numpy.random.randint(0,high=numInList[3],size=40)
    #now make one big list with all the filenames--much easier for showing them in the loop!!
    imageNameSequence = ['']*numImages
    Acounter=0
    Bcounter=0
    Ccounter=0
    Dcounter=0
    imCounter=0
    #for iIm in xrange(numTrials):?
    for iIm in range(numTrials):
        if designMatrix[iIm,0]==1:
            #next Aimage
            imageNameSequence[imCounter]=Aimages[Asequence[Acounter]]
            Acounter+=1
            imCounter+=1
        elif designMatrix[iIm,1]==1:
            #next Bimage
            imageNameSequence[imCounter]=Bimages[Bsequence[Bcounter]]
            Bcounter+=1
            imCounter+=1
        elif designMatrix[iIm,2]==1:
            #next Cimage
            imageNameSequence[imCounter]=Cimages[Csequence[Ccounter]]
            Ccounter+=1
            imCounter+=1
        elif designMatrix[iIm,3]==1:
            #next Dimage
            imageNameSequence[imCounter]=Dimages[Dsequence[Dcounter]]
            Dcounter+=1
            imCounter+=1
    numpy.savetxt('vwfaImagesdesignMatrix.txt',designMatrix,fmt='%.3i',header='faces,houses,chairs,letters')


    #make a fixation square which will enlarge on occasion
    fixSize=IR/2.0
    fix0 = visual.Rect(winSub,width=fixSize,height=fixSize,autoLog=False)
    fix0.setFillColor(color=[0.5,0.5,0.5],colorSpace='rgb')
    fix0.setLineColor(color=[1,-1,-1],colorSpace='rgb')

    #create the dictionary of images, but load only one
    currentImageNumber = 0
    imageStimDict=dict.fromkeys(numpy.arange(0,40*4))
#    imageStimDict[currentImageNumber]=visual.ImageStim(winSub,image=imageNameSequence[currentImageNumber])
    imageStimDict[currentImageNumber]=visual.SimpleImageStim(winSub,image=imageNameSequence[currentImageNumber])

    msg1x=visual.TextStim(winSub, pos=[0,+8],text='visual wordform area localizer with images')
    msg1a = visual.TextStim(winSub, pos=[0,+5],text='During the scan, please keep your eyes on the + in the center.',height=1)
    msg1b = visual.TextStim(winSub, pos=[0,+2],text='Hit any button any time the fixation square becomes bigger.',height=1)
    msg1=visual.TextStim(winSub,pos=[0,-3],text='Subject: Hit a button when ready.',color=[1,-1,-1],colorSpace='rgb')
    msg1.draw()
    msg1a.draw()
    msg1b.draw()
    msg1x.draw()
    fix0.draw()
#    fix1.draw()
#    fix2.draw()
    winSub.flip()


    #wait for subject
    thisKey=None
    responseKeys=list(scanDict['subjectResponse'])
    responseKeys.extend('q')
    responseKeys.extend('escape')
    while thisKey==None:
        thisKey = event.waitKeys(keyList=responseKeys)
    if thisKey in ['q','escape']:
        core.quit() #abort
    else:
        event.clearEvents()
    responseKeys=list(scanDict['subjectResponse'])


    msg1a = visual.TextStim(winSub, pos=[0,+5],text='   ',height=1)
    msg1b = visual.TextStim(winSub, pos=[0,+2],text='Waiting for magnet',height=1)
    #msg1c.draw()
    msg1a.draw()
    msg1b.draw()
    fix0.draw()
    #fix1.draw()
    #fix2.draw()
    winSub.flip()

    #wait for trigger
    trig=None
    triggerKeys=list(scanDict['trigger'])
    triggerKeys.extend('q')
    triggerKeys.extend('escape')
    while trig==None:
        #wait for trigger "keypress"
        trig=event.waitKeys(keyList=triggerKeys)
    if trig in ['q','escape']:
        core.quit()
    else: #stray key
        event.clearEvents()



    #start the timer
    scanTimer=core.Clock()
    startTime=scanTimer.getTime()
    timeNow=scanTimer.getTime()
    # msg = visual.TextStim(winOp,pos=[0,-1],text = 't = %.3f' %timeNow)
    # msg.draw()
#    trialTimer=core.Clock()
#    trialTime=trialTimer.getTime()
    trialTimerNew=core.CountdownTimer()
    fixTimer=core.Clock()
    respTimer=core.Clock()
    #start counters for each list
    Acounter=0
    Bcounter=0
    Ccounter=0
    respCounter=0
    numCoins=0
    currentImageNumber = -1
    #loop through the number of trials, presenting appropriate stimulus or rest
    for iTrial in range(numTrials):
        #print iTrial
#        print designMatrix[iTrial,:]
        respTimer.reset()
        flipCoin=numpy.random.ranf()
        if flipCoin<fixPercentage:
            #change fixation size
            fixSize*=1.2
            fixTimer.reset()
            respTimer.reset()
            numCoins+=1
            subjectResponse[numCoins]=0
        fix0.setWidth(fixSize)
        fix0.setHeight(fixSize)

        if designMatrixX[iTrial,0]==1:
            #stim
            #load next image
            currentImageNumber+=1
            if currentImageNumber+1<len(imageNameSequence): #don't load an image past the last one!
                imageStimDict[currentImageNumber+1]=visual.ImageStim(winSub,image=imageNameSequence[currentImageNumber+1])

            #delete the 2nd previous one
            if currentImageNumber>3:
                del imageStimDict[currentImageNumber-1]
            #print imageStimDict[currentImageNumber]
            #print imageStimDict[currentImageNumber+1]
            #thisThing.draw()
            imageStimDict[currentImageNumber].draw()
            drawFix=0
            drawStim=1
            winSub.flip()
        else:
            #rest
            drawFix=1
            drawStim=0
            fix0.draw()
            #fix1.draw()
            #fix2.draw()

        #dispay stim for stimDuration amount of time
        trialTimerNew.add(stimDur)
        while trialTimerNew.getTime()>0:
            timeNow = scanTimer.getTime()
            fixTimeCheck=fixTimer.getTime()
            respTimeCheck=respTimer.getTime()
            #print trialTimerNew.getTime()
            if fixTimeCheck>fixDuration:
                fixSize=IR/2.0
                fix0.setWidth(fixSize)
                fix0.setHeight(fixSize)

            if drawStim==1:

                imageStimDict[currentImageNumber].draw()
            if drawFix==1:
                fix0.draw()

            # msg.setText('t = %.3f' %timeNow)
            # msg.draw()
            # msgScanLength.draw()
            # msgScanTr.draw()
            winSub.flip()
            # winOp.flip()
            for key in event.getKeys():
                if key in ['q','escape']:
                    core.quit()
                elif key in responseKeys and respTimeCheck<respDuration:
                    subjectResponse[numCoins]=1

        #then show fixation for ISI time
        trialTimerNew.add(trialLength-stimDur)
        while trialTimerNew.getTime()>0:
            #then show fixation for ISI time
            timeNow = scanTimer.getTime()
            fixTimeCheck=fixTimer.getTime()
            respTimeCheck=respTimer.getTime()
            #print trialTimerNew.getTime()
            if fixTimeCheck>fixDuration:
                fixSize=IR/2.0
                fix0.setWidth(fixSize)
                fix0.setHeight(fixSize)

            fix0.draw()
            winSub.flip()
            # msg.setText('t = %.3f' %timeNow)
            # msg.draw()
            # msgScanLength.draw()
            # msgScanTr.draw()
            # winOp.flip()
            for key in event.getKeys():
                if key in ['q','escape']:
                    core.quit()
                elif key in responseKeys and respTimeCheck<respDuration:
                    subjectResponse[numCoins]=1
    findResp=subjectResponse[~numpy.isnan(subjectResponse)]
    calcResp=findResp[findResp==1]
    numCorrect=float(calcResp.shape[0])
    if numCoins>0:
        percentCorrect=100.0*float(numCorrect)/(float(numCoins))
    else:
        percentCorrect=100.0

    msgText='You got %.0f %% correct!' %(percentCorrect,)
    msgPC=visual.TextStim(winSub,pos=[0,+3],text=msgText)
    msgPC.draw()
    winSub.flip()

    #create an output file in a subdirectory
    #check for the subdirectory
    if os.path.isdir('subjectResponseFiles')==False:
        #create directory
        os.makedirs('subjectResponseFiles')
    nowTime=datetime.datetime.now()
    outFile='vwfaImResponse%04d%02d%02d_%02d%02d.txt'%(nowTime.year,nowTime.month,nowTime.day,nowTime.hour,nowTime.minute)
    outFilePath=os.path.join('subjectResponseFiles',outFile)
    numpy.savetxt(outFilePath,findResp,fmt='%.0f')
    core.wait(2)
    # winOp.close()
    winSub.close()
Exemplo n.º 36
0
def do_run(stimset):
    #instructions
    if version == 'A' or 'B':
        instruct_screen.draw()
    else:
        instruct_screen_practice.draw()
    win.flip()
    event.waitKeys(keyList=('space','2'))
    
    if stimset == 'face':
        instruct_screen1_face.draw()
        win.flip()
    else:
        instruct_screen1_image.draw()
        win.flip()
    event.waitKeys(keyList=('space','2'))
    
    instruct_screen2.draw()
    win.flip()
    event.waitKeys(keyList=('space','2'))
    
    if stimset == 'face':
        if version == 'A' or 'B':
            instruct_screen3_face.draw()
        else:
            instruct_screen3_face_practice.draw()
    else:
        if version == 'A' or 'B':
            instruct_screen3_image.draw()
        else:
            instruct_screen3_image_practice.draw()
    win.flip()
    event.waitKeys(keyList=('space','2'))
    
    #wait for scan trigger 
    if version == 'A' or 'B':
        ready_screen.draw()
    else:
        ready_screen_practice.draw()
    win.flip()
    event.waitKeys(keyList=('equal'))
    run_start = time.time()
    
    #set Version ITI, Image orders, feedback order
    pic_path = os.path.join(os.getcwd(), 'pictureFolder', f'{version}_{stimset}')
    
    #lists to store logging
    clock = core.Clock()
    clock.reset()
    onset = []
    duration = []
    condition = []
    resp_val = []
    responsetime = []
    b_1 = []
    b_2 = []
    b_3 = []

    for trial in reference.iterrows():
        trial_start = clock.getTime()
        row_counter = trial[0]
        pic_L = visual.ImageStim(win,os.path.join(pic_path, reference.loc[reference.index[row_counter], f'{version}_{stimset}_L']), pos =(-7,0),size=(11.2,17.14))
        pic_R = visual.ImageStim(win,os.path.join(pic_path, reference.loc[reference.index[row_counter], f'{version}_{stimset}_R']), pos =(7,0),size=(11.2,17.14))
        border = visual.ShapeStim(win, vertices=pic_L.verticesPix, units='pix', fillColor = 'grey', lineColor = 'grey')
        border2 = visual.ShapeStim(win, vertices=pic_R.verticesPix, units='pix', fillColor = 'grey', lineColor = 'grey')

        trial_timer = core.CountdownTimer(5.2)   
        while trial_timer.getTime() > 0:
            #1st fixation
            if stimset == 'image':
                timer = core.CountdownTimer(fixation_time + 0.034)
            else:
                timer = core.CountdownTimer(fixation_time)
            while timer.getTime() > 0:
                fixation.draw()
                win.flip()
            fixationPre_dur = clock.getTime() - trial_start
            
            #decision_phase
            timer = core.CountdownTimer(decision_time)
            resp = event.getKeys(keyList = responseKeys)
            decision_onset = clock.getTime()
            while timer.getTime() > 0:
                pic_L.draw()
                pic_R.draw()
                win.flip()
                resp = event.getKeys(keyList = responseKeys)
                if len(resp)>0:
                    if 'z' in resp:
                        log.to_csv(os.path.join("data",subj_id, f"{subj_id}_{stimset}-{version}.tsv"), sep='\t', index = False)
                        core.quit()
                    if selected == 2 or 3:
                        selected = int(resp[0])
                        resp_onset = clock.getTime()
                        rt = resp_onset - decision_onset
                        border.autoDraw=True
                        border2.autoDraw=True
                        pic_L.draw()
                        pic_R.draw()
                        win.flip()
                        core.wait(decision_time - rt)
                        break
                else:
                    selected = '999'
                    rt = '999'
                    core.wait(.25)
            decision_dur = clock.getTime() - decision_onset
            border.autoDraw=False
            border2.autoDraw=False
            
            #2nd fixation
            timer = core.CountdownTimer(fixation_time)
            fixationPost_onset = clock.getTime()
            while timer.getTime() > 0:
                fixation.draw()
                win.flip()
            fixationPost_dur = clock.getTime() - fixationPost_onset

            #feedback
            timer = core.CountdownTimer(fb_dur)
            feedback_onset = clock.getTime()
            fb_type = reference.loc[reference.index[row_counter], f'{version}_feedback']
            if fb_type == 'loss':
                while timer.getTime() > 0:
                    down_arrow.draw()
                    win.flip()   
            elif fb_type == 'win':
                while timer.getTime() > 0:
                    up_arrow.draw()
                    win.flip() 
            else:
                print('Feedback Error')
            feedback_dur = clock.getTime() - feedback_onset
            
            #ITI
            ITI_onset = clock.getTime()
            ITI = reference.loc[reference.index[row_counter], f'{version}_ITI']
            timer = core.CountdownTimer(ITI)
            while timer.getTime() > 0:
                fixation.draw()
                win.flip()
                core.wait(ITI)
            ITI_dur = clock.getTime() - ITI_onset
            
            #logging
            condition.append('fixation_1')
            onset.append(trial_start)
            duration.append(fixationPre_dur)
            resp_val.append('999')
            responsetime.append('999')

            condition.append('face')
            onset.append(decision_onset)
            duration.append(decision_dur)
            resp_val.append(selected)
            responsetime.append(rt)
            
            condition.append('fixation_2')
            onset.append(fixationPost_onset)
            duration.append(fixationPre_dur)
            resp_val.append('999')
            responsetime.append('999')
            
            condition.append('feedback ' + fb_type)
            onset.append(feedback_onset)
            duration.append(feedback_dur)
            resp_val.append('999')
            responsetime.append('999')
           
            condition.append('ITI')
            onset.append(ITI_onset)
            duration.append(ITI_dur)
            resp_val.append('999')
            responsetime.append('999')
            
            #BIDS Log
            b_1.append(decision_onset)
            b_2.append(decision_dur)
            b_3.append(fb_type)

        #data to frame 
        log = pd.DataFrame(
                {'onset':onset, 
                'duration':duration,
                'trial_type':condition,
                'rt':responsetime,
                'resp':resp_val})

        bidsEvents = pd.DataFrame(
                {'onset':b_1, 
                'duration':b_2,
                'trial_type':b_3})
        log.to_csv(os.path.join("data",subj_id, f"sub-{subj_id}_{stimset}-{version}.tsv"), sep='\t', index = False)
        bidsEvents.to_csv(os.path.join("data",subj_id, f"sub-{subj_id}_task-socialReward-{stimset}-{version}.tsv"), sep='\t', index = False)
    run_end = time.time()
    run_length = run_end -run_start
    print(run_length)
    event.clearEvents()
    return;
Exemplo n.º 37
0
    def experiment_step(self):
        """
        Run one step in the experiment
        """
        trial_condition = self.state_machine.get_trial_condition()
        presentation_time = self.state_machine.get_presentation_time()
        timeout_ms = self.state_machine.get_timeout_ms()
        isi = self.state_machine.get_isi()
        trial_data = {
            'trial_num': self.trial_num,
            'x': trial_condition.x,
            'y': trial_condition.y,
            'color': trial_condition.color,
            'fixation_color': trial_condition.fixation_color,
            'isi': isi,
            'presentation_time': presentation_time,
            'catch_trial': False
        }
        self.state_machine.set_fixaction_color(trial_condition.fixation_color)
        self.state_machine.draw_fixation()
        self.state_machine.flip_window()
        self.state_machine.wait(isi / 1000.)
        self.beeper.play_locking_start_tone()
        present_stimulus = True
        if self.state_machine.is_catch_trial():
            trial_data['catch_trial'] = True
            trial_data['x'] = -999
            trial_data['y'] = -999
            present_stimulus = False
        else:
            self.state_machine.increment_trial_number()

        stim_start = time.time()
        response = None
        while (time.time() - stim_start) < (presentation_time /
                                            1000.) and response is None:
            self.state_machine.draw_fixation()
            if present_stimulus:
                self.state_machine.set_stimulus_position(
                    trial_condition.x, trial_condition.y)
                self.state_machine.set_stimulus_color(trial_condition.color)
                self.state_machine.draw_stimulus()
            self.state_machine.flip_window()
            all_keys = event.getKeys()
            if len(all_keys) > 0:
                if 'space' in all_keys:
                    response = 'seen'
                elif 'return' in all_keys or 'enter' in all_keys:
                    response = 'not_seen'
                elif 'q' in all_keys:
                    response = 'quit'
                    self.quit_task = True
                else:
                    response = 'invalid'
            event.clearEvents()

        while (time.time() - stim_start) < (
                timeout_ms /
                1000.) and response is None and not self.quit_task:
            self.state_machine.draw_fixation()
            self.state_machine.flip_window()
            all_keys = event.getKeys()
            if len(all_keys) > 0:
                if 'space' in all_keys:
                    response = 'seen'
                elif 'return' in all_keys or 'enter' in all_keys:
                    response = 'not_seen'
                elif 'q' in all_keys:
                    response = 'quit'
                    self.quit_task = True
                else:
                    response = 'invalid'
            event.clearEvents()

        end_time = time.time()
        reaction_time = int((end_time - stim_start) * 1000)
        self.beeper.play_locking_end_tone()

        self.state_machine.draw_fixation()
        self.state_machine.flip_window()
        trial_data[
            'response'] = response if response is not None else 'TIMEOUT'
        trial_data['reaction_time'] = reaction_time if (
            response is not None and response is not 'quit') else -999
        event.clearEvents()
        return trial_data
Exemplo n.º 38
0
def CheckForEscape():
    '''Check for 'escape' key.'''
    KeyPress = event.getKeys(keyList=['escape'])
    if KeyPress: QuitTask()
    event.clearEvents()
Exemplo n.º 39
0
def showtext (thetext):
	event.clearEvents()
	thetext.draw()
	win.flip()
            while trialcounter < trials[-1] + 4:
                if trialcounter < trials[-1] + 3:
                    theseKeys = event.getKeys(keyList=['y', 'n'])
                else:
                    theseKeys = event.getKeys(keyList=['l', 's', 'n'])
                if theseKeys:
                    thisExp.addData('Trial', trialcounter)
                    if trialcounter < trials[-1] + 2:
                        Post_Q1.setAutoDraw(False)
                        Post_Q2.setAutoDraw(True)
                    elif trialcounter < trials[-1] + 3:
                        Post_Q2.setAutoDraw(False)
                        Post_Q3.setAutoDraw(True)
                    trialcounter += 1
                    thisExp.addData('Response', theseKeys[-1])
                    event.clearEvents(eventType='keyboard')
                    thisExp.nextEntry()
                else:
                    win.flip()
            Post_Q3.setAutoDraw(False)
            win.flip()
            trials = range(posttrials)

        # Probes about cues' meanings in exps 2 + 4, doesn't advance unless all three questions are answered correctly
        acclist = []
        random.shuffle(CueTest_list)
        cloop = 0
        Instr1.setText(
            'In the instructions, you were informed that certain '  # Starting Instr1 that gets inherited into the start of cloop
            'number cues either predicted task-switches (hard '
            'trials) or task-repeats (easy trials), or were non-'
def trackingTrial(win,
                  experimentalInfo,
                  ballSpeed,
                  thisCondition,
                  simulation=False,
                  isCatchTrial=0):
    from psychopy import visual, event
    """
    Start the tracking trial
    1) Generate random balls
    2) Generate the central white fixation dot
    3) Start blinking 2 balls in the left or right zone, for unilateral, in both zones for bilateral
    4) Move the balls in random directions, bouncing on walls and on theirselves
    """
    # Generate a list of 4 balls on left side for unilateral condition
    trialClock = core.Clock()

    rectWidth, rectHeight = experimentalInfo['RectWidth'], experimentalInfo[
        'RectHeight']
    displacementX = 4  # 1 cm central displacement
    nBallsPerRectangle = experimentalInfo['NumBalls']
    ballRadius = experimentalInfo['BallRadius']

    leftRightRectangles = [[
        -rectWidth - displacementX / 2.0, -rectHeight / 2.0,
        -displacementX / 2.0, rectHeight / 2.0
    ],
                           [
                               displacementX / 2.0, -rectHeight / 2.0,
                               rectWidth + displacementX / 2.0,
                               rectHeight / 2.0
                           ]]

    ballsLeft, rectanglesLeft = createBalls(win,
                                            nBallsPerRectangle,
                                            radius=ballRadius,
                                            boundRect=leftRightRectangles[0],
                                            speed=ballSpeed)
    ballsRight, rectanglesRight = createBalls(win,
                                              nBallsPerRectangle,
                                              radius=ballRadius,
                                              boundRect=leftRightRectangles[1],
                                              speed=ballSpeed)

    #allBallsList = { 0:ballsLowerLeft, 1:ballsLowerRight, 2:ballsUpperLeft,3:ballsUpperRight }
    allBallsList = {0: ballsLeft, 1: ballsRight}

    fixationBall = Ball(win,
                        position=np.array([0.0, 0.0]),
                        direction=np.array([0.0, 0.0]),
                        speed=0.0,
                        radius=0.10,
                        color='White')
    trialClock.reset()
    blinkingBalls = list()

    whichSide = None
    if thisCondition['Side'] == 'Left':
        whichSide = 0
    if thisCondition['Side'] == 'Right':
        whichSide = 1

    runMode = None
    if thisCondition['label'].split('-')[0] == 'Unilateral':
        runMode = 0
    if thisCondition['label'].split('-')[0] == 'Bilateral':
        runMode = 1

    runModes = {0: 'Unilateral', 1: 'Bilateral'}

    if runModes[runMode] == 'Unilateral':
        blinkingBalls = [
            allBallsList[whichSide][0], allBallsList[whichSide][1]
        ]
    if runModes[runMode] == 'Bilateral':
        blinkingBalls = [
            allBallsList[0][0], allBallsList[0][1], allBallsList[1][0],
            allBallsList[1][1]
        ]

    if runModes[runMode] != 'Unilateral' and runModes[runMode] != 'Bilateral':
        raise Exception("Run mode must be \"Unilateral\" or \"Bilateral\"")

    blinkTimer = core.Clock()
    blinkInteger = 0
    rectanglesVisual = []
    for r in rectanglesLeft + rectanglesRight:
        rectanglesVisual.append(
            visual.Rect(win,
                        width=(r[2] - r[0]),
                        height=(r[3] - r[1]),
                        fillColor=None,
                        lineColor='Red',
                        units='cm',
                        pos=[(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]))

    # Start first part of the experiment, 2 balls blink for a certain amount
    # of time controlled by experimentalInfo['BlinkTime']
    while trialClock.getTime() < experimentalInfo['BlinkTime']:
        fixationBall.draw()
        # speedText.draw()
        if experimentalInfo['DrawRectangles']:
            for r in rectanglesVisual:
                r.draw()
        for ballListID, ballList in allBallsList.iteritems():
            for ball1 in ballList:
                ball1.draw()

        if (blinkTimer.getTime() > 0.125):
            blinkInteger = blinkInteger + 1
            blinkTimer.reset()
        if (blinkInteger % 2):
            for blinkBall in blinkingBalls:
                blinkBall.setColor('White')
        else:
            for blinkBall in blinkingBalls:
                blinkBall.setColor('Black')
        if (experimentalInfo['SaveVideo']):
            win.getMovieFrame()
        win.flip()

    # Reset all colors of the balls to black and move each ball in its right
    # part of space
    for ballListID, ballList in allBallsList.iteritems():
        for ball1 in ballList:
            ball1.setColor('Black')
            if (isCatchTrial == 1):
                ball1.setColor('Yellow')
            if (isCatchTrial == 2):
                ball1.setColor('Magenta')
            ball1.draw()

    fixationBall.draw()
    if (experimentalInfo['SaveVideo']):
        win.getMovieFrame()

    win.flip()
    trialClock.reset()
    # This function pregenerates all the trajectories so that in displaying
    # them we have no slowing
    allFrames = preGenerateTrajectories(ballSpeed / win.fps(),
                                        experimentalInfo,
                                        allBallsList,
                                        leftRightRectangles,
                                        repulsionStrength=2000.0 * ballSpeed,
                                        edgerepulsionStrength=10.0 * ballSpeed,
                                        centerAttraction=0.0001)

    trialClock.reset()
    for balls in allFrames:
        for ball, pos in balls.iteritems():
            ball.setPos(pos)
            ball.draw()
        # speedText.draw()
        if experimentalInfo['DrawRectangles']:
            for r in rectanglesVisual:
                r.draw()
        fixationBall.draw()
        if (experimentalInfo['SaveVideo']):
            win.getMovieFrame()

        win.flip()
    event.clearEvents(eventType='keyboard')

    trialClock.reset()
    randomBall = allBallsList[whichSide][randrange(0, nBallsPerRectangle)]

    randomBall.setColor('Red')
    event.clearEvents(eventType='keyboard')

    trialClock.reset()
    responseKey = None
    response = None
    while True:
        keys = event.getKeys()
        fixationBall.draw()
        for ballListID, ballList in allBallsList.iteritems():
            for ball1 in ballList:
                ball1.draw()
        randomBall.draw()

        if 's' in keys:
            responseKey = True
            response = responseKey == (randomBall in blinkingBalls)
            trialClock.reset()

        if 'd' in keys:
            responseKey = False
            response = responseKey == (randomBall in blinkingBalls)
            trialClock.reset()

        # Plot the green/red dot for 0.5 seconds
        if response is not None:
            break

        if 'escape' in keys:
            win.close()
            core.quit()
        if (experimentalInfo['SaveVideo']):
            win.getMovieFrame()
        win.flip()

    if response is True:
        fixationBall.setColor('Green')
    if response is False:
        fixationBall.setColor('Red')

    trialClock.reset()
    while trialClock.getTime() < 0.4:
        keys = event.getKeys()
        fixationBall.draw()
        for ballListID, ballList in allBallsList.iteritems():
            for ball1 in ballList:
                ball1.draw()
        randomBall.draw()
        if (experimentalInfo['SaveVideo']):
            win.getMovieFrame()
        win.flip()

    if (experimentalInfo['SaveVideo']):
        import os
        currentpath = os.getcwd()
        savedatapath = currentpath + os.path.sep + 'data'
        outputVideo = savedatapath + os.path.sep + \
            "frames" + os.path.sep + 'Tracking.png'
        print "Saving video to " + outputVideo
        win.saveMovieFrames(outputVideo)

    return response
Exemplo n.º 42
0
def do_run(run, trials):
    resp = []
    fileName = log_file.format(subj_id, run)

    #wait for trigger
    ready_screen.draw()
    win.flip()
    event.waitKeys(keyList=('equal'))
    globalClock.reset()
    studyStart = globalClock.getTime()

    #Initial Fixation screen
    fixation.draw()
    win.flip()
    core.wait(initial_fixation_dur)

    for trial in trials:
        condition_label = stim_map[trial['Partner']]
        image_label = image_map[trial['Partner']]
        imagepath = os.path.join(expdir, 'Images')
        image = os.path.join(imagepath, "%s.png") % image_label
        nameStim.setText(condition_label)
        pictureStim.setImage(image)

        #decision phase
        timer.reset()
        event.clearEvents()

        resp = []
        resp_val = None
        resp_onset = None

        decision_onset = globalClock.getTime()
        trials.addData('decision_onset', decision_onset)

        while timer.getTime() < decision_dur:
            cardStim.draw()
            question.draw()
            pictureStim.draw()
            nameStim.draw()
            win.flip()

            resp = event.getKeys(keyList=responseKeys)

            if len(resp) > 0:
                if resp[0] == 'z':
                    #trials.saveAsText(fileName=log_file.format(subj_id),delim=',',dataOut='all_raw')
                    os.chdir(subjdir)
                    trials.saveAsWideText(fileName)
                    os.chdir(expdir)
                    win.close()
                    core.quit()
                resp_val = int(resp[0])
                if resp_val == 2:
                    resp_onset = globalClock.getTime()
                    question.setColor('darkorange')
                    rt = resp_onset - decision_onset
                    #core.wait(decision_dur - rt)
                if resp_val == 3:
                    resp_onset = globalClock.getTime()
                    question.setColor('darkorange')
                    rt = resp_onset - decision_onset
                    #core.wait(decision_dur -rt)
                cardStim.draw()
                question.draw()
                pictureStim.draw()
                nameStim.draw()
                win.flip()
                core.wait(decision_dur - rt)
                break
            else:
                resp_val = 0
                resp_onset = 999
                rt = 999

        trials.addData('resp', int(resp_val))
        trials.addData('resp_onset', resp_onset)
        trials.addData('rt', rt)

        ###reset question mark color
        question.setColor('white')
        #outcome phase
        timer.reset()
        #win.flip()
        outcome_onset = globalClock.getTime()

        while timer.getTime() < outcome_dur:
            outcome_cardStim.draw()
            pictureStim.draw()
            nameStim.draw()
            #win.flip()

            if trial['Feedback'] == '3' and resp_val == 2:
                outcome_txt = int(random.randint(1, 4))
                outcome_moneyTxt = 'h'
                outcome_color = 'lime'
                trials.addData('outcome_val', int(outcome_txt))
            elif trial['Feedback'] == '3' and resp_val == 3:
                outcome_txt = int(random.randint(6, 9))
                outcome_moneyTxt = 'h'
                outcome_color = 'lime'
                trials.addData('outcome_val', int(outcome_txt))
            elif trial['Feedback'] == '2' and resp_val == 2:
                outcome_txt = int(5)
                outcome_moneyTxt = 'n'
                outcome_color = 'white'
                trials.addData('outcome_val', int(outcome_txt))
            elif trial['Feedback'] == '2' and resp_val == 3:
                outcome_txt = int(5)
                outcome_moneyTxt = 'n'
                outcome_color = 'white'
                trials.addData('outcome_val', int(outcome_txt))
            elif trial['Feedback'] == '1' and resp_val == 2:
                outcome_txt = int(random.randint(6, 9))
                outcome_moneyTxt = 'i'
                outcome_color = 'darkred'
                trials.addData('outcome_val', int(outcome_txt))
            elif trial['Feedback'] == '1' and resp_val == 3:
                outcome_txt = int(random.randint(1, 4))
                outcome_moneyTxt = 'i'
                outcome_color = 'darkred'
                trials.addData('outcome_val', int(outcome_txt))
            elif resp_val == 0:
                outcome_txt = '#'
                outcome_moneyTxt = ''
                outcome_color = 'white'
                outcome_value = '999'
                trials.addData('outcome_val', int(outcome_value))

            #print outcome_txt
            outcome_text.setText(outcome_txt)
            outcome_money.setText(outcome_moneyTxt)
            outcome_money.setColor(outcome_color)
            outcome_text.draw()
            outcome_money.draw()
            win.flip()
            core.wait(outcome_dur)
            #trials.addData('outcome_val', outcome_txt)
            trials.addData('outcome_onset', outcome_onset)

            outcome_offset = globalClock.getTime()
            trials.addData('outcome_offset', outcome_offset)

            duration = outcome_offset - decision_onset
            trials.addData('trialDuration', duration)
            event.clearEvents()
        print "got to check 3"

        #ITI
        logging.log(level=logging.DATA, msg='ITI')  #send fixation log event
        timer.reset()
        ITI_onset = globalClock.getTime()
        iti_for_trial = float(trial['ITI'])
        while timer.getTime() < iti_for_trial:
            fixation.draw()
            win.flip()
        ITI_offset = globalClock.getTime()
        trials.addData('ITIonset', ITI_onset)
        trials.addData('ITIoffset', ITI_offset)

    # Final Fixation screen after trials completed
    fixation.draw()
    win.flip()
    #core.wait(final_fixation_dur)
    os.chdir(subjdir)
    trials.saveAsWideText(fileName)
    os.chdir(expdir)
    endTime = 0.01  # not sure if this will take a 0, so giving it 0.01 and making sure it is defined
    expected_dur = 398
    buffer_dur = 10
    total_dur = expected_dur + buffer_dur
    if globalClock.getTime() < total_dur:
        endTime = (total_dur - globalClock.getTime())
    else:
        endTime = buffer_dur
    core.wait(endTime)
    print globalClock.getTime()
Exemplo n.º 43
0
    def run(self):

        #setup monitor
        self.prepareRun()
        self._win.units = 'pix'

        event.clearEvents()
        mouse = event.Mouse(win=self._win)
        mouse.setVisible(0)

        stim = visual.Rect(self._win)
        stim.height = self.boxSize
        stim.width = self.boxSize
        stim.pos = (self.trialBoxPosition[0], self.trialBoxPosition[1])
        stim.fillColor = self.boxColors[0]
        stim.lineColor = self.boxColors[0]
        lastMouseWheelButton = 0
        numFrames = 0
        mousePos = np.array([0, 0])
        while True:

            #            mousePos = mouse.getPos()
            mousePos += mouse.getRel()
            stim.pos = (mousePos[0], mousePos[1])
            if self.toggleColor and (numFrames % self.togglePeriod == 0):
                stim.fillColor = -stim.fillColor
                stim.lineColor = -stim.lineColor

            stim.draw()

            self.visStimFlip()
            keys = event.getKeys(
                ['space', 'escape', 'period', 'comma', 'up', 'down', 'p'])
            mouseWheel = mouse.getWheelRel()
            mouseButtons = mouse.getPressed()
            stepSize = 10
            if max(mouseButtons[0], mouseButtons[2]) == 0:
                stim.height += stepSize * mouseWheel[1]
                stim.width += stepSize * mouseWheel[1]
            else:
                if [mouseButtons[0], mouseButtons[2]] == [1, 0]:
                    stim.height += stepSize * mouseWheel[1]
                if [mouseButtons[0], mouseButtons[2]] == [0, 1]:
                    stim.width += stepSize * mouseWheel[1]
                if [mouseButtons[0], mouseButtons[2]] == [1, 1]:
                    stim.height = (stim.height + stim.width) / 2
                    stim.width = (stim.height + stim.width) / 2
            if mouseButtons[1] - lastMouseWheelButton == 1:
                stim.fillColor = -stim.fillColor
                stim.lineColor = -stim.lineColor

            if len(keys) > 0:
                if 'space' in keys:
                    self.toggleColor = False if self.toggleColor else True
                if 'comma' in keys:
                    self.togglePeriod -= 5
                    self.togglePeriod = 1 if self.togglePeriod <= 0 else self.togglePeriod
                if 'period' in keys:
                    self.togglePeriod += 5
                if 'up' in keys:
                    stim.ori += 5
                if 'down' in keys:
                    stim.ori -= 5
                if 'escape' in keys:
                    break
                if 'p' in keys:
                    print[pos / self.pixelsPerDeg for pos in stim.pos]
            lastMouseWheelButton = mouseButtons[1]
            numFrames += 1

        event.clearEvents()
        self.completeRun()
Exemplo n.º 44
0
grating = visual.GratingStim(win, mask='gauss', ori=45, sf=2)

# Using bits++ with one stimulus
globalClock = core.Clock()
while True:
    # get new contrast
    t = globalClock.getTime()
    newContr = numpy.sin(t * numpy.pi * 2)  # sinusoidally modulate contrast

    # set whole screen to this contrast
    bitsBox.setContrast(newContr)

    # draw gratings and update screen
    grating.draw()
    win.flip()

    # check for a keypress
    if event.getKeys():
        break
    event.clearEvents('mouse')  # only really needed for pygame windows

# reset the bits++(and update the window so that this is done properly)
bitsBox.setContrast(1)
win.flip()

win.close()
core.quit()

# The contents of this file are in the public domain.
Exemplo n.º 45
0
def displayCircularStimuli(directions, colors, colors_wheel, thicknesses,
                           speeds, duration):
    global mywin, plate, white
    mywin = visual.Window([1280, 1024],
                          monitor="Dell Inc. 17",
                          units="pix",
                          fullscr=False,
                          screen=1,
                          color='white')
    plate = visual.Rect(win=mywin,
                        size=(width_plate, height_plate),
                        lineColor=[0, 0, 0],
                        lineColorSpace="rgb255",
                        lineWidth=4)
    white = visual.ImageStim(win=mywin,
                             image="Solid_white.png",
                             size=(1280, 1024),
                             pos=[0, 0])

    ops = []
    for d in directions:
        if d == 'Clockwise':
            ops.append('+')
        else:
            ops.append('-')

    shape1 = visual.ShapeStim(mywin,
                              units='',
                              lineWidth=thicknesses[0],
                              lineColor=colors_wheel[0],
                              lineColorSpace='rgb',
                              fillColor='red',
                              fillColorSpace='rgb',
                              vertices=np.multiply(wheel, scalingFactor),
                              windingRule=None,
                              closeShape=True,
                              pos=(-width_plate / 6.4, height_plate / 8.2),
                              size=1,
                              ori=0.0,
                              opacity=1.0,
                              contrast=1.0,
                              depth=0,
                              interpolate=True,
                              name=None,
                              autoLog=None,
                              autoDraw=False)

    shape1b = visual.Circle(mywin,
                            radius=scalingFactor,
                            fillColor=colors[0],
                            pos=(-width_plate / 6.4, height_plate / 8.2))

    shape2 = visual.ShapeStim(mywin,
                              units='',
                              lineWidth=thicknesses[1],
                              lineColor=colors_wheel[1],
                              lineColorSpace='rgb',
                              fillColor='red',
                              fillColorSpace='rgb',
                              vertices=np.multiply(wheel, scalingFactor),
                              windingRule=None,
                              closeShape=True,
                              pos=(0, height_plate / 8.2),
                              size=1,
                              ori=0.0,
                              opacity=1.0,
                              contrast=1.0,
                              depth=0,
                              interpolate=True,
                              name=None,
                              autoLog=None,
                              autoDraw=False)

    shape2b = visual.Circle(mywin,
                            radius=scalingFactor,
                            fillColor=colors[1],
                            pos=(0, height_plate / 8.2))

    shape3 = visual.ShapeStim(mywin,
                              units='',
                              lineWidth=thicknesses[2],
                              lineColor=colors_wheel[2],
                              lineColorSpace='rgb',
                              fillColor='red',
                              fillColorSpace='rgb',
                              vertices=np.multiply(wheel, scalingFactor),
                              windingRule=None,
                              closeShape=True,
                              pos=(width_plate / 6.4, height_plate / 8.2),
                              size=1,
                              ori=0.0,
                              opacity=1.0,
                              contrast=1.0,
                              depth=0,
                              interpolate=True,
                              name=None,
                              autoLog=None,
                              autoDraw=False)

    shape3b = visual.Circle(mywin,
                            radius=scalingFactor,
                            fillColor=colors[2],
                            pos=(width_plate / 6.4, height_plate / 8.2))

    shape4 = visual.ShapeStim(mywin,
                              units='',
                              lineWidth=thicknesses[3],
                              lineColor=colors_wheel[3],
                              lineColorSpace='rgb',
                              fillColor='red',
                              fillColorSpace='rgb',
                              vertices=np.multiply(wheel, scalingFactor),
                              windingRule=None,
                              closeShape=True,
                              pos=(-width_plate / 6.4, -height_plate / 8.2),
                              size=1,
                              ori=0.0,
                              opacity=1.0,
                              contrast=1.0,
                              depth=0,
                              interpolate=True,
                              name=None,
                              autoLog=None,
                              autoDraw=False)

    shape4b = visual.Circle(mywin,
                            radius=scalingFactor,
                            fillColor=colors[3],
                            pos=(-width_plate / 6.4, -height_plate / 8.2))

    shape5 = visual.ShapeStim(mywin,
                              units='',
                              lineWidth=thicknesses[4],
                              lineColor=colors_wheel[4],
                              lineColorSpace='rgb',
                              fillColor='red',
                              fillColorSpace='rgb',
                              vertices=np.multiply(wheel, scalingFactor),
                              windingRule=None,
                              closeShape=True,
                              pos=(0, -height_plate / 8.2),
                              size=1,
                              ori=0.0,
                              opacity=1.0,
                              contrast=1.0,
                              depth=0,
                              interpolate=True,
                              name=None,
                              autoLog=None,
                              autoDraw=False)

    shape5b = visual.Circle(mywin,
                            radius=scalingFactor,
                            fillColor=colors[4],
                            pos=(0, -height_plate / 8.2))

    shape6 = visual.ShapeStim(mywin,
                              units='',
                              lineWidth=thicknesses[5],
                              lineColor=colors_wheel[5],
                              lineColorSpace='rgb',
                              fillColor='red',
                              fillColorSpace='rgb',
                              vertices=np.multiply(wheel, scalingFactor),
                              windingRule=None,
                              closeShape=True,
                              pos=(width_plate / 6.4, -height_plate / 8.2),
                              size=1,
                              ori=0.0,
                              opacity=1.0,
                              contrast=1.0,
                              depth=0,
                              interpolate=True,
                              name=None,
                              autoLog=None,
                              autoDraw=False)

    shape6b = visual.Circle(mywin,
                            radius=scalingFactor,
                            fillColor=colors[5],
                            pos=(width_plate / 6.4, -height_plate / 8.2))

    mywin.winHandle.maximize()
    mywin.winHandle.set_fullscreen(True)
    mywin.winHandle.activate()

    # display white
    while True:
        white.draw()
        plate.draw()
        mywin.flip()
        if event.waitKeys(0.5) == ["escape"]:
            break
    event.clearEvents()
    startCamera(duration)
    clock = core.Clock()
    for frameN in range(duration):
        white.draw()
        plate.draw()

        shape1.setOri(speeds[0], operation=ops[0])
        shape1b.draw()
        shape1.draw()

        shape2.setOri(speeds[1], operation=ops[1])
        shape2b.draw()
        shape2.draw()

        shape3.setOri(speeds[2], operation=ops[2])
        shape3b.draw()
        shape3.draw()

        shape4.setOri(speeds[3], operation=ops[3])
        shape4b.draw()
        shape4.draw()

        shape5.setOri(speeds[4], operation=ops[4])
        shape5b.draw()
        shape5.draw()

        shape6.setOri(speeds[5], operation=ops[5])
        shape6b.draw()
        shape6.draw()

        mywin.logOnFlip(level=logging.CRITICAL, msg='sent on actual flip')
        mywin.flip()

    for frameN in range(300):
        white.draw()
        plate.draw()
        mywin.flip()

    mywin.close()
    core.quit()
Exemplo n.º 46
0
 def test_clearEvents(self):
     for t in ['mouse', 'joystick', 'keyboard', None]:
         event.clearEvents(t)
Exemplo n.º 47
0
def do_run(run_number, trials):
    timer = core.Clock()
    ##############################
    # 1. display ready screen and wait for 't' to be sent to indicate scanner trigger
    ready_screen.draw()
    # Change to the next slide
    win.flip()  #showing "Ready"
    # wait until the key 't' appears
    event.waitKeys(keyList='t')
    # reset globalClock
    globalClock.reset()
    # send START log event
    logging.log(level=logging.DATA,
                msg='******* START (trigger from scanner) - run %i *******' %
                run_number)

    ################

    # SHOW INSTRUCTIONS

    ################

    timer.reset()

    #Change to the next slide:
    # - "Please review..." for "INSTRUCT_DUR" (8s)
    while timer.getTime() < INSTRUCT_DUR:
        instruction_text.draw()
        win.flip()

    timer.reset()
    #Change to the next slide:
    # - "pre-task fixation" for "FIXATION_DUR" (1.5 s)
    while timer.getTime() < FIXATION_DUR:
        fixation.draw()
        win.flip()

    ################

    # MAIN LOOP
    # present trials
    for tidx, trial in enumerate(trials):
        # Set up local parameters--------------------------------
        # Image 1---------------------
        trial_type = trial['type']
        cond = trial['cond']
        theme = trial['theme']
        image = "images/%s/First Image/%s_%s.png" % (cond, theme, trial_type)
        # print(image)
        pictureStim_image1.setImage(image)
        # send MESSAGE log event
        logging.log(level=logging.DATA,
                    msg="MESSAGE: %s - %s - %s" % (cond, theme, trial_type))
        trials.addData('stim_onset', globalClock.getTime())
        timer.reset()
        #Change to the next slide:---------------------------------
        # - "trial picture" for "MESSAGE_DUR" (3s)
        while timer.getTime() < MESSAGE_DUR:
            pictureStim_image1.draw()
            win.flip()

        # send SHOW RATING log event
        logging.log(level=logging.DATA, msg="SHOW RATING")
        trials.addData('resp_onset', globalClock.getTime())

        # clear event buffer
        event.clearEvents()
        resp_onset = globalClock.getTime()

        #Change to the next slide:---------------------------------
        # - trial picture along with"rating" for "RATING_DUR" (2s)
        # show rating and collect response
        timer.reset()
        while timer.getTime() < RATING_DUR:
            # draw the trial picture
            pictureStim_image1.draw()

            # draw the rating scale and anchors
            for rate_stim in ratingStim:
                rate_stim.draw()
            anchor1.draw()
            anchor4.draw()
            # Show the rating stimulus
            win.flip()
            # get key response
            resp = event.getKeys(keyList=BUTTONS)
            # the case when the subject did press a button
            if len(resp) > 0:
                # get the first button response
                resp_value = resp[0]
                # Mark the pressed value as red
                # (will be shown at the next win.flip())
                ratingStim[BUTTON_LABELS[resp_value]].setColor('red')

                # Logging: add response value to the trial handler logging
                #pdb.set_trace()
                # Why is the reponse being ovewritten by the next trial?? (2019/04/01)
                # Note that the previous response is no unsaved. It IS overwritten.
                trials.addData('resp', resp_value)
                trials.addData('rt', globalClock.getTime() - resp_onset)
                #trials.nextEntry() #not working...
                #pdb.set_trace()
        # End of the rating slide

        #Change to the next slide:---------------------------------
        # - image2 (3s)
        # show rating and collect response
        image2 = "images/%s/Second Image/%s_%s.png" % (cond, theme, trial_type)
        pictureStim_image2.setImage(image2)
        timer.reset()
        while timer.getTime() < MESSAGE_DUR:
            pictureStim_image2.draw()
            win.flip()

        # Reset rating number color
        for rate in ratingStim:
            rate.setColor('#FFFFFF')
        # ------------ FIXATION ------------
        # logging: send FIXATION log event
        logging.log(level=logging.DATA, msg='FIXATION')

        # Get the fixation duration (a random int from 1 to 5)
        fixation_for_trial = fixations[run_number - 1][tidx]

        timer.reset()
        #Change to the next slide:
        # - "rating" for "RATING_DUR" (1-5s)
        while timer.getTime() < fixation_for_trial:
            #for frame in range(FIXATION_DUR):
            fixation.draw()
            win.flip()
    # End of all trials

    # Logging: Send END log event
    logging.log(level=logging.DATA,
                msg='******* END run %i *******' % run_number)

    #pdb.set_trace()

    # Save the trial infomation from trial handler
    log_filename2 = "%s_%i.csv" % (log_filename[:-4], run_number)

    # the data to write to csv is stored in "trials.data"
    # (1) trials.addDataData(): 'stim_onset', 'resp_onset', 'resp', 'rt'
    # - Comes from trials.addDataData()
    # (2) from trials.extraInfo: 'Participant ID', 'Date', 'Description'
    # - Comes from 'run_data'
    trials.saveAsWideText(log_filename2)

    # Show the run-ending slide
    run_end_screen.draw()
    win.flip()

    #trials.saveAsText(log_filename2, delim=',', dataOut=('n', 'all_raw')) #####FAIL with "-1"
    # Press 'space' to and the run (will move on to the next run if there is one)
    event.waitKeys(keyList=('space'))
Exemplo n.º 48
0
def do_run(trials):
    resp = []

    #wait for button press from RA ('spacebar' key press)

    ready_screen.draw()
    win.flip()
    event.waitKeys(keyList=('space'))
    globalClock.reset()

    for trial in trials:

        # add trial logic
        # i.e. show stimuli
        # get resp
        # add data to 'trial'

        condition_label = stim_map[trial['Partner']]
        shareStim.setText(condition_label)
        resp_left = trial['cLeft']
        respcLeft = 'Share $%s.00' % resp_left
        resp_text_left.setText(respcLeft)
        resp_right = trial['cRight']
        respcRight = 'Share $%s.00' % resp_right
        resp_text_right.setText(respcRight)

        if resp == ['z']:
            core.quit()

        #decision phase
        timer.reset()

        event.clearEvents()

        resp = []
        resp_val = None
        resp_onset = None
        answer = 0
        trial_onset = globalClock.getTime()
        ISI_pad = []

        while timer.getTime() < .5:
            shareStim.draw()
            win.flip()

        while timer.getTime() < decision_dur:
            shareStim.draw()
            resp_text_left.draw()
            resp_text_right.draw()
            win.flip()

            if answer == 0:
                resp = event.getKeys(keyList=responseKeys)

            if len(resp) == 0:
                resp_val = 'NA'
                response = 'NA'
                resp_onset = globalClock.getTime()
                highlow = 'NA'
                ISI_pad = decision_dur - resp_onset

            if answer == 0 and len(resp) > 0:
                resp_val = int(resp[0])
                resp_onset = globalClock.getTime()
                ISI_pad = decision_dur - resp_onset
                answer = 1
                if resp_val == 2:
                    resp_text_left.setColor('red')
                    response = resp_left
                    if resp_left < resp_right:
                        highlow = 'low'
                    else:
                        highlow = 'high'
                if resp_val == 3:
                    resp_text_right.setColor('red')
                    response = resp_right
                    if resp_left < resp_right:
                        highlow = 'high'
                    else:
                        highlow = 'low'
                shareStim.draw()
                resp_text_left.draw()
                resp_text_right.draw()
                win.flip()
                core.wait(.5)
                break

        trials.addData('onset', trial_onset)
        trials.addData('bpress', resp_val)
        trials.addData('resp', response)
        trials.addData('resp_onset', resp_onset)
        trials.addData('highlow', highlow)
        trials.addData('rt', resp_onset - trial_onset)

        #reset rating number and amount
        resp_text_left.setColor('#FFFFFF')
        resp_text_right.setColor('#FFFFFF')
        resp_text_left.setText()
        resp_text_right.setText()

        #ISI
        #logging.log(level=logging.DATA, msg='ISI') #send fixation log event
        ISI_onset = globalClock.getTime()
        trials.addData('ISI_onset', ISI_onset)
        timer.reset()
        isi_for_trial = float(trial['ISI'])
        while timer.getTime() < isi_for_trial + ISI_pad:
            waiting.draw()
            win.flip()

        #outcome phase
        partner_resp = float(trial['Reciprocate'])

        if len(resp) > 0:
            if (int(trial['cLeft']) == 0
                    and resp_val == 2) or (int(trial['cRight']) == 0
                                           and resp_val == 3):
                core.wait(.5)
                outcome_onset = 'NA'
            else:
                outcome_txt = outcome_map[2][partner_resp].format(
                    condition_label)
                outcome_stim.setText(outcome_txt)
                outcome_stim.draw()
                win.flip()
                core.wait(2)
                outcome_onset = globalClock.getTime()
        else:
            outcome_txt = outcome_map[resp_val]
            outcome_stim.setText(outcome_txt)
            outcome_stim.draw()
            win.flip()
            core.wait(2)
            outcome_onset = 'NA'

        trials.addData('outcome_onset', outcome_onset)
        trial_duration = globalClock.getTime()
        trials.addData('duration', trial_duration - trial_onset)

        #ITI
        #logging.log(level=logging.DATA, msg='ITI') #send fixation log event
        timer.reset()
        iti_for_trial = float(trial['ITI'])
        ITI_onset = globalClock.getTime()
        while timer.getTime() < iti_for_trial:
            fixation.draw()
            win.flip()
        trials.addData('ITI_onset', ITI_onset)

    trials.saveAsWideText(fileName=log_file.format(subj_id, subj_id),
                          delim=',',
                          appendFile=True)
Exemplo n.º 49
0
    if setsize == 2:
        updates = run_details[2]
        A1.pos = (0, 140)
        B1.pos = (0, -140)

        A1.text = run_details[0]['A1']
        B1.text = run_details[0]['B1']

        reset_box_color()
        box_draw(2)
        A1.draw()
        B1.draw()
        win.flip()

        event.clearEvents()
        event.waitKeys(keyList=['space'])

        box_draw(2)
        win.flip()
        core.wait(0.5)

        stim_track = []

        for stim in updates:
            if stim['dig'] > 0:
                stim_dig = '+' + str(stim['dig'])
            else:
                stim_dig = str(stim['dig'])

            exec("%s.text = stim_dig" % stim['pos'])
Exemplo n.º 50
0
def stimuli_presentation(subject, hz_list, acquisition_scheme, order_volume,
                         order_presentation, single_run):
    """function to present stimuli
    if single_run == True
        present a single trial with specified order of volume
        and frequency progression,

    if single_run == False
        presents all possible combinations of volume and frequency
        progression (2x2) for one specifies acquisition_scheme

    subject = subject code
    hz_list = list containing paths to stimuli
    acquisition_scheme = name of specified acq-scheme
    order_volume = volume progression either "increasing" or "decreasing"
    order_presentation = frequency progression either "ascending" or
                         "descending"
    """

    # setup your screen specifications
    #hz_list = pd.read_csv('/home/michael/atom/stimuli.csv')
    run_list = hz_list.columns

    if single_run == True:
        # setup window for stimuli presentation
        # set fullscr=True for fullscree presentation
        win = visual.Window([800, 600],
                            monitor="testMonitor",
                            units="deg",
                            fullscr=False)
        print(acquisition_scheme)
        content['acq'] = str(acquisition_scheme)

        #  reverse stimuli list if different order of frequency presentation is specified
        if order_presentation == 'descending':
            run_list = reversed(list(run_list))

        #  get order of volume and in what range they should be presented
        if order_volume == 'increasing':
            order = list(range(0, 9))

        elif order_volume == 'decreasing':
            order = list(reversed(range(0, 9)))

        #  get instruction for increasing or decreasing volume condition
        if order_volume == 'increasing':
            instruction = 'Press the button, once you - DO - hear a tone.'
        elif order_volume == 'decreasing':
            instruction = 'Press the button, if you - DO NOT - hear the tone anymore'

        #  append order of volume and frequency presentation to json-file
        content.setdefault('volume_progression', []).append(order_volume)
        content.setdefault('frequency_progression',
                           []).append(order_presentation)

        #  create lists to keep track what and when stimuli is presented
        result_list = []
        stim_start_type = []
        stim_onset_list = []
        rt_list = []
        trial_onset_list = []
        trial_end_list = []
        all_stim_list = []

        #  specify and present instrtuction
        win.clearBuffer()
        win.flip()  # update screen, display message
        message = visual.TextStim(win, text=instruction)
        win.flip()  # update screen, display message
        message.setAutoDraw(True)  # automatically draw every frame
        win.flip()  # update screen, display message
        core.wait(1.5)  # wait for given amount in seconds

        # wait for mri-trigger
        for i in range(3):
            while True:
                #  get timestamp for first trigger
                if i == 0:
                    trial_onset = time.time()

                #  get trigger as keyboard input, 't' is the standard input for
                #  our scanner, eventually needs to be changed for different
                #  scanner
                theseKeys = event.getKeys('t')  #
                if 't' in theseKeys:
                    event.clearEvents(eventType='keyboard')
                    print('trigger')
                    break
                #  end experiment by pressing "q"
                key_escape = event.getKeys('q')  # to end exp, if need be
                if 'q' in key_escape:
                    win.close()
                    core.quit()
        trial_onset_list.append(trial_onset)

        #  present msg indicating that trial begins
        message.setText('Run starts!')
        message.setAutoDraw(True)  # automatically draw every frame
        win.flip()  # update screen, display message

        #  end experiment by pressing "q"
        key_escape = event.getKeys('q')  # to end exp, if need be
        if 'q' in key_escape:
            win.close()
            core.quit()

        #  present fixation cross
        win.clearBuffer()
        win.flip()  # update screen, display message
        message.setText('+')
        win.flip()

        #######################################################################
        # stimuli presentation starts here
        #######################################################################
        #counter = 0  # counter
        #  iterate over list of stimuli
        for i in run_list:
            for j in order:
                core.wait(1)  # wait for one second before stimuli presentation
                #print(j)

                #  which stimuli to play
                hz = hz_list[i][j]

                # condition to break loop once participants responds to stimuli
                stop_loop = False

                # set stimuli as sound object
                stim = sound.Sound(_thisDir + '/stimuli/' + hz)

                win.clearBuffer()
                win.flip()  # update screen, display message

                #  end experiment by pressing "q"
                key_escape = event.getKeys('q')  # to end exp, if need be
                if 'q' in key_escape:
                    win.close()
                    core.quit()
                #core.wait(0.2)  # wait for 0.2s for system to settle
                #  clock object to keep track of presentation time
                trial_clock = core.Clock()

                stim.play()  # play stimuli
                #  get timestamp of stimuli presentation and append to list
                stim_start_absolute = time.time()
                stim_start = stim_start_absolute - trial_onset
                stim_start_type.append(hz)
                all_stim_list.append(stim_start)

                #  present stimuli for 2s and wait for participants response
                while trial_clock.getTime(
                ) < 2.0:  # clock times are in seconds
                    if 0.0 <= trial_clock.getTime() < 2.0:

                        #  if participant presses the "7" key stop volume volume
                        #  progression and jump to next stimuli
                        this_key = event.getKeys('7')
                        if '7' in this_key:
                            stim.stop()
                            stim_onset_list.append(
                                stim_start)  #timestamp for stim onset
                            #counter += 1
                            #  get specific volume that was responded to
                            result_list.append(hz)

                            #  get timestamp for participant response
                            rt_absolute = time.time()
                            rt = rt_absolute - trial_onset
                            rt_list.append(rt)
                            stop_loop = True  # indicates that next stimuli should be picked
                            break
                        elif order_volume == 'decreasing' and j is 0 and '7' not in this_key and trial_clock.getTime(
                        ) > 1.9:
                            print('not_discovered')
                            result_list.append(str(hz) + '/not_discovered')
                            stim_onset_list.append(stim_start)
                            #counter += 1
                            stim.stop()
                            rt_absolute = time.time()
                            rt = rt_absolute - trial_onset
                            rt_list.append(rt)
                            stop_loop = True
                            break

                        elif order_volume == 'increasing' and j is 8 and '7' not in this_key and trial_clock.getTime(
                        ) > 1.9:
                            print('not_discovered')

                            result_list.append(str(hz) + '/not_discovered')
                            stim.stop()
                            stim_onset_list.append(stim_start)
                            #counter += 1
                            rt_absolute = time.time()
                            rt = rt_absolute - trial_onset
                            rt_list.append(rt)
                            stop_loop = True
                            break

                        key_escape = event.getKeys(
                            'q')  # to end exp, if need be
                        if 'q' in key_escape:
                            win.close()
                            core.quit()

                if stop_loop is True:
                    break
        #  close window for presentation
        win.close()

        #  create DataFrame to save results
        df_results = pd.DataFrame({'stimuli': result_list})

        order_presentation_list = []
        volumes = []
        frequencies = []
        acquisition_scheme_list = []
        order_volume_list = []
        subject_name = []

        for i in df_results.columns:
            for item in df_results[i]:
                subject_name.append(subject)
                # get info on acquisition_scheme
                if 'baseline' in acquisition_scheme:
                    acquisition_scheme_list.append('baseline')
                elif 'epi_fast(TR1s)' in acquisition_scheme:
                    acquisition_scheme_list.append('epi_fast(TR1s)')
                elif 'epi_standard(TR2s)' in acquisition_scheme:
                    acquisition_scheme_list.append('epi_standard(TR2s)')
                elif 'mprage(T1w)' in acquisition_scheme:
                    acquisition_scheme_list.append('mprage(T1w)')
                else:
                    acquisition_scheme_list.append('mprage(T1w)')

                # get info on volume order
                if 'decreasing' in order_volume:
                    order_volume_list.append('decreasing')
                elif 'increasing' in order_volume:
                    order_volume_list.append('increasing')
                # get info on stimuli order
                if 'ascending' in order_presentation:
                    order_presentation_list.append('ascending')
                elif 'descending' in order_presentation:
                    order_presentation_list.append('descending')

                # extract discovered volume
                if 'not_discovered' in item:
                    volumes.append('0')
                #elif '10dBFS' in item:
                #    volumes.append(-10)
                elif '20dBFS' in item:
                    volumes.append(-20)
                elif '30dBFS' in item:
                    volumes.append(-30)
                elif '40dBFS' in item:
                    volumes.append(-40)
                elif '50dBFS' in item:
                    volumes.append(-50)
                elif '60dBFS' in item:
                    volumes.append(-60)
                elif '70dBFS' in item:
                    volumes.append(-70)
                elif '80dBFS' in item:
                    volumes.append(-80)
                elif '90dBFS' in item:
                    volumes.append(-90)
                elif '100dBFS' in item:
                    volumes.append(-100)

                if '150hz' in item:
                    frequencies.append(150)
                elif '1000hz' in item:
                    frequencies.append(1000)
                elif '1500hz' in item:
                    frequencies.append(1500)
                elif '2000hz' in item:
                    frequencies.append(2000)
                elif '2250hz' in item:
                    frequencies.append(2250)
                elif '2500hz' in item:
                    frequencies.append(2500)
                elif '2750hz' in item:
                    frequencies.append(2750)
                elif '3000hz' in item:
                    frequencies.append(3000)
                elif '4000hz' in item:
                    frequencies.append(4000)
                elif '6000hz' in item:
                    frequencies.append(6000)
                elif '8000hz' in item:
                    frequencies.append(8000)
                elif '250hz' in item:
                    frequencies.append(250)
                elif '500hz' in item:
                    frequencies.append(500)

        # set datframe containing exp results
        date = data.getDateStr()  # get date
        df = pd.DataFrame({
            'stimuli': result_list,
            'subject': subject_name,
            'onset': stim_onset_list,
            'reaction_time': rt_list,
            'acquisition_scheme': acquisition_scheme_list,
            'Level (dBFS)': volumes,
            'Frequency (Hz)': frequencies,
            'order_volume': order_volume_list,
            'order_presentation': order_presentation_list
        })

        # save data as csv
        df.to_csv('{first}_{second}_{third}_{fourth}_{last}.tsv'.format(
            first=subject,
            second=acquisition_scheme,
            third=order_volume,
            fourth=order_presentation,
            last=str(date)),
                  encoding='utf-8',
                  index=False,
                  sep='\t')

        # save trial_start times
        df_trial_start = pd.DataFrame({'trial_start': trial_onset_list})
        df_trial_start.to_csv(
            '{first}_{second}_{third}_{fourth}_trial_start_{last}.tsv'.format(
                first=subject,
                second=acquisition_scheme,
                third=order_volume,
                fourth=order_presentation,
                last=str(date)),
            encoding='utf-8',
            index=False,
            sep='\t')
        # save all stimuli onsets
        df_stimuli_onsets = pd.DataFrame({
            'stimuli_onset': all_stim_list,
            'Frequency (Hz)': stim_start_type
        })
        df_stimuli_onsets.to_csv(
            '{first}_{second}_{third}_{fourth}__stimuli_onsets_{last}.tsv'.
            format(first=subject,
                   second=acquisition_scheme,
                   third=order_volume,
                   fourth=order_presentation,
                   last=str(date)),
            encoding='utf-8',
            index=False,
            sep='\t')

        #  write json-summary-file for trial
        with open(
                '{first}_{second}_{third}_{fourth}_{last}.json'.format(
                    first=subject,
                    second=acquisition_scheme,
                    third=order_volume,
                    fourth=order_presentation,
                    last=str(date)), 'w') as f:
            json.dump(content, f, indent=4)

    ## if user specified to run all volume and presentation orders
    elif single_run == False:
        #  repeat loop for each possible combination of conditions
        for x in range(4):
            content['acq'] = acquisition_scheme

            list_volume = ['increasing', 'decreasing']
            list_order = ['ascending', 'descending']

            if x == 0:
                # setup window for stimuli presentation
                # set fullscr=True for fullscree presentation
                win = visual.Window([800, 600],
                                    monitor="testMonitor",
                                    units="deg")

                #  create lists to keep track what and when stimuli is presented
                result_list = []
                stim_start_type = []
                stim_onset_list = []
                rt_list = []
                trial_onset_list = []
                trial_end_list = []
                order_presentation_list = []
                order_volume_list = []
                all_stim_list = []

            #  x = how often loop was performed; which trial we're in
            if x == 0:
                #  get presentation conditions for first trial
                order_volume = list_volume[0]
                order_presentation = list_order[0]
                instruction = 'Press the button, once you - DO - hear a tone.'

            elif x == 1:
                #  get presentation conditions for second trial
                order_volume = list_volume[1]
                order_presentation = list_order[0]
                instruction = 'Press the button, if you - DO NOT - hear the tone anymore'

            elif x == 2:
                #  get presentation conditions for third trial

                order_volume = list_volume[0]
                order_presentation = list_order[1]
                instruction = 'Press the button, once you - DO - hear a tone.'

            elif x == 3:
                #  get presentation conditions for second trial
                order_volume = list_volume[1]
                order_presentation = list_order[1]
                instruction = 'Press the button, if you - DO NOT - hear the tone anymore'

            #  list containing stimuli categories (e.g. 150hz, 250hz, etc.)
            run_list = hz_list.columns

            #  reverse stimuli list if different order of frequency presentation is specified
            if order_presentation == 'descending':
                run_list = reversed(list(hz_list))

            #  get order of volume and in what range they should be presented
            if order_volume == 'increasing':
                order = list(range(0, 9))

            elif order_volume == 'decreasing':
                order = list(reversed(range(0, 9)))

            #  append order of volume and frequency presentation to json-file
            content.setdefault('volume_progression', []).append(order_volume)
            content.setdefault('frequency_progression',
                               []).append(order_presentation)

            #  to avoid overlap of different instructions on screen
            if x is not 0:
                message.setAutoDraw(False)  # automatically draw every frame
                win.flip()

            #  specify and present instrtuction
            message = visual.TextStim(win, text=instruction)
            message.setAutoDraw(True)  # automatically draw every frame
            win.flip()  # update screen, display message
            core.wait(1.5)  # wait for given amount in seconds

            # wait for mri-trigger
            for i in range(3):
                while True:
                    #  get timestamp for first trigger
                    if i == 0:
                        trial_onset = time.time()

                    #  get trigger as keyboard input, 't' is the standard input for
                    #  our scanner, eventually needs to be changed for different
                    #  scanner
                    theseKeys = event.getKeys('t')
                    if 't' in theseKeys:
                        event.clearEvents(eventType='keyboard')
                        print('trigger')
                        break
                    key_escape = event.getKeys('q')  # to end exp, if need be
                    if 'q' in key_escape:
                        win.close()
                        core.quit()

            trial_onset_list.append(trial_onset)

            key_escape = event.getKeys('q')  # to end exp, if need be
            if 'q' in key_escape:
                win.close()
                core.quit()

            #  present fixation cross
            message.setText('+')
            message.setAutoDraw(True)  # automatically draw every frame
            win.flip()

            #counter = 0
            #  iterate over list of stimuli
            for i in run_list:
                for j in order:
                    # wait for 1 sec, otherwise next trial is started to quick
                    core.wait(1)

                    #  which stimuli to play
                    hz = hz_list[i][j]

                    # condition to break loop once participants responds to stimuli
                    stop_loop = False

                    # set stimuli as sound object
                    stim = sound.Sound(_thisDir + '/stimuli/' + hz)

                    key_escape = event.getKeys('q')  # to end exp, if need be
                    if 'q' in key_escape:
                        win.close()
                        core.quit()
                    #core.wait(0.2)
                    trial_clock = core.Clock()

                    stim.play()  # play stimuli
                    #  get timestamp of stimuli presentation and append to list
                    stim_start_absolute = time.time()
                    stim_start = stim_start_absolute - trial_onset
                    stim_start_type.append(hz)
                    all_stim_list.append(stim_start)

                    #  present stimuli for 2s and wait for participants response
                    while trial_clock.getTime(
                    ) < 2.0:  # clock times are in seconds

                        if 0.0 <= trial_clock.getTime() < 2.0:

                            #  if participant presses the "7" key stop volume volume
                            #  progression and jump to next stimuli
                            this_key = event.getKeys('7')
                            if '7' in this_key:
                                stim.stop()
                                stim_onset_list.append(stim_start)
                                #counter += 1

                                #  get specific volume that was responded to
                                result_list.append(hz)

                                #  get timestamp for participant response
                                rt_absolute = time.time()
                                rt = rt_absolute - trial_onset
                                rt_list.append(rt)
                                order_presentation_list.append(
                                    order_presentation)
                                order_volume_list.append(order_volume)
                                stop_loop = True  # indicates that next stimuli should be picked
                                break
                            elif order_volume == 'decreasing' and j is 0 and '7' not in this_key and trial_clock.getTime(
                            ) > 1.9:
                                result_list.append(str(hz) + '/not_discovered')
                                stim_onset_list.append(stim_start)
                                #counter += 1
                                stim.stop()
                                rt_absolute = time.time()
                                rt = rt_absolute - trial_onset
                                rt_list.append(rt)
                                order_presentation_list.append(
                                    order_presentation)
                                order_volume_list.append(order_volume)
                                stop_loop = True
                                break

                            elif order_volume == 'increasing' and j is 8 and '7' not in this_key and trial_clock.getTime(
                            ) > 1.9:
                                result_list.append(str(hz) + '/not_discovered')
                                stim.stop()
                                stim_onset_list.append(stim_start)
                                #counter += 1
                                rt_absolute = time.time()
                                rt = rt_absolute - trial_onset
                                rt_list.append(rt)
                                order_presentation_list.append(
                                    order_presentation)
                                order_volume_list.append(order_volume)

                                stop_loop = True
                                break

                            key_escape = event.getKeys(
                                'q')  # to end exp, if need be
                            if 'q' in key_escape:
                                win.close()
                                core.quit()

                    if stop_loop is True:
                        break
        #  if fourth trial is done
        if x == 3:

            #  create DataFrame to save results
            df_results = pd.DataFrame({'stimuli': result_list})

            volumes = []
            frequencies = []
            acquisition_scheme_list = []
            subject_name = []

            for i in df_results.columns:
                for item in df_results[i]:
                    subject_name.append(subject)
                    # get info on acquisition_scheme
                    if 'baseline' in acquisition_scheme:
                        acquisition_scheme_list.append('baseline')
                    elif 'epi_fast(TR1s)' in acquisition_scheme:
                        acquisition_scheme_list.append('epi_fast(TR1s)')
                    elif 'epi_standard(TR2s)' in acquisition_scheme:
                        acquisition_scheme_list.append('epi_standard(TR2s)')
                    elif 'mprage(T1w)' in acquisition_scheme:
                        acquisition_scheme_list.append('mprage(T1w)')
                    else:
                        acquisition_scheme_list.append('mprage(T1w)')

                    # extract discovered volume
                    if 'not_discovered' in item:
                        volumes.append('0')
                    #elif '10dBFS' in item:
                    #volumes.append(-10)
                    elif '20dBFS' in item:
                        volumes.append(-20)
                    elif '30dBFS' in item:
                        volumes.append(-30)
                    elif '40dBFS' in item:
                        volumes.append(-40)
                    elif '50dBFS' in item:
                        volumes.append(-50)
                    elif '60dBFS' in item:
                        volumes.append(-60)
                    elif '70dBFS' in item:
                        volumes.append(-70)
                    elif '80dBFS' in item:
                        volumes.append(-80)
                    elif '90dBFS' in item:
                        volumes.append(-90)
                    elif '100dBFS' in item:
                        volumes.append(-100)

                    # print(volumes)
                    if '150hz' in item:
                        frequencies.append(150)
                    elif '1000hz' in item:
                        frequencies.append(1000)
                    elif '1500hz' in item:
                        frequencies.append(1500)
                    elif '2000hz' in item:
                        frequencies.append(2000)
                    elif '2250hz' in item:
                        frequencies.append(2250)
                    elif '2500hz' in item:
                        frequencies.append(2500)
                    elif '2750hz' in item:
                        frequencies.append(2750)
                    elif '3000hz' in item:
                        frequencies.append(3000)
                    elif '4000hz' in item:
                        frequencies.append(4000)
                    elif '6000hz' in item:
                        frequencies.append(6000)
                    elif '8000hz' in item:
                        frequencies.append(8000)
                    elif '250hz' in item:
                        frequencies.append(250)
                    elif '500hz' in item:
                        frequencies.append(500)

                # set datframe containing exp results
                date = data.getDateStr()  # get date
                df = pd.DataFrame({
                    'stimuli': result_list,
                    'subject': subject_name,
                    'onset': stim_onset_list,
                    'reaction_time': rt_list,
                    'acquisition_scheme': acquisition_scheme_list,
                    'Level (dBFS)': volumes,
                    'Frequency (Hz)': frequencies,
                    'order_volume': order_volume_list,
                    'order_presentation': order_presentation_list
                })

                # save data as tsv
                df.to_csv('{first}_{second}_{last}.tsv'.format(
                    first=subject, second=acquisition_scheme, last=str(date)),
                          encoding='utf-8',
                          index=False,
                          sep='\t')

                # save trial_start times
                df_trial_start = pd.DataFrame(
                    {'trial_start': trial_onset_list})
                df_trial_start.to_csv(
                    '{first}_{second}_trial_start_{last}.tsv'.format(
                        first=subject,
                        second=acquisition_scheme,
                        last=str(date)),
                    encoding='utf-8',
                    index=False,
                    sep='\t')

                # save all stimuli onsets
                df_stimuli_onsets = pd.DataFrame({
                    'stimuli_onset':
                    all_stim_list,
                    'Frequency (Hz)':
                    stim_start_type
                })
                df_stimuli_onsets.to_csv(
                    '{first}_{second}__stimuli_onsets_{last}.tsv'.format(
                        first=subject,
                        second=acquisition_scheme,
                        last=str(date)),
                    encoding='utf-8',
                    index=False,
                    sep='\t')

                #  write json-summary-file for trial
                with open(
                        '{first}_{second}_{last}.json'.format(
                            first=subject,
                            second=acquisition_scheme,
                            last=str(date)), 'w') as f:
                    json.dump(content, f, indent=4)
        #  close window for presentation
        win.close()
Exemplo n.º 51
0
def runBlock(nReps, saveTrials=True):
    #set up the trials/experiment
    conditions = data.importConditions(
        'conditions.csv')  #import conditions from file
    trials = data.TrialHandler(trialList=conditions,
                               nReps=nReps)  #create trial handler (loop)

    #(optional) set up logging if events should be saved
    if saveTrials:
        #create the base filename for our data files
        filename = "data/{participant}_{dateStr}".format(**info)
        logfile = logging.LogFile(
            filename + ".log",
            filemode=
            'w',  #if you set this to 'a' it will append instead of overwriting
            level=logging.EXP)
        #add trials to the experiment handler to store data
        thisExp = data.ExperimentHandler(
            name='Posner',
            version='1.0',  #not needed, just handy
            extraInfo=info,  #the info we created earlier
            dataFileName=filename,  # using our string with data/name_date
        )
        thisExp.addLoop(
            trials)  #there could be other loops (like practice loop)

    # Actually present stimuli: loop through trials
    for thisTrial in trials:

        # set up this trial
        resp = None
        rt = None
        probe.setPos([thisTrial['probeX'], 0])
        cue.setOri(thisTrial['cueOri'])

        #fixation period
        fixation.setAutoDraw(True)
        for frameN in range(info['fixFrames']):
            win.flip()

        #present cue
        cue.setAutoDraw(True)
        for frameN in range(info['cueFrames']):
            win.flip()
        cue.setAutoDraw(False)

        #present probe and collect responses during presentation
        probe.setAutoDraw(True)
        win.callOnFlip(respClock.reset)  #NB: reset not reset()
        event.clearEvents()
        for frameN in range(info['probeFrames']):
            keys = event.getKeys(keyList=['left', 'right', 'escape'])
            if len(keys) > 0:
                resp = keys[0]  #take the first keypress as the response
                rt = respClock.getTime()
                break  #out of the probe-drawing loop
            win.flip()
        probe.setAutoDraw(False)
        fixation.setAutoDraw(False)

        #clear screen
        win.flip()

        #wait for response if we didn't already have one
        if resp is None:
            keys = event.waitKeys(keyList=['left', 'right', 'escape'])
            resp = keys[0]  #take first response
            rt = respClock.getTime()

        #check if the response was correct
        if thisTrial['probeX'] > 0 and resp == 'right':
            corr = 1
        elif thisTrial['probeX'] < 0 and resp == 'left':
            corr = 1
        elif resp == 'escape':
            corr = None
            trials.finished = True
        else:
            corr = 0

        #store the response and RT
        trials.addData('resp', resp)
        trials.addData('rt', rt)
        trials.addData('corr', corr)

        # Register end of trial in the log file
        if saveTrials:
            thisExp.nextEntry()
    win.update()

    #get response
    thisResp = None
    while thisResp == None:
        allKeys = event.waitKeys()
        for thisKey in allKeys:
            if thisKey == 'left':
                if targetSide == -1: thisResp = 1  #correct
                else: thisResp = -1  #incorrect
            elif thisKey == 'right':
                if targetSide == 1: thisResp = 1  #correct
                else: thisResp = -1  #incorrect
            elif thisKey in ['q', 'escape']:
                core.quit()  #abort experiment
        event.clearEvents(
        )  #must clear other (eg mouse) events - they clog the buffer

    #add the data to the staircase so it can calculate the next level
    staircase.addData(thisResp)
    dataFile.write('%i,%.3f,%i\n' % (targetSide, thisIncrement, thisResp))

#staircase has ended
dataFile.close()
staircase.saveAsPickle(
    fileName)  #special python binary file to save all the info

#give some output to user
print 'reversals:'
print staircase.reversalIntensities
print 'mean of final 6 reversals = %.3f' % (numpy.average(
    staircase.reversalIntensities[-6:]))
Exemplo n.º 53
0
def interbreak (thewait):
	event.clearEvents()
	win.flip()
	core.wait(thewait)
	if event.getKeys(['escape']):
		savequit()
Exemplo n.º 54
0
def present(duration=120, stim_types=None, itis=None, secs=0.07, volume=0.8):

    #def present(duration=120, n_trials=10, iti=0.3, soa=0.2, jitter=0.2,
    #            secs=0.2, volume=0.8, random_state=None):

    # Create markers stream outlet
    info = StreamInfo('Markers', 'Markers', 1, 0, 'int32', 'myuidw43536')
    outlet = StreamOutlet(info)

    #np.random.seed(random_state)
    markernames = [1, 2]
    start = time.time()

    # Set up trial parameters
    record_duration = np.float32(duration)

    # Initialize stimuli
    #aud1 = sound.Sound('C', octave=5, sampleRate=44100, secs=secs)
    aud1 = sound.Sound(440,
                       secs=secs)  #, octave=5, sampleRate=44100, secs=secs)
    aud1.setVolume(volume)

    aud1.setVolume(volume)
    #aud2 = sound.Sound('D', octave=6, sampleRate=44100, secs=secs)
    aud2 = sound.Sound(528, secs=secs)
    aud2.setVolume(volume)
    auds = [aud1, aud2]

    # Setup trial list
    #sound_ind = np.random.binomial(1, 0.25, n_trials)
    #itis = iti + np.random.rand(n_trials) * jitter
    #trials = DataFrame(dict(sound_ind=sound_ind, iti=itis))
    #trials['soa'] = soa
    #trials['secs'] = secs
    trials = DataFrame(dict(sound_ind=stim_types, iti=itis))

    # Setup graphics
    mywin = visual.Window([1920, 1080],
                          monitor='testMonitor',
                          units='deg',
                          fullscr=True)
    fixation = visual.GratingStim(win=mywin,
                                  size=0.2,
                                  pos=[0, 0],
                                  sf=0,
                                  rgb=[1, 0, 0])
    fixation.setAutoDraw(True)
    mywin.flip()

    for ii, trial in trials.iterrows():

        # Intertrial interval
        time.sleep(trial['iti'])

        # Select and play sound
        ind = int(trial['sound_ind'])
        auds[ind].stop()
        auds[ind].play()

        # Send marker
        timestamp = time.time()
        outlet.push_sample([markernames[ind]], timestamp)

        # Offset
        #time.sleep(soa)
        #if (time.time() - start) > record_duration:
        #    break

        # offset
        #core.wait(soa)

        if len(event.getKeys()) > 0 or (time.time() - start) > record_duration:
            break
        event.clearEvents()

        #if len(event.getKeys()) > 0 or (time() - start) > record_duration:
        #    break
        #event.clearEvents()

    # Cleanup
    mywin.close()

    return trials
Exemplo n.º 55
0
def show(win, screen_res, experiment, config, part_id, port_eeg, trigger_no, triggers_list, frame_time=1 / 60.):
    beh = []
    rt_sum = 0
    rt_mean = 0
    fixation = visual.TextStim(win, color='black', text='+', height=2 * config['Fix_size'], pos=(0, 10))
    clock = core.Clock()

    for block in experiment:

        if block['type'] == 'break':
            show_info(win=win, file_name=block['file_name'], text_size=config['Text_size'],
                      screen_width=screen_res['width'], part_id=part_id, beh=beh, triggers_list=triggers_list)
            continue

        if block['type'] == 'calibration':
            rt_mean = 0
            rt_sum = 0

        for trial in block['trials']:
            trigger_name = prepare_trigger_name(trial=trial, block_type=block['type'])
            reaction_time = None
            response = None
            acc = 'negative'

            # draw fixation
            fixation_show_time = random.uniform(config['Fixation_show_time'][0], config['Fixation_show_time'][1])
            show_text(win, fixation, fixation_show_time, part_id, beh, triggers_list)

            # draw cue
            trigger_no, triggers_list = prepare_trigger(trigger_type=TriggerTypes.CUE, trigger_no=trigger_no,
                                                        triggers_list=triggers_list, trigger_name=trigger_name)
            cue_show_time = random.uniform(config['Cue_show_time'][0], config['Cue_show_time'][1])
            trial['cue']['stimulus'].setAutoDraw(True)
            win.callOnFlip(clock.reset)
            event.clearEvents()
            win.flip()

            send_trigger(port_eeg=port_eeg, trigger_no=trigger_no, send_eeg_triggers=config['Send_EEG_trigg'])

            while clock.getTime() < cue_show_time:
                check_exit(part_id=part_id, beh=beh, triggers_list=triggers_list)
                win.flip()
            # print (cue_show_time - clock.getTime())*1000
            trial['cue']['stimulus'].setAutoDraw(False)
            win.flip()

            # draw target
            trigger_no, triggers_list = prepare_trigger(trigger_type=TriggerTypes.TARGET, trigger_no=trigger_no,
                                                        triggers_list=triggers_list, trigger_name=trigger_name)
            target_show_time = random.uniform(config['Target_show_time'][0], config['Target_show_time'][1])
            trial['target']['stimulus'].setAutoDraw(True)
            win.callOnFlip(clock.reset)
            event.clearEvents()
            win.flip()

            send_trigger(port_eeg=port_eeg, trigger_no=trigger_no, send_eeg_triggers=config['Send_EEG_trigg'])

            while clock.getTime() < target_show_time:
                key = event.getKeys(keyList=config['Keys'])
                if key:
                    reaction_time = clock.getTime()
                    trigger_no, triggers_list = prepare_trigger(trigger_type=TriggerTypes.RE, trigger_no=trigger_no,
                                                                triggers_list=triggers_list, trigger_name=trigger_name[:-1]+key[0])
                    send_trigger(port_eeg=port_eeg, trigger_no=trigger_no, send_eeg_triggers=config['Send_EEG_trigg'])
                    response = key[0]
                    break

                check_exit(part_id=part_id, beh=beh, triggers_list=triggers_list)
                win.flip()
            # print (target_show_time-clock.getTime())*1000
            trial['target']['stimulus'].setAutoDraw(False)
            win.flip()

            # empty screen
            empty_screen_show_time = random.uniform(config['Empty_screen_show_time'][0],
                                                    config['Empty_screen_show_time'][1])
            while clock.getTime() < empty_screen_show_time:
                check_exit(part_id=part_id, beh=beh, triggers_list=triggers_list)
                win.flip()
            # print (empty_screen_show_time-clock.getTime())*1000

            # verify reaction
            if response and trial['type'] == 'go':
                if not (block['type'] == 'experiment' and reaction_time > rt_mean - rt_mean * block['cutoff']):
                    acc = 'positive'
            elif not response and trial['type'] != 'go':
                acc = 'positive'

            # calibration
            if block['type'] == 'calibration' and trial['type'] == 'go' and reaction_time is not None:
                rt_sum += reaction_time

            # feedback
            if block['type'] == 'experiment':
                # choose feedback type
                feedback_type = 'Feedback_{}_{}_'.format(trial['type'], acc)

                # draw feedback
                if config[feedback_type + 'show']:
                    feedback_text = config[feedback_type + 'text']
                    feedback_text = visual.TextStim(win, color='black', text=feedback_text,
                                                    height=config['Feedback_size'])
                    feedback_show_time = random.uniform(config['Feedback_show_time'][0],
                                                        config['Feedback_show_time'][1])
                    if acc == 'positive':
                        trigger_type = TriggerTypes.FEEDB_GOOD
                    else:
                        trigger_type = TriggerTypes.FEEDB_BAD

                    trigger_no, triggers_list = prepare_trigger(trigger_type=trigger_type, trigger_no=trigger_no,
                                                                triggers_list=triggers_list, trigger_name=trigger_name)
                    feedback_text.setAutoDraw(True)
                    win.flip()
                    send_trigger(port_eeg=port_eeg, trigger_no=trigger_no, send_eeg_triggers=config['Send_EEG_trigg'])
                    time.sleep(feedback_show_time - frame_time)
                    feedback_text.setAutoDraw(False)
                    check_exit(part_id=part_id, beh=beh, triggers_list=triggers_list)
                    win.flip()

            # save beh
            beh.append({'block type': block['type'],
                        'trial type': trial['type'],
                        'cue name': trial['cue']['name'],
                        'target name': trial['target']['name'],
                        'response': response,
                        'rt': reaction_time,
                        'reaction': True if acc == 'positive' else False,
                        'cal mean rt': rt_mean,
                        'cutoff': block['cutoff'] if block['type'] == 'experiment' else None})

        if block['type'] == 'calibration':
            rt_mean = rt_sum / len([trial for trial in block['trials'] if trial['type'] == 'go'])

    return beh, triggers_list