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)
 def __set__(self, obj, value):
     newValue = self.func(obj, value)
     if (obj.autoLog is True) and (self.func.__name__ is not 'autoLog'):
         message = "%s: %s = %s" % (obj.__class__.__name__, self.func.__name__, value)
         try:
             obj.win.logOnFlip(message, level=logging.EXP, obj=obj)
         except AttributeError:  # this is probably a Window, having no "win" attribute
             logging.log(message, level=logging.EXP, obj=obj)
     return newValue
def logThis( msg ):
    ''' Write to log file and to LSL outlet. '''
    global lsl_outlet_log
    global USE_LSL

    logging.log(msg, level = myLogLevel)

    if USE_LSL:
        lsl_outlet_log.push_sample([msg])
def logAttrib(obj, log, attrib, value=None):
    """Logs a change of a visual attribute on the next window.flip.
    If value=None, it will take the value of self.attrib.
    """
    # Default to autoLog if log isn't set explicitly
    if log or log is None and obj.autoLog:
        if value is None:
            value = getattr(obj, attrib)

        # Log on next flip
        message = "%s: %s = %s" % (obj.name, attrib, value.__repr__())
        try:
            obj.win.logOnFlip(message, level=logging.EXP, obj=obj)
        except AttributeError:
            # this is probably a Window, having no "win" attribute
            logging.log(message, level=logging.EXP, obj=obj)
Exemple #5
0
def throw_ball(fromP, toP):
    global trialCnt, holder, rndCnt
    key = "%ito%i" % (fromP,toP)
    
    logging.log(level=logging.DATA, msg="round %i - trial %i - throw: %s - %s" % (round, trialCnt, key, condition))
    
    for s in throw[key]:
        players.setImage('images/%s/%s' % (key,s))
        players.draw()
        win.flip()
        core.wait(0.15)
    
    trialCnt+=1
    rndCnt+=1
    holder=toP
    logging.flush()
    select_throw()
Exemple #6
0
def play_round():
    global rndCnt
    rndCnt=0
    logging.log(level=logging.DATA, msg="Displaying Round %i label" % round)
    round_fix.setText("Round %i" % round)
    round_fix.draw()
    win.flip()
    core.wait(2)
    logging.log(level=logging.DATA, msg="Starting Round %i" % round)
    trialClock.reset()
    players.draw()
    player_names(True)
    win.flip()
    core.wait(0.2)
    select_throw()
    player_names(False)
    fixation.draw()
    win.flip()
    core.wait(5)
Exemple #7
0
def select_throw():
    global condition
    if holder==2:
        logging.log(level=logging.DATA,msg="PLAYER HAS BALL")
        got_ball_time = trialClock.getTime()
        
        choice=[]
        while len(choice)==0 or choice [0] not in ('2','3'):
            core.wait(0.01)
            if trialCnt > maxTrials or trialClock.getTime() > maxTime:
                return
            choice = event.getKeys(keyList=['2','3'])
        if choice[0]=='2':
            throwTo=1
        elif choice[0]=='3':
            throwTo=3
            
        logging.log(level=logging.DATA,msg="PLAYER THROWS TO %i - RT %0.4f" % (throwTo, trialClock.getTime()-got_ball_time))
    else:
        core.wait(random.randint(500,3500)/1000)
    
        if round==2 and rndCnt>8:
            condition="UBALL"
            ft=0.5
        else:
            ft=0.0
        
        throwChoice = random.random() - ft
        if throwChoice < 0.5:
            if holder==1:
                throwTo=3
            else:
                throwTo=1
        else:
            throwTo=2
    
    if trialCnt > maxTrials or trialClock.getTime() > maxTime:
        return
    else:
        throw_ball(holder,throwTo)
def RunQuestions_Move(question_list,options_list, win, name='Question', questionDur=float('inf'), isEndedByKeypress=True, upKey='up', downKey='down', selectKey='enter'):
    # import visual package
    from psychopy import visual
    # set up
    nQuestions = len(question_list)
    allKeys = ['']*nQuestions
    trialClock = core.Clock()
    iQ = 0
    iA = 0
    respKeys=[upKey,downKey,selectKey]
    # make visuals
    questionText = visual.TextStim(win, pos=[0,+.5], wrapWidth=1.5, color='#000000', alignHoriz='center', name='questionText', text="aaa",units='norm')
    optionsText = []
    for iResp in range(0,len(options_list[0])):
        optionsText.append(visual.TextStim(win, pos=[0,-.1*iResp], wrapWidth=1.5, color='#000000', alignHoriz='center', name='option%d'%(iResp+1), text="aaa",units='norm',autoLog=False))
    
    while iQ < nQuestions:
        print('iQ = %d/%d'%(iQ+1,nQuestions))
        # default response is middle response (and round down)
        iA = int((len(options_list[iQ])-1)*0.5)
        # set and draw text
        questionText.setText(question_list[iQ])
        questionText.draw()
        optionsText[iA].bold = True # make currently selected answer bold
        for iResp in range(0,len(options_list[iQ])):
            optionsText[iResp].setText('%d) %s'%((iResp+1),options_list[iQ][iResp]))
            optionsText[iResp].draw()
                
        # Flush the key buffer and mouse movements
        event.clearEvents()
        # Put the image on the screen
        win.logOnFlip(level=logging.EXP, msg='Display %s%d'%(name,iQ));
        win.flip()
        # 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.
        trialClock.reset()
        # Wait for keypress
        endQuestion = False;
        while (trialClock.getTime()<questionDur and not endQuestion):
            newKeys = event.getKeys(keyList=(respKeys + ['q','escape','backspace','period']),timeStamped=trialClock)
            for newKey in newKeys:
                # check for quit keys
                if newKey[0] in ['q', 'escape']:
                    endQuestion = True; # end the loop
                elif newKey[0] == 'backspace':
                    print('backspace')
                    iQ = max(0,iQ-1) # go back one
                    endQuestion = True;
                elif newKey[0] == 'period': 
                    iQ +=1 # skip fwd without recording response
                    endQuestion = True;
                elif newKey[0] == upKey: # move response up
                    # remove old bold
                    optionsText[iA].bold = False
                    # update answer
                    iA -= 1
                    if iA<0:
                        iA=0
                    # make newly selected answer bold
                    optionsText[iA].bold = True
                    # redraw everything
                    questionText.draw()
                    for iResp in range(0,len(options_list[iQ])):
                        optionsText[iResp].draw()
                    win.flip()
                elif newKey[0] == downKey: # move response down
                    # remove old bold
                    optionsText[iA].bold = False
                    # update answer
                    iA += 1
                    if iA>=len(options_list[iQ]):
                        iA = len(options_list[iQ])-1
                    # make newly selected answer bold
                    optionsText[iA].bold = True
                    # redraw everything
                    questionText.draw()
                    for iResp in range(0,len(options_list[iQ])):
                        optionsText[iResp].draw()
                    win.flip()
                elif newKey[0] == selectKey:
                    # log response
                    allKeys[iQ] = (iA+1, newKey[1]) # make new tuple with answer index and response time
                    logging.log(level=logging.EXP, msg= 'Responded %d'%(iA+1))
                    # remove old bold
                    optionsText[iA].bold = False
                    # advance question index
                    iQ +=1
                    if isEndedByKeypress:
                        endQuestion = True;
                else:
                    print('pressed %s'%newKey[0])
        
        if len(newKeys)>0 and newKey[0] in ['q', 'escape']: 
            break # end the loop
    # return result
    return allKeys
# make squares
squares = []
for i in range(0, 4):
    xpos = i * 2 - 3
    squares.append(visual.Rect(win, pos=[xpos, 0], width=1, height=1, lineColor="black", fillColor="gray"))
# make arrows
line = visual.Line(win, start=(-2, 0), end=(2, 0), lineColor="black")
leftArrow = visual.Polygon(win, edges=3, radius=0.5, pos=(-2, 0), ori=30, lineColor="black", fillColor="black")
rightArrow = visual.Polygon(win, edges=3, radius=0.5, pos=(2, 0), ori=-30, lineColor="black", fillColor="black")

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
logging.LogFile((fileName + ".log"), level=logging.INFO)  # , mode='w') # w=overwrite
logging.log(level=logging.INFO, msg="Subject %s, Session %s" % (expInfo["subject"], expInfo["session"]))
for i in range(0, len(sequences)):
    logging.log(level=logging.INFO, msg="sequence %d: %s" % (i, sequences[i]))

# ============================ #
# ======= SUBFUNCTIONS ======= #
# ============================ #


def PlaySequence(sequence):
    # get block start time
    tBlock = globalClock.getTime() * 1000

    # draw fixation dot
    fixation.draw()
    win.logOnFlip(level=logging.EXP, msg="Fixation")
if dlg.OK:
    toFile("lastSartParams.pickle", expInfo)  # save params to file for next time
else:
    core.quit()  # the user hit cancel so exit

# get volume from dialogue
targetDigit = expInfo["target digit"]

# make a log file to save parameter/event  data
fileName = "Sart-%s-%d-%s" % (
    expInfo["subject"],
    expInfo["session"],
    dateStr,
)  #'Sart-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName + ".log"), level=logging.INFO)  # , mode='w') # w=overwrite
logging.log(level=logging.INFO, msg="---START PARAMETERS---")
logging.log(level=logging.INFO, msg="subject: %s" % expInfo["subject"])
logging.log(level=logging.INFO, msg="session: %s" % expInfo["session"])
logging.log(level=logging.INFO, msg="date: %s" % dateStr)
logging.log(level=logging.INFO, msg="isPractice: %i" % isPractice)
logging.log(level=logging.INFO, msg="nBlocks: %d" % nBlocks)
logging.log(level=logging.INFO, msg="nTrialsPerBlock: %d" % nTrialsPerBlock)
logging.log(level=logging.INFO, msg="fixDur_min: %f" % fixDur_min)
logging.log(level=logging.INFO, msg="fixDur_range: %f" % fixDur_range)
logging.log(level=logging.INFO, msg="digitDur: %f" % digitDur)
logging.log(level=logging.INFO, msg="respDur: %d" % respDur)
logging.log(level=logging.INFO, msg="ITI: %f" % ITI)
logging.log(level=logging.INFO, msg="IBI: %f" % IBI)
logging.log(level=logging.INFO, msg="targetDigit: %s" % targetDigit)
logging.log(level=logging.INFO, msg="targetFrac: %f" % targetFrac)
logging.log(level=logging.INFO, msg="targetProb: %f" % targetProb)
Exemple #11
0
message=visual.TextStim(win, text='')

subdata['trialdata']={}
clock.reset()
event.clearEvents()

for trial in range(ntrials):
    if check_for_quit(subdata,win):
        exptutils.shut_down_cleanly(subdata,win)
        sys.exit()

    trialdata={}
    print 'trial %d'%trial
    trialdata['onset']=onsets[trial]
    print 'condition %d'%trialcond[trial]
    logging.log(logging.DATA,"Condition: %d"%trialcond[trial])
    print 'showing image: %s'%stim_images[trialcond[trial]]
    visual_stim.setImage(stim_images[trialcond[trial]])
    visual_stim.draw()
    logging.log(logging.DATA, "image=%s"%stim_images[trialcond[trial]])
    while clock.getTime()<trialdata['onset']:#wait until the specified onset time to display image_file
        if check_for_quit(subdata,win):
            exptutils.shut_down_cleanly(subdata,win)
            sys.exit()
    win.flip()

    while clock.getTime()<(trialdata['onset']+cue_time):#show the image
        pass

    if hasPump:
        print 'injecting via pump at address %d'%pump[trial]
     continueRoutine = False  # will revert to True if at least one component still running
     for thisComponent in trialComponents:
         if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
             continueRoutine = True
             break  # at least one component has not yet finished
     
     # check for quit (the [Esc] key)
     if event.getKeys(["escape"]):
         core.quit()
     
     # refresh the screen
     if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
         win.flip()
         if fixCrossTrial.status == STARTED and fixCrossTrial.frameNStart == frameN:
             writeTrigger(8)
             logging.log(level=logging.DEBUG, msg='showFixCrossTrial')
         if grating1.status == STARTED and grating1.frameNStart == frameN:
             writeTrigger(gratingTriggers[str(thisMainTrial.contrast)])
             logging.log(level=logging.DEBUG, msg='showGrating1')
         core.wait(0.05)
         writeTrigger(0)
 
 #-------Ending Routine "trial"-------
 for thisComponent in trialComponents:
     if hasattr(thisComponent, "setAutoDraw"):
         thisComponent.setAutoDraw(False)
 
 
 #------Prepare to start Routine"interTrialInterval"-------
 t = 0
 interTrialIntervalClock.reset()  # clock 
Exemple #13
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
#answers_all = [answers_all[i] for i in newOrder]
params['questionOrder'] = newOrder

# print params to Output
print 'params = {'
for key in sorted(params.keys()):
    print "   '%s': %s"%(key,params[key]) # print each value as-is (no quotes)
print '}'
    
# save experimental info
toFile('lastDistractionPracticeInfo_behavior.pickle', expInfo)#save params to file for next time

#make a log file to save parameter/event  data
filename = 'DistractionPractice-%s-%d-%s'%(expInfo['subject'], expInfo['session'], dateStr) #'Sart-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((filename+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='filename: %s'%filename)
logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s'%dateStr)
for key in sorted(params.keys()): # in alphabetical order
    logging.log(level=logging.INFO, msg='%s: %s'%(key,params[key]))

logging.log(level=logging.INFO, msg='---END PARAMETERS---')


# ========================== #
# ===== GET SCREEN RES ===== #
# ========================== #

# kluge for secondary monitor
def do_run(run_number, trials):


    # 1. add ready screen and wait for trigger
    ready_screen.draw()
    win.flip()
    event.waitKeys(keyList='space')

    # reset globalClock
    globalClock.reset()

    # send START log event
    logging.log(level=logging.DATA, msg='******* START (trigger from scanner) *******')


    ################ 
    # SHOW INSTRUCTIONS
    ################ 
    #for frame in range(instruct_dur):
    instruction_image.draw()
    instruction_text.draw()
    win.flip()
    event.waitKeys(keyList='space')



    # 2. fixation disdaqs
    #for frame in range(disdaq_dur):
    #   fixation.draw()
    #   win.flip()

    #######################
    # MAIN LOOP for trials
    # loop over stimuli
    for tidx, trial in enumerate(trials):
        
        value = trial['value']
        prime_label = trial['message']
        situation = trial['target']
        target = trial['target']

        valueStim.setText(prime_label)
        thinkStim.setText(prime_label)

        # 1. show prime
        primeStim.setText(prime_label)
        if tidx%2==0:
            primeStim.draw()
            win.flip()
            event.waitKeys(keyList=('space'))
        else:
            for frame in range(prime_dur):
                primeStim.draw()
                win.flip()

        # 2. show situation
        situationStim.setText(situation)
        if tidx%2==0:
            situationStim.draw()
            thinkStim.draw()
            win.flip()
            event.waitKeys(keyList=('space'))
        else:
            for frame in range(situation_dur):
                situationStim.draw()
                thinkStim.draw()
                win.flip()            
            
        event.clearEvents()

        # 3. show rating and get response
        timer = core.Clock()
        timer.reset()
        space_pressed = False
        while (tidx % 2 != 0 and timer.getTime()<rating_dur/frame_rate) or (tidx % 2 == 0 and space_pressed==False):        
        #for frame in range(rating_dur):
            situationStim.draw()
            valueStim.draw()
            anchor1.draw()
            anchor4.draw()
            
            for resp in ratingStim:
                resp.draw()
            win.flip()

            # get key response
            resp = event.getKeys(keyList = buttons)
        
            if len(resp) > 0 :
                if resp[0]=='space':
                    space_pressed=True
                    continue
                resp_value = button_labels[resp[0]]
                ratingStim[resp_value].setColor('red')
        
        # reset rating number color
        for rate in ratingStim:
            rate.setColor('white')
        
       
        # 4. fixation
        for frame in range(fixation_dur):
            fixation.draw()
            win.flip()
            
        ready_screen.draw()
        win.flip()
        event.waitKeys(keyList=['space'])
            
            
    # write logs

    # send END log event
    logging.log(level=logging.DATA, msg='******* END Run %i *******' % run_number)

    # save the trial infomation from trial handler
    log_filename2 = "%s_%i.csv" % (log_filename[:-4], run_number )
    trials.saveAsText(log_filename2, delim=',', dataOut=('n', 'all_raw'))
        core.wait(1.0 / 60.0)
    #init stim
    stim = visual.TextStim(win,
                           text=TRIAL_LIST[index]['Stim'],
                           pos=[0.0, 0.0],
                           color="black",
                           height=50,
                           alignHoriz='center',
                           alignVert='center',
                           font="Arial",
                           wrapWidth=1000,
                           autoLog=True)
    stim.draw()
    win.flip()
    onset = globalClock.getTime()
    logging.log("Datalog.log", level=logging.EXP)
    win.logOnFlip("Datalog.log", level=logging.EXP)
    onset_tr = onset - t0
    core.wait(1.0 - (globalClock.getTime() - onset))
    null_txt.draw()
    win.flip()
    onset = globalClock.getTime()
    core.wait(1.5 - (globalClock.getTime() - onset))
    # store data into the numpy array
    data = np.vstack(
        (data, np.hstack((
            TRIAL_LIST[index]['StimType'],
            onset_tr,
        ))))
#clear screen
null_txt.draw()
Exemple #17
0
def do_run(run_number, trials):

    # 1. add ready screen and wait for trigger
    ready_screen.draw()
    win.flip()
    event.waitKeys(keyList='space')

    # reset globalClock
    globalClock.reset()

    # send START log event
    logging.log(level=logging.DATA,
                msg='******* START (trigger from scanner) - Run %i *******' %
                run_number)

    ################
    # SHOW INSTRUCTIONS
    ################
    #for frame in range(instruct_dur):
    instruction_image.draw()
    instruction_text.draw()
    win.flip()
    event.waitKeys(keyList=('space'))

    #######################
    # MAIN LOOP for trials
    # loop over stimuli
    for tidx, trial in enumerate(trials):
        value = trial['value']
        prime_label = 'Daily Activity' if value == 'control' else value.title()
        situation = trial['message']
        valueStim.setText(prime_label)

        # test for REST trial
        if trial['value'] == 'REST':

            for frame in range(rest_dur):
                fixation.draw()
                win.flip()

            # fixation
            for frame in range(fixation_dur):
                fixation.draw()
                win.flip()
            continue

        # 1. show prime
        primeStim.setText(prime_label)

        if tidx % 2 == 0:
            primeStim.draw()
            win.flip()
            event.waitKeys(keyList=('space'))
        else:
            for frame in range(prime_dur):
                primeStim.draw()
                win.flip()

        # 2. show situation
        situationStim.setText(situation)
        if tidx % 2 == 0:
            situationStim.draw()
            thinkStim.draw()
            win.flip()
            event.waitKeys(keyList=('space'))
        else:
            for frame in range(situation_dur):
                situationStim.draw()
                thinkStim.draw()
                win.flip()

        event.clearEvents()

        # 3. show rating and get response
        timer = core.Clock()
        timer.reset()
        space_pressed = False
        while (tidx % 2 != 0 and timer.getTime() < rating_dur / frame_rate
               ) or (tidx % 2 == 0 and space_pressed == False):
            #for frame in range(rating_dur):
            situationStim.draw()
            valueStim.draw()
            anchor1.draw()
            anchor4.draw()

            # draw rating
            for resp in ratingStim:
                resp.draw()
            win.flip()

            # get key response
            resp = event.getKeys(keyList=buttons)

            if len(resp) > 0:
                if resp[0] == 'space':
                    space_pressed = True
                    continue
                resp_value = button_labels[resp[0]]
                ratingStim[resp_value].setColor('red')
                trials.addData('resp', resp_value + 1)

        # reset rating number color
        for rate in ratingStim:
            rate.setColor('white')

        # 4. fixation
        for frame in range(fixation_dur):
            fixation.draw()
            win.flip()

        ready_screen.draw()
        win.flip()
        event.waitKeys(keyList=['space'])

    # write logs

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

    # save the trial infomation from trial handler
    log_filename2 = "%s_%i.csv" % (log_filename[:-4], run_number)
    trials.saveAsText(log_filename2, delim=',', dataOut=('n', 'all_raw'))
def run_block(fix):

    # Await scan trigger
    while True:
        scan_trigger_text.draw()
        win.flip()
        if 'o' in event.waitKeys():
            logging.log(logging.DATA, "start key press")
            break
        event.clearEvents()
        
    clock=core.Clock()
    t = clock.getTime()
    
    
    #start the loop
    for trial in range(ntrials):
        #check for quit
        if check_for_quit(subdata,win):
            exptutils.shut_down_cleanly(subdata,win)
            sys.exit()
        #empty trial data 
        trialdata={}
        trialdata['onset']=onsets[trial]
        
        #shuffle the positions
        shuffle(pos_ind)
        visual_stim1=visual.ImageStim(win, image=N.zeros((300,300)),pos=positions[pos_ind[0]], size=(0.25,0.25),units='height')
        visual_stim2=visual.ImageStim(win, image=N.zeros((300,300)),pos=positions[pos_ind[1]], size=(0.25,0.25),units='height')
        
        #set which image is which
        x=int(N.random.choice(stim_index, 1, p=[0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125]))
        print("here is the list")
        print(stim_list)
        print(x)
        stim_img_trial=stim_list[x]
        print(stim_img_trial)
        
        #set which image appears on what side
        visual_stim1.setImage(stim_img_trial[img_index[0]])
        visual_stim2.setImage(stim_img_trial[img_index[1]])
        
        
        shuffle(img_index)
        #creating a dictory which will store the image set and which image is at what postion
        mydict={}
        mydict[positions_eng[pos_ind[1]]] = [stim_img_trial[img_index[1]]]
        mydict[positions_eng[pos_ind[0]]] = [stim_img_trial[img_index[0]]]
        print(mydict)
        
        #which is sweet?
        message=visual.TextStim(win, text='Which is Correct?',pos=(0,5))
        print trial
        t = clock.getTime()
        
        #get the time of the image and log, this log is appending it to the csv file 
        visual_stim1.draw()#making image of the logo appear
        visual_stim2.draw()
        message.draw()
        RT = core.Clock()
        
        logging.log(logging.DATA, "%s at position=%s and %s at position=%s"%(stim_img_trial[img_index[0]],positions_eng[pos_ind[0]],stim_img_trial[img_index[1]],positions_eng[pos_ind[1]]))
        
        while clock.getTime()<trialdata['onset']:
            pass
        win.flip()
        
        RT.reset() # reaction time starts immediately after flip 
        
        while clock.getTime()<(trialdata['onset']+cue_time):#show the image, while clock is less than onset and cue, show cue
            pass
        
        keys = event.getKeys(timeStamped=RT)
        message=visual.TextStim(win, text='')
        message.draw()
        win.flip()
        
        # get the key press logged, and time stamped 
        
        if len(keys)>0:
            logging.log(logging.DATA, "keypress=%s at time= %f"%(keys[0][0],keys[0][1]))
            print("here are the keys:")
            print(keys)
            t = clock.getTime()
            #back up of the key press
            tempArray = [t, keys[0]]
            key_responses.append(tempArray)
            ratings_and_onsets.append(["keypress=%s"%keys[0][0],t])
        else:
            taste=0
            t = clock.getTime()
            logging.log(logging.DATA,"Key Press Missed!")
            keys=keys.append(['MISS',t])
            message=visual.TextStim(win, text='Please answer quicker', pos=(0, 0), height=2)#this lasts throught the taste
            message.draw()
            win.flip()

        while clock.getTime()<(trialdata['onset']+cue_time+delivery_time):
            pass
        
        message=visual.TextStim(win, text='+', pos=(0, 0), height=2)#this lasts throught the wait
        message.draw()
        win.flip()
        t = clock.getTime()
        ratings_and_onsets.append(["wait", t])

        #trialdata['dis']=[ser.write('0DIS\r'),ser.write('1DIS\r')]
        #print(trialdata['dis'])
        
        while clock.getTime()<(trialdata['onset']+cue_time+delivery_time+wait_time):
            pass

      
        
        while clock.getTime()<(trialdata['onset']+cue_time+delivery_time+wait_time):
            pass

        message=visual.TextStim(win, text='+', pos=(0, 0), height=2)#lasts through the jitter 
        message.draw()
        win.flip()
        t = clock.getTime()
        ratings_and_onsets.append(["jitter", t])

        while clock.getTime()<(trialdata['onset']+cue_time+delivery_time+wait_time):
            pass
        
        t = clock.getTime()
        ratings_and_onsets.append(['end time', t])
        logging.log(logging.DATA,"finished")
        subdata['trialdata'][trial]=trialdata
        
      
        
        print(key_responses)
        
    win.close()
Exemple #19
0
    # load params file
    params = fromFile(expInfo['paramsFile'])

# print params to Output
print 'params = {'
for key in sorted(params.keys()):
    print "   '%s': %s"%(key,params[key]) # print each value as-is (no quotes)
print '}'
    
# save experimental info
toFile('lastSingingInfo.pickle', expInfo)#save params to file for next time

#make a log file to save parameter/event  data
filename = 'Singing-%s-%d-%s'%(expInfo['subject'], expInfo['session'], dateStr) #'Sart-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((filename+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='filename: %s'%filename)
logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s'%dateStr)
for key in sorted(params.keys()): # in alphabetical order
    logging.log(level=logging.INFO, msg='%s: %s'%(key,params[key]))

logging.log(level=logging.INFO, msg='---END PARAMETERS---')

# ========================== #
# ===== SET UP STIMULI ===== #
# ========================== #
from psychopy import visual

# kluge for secondary monitor
Exemple #20
0
def RunQuestions_Move(question_list,
                      options_list,
                      win,
                      name='Question',
                      questionDur=float('inf'),
                      isEndedByKeypress=True,
                      upKey='up',
                      downKey='down',
                      selectKey='enter'):
    # set up
    nQuestions = len(question_list)
    allKeys = [''] * nQuestions
    trialClock = core.Clock()
    iQ = 0
    iA = 0
    respKeys = [upKey, downKey, selectKey]
    # make visuals
    from psychopy import visual
    questionText = visual.TextStim(win,
                                   pos=[0, +.5],
                                   wrapWidth=1.5,
                                   color='#000000',
                                   alignHoriz='center',
                                   name='questionText',
                                   text="aaa",
                                   units='norm')
    optionsText = []
    for iResp in range(0, len(options_list[0])):
        optionsText.append(
            visual.TextStim(win,
                            pos=[0, -.1 * iResp],
                            wrapWidth=1.5,
                            color='#000000',
                            alignHoriz='center',
                            name='option%d' % (iResp + 1),
                            text="aaa",
                            units='norm',
                            autoLog=False))

    while iQ < nQuestions:
        print('iQ = %d/%d' % (iQ + 1, nQuestions))
        # default response is middle response (and round down)
        iA = int((len(options_list[iQ]) - 1) * 0.5)
        # set and draw text
        questionText.setText(question_list[iQ])
        questionText.draw()
        optionsText[iA].bold = True  # make currently selected answer bold
        for iResp in range(0, len(options_list[iQ])):
            optionsText[iResp].setText('%d) %s' %
                                       ((iResp + 1), options_list[iQ][iResp]))
            optionsText[iResp].draw()

        # Flush the key buffer and mouse movements
        event.clearEvents()
        # Put the image on the screen
        win.logOnFlip(level=logging.EXP, msg='Display %s%d' % (name, iQ))
        win.flip()
        # 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.
        trialClock.reset()
        # Wait for keypress
        endQuestion = False
        while (trialClock.getTime() < questionDur and not endQuestion):
            newKeys = event.getKeys(
                keyList=(respKeys + ['q', 'escape', 'backspace', 'period']),
                timeStamped=trialClock)
            for newKey in newKeys:
                # check for quit keys
                if newKey[0] in ['q', 'escape']:
                    endQuestion = True
                    # end the loop
                elif newKey[0] == 'backspace':
                    print('backspace')
                    iQ = max(0, iQ - 1)  # go back one
                    endQuestion = True
                elif newKey[0] == 'period':
                    iQ += 1  # skip fwd without recording response
                    endQuestion = True
                elif newKey[0] == upKey:  # move response up
                    # remove old bold
                    optionsText[iA].bold = False
                    # update answer
                    iA -= 1
                    if iA < 0:
                        iA = 0
                    # make newly selected answer bold
                    optionsText[iA].bold = True
                    # redraw everything
                    questionText.draw()
                    for iResp in range(0, len(options_list[iQ])):
                        optionsText[iResp].draw()
                    win.flip()
                elif newKey[0] == downKey:  # move response down
                    # remove old bold
                    optionsText[iA].bold = False
                    # update answer
                    iA += 1
                    if iA >= len(options_list[iQ]):
                        iA = len(options_list[iQ]) - 1
                    # make newly selected answer bold
                    optionsText[iA].bold = True
                    # redraw everything
                    questionText.draw()
                    for iResp in range(0, len(options_list[iQ])):
                        optionsText[iResp].draw()
                    win.flip()
                elif newKey[0] == selectKey:
                    # log response
                    allKeys[iQ] = (
                        iA + 1, newKey[1]
                    )  # make new tuple with answer index and response time
                    logging.log(level=logging.EXP,
                                msg='Responded %d' % (iA + 1))
                    # remove old bold
                    optionsText[iA].bold = False
                    # advance question index
                    iQ += 1
                    if isEndedByKeypress:
                        endQuestion = True
                else:
                    print('pressed %s' % newKey[0])

        if len(newKeys) > 0 and newKey[0] in ['q', 'escape']:
            break  # end the loop
    # return result
    return allKeys
Exemple #21
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=('2'))
    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']]
        imagepath = os.path.join(expdir, 'Images')
        #image = os.path.join(imagepath, "human.png") # % condition_label
        #pictureStim.setImage(image)

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

        # 1 = UG Proposer, 2 = DG Proposer, 3 = UG responder
        if trial['Block'] == '3':  #UG Responder
            while timer.getTime() < 1:
                cue = os.path.join(imagepath, "UGResponder_circle.png")
                cueStim.setImage(cue)
                cue_Onset = globalClock.getTime()
                trials.addData('cue_Onset', cue_Onset)
                cueStim.draw()
                cueStimCirText.draw()
                win.flip()
                core.wait(1)

            while timer.getTime() >= 1 and timer.getTime() <= 2:
                endowment_onset = globalClock.getTime()
                trials.addData('endowment_onset', endowment_onset)
                endowment = trial['Endowment']
                endowmentText = 'Partner was given $%s' % (endowment)
                endowment_text.setText(endowmentText)
                cueStim.draw()
                cueStimCirText.draw()
                endowment_text.draw()
                #pictureStim.draw()
                win.flip()
                core.wait(1)
                endowment_offset = globalClock.getTime()
                trials.addData('endowment_offset', endowment_offset)

            endowment_offset = globalClock.getTime()
            trials.addData('endowment_offset', endowment_offset)
            timer.reset()

            #ISI
            ISI_onset = globalClock.getTime()
            trials.addData('ISI_onset', ISI_onset)
            isi_for_trial = float(trial['ISI'])
            fixation.draw()
            win.flip()
            core.wait((isi_for_trial))
            ISI_offset = globalClock.getTime()
            trials.addData('ISI_offset', ISI_offset)

            timer.reset()

            event.clearEvents()

            resp_val = None
            resp_onset = None

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

            while timer.getTime() < decision_dur:
                cueStim.draw()
                cueStimCirText.draw()
                if trial['L_Option'] == '0':
                    partner_offer = trial['R_Option']
                else:
                    partner_offer = trial['L_Option']
                partnerOffer = 'Partner offers you: $%s' % (partner_offer)
                resp_left = trial['L_Option']
                resp_right = trial['R_Option']

                if resp_left == '0':
                    resp_text_left.setText('Reject offer')
                    resp_text_right.setText('Accept offer')
                else:
                    resp_text_left.setText('Accept offer')
                    resp_text_right.setText('Reject offer')
                resp_text_left.draw()
                resp_text_right.draw()
                #resp_text_accept.draw()
                #resp_text_reject.draw()
                #pictureStim.draw()
                endowment_text.draw()
                offer_text.setText(partnerOffer)
                offer_text.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])
                    resp_onset = globalClock.getTime()
                    rt = resp_onset - decision_onset
                    if resp_val == 2:
                        resp_text_left.setColor('darkorange')
                    if resp_val == 3:
                        resp_text_right.setColor('darkorange')
                    cueStim.draw()
                    cueStimCirText.draw()
                    resp_text_left.draw()
                    resp_text_right.draw()
                    endowment_text.draw()
                    #pictureStim.draw()
                    offer_text.setText(partnerOffer)
                    offer_text.draw()
                    win.flip()
                    core.wait((decision_dur - rt + .5))
                    decision_offset = globalClock.getTime()
                    break
                else:
                    resp_val = 999
                    rt = 999
                    resp_onset = 999
                    outcome_txt = outcome_map[resp_val]
                    decision_offset = globalClock.getTime()

        elif trial['Block'] == '1':  #UGProposer
            while timer.getTime() < 1:
                cue = os.path.join(imagepath, "UGProposer_sq.png")
                cueStim.setImage(cue)
                cue_Onset = globalClock.getTime()
                trials.addData('cue_Onset', cue_Onset)
                cueStim.draw()
                cueStimSqText.draw()
                win.flip()
                core.wait(1)

            while timer.getTime() >= 1 and timer.getTime() <= 2:
                endowment_onset = globalClock.getTime()
                trials.addData('endowment_onset', endowment_onset)
                endowment = trial['Endowment']
                endowmentOffer = 'You are given $%s' % endowment
                endowment_text.setText(endowmentOffer)
                cueStim.draw()
                cueStimSqText.draw()
                endowment_text.draw()
                #pictureStim.draw()
                win.flip()
                core.wait(1)

            resp_val = None
            resp_onset = None

            timer.reset()

            event.clearEvents()

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

            #ISI
            ISI_onset = globalClock.getTime()
            trials.addData('ISI_onset', ISI_onset)
            isi_for_trial = float(trial['ISI'])
            fixation.draw()
            win.flip()
            core.wait((isi_for_trial))
            ISI_offset = globalClock.getTime()
            trials.addData('ISI_offset', ISI_offset)

            timer.reset()

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

            while timer.getTime() < decision_dur:
                resp_left = trial['L_Option']
                resp_right = trial['R_Option']
                respcLeft = 'Offer $%s' % resp_left
                resp_text_left.setText(respcLeft)
                respcRight = 'Offer $%s' % resp_right
                resp_text_right.setText(respcRight)
                cueStim.draw()
                cueStimSqText.draw()
                resp_text_left.draw()
                resp_text_right.draw()
                #pictureStim.draw()
                endowment_text.setText(endowmentOffer)
                endowment_text.draw()
                win.flip()

                resp = event.getKeys(keyList=responseKeys)

                if len(resp) > 0:
                    if resp[0] == 'z':
                        os.chdir(subjdir)
                        trials.saveAsWideText(fileName)
                        os.chdir(expdir)
                        win.close()
                        core.quit()
                    resp_val = int(resp[0])
                    resp_onset = globalClock.getTime()
                    rt = resp_onset - decision_onset
                    if resp_val == 2:
                        resp_text_left.setColor('darkorange')
                    if resp_val == 3:
                        resp_text_right.setColor('darkorange')
                    cueStim.draw()
                    cueStimSqText.draw()
                    resp_text_left.draw()
                    resp_text_right.draw()
                    #pictureStim.draw()
                    endowment_text.setText(endowmentOffer)
                    endowment_text.draw()
                    win.flip()
                    core.wait((decision_dur - rt + .5))
                    decision_offset = globalClock.getTime()
                    break
                else:
                    resp_val = 999
                    rt = 999
                    resp_onset = 999
                    outcome_txt = outcome_map[resp_val]
                    decision_offset = globalClock.getTime()

        else:
            trial['Block'] == '2'
            while timer.getTime() < 1:
                cue = os.path.join(imagepath, "DGProposer_triangle.png")
                cueStim.setImage(cue)
                cue_Onset = globalClock.getTime()
                trials.addData('cue_Onset', cue_Onset)
                cueStim.draw()
                cueStimTriText.draw()
                win.flip()
                core.wait(1)

            while timer.getTime() >= 1 and timer.getTime() <= 2:
                endowment_onset = globalClock.getTime()
                trials.addData('endowment_onset', endowment_onset)
                endowment = trial['Endowment']
                endowmentOffer = 'You are given $%s' % endowment
                endowment_text.setText(endowmentOffer)
                cueStim.draw()
                cueStimTriText.draw()
                endowment_text.draw()
                #pictureStim.draw()
                win.flip()
                core.wait(1)

            resp_val = None
            resp_onset = None

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

            timer.reset()

            event.clearEvents()

            #ISI
            ISI_onset = globalClock.getTime()
            trials.addData('ISI_onset', ISI_onset)
            isi_for_trial = float(trial['ISI'])
            fixation.draw()
            win.flip()
            core.wait((isi_for_trial))
            ISI_offset = globalClock.getTime()
            trials.addData('ISI_offset', ISI_offset)

            timer.reset()

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

            while timer.getTime() < decision_dur:
                resp_left = trial['L_Option']
                resp_right = trial['R_Option']
                respcLeft = 'Give $%s' % resp_left
                resp_text_left.setText(respcLeft)
                respcRight = 'Give $%s' % resp_right
                resp_text_right.setText(respcRight)
                resp_text_left.draw()
                resp_text_right.draw()
                cueStim.draw()
                cueStimTriText.draw()
                #pictureStim.draw()
                endowment_text.setText(endowmentOffer)
                endowment_text.draw()
                win.flip()

                resp = event.getKeys(keyList=responseKeys)

                if len(resp) > 0:
                    if resp[0] == 'z':
                        os.chdir(subjdir)
                        trials.saveAsWideText(fileName)
                        os.chdir(expdir)
                        win.close()
                        core.quit()
                    resp_val = int(resp[0])
                    resp_onset = globalClock.getTime()
                    rt = resp_onset - decision_onset
                    if resp_val == 2:
                        resp_text_left.setColor('darkorange')
                    if resp_val == 3:
                        resp_text_right.setColor('darkorange')
                    resp_text_left.draw()
                    resp_text_right.draw()
                    cueStim.draw()
                    cueStimTriText.draw()
                    #pictureStim.draw()
                    endowment_text.setText(endowmentOffer)
                    endowment_text.draw()
                    win.flip()
                    core.wait((decision_dur - rt + .5))
                    decision_offset = globalClock.getTime()
                    break
                else:
                    resp_val = 999
                    rt = 999
                    resp_onset = 999
                    outcome_txt = outcome_map[resp_val]
                    decision_offset = globalClock.getTime()

        trials.addData('resp', resp_val)
        trials.addData('rt', rt)
        trials.addData('resp_onset', resp_onset)
        trials.addData('decision_offset', decision_offset)
        #win.flip()

        timer.reset()
        if resp_val == 999:
            outcome_stim.setText(outcome_txt)
            outcome_stim.draw()
            win.flip()
            missFB_onset = globalClock.getTime()
            core.wait(.5)
            missFB_offset = globalClock.getTime()

        #reset rating number color
        resp_text_left.setColor('#FFFFFF')
        resp_text_right.setColor('#FFFFFF')

        #resp_text_accept.setColor('#FFFFFF')
        #resp_text_reject.setColor('#FFFFFF')

        trial_offset = globalClock.getTime()
        duration = trial_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'])
        fixation.draw()
        win.flip()
        core.wait(iti_for_trial)
        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
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='Numerical SART task', fixed=['date'], order=['subject','session','target letter'])
if dlg.OK:
    toFile('lastAudSartParams.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

# get volume from dialogue
targetLetter = expInfo['target letter']

#make a log file to save parameter/event  data
fileName = 'AudSart-%s-%d-%s'%(expInfo['subject'], expInfo['session'], dateStr) #'Sart-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s'%dateStr)
logging.log(level=logging.INFO, msg='isPractice: %i'%isPractice)
logging.log(level=logging.INFO, msg='blockLengths: %s'%blockLengths)
logging.log(level=logging.INFO, msg='randomizeBlocks: %d'%randomizeBlocks)
logging.log(level=logging.INFO, msg='ITI_min: %f'%ITI_min)
logging.log(level=logging.INFO, msg='ITI_range: %f'%ITI_range)
logging.log(level=logging.INFO, msg='respDur: %d'%respDur)
logging.log(level=logging.INFO, msg='blankDur: %f'%blankDur)
logging.log(level=logging.INFO, msg='IBI: %f'%IBI)
logging.log(level=logging.INFO, msg='targetLetter: %s'%targetLetter)
logging.log(level=logging.INFO, msg='nontargets: %s'%nontargets)
logging.log(level=logging.INFO, msg='targetFrac: %f'%targetFrac)
logging.log(level=logging.INFO, msg='targetProb: %f'%targetProb)
Exemple #23
0
def msTime():
    deltadt = datetime.datetime.utcnow() - gStartDt
    deltatt = time.time() - gStartTt
    deltatc = time.clock()
    return deltadt.total_seconds(), deltatt, deltatc 
    #delta#int(delta.total_seconds() * 1000)

#setup log
myLogLevel = logging.CRITICAL + 1
logging.addLevel( myLogLevel, '' )
myLog = logging.LogFile( '.\\timings.log', filemode='w', level = myLogLevel, encoding='utf8') #= myLogLevel )

coreClock = core.Clock()
logging.setDefaultClock( coreClock )

logging.log('Run: ' + str(datetime.datetime.utcnow()) , myLogLevel)
logging.log('PP timestamp, datetime, timetime, timeclock', myLogLevel)
#setup window
win = visual.Window([400,400])
msg = visual.TextStim(win, text='<esc> to quit')
msg.draw()
win.flip()

while run:
    
    for i in range( gFrameInterval ): #accurate timing trick
        msg.setText('<esc> to quit\n' + str(i))
        msg.draw(win)
        win.flip()

    times = msTime()
Exemple #24
0
        now = datetime.now()  # grab system time
        current_time = now.strftime(
            "%H:%M:%S:%f")  # convert system time to string format
        logging.log(
            level=logging.DATA, msg="FIXATED TIME: %s" %
            (current_time))  # logging fixate button press and time occured
    win.flip()


# ================================
# setup logging #
# ================================
log_file = logging.LogFile("logs/%s.log" % (subj_id),
                           level=logging.DATA,
                           filemode="w")
logging.log(level=logging.DATA, msg="START")

#starting the INTRO SURVEY
logging.log(level=logging.DATA, msg="Intro Survey")
survey_intro()

if exp_cond == 0 or exp_cond == 1:
    show_instructions_cyberball()
else:
    show_instructions_iaps()
ready_screen.setText('''Press Space to start''')
ready_screen.draw()
win.flip()
event.waitKeys(keyList=['space'])

#################
for key in sorted(params.keys()):
    print "   '%s': %s" % (key, params[key]
                           )  # print each value as-is (no quotes)
print '}'

# save experimental info
toFile('%s-lastExpInfo.pickle' % scriptName,
       expInfo)  #save params to file for next time

#make a log file to save parameter/event  data
dateStr = ts.strftime("%b_%d_%H%M", ts.localtime())  # add the current time
filename = '%s-%s-%d-%s' % (scriptName, expInfo['subject'], expInfo['session'],
                            dateStr)  # log filename
logging.LogFile((filename + '.log'),
                level=logging.INFO)  #, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='filename: %s' % filename)
logging.log(level=logging.INFO, msg='subject: %s' % expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s' % expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s' % dateStr)
# log everything in the params struct
for key in sorted(params.keys()):  # in alphabetical order
    logging.log(level=logging.INFO,
                msg='%s: %s' % (key, params[key]))  # log each parameter

logging.log(level=logging.INFO, msg='---END PARAMETERS---')

# ========================== #
# ===== GET SCREEN RES ===== #
# ========================== #
Exemple #26
0
def run_block():

    # Await scan trigger
    while True:
        scan_trigger_text.draw()
        win.flip()
        if 'o' in event.waitKeys():
            logging.log(logging.DATA, "start key press")
            break
        event.clearEvents()

    clock = core.Clock()
    t = clock.getTime()
    ratings_and_onsets.append(['fixation', t])
    show_stim(fixation_text, 8)  # 8 sec blank screen with fixation cross
    t = clock.getTime()
    clock.reset()
    ratings_and_onsets.append(['start', t])
    #logging.log(logging.DATA, "start")
    for trial in range(ntrials):
        if check_for_quit(subdata, win):
            exptutils.shut_down_cleanly(subdata, win)
            sys.exit()

        trialdata = {}
        trialdata['onset'] = onsets[trial]
        visual_stim.setImage(stim_images[trialcond[trial]])
        print trial
        print 'condition %d' % trialcond[trial]
        print 'showing image: %s' % stim_images[trialcond[trial]]
        t = clock.getTime()
        ratings_and_onsets.append(
            ["image=%s" % stim_images[trialcond[trial]], t])
        visual_stim.draw()
        logging.log(logging.DATA, "image=%s" % stim_images[trialcond[trial]])

        while clock.getTime() < trialdata['onset']:
            pass
        win.flip()

        while clock.getTime() < (trialdata['onset'] +
                                 cue_time):  #show the image
            pass

        print 'injecting via pump at address %d' % pump[trial]
        logging.log(logging.DATA,
                    "injecting via pump at address %d" % pump[trial])
        t = clock.getTime()
        ratings_and_onsets.append(
            ["injecting via pump at address %d" % pump[trial], t])
        ser.write('%drun\r' % pump[trial])

        while clock.getTime() < (trialdata['onset'] + cue_time +
                                 delivery_time):
            pass

        message = visual.TextStim(win, text='')
        #ratings_and_onsets.append(["wait", t])
        message.draw()
        win.flip()

        trialdata['dis'] = [ser.write('0DIS\r'), ser.write('1DIS\r')]
        print(trialdata['dis'])

        while clock.getTime() < (trialdata['onset'] + cue_time +
                                 delivery_time + wait_time):
            pass

        print 'injecting rinse via pump at address %d' % 0
        t = clock.getTime()
        ratings_and_onsets.append(
            ['injecting rinse via pump at address %d' % 0, t])
        ser.write('%dRUN\r' % 0)

        while clock.getTime() < (trialdata['onset'] + cue_time +
                                 delivery_time + wait_time + rinse_time):
            pass

        message = visual.TextStim(win, text='swallow')
        #ratings_and_onsets.append(["swallow", t])
        message.draw()
        win.flip()

        while clock.getTime() < (trialdata['onset'] + cue_time + delivery_time
                                 + wait_time + rinse_time + jitter[trial]):
            pass
        message = visual.TextStim(win, text='')
        message.draw()
        win.flip()

        while clock.getTime() < (trialdata['onset'] + cue_time + delivery_time
                                 + wait_time + rinse_time + jitter[trial]):
            pass

        t = clock.getTime()
        ratings_and_onsets.append(['end time', t])
        logging.log(logging.DATA, "finished")
        subdata['trialdata'][trial] = trialdata
    win.close()
Exemple #27
0
                      title='Numerical SART task',
                      fixed=['date'],
                      order=['subject', 'session'])
if dlg.OK:
    toFile('lastSimonParams.pickle',
           expInfo)  #save params to file for next time
else:
    core.quit()  #the user hit cancel so exit

#make a log file to save parameter/event  data
fileName = 'Simon-%s-%d-%s' % (
    expInfo['subject'], expInfo['session'], dateStr
)  #'Sart-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName + '.log'),
                level=logging.INFO)  #, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='fileName: %s' % fileName)
logging.log(level=logging.INFO, msg='subject: %s' % expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s' % expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s' % dateStr)
logging.log(level=logging.INFO, msg='isPractice: %i' % isPractice)
logging.log(level=logging.INFO, msg='skipInstructions: %i' % skipInstructions)
logging.log(level=logging.INFO, msg='tSessionMax: %d' % tSessionMax)
logging.log(level=logging.INFO, msg='nBlocks: %d' % nBlocks)
logging.log(level=logging.INFO, msg='nTrialsPerBlock: %d' % nTrialsPerBlock)
logging.log(level=logging.INFO, msg='ITI_min: %1.3f' % ITI_min)
logging.log(level=logging.INFO, msg='ITI_range: %1.3f' % ITI_range)
logging.log(level=logging.INFO, msg='stimDur: %1.3f' % stimDur)
logging.log(level=logging.INFO, msg='pauseDur: %1.3f' % pauseDur)
logging.log(level=logging.INFO, msg='tRespPerItem: %1.3f' % tRespPerItem)
logging.log(level=logging.INFO, msg='tRespRoundOff: %1.3f' % tRespRoundOff)
expInfo['date'] = dateStr
expInfo['expName'] = expName

fixedExpInfo.update(expInfo)

print(fixedExpInfo['group'])

fileName = fixedExpInfo['group'] +' SubID-' + fixedExpInfo['Subject ID'] + '-' + dateStr
globalClock = core.Clock()
logging.setDefaultClock(globalClock)

# --------------- LOGGING FILE --------------- #
logFileName = 'MyFlanker-%s-%s' % (expInfo['date'], dateStr)
logging.LogFile((logFileName + '.log'), level=logging.INFO)
logging.log(level=logging.INFO, msg='---START PARAMS---')
logging.log(level=logging.INFO, msg='date: %s' % expInfo['date'])
logging.log(level=logging.INFO, msg='group: %s' % fixedExpInfo['group'])
logging.log(level=logging.INFO, msg='date: %s' % dateStr)
logging.log(level=logging.INFO, msg='respKeys: %s' % respKeys)



endExpNow = False #flag for 'escape' from exp

# Handles exp data as a whole. 
thisExp = data.ExperimentHandler(
        name=expName,
        extraInfo=fixedExpInfo,
        savePickle=True,
        saveWideText=True,
Exemple #29
0
 #
 
 currentLoop.addData('probePhaseShift', phaseShift)
 #
 
 if direction == 1:
     directionCueText = u"\u2192"
 elif direction == -1:
     directionCueText = u"\u2190"
 cue.setText(directionCueText)
 stimulus.setOpacity(initialContrast)
 # each routine
 
 increment = contrast/float(tDurationFadeOut)
 incrementLog = "Fade out/in increment: %f" % increment
 logging.log(level=logging.DEBUG, msg=incrementLog)
 
 #
 
 
 probe.setOpacity(0)
 
 fixCross.setColor(fixCrossColorRGB, colorSpace='rgb')
 keyResponse = event.BuilderKeyResponse()  # create an object of type KeyResponse
 keyResponse.status = NOT_STARTED
 
 # keep track of which components have finished
 trialComponents = []
 trialComponents.append(cue)
 trialComponents.append(circleTrajectory)
 trialComponents.append(stimulus)
Exemple #30
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)
Exemple #31
0
def RunTrial(iTrial):
    # Flush the key buffer and mouse movements
    event.clearEvents()

    # Decide Trial Params
    if alphaVsRemem:
        isRememberTrial = pseudorandTrialOrder[iTrial - 1]
        isCatchTrial = random.random() < params['catchProb']
    else:
        isRememberTrial = random.random() < params['rememberProb']
        isCatchTrial = pseudorandTrialOrder[iTrial - 1]
    if isLoc:
        isCatchTrial = random.random() < params['catchProb']
        isRememberTrial = random.random() < params['rememberProb']

    delayDur = random.uniform(params['minDelayDur'], params['maxDelayDur'])
    ISI = random.uniform(params['minISI'], params['maxISI'])
    startLetters = random.sample(
        params['letters'],
        params['nLetters'])  # get list of letters to present to subject
    startString = ''.join(startLetters)  # turn them into a string
    testLoc = random.randint(0, params['nLetters'] -
                             1)  # the letter to test the subject on
    if isCatchTrial:
        testLetter = '*'  # indicates no response is required.
    else:
        if isRememberTrial:
            testLetter = startLetters[testLoc]
        else:  # alphabetize!
            sortedLetters = sorted(startLetters)
            testLetter = sortedLetters[testLoc]
    testString = '%s?' % (testLetter)

    # display info to experimenter
    print(
        'trial: iTrial = %d, isRemember = %d, delayDur = %.1f, ISI = %.1f, startString = %s, testLetter = %s, testLoc = %d, isCatchTrial = %d'
        % (iTrial, isRememberTrial, delayDur, ISI, startString, testLetter,
           testLoc + 1, isCatchTrial))
    logging.log(
        level=logging.EXP,
        msg=
        'trial: iTrial = %d, isRemember = %d, delayDur = %.1f, ISI = %.1f, startString = %s, testLetter = %s, testLoc = %d, isCatchTrial = %d'
        % (iTrial, isRememberTrial, delayDur, ISI, startString, testLetter,
           testLoc + 1, isCatchTrial))

    # Draw letters
    mainText.setText(startString)
    mainText.draw()
    win.logOnFlip(level=logging.EXP, msg='Display string (%s)' % startString)
    # Wait until it's time to display
    while (globalClock.getTime() < tNextFlip[0]):
        LogAnyKeys()
    # log & flip window to display image
    win.flip()
    tStringStart = globalClock.getTime()  # record time when window flipped
    # set up next win flip time after this one
    AddToFlipTime(params['stringDur'])  # add to tNextFlip[0]

    # Draw fixation (PAUSE)
    fixation.draw()
    win.logOnFlip(level=logging.EXP, msg='Display fixation (pause)')
    # Wait until it's time to display
    while (globalClock.getTime() < tNextFlip[0]):
        LogAnyKeys()
    # log & flip window to display image
    win.flip()
    # set up next win flip time after this one
    AddToFlipTime(params['pauseDur'])  # add to tNextFlip[0]

    # Draw cue
    if isRememberTrial:
        mainText.setText(params['cues'][0])
        win.logOnFlip(level=logging.EXP,
                      msg='Display cue (%s)' % params['cues'][0])
    else:
        mainText.setText(params['cues'][1])
        win.logOnFlip(level=logging.EXP,
                      msg='Display cue (%s)' % params['cues'][1])
    mainText.draw()
    # Wait until it's time to display
    while (globalClock.getTime() < tNextFlip[0]):
        LogAnyKeys()
    # log & flip window to display image
    win.flip()
    tStimStart = globalClock.getTime()  # record time when window flipped
    # set up next win flip time after this one
    AddToFlipTime(params['cueDur'])  # add to tNextFlip[0]

    # Draw fixation (DELAY)
    fixation.draw()
    win.logOnFlip(level=logging.EXP, msg='Display fixation (delay)')
    # Wait until it's time to display
    while (globalClock.getTime() < tNextFlip[0]):
        LogAnyKeys()
    # log & flip window to display image
    win.flip()
    # set up next win flip time after this one
    AddToFlipTime(delayDur)  # add to tNextFlip[0]

    # Draw letters (test
    mainText.setText(testString)
    mainText.draw()
    win.logOnFlip(level=logging.EXP, msg='Display test stim (%s)' % testString)
    # Wait until it's time to display
    while (globalClock.getTime() < tNextFlip[0]):
        LogAnyKeys()
    # log & flip window to display image
    win.flip()
    # set up next win flip time after this one
    AddToFlipTime(params['testDur'])  # add to tNextFlip[0]

    # Draw fixation for next frame (but don't display yet)
    fixation.draw()  # draw it
    win.logOnFlip(level=logging.EXP, msg='Display fixation (ISI)')

    # Wait for 'testDur' seconds while recording relevant key presses
    respKey = None
    while (globalClock.getTime() <
           tNextFlip[0]):  # until it's time for the next frame
        # get new keypress
        respKey = LogAnyKeys(respKey)

    # Display fixation cross (ISI)
    win.flip()
    AddToFlipTime(ISI)  # -1 to give the next trial time to load up

    # Keep waiting while recording relevant key presses
    while (globalClock.getTime() <
           tNextFlip[0] - 1):  # Include -1 to give time for next trial to load
        # get new keypress
        respKey = LogAnyKeys(respKey)

    return
Exemple #32
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']]
        imagepath = os.path.join(expdir,'Images')
        image = os.path.join(imagepath, "%s.png") % condition_label
        pictureStim.setImage(image)

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

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

        #while timer.getTime() < decision_dur:
        while timer.getTime() < 1:
            partner_offer = trial['Offer']
            partnerOffer = 'Proposal: $%s.00 out of $20.00' % partner_offer
            offer_text.setText(partnerOffer)
            offer_text.draw()
            offer_text.draw()
            pictureStim.draw()
            win.flip()

        resp_val=None
        resp_onset=None

        while timer.getTime() < (decision_dur):
            resp_text_accept.draw()
            resp_text_reject.draw()
            pictureStim.draw()
            offer_text.setText(partnerOffer)
            offer_text.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])
                resp_onset = globalClock.getTime()
                rt = resp_onset - decision_onset
                if resp_val == 2:
                    resp_text_reject.setColor('darkorange')
                if resp_val == 3:
                    resp_text_accept.setColor('darkorange')
                resp_text_accept.draw()
                resp_text_reject.draw()
                pictureStim.draw()
                offer_text.setText(partnerOffer)
                offer_text.draw()
                win.flip()
                core.wait((decision_dur - rt)+.5)
                decision_offset = globalClock.getTime()
                break
            else:
                resp_val = 999
                rt = 999
                resp_onset = 999
                outcome_txt = outcome_map[resp_val]
                decision_offset = globalClock.getTime()

        trials.addData('resp', resp_val)
        trials.addData('rt',rt)
        trials.addData('resp_onset',resp_onset)
        trials.addData('decision_offset',decision_offset)
                #win.flip()

        timer.reset()
        if resp_val == 999:
            outcome_stim.setText(outcome_txt)
            outcome_stim.draw()
            win.flip()
            missFB_onset = globalClock.getTime()
            core.wait(.5)
            missFB_offset = globalClock.getTime()



        #reset rating number color
        resp_text_accept.setColor('#FFFFFF')
        resp_text_reject.setColor('#FFFFFF')

        trial_offset = globalClock.getTime()
        duration = trial_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'])
        fixation.draw()
        win.flip()
        core.wait(iti_for_trial)
        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()
    def presentSound(self, wavfile, responseTime=0, keyList=['1', '2']):
        """
        Play a sound with additional time to wait for a key response. 
        Response and reaction time relative to the end of the wave file are recorded.
        
        Parameters
        ----------
        wavfile : str 
            wave file to play (either absolute path or relative to the folder of the python file)
        responseTime: double
            time in seconds to wait for a response after the end of the wave file (default: 0s)
        keyList : list of str
            list of keys to record as response. Only the first key is recorded and the response does not end the trial (default: 1 and 2)
        """
        trialClock = core.Clock()
        wav = sound.Sound(wavfile,
                          secs=-1,
                          stereo=True,
                          hamming=True,
                          name="sound stimulus")
        wav.setVolume(1)
        trialDuration = wav.getDuration() + responseTime
        keyb = keyboard.Keyboard()

        trialComponents = [wav]
        self.resetTrialComponents(trialComponents)

        response = ''
        rt = -1
        resetDone = False

        # reset timers
        t = 0
        startTime = trialClock.getTime()
        startTimeGlobal = self.globalClock.getTime()
        _timeToFirstFrame = self.win.getFutureFlipTime(clock="now")
        trialClock.reset(
            -_timeToFirstFrame)  # t0 is time of first possible flip
        frameN = -1
        continueRoutine = True

        while continueRoutine:
            # get current time
            t = trialClock.getTime()
            tThisFlip = self.win.getFutureFlipTime(clock=trialClock)
            tThisFlipGlobal = self.win.getFutureFlipTime(clock=None)
            frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
            # update/draw components on each frame

            if wav.status == NOT_STARTED and t >= 0.0 - self.frameTolerance:
                # keep track of start time/frame for later
                wav.frameNStart = frameN  # exact frame index
                wav.tStart = t  # local t and not account for scr refresh
                wav.tStartRefresh = tThisFlipGlobal  # on global time
                wav.play()  # start the sound (it finishes automatically)
                logging.log(level=logging.EXP,
                            msg='Playback started\t' +
                            str(self.globalClock.getTime()) + '\t' + wavfile)

            # Check for a response. This doesn't need to be sychronized with the next
            # frame flip
            if wav.status == FINISHED and rt == -1:
                if resetDone:
                    theseKeys = keyb.getKeys(keyList=keyList,
                                             waitRelease=False)
                    if len(theseKeys):
                        response = theseKeys[0].name
                        rt = theseKeys[0].rt
                else:
                    keyb.clock.reset()
                    resetDone = True

            # check for fMRI trigger and responses to log
            trigger, button1, button2 = checkForFMRITriggerOrResponse(self)
            if trigger:
                gt = self.globalClock.getTime()
                logging.log(level=logging.EXP, msg='fMRI trigger\t' + str(gt))
            if button1 == BUTTON_PRESSED:
                logging.log(level=logging.EXP, msg='Button 1 pressed')
            if button2 == BUTTON_PRESSED:
                logging.log(level=logging.EXP, msg='Button 2 pressed')

            # check for quit (typically the Esc key)
            if self.endExpNow or self.defaultKeyboard.getKeys(
                    keyList=["escape"]):
                core.quit()

            if wav.status == FINISHED and tThisFlipGlobal > wav.tStartRefresh + trialDuration - self.frameTolerance:
                continueRoutine = False

            # refresh the screen
            if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
                self.win.flip()

        # -------Ending Routine -------
        wav.stop()  # ensure sound has stopped at end of routine
        endTime = trialClock.getTime()
        logging.log(level=logging.EXP,
                    msg='Trial ended\t' + str(self.globalClock.getTime()))

        self.thisExp.addData('wavfile', wavfile)
        self.thisExp.addData('response', response)
        self.thisExp.addData('rt', rt)
        self.thisExp.addData('wav.started', wav.tStart)
        self.thisExp.addData('startTime', startTime)
        self.thisExp.addData('startTimeGlobal', startTimeGlobal)
        self.thisExp.addData('endTime', endTime)
        self.thisExp.addData('responseTime', responseTime)
        self.thisExp.nextEntry()

        self.routineTimer.reset()
Exemple #34
0
def log(msg):
    """Prints messages in the promt and adds msg to PsychoPy log file. """
    logging.log(level=logging.EXP, msg=msg)
Exemple #35
0
           'Session':'001', \
           'Configuration': ['Task', 'Practice'], \
           'Starting Block': ['Control', 'Interference']}

dlg = gui.DlgFromDict(dictionary=expInfo, title=expName, fixed=[])

# if user pressed cancel, quit
if dlg.OK == False:
    core.quit()

# set a few more configuration parameters
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName

if expInfo['Configuration'] == 'Practice':
    logging.log(level=logging.EXP, msg="Configuration: Practice")
    print "Configuration: Practice"
elif expInfo['Configuration'] == 'Task':
    logging.log(level=logging.EXP, msg="Configuration: Task")
    print "Configuration: Task"


# if practice, reconfigure some aspects
if expInfo['Configuration'] == 'Practice':
    FIXATION_BUFFER_SECONDS = 3.0

# if interference first, swap stim
if expInfo['Starting Block'] == 'Interference':
    all_first_text=all_int_stim
    all_second_stim=all_control_stim
else:
def run_block(fix):

    # Await scan trigger
    while True:
        scan_trigger_text.draw()
        win.flip()
        if 'o' in event.waitKeys():
            logging.log(logging.DATA, "start key press")
            break
        event.clearEvents()

    clock = core.Clock()
    t = clock.getTime()

    #set up the fixation
    ratings_and_onsets.append(['fixation', t])
    logging.log(logging.DATA, "fixation %f" % t)
    show_stim(fixation_text, fix)  # 8 sec blank screen with fixation cross

    #log fixation
    logging.log(logging.DATA, "fixation end %f" % t)
    t = clock.getTime()

    #reset the clock so the onsets are correct (if onsets have the 8 sec in them then you dont need this)
    clock.reset()
    ratings_and_onsets.append(['start', t])
    logging.log(logging.DATA, "START")

    #start the taste loop
    for trial in range(ntrials):
        #check for quit
        if check_for_quit(subdata, win):
            exptutils.shut_down_cleanly(subdata, win)
            sys.exit()
        #empty trial data
        trialdata = {}
        trialdata['onset'] = onsets[trial]

        #shuffle the position of the images
        shuffle(pos_ind)
        visual_stim1 = visual.ImageStim(win,
                                        image=N.zeros((300, 300)),
                                        pos=positions[pos_ind[0]],
                                        size=(0.25, 0.25),
                                        units='height')
        visual_stim2 = visual.ImageStim(win,
                                        image=N.zeros((300, 300)),
                                        pos=positions[pos_ind[1]],
                                        size=(0.25, 0.25),
                                        units='height')

        #set which image pair to show
        x = trialcond[trial]
        print(x)

        stim_images = stim_list[x]
        trial_prob = prob_list[x]
        trial_inv_prob = inv_prob_list[x]
        visual_stim1.setImage(
            stim_images[indices[0]])  #set which image appears
        print("GRACE THIS IS VISUAL STIM 1 %s" % (stim_images[indices[0]]))
        visual_stim2.setImage(
            stim_images[indices[1]])  #set which image appears
        print("GRACE THIS IS VISUAL STIM 2 %s" % (stim_images[indices[1]]))
        master_prob_list = [trial_prob, trial_inv_prob]

        shuffle(indices)

        #creating a dictory which will store the postion with the image and pump, the image and pump need to match
        mydict = {}
        mydict[positions_scan[pos_ind[1]]] = [
            stim_images[indices[1]], master_prob_list[indices[1]]
        ]
        mydict[positions_scan[pos_ind[0]]] = [
            stim_images[indices[0]], master_prob_list[indices[0]]
        ]
        print("<3 <3 <3 LOOK HERE <3 <3 <3")
        print(mydict)

        #Question Prompt
        message = visual.TextStim(win, text='Which is Correct?', pos=(0, 5))
        print trial
        t = clock.getTime()

        #get the time of the image and log, this log is appending it to the csv file
        visual_stim1.draw()  #making image of the logo appear
        visual_stim2.draw()  #making image of the logo appear
        message.draw()
        RT = core.Clock()

        #this is logging when the message is shown
        logging.log(
            logging.DATA, "%s at position=%s and %s at position=%s" %
            (stim_images[indices[0]], positions_eng[pos_ind[0]],
             stim_images[indices[1]], positions_eng[pos_ind[1]]))
        logging.flush()

        while clock.getTime() < trialdata['onset']:
            pass
        win.flip()

        RT.reset()  # reaction time starts immediately after flip

        while clock.getTime() < (
                trialdata['onset'] + cue_time
        ):  #show the image, while clock is less than onset and cue, show cue
            pass

        keys = event.getKeys(keyList=['1', '2'], timeStamped=RT)
        print(keys)
        win.flip()

        # get the key press logged, and time stamped

        if len(keys) > 0:
            logging.log(logging.DATA,
                        "keypress=%s at time= %f" % (keys[0][0], keys[0][1]))
            print("here are the keys:")
            print(keys)
            t = clock.getTime()
            logging.flush()

            #back up of the key press
            tempArray = [t, keys[0]]
            key_responses.append(tempArray)
            ratings_and_onsets.append(["keypress=%s" % keys[0][0], t])
            if keys[0][0] == '1':
                #show the image on the left
                visual_stim_feedback = visual.ImageStim(win,
                                                        image=N.zeros(
                                                            (300, 300)),
                                                        pos=(0, 0),
                                                        size=(0.25, 0.25),
                                                        units='height')
                cats = (mydict['1'][0])
                visual_stim_feedback.setImage(
                    cats)  #set which image appears as feedback for response
                visual_stim_feedback.draw()
                logging.log(logging.DATA, "SHOWING IMAGE %s" % (cats))
                #from the dictionary find the image code associated with the key press
                #taste=int(mydict['left'][1])

                trial_prob = (mydict['1'][1])

                #choose the feedback
                taste = int(
                    N.random.choice(reinforcer_responses, 1, p=trial_prob))
                print(taste)
                if taste == 1:
                    message = visual.TextStim(win,
                                              text='Correct',
                                              pos=(0, 5),
                                              height=2)
                    message.draw()
                    print 'Reinforcement is correct'
                else:
                    message = visual.TextStim(win,
                                              text='Incorrect',
                                              pos=(0, 5),
                                              height=2)
                    message.draw()
                    print 'Reinforcement is incorrect'
                #log the pump used, time, and key press
                print 'Reinforcement is %s' % taste
                logging.log(
                    logging.DATA,
                    "Reinforcement of %s and a keypress of %s for image of %s"
                    % (taste, keys[0][0], cats))
                t = clock.getTime()
                ratings_and_onsets.append(
                    ["Reinforcement is %s" % taste, t, keys[0][0]])
                #trigger pump with the numeral from the dictonary above
                #ser.write('%dRUN\r'%taste)
                logging.flush()
            elif keys[0][0] == '2':
                # show the image on the right
                cats = (mydict['2'][0])
                visual_stim_feedback = visual.ImageStim(win,
                                                        image=N.zeros(
                                                            (300, 300)),
                                                        pos=(0, 0),
                                                        size=(0.25, 0.25),
                                                        units='height')
                visual_stim_feedback.setImage(
                    cats)  #set which image appears as feedback for response
                visual_stim_feedback.draw()
                #from the dictonary get the image associated with the right key press
                trial_prob = (mydict['2'][1])
                taste = int(
                    N.random.choice(reinforcer_responses, 1, p=trial_prob))
                print(taste)
                if taste == 1:
                    message = visual.TextStim(win,
                                              text='Correct',
                                              pos=(0, 5),
                                              height=2)
                    message.draw()
                    print 'Reinforcement is correct'
                else:
                    message = visual.TextStim(win,
                                              text='Incorrect',
                                              pos=(0, 5),
                                              height=2)
                    message.draw()
                    print 'Reinforcement is incorrect'

                #log the time, keypress, and pump
                print 'Reinforcement is %s' % taste
                logging.log(
                    logging.DATA,
                    "Reinforcement of %s and a keypress of %s for image of %s"
                    % (taste, keys[0][0], cats))
                t = clock.getTime()
                ratings_and_onsets.append(
                    ["Reinforcement is %s" % taste, t, keys[0][0]])
                #trigger the pump with the numeral from the dictionary
                #ser.write('%dRUN\r'%taste)
                logging.flush()
        else:
            taste = 0
            t = clock.getTime()
            logging.log(logging.DATA, "Key Press Missed!")
            keys = keys.append(['MISS', t])
            logging.flush()
            message = visual.TextStim(win,
                                      text='Please answer quicker',
                                      pos=(0, 0),
                                      height=2)  #this lasts throught the taste
            message.draw()
            win.flip()

        while clock.getTime() < (trialdata['onset'] + cue_time +
                                 delivery_time):
            pass

        message = visual.TextStim(win, text='', pos=(0, 0),
                                  height=2)  #this lasts throught the wait
        message.draw()
        win.flip()
        t = clock.getTime()
        ratings_and_onsets.append(["wait", t])

        while clock.getTime() < (trialdata['onset'] + cue_time +
                                 delivery_time + wait_time):
            pass

        message = visual.TextStim(win, text='', pos=(0, 0),
                                  height=2)  #this lasts throught the rinse
        message.draw()
        win.flip()

        #print 'injecting rinse via pump at address %d'%0
        #t = clock.getTime()
        #ratings_and_onsets.append(['injecting rinse via pump at address %d'%0, t])
        #ser.write('%dRUN\r'%0)
        #logging.log(logging.DATA, "RINSE")
        #logging.flush()

        while clock.getTime() < (trialdata['onset'] + cue_time +
                                 delivery_time + wait_time + rinse_time):
            pass

        message = visual.TextStim(win, text='+', pos=(0, 0),
                                  height=2)  #lasts through the jitter
        message.draw()
        win.flip()
        t = clock.getTime()
        ratings_and_onsets.append(["jitter", t])

        while clock.getTime() < (trialdata['onset'] + cue_time + delivery_time
                                 + wait_time + rinse_time + jitter[trial]):
            pass

        t = clock.getTime()
        ratings_and_onsets.append(['end time', t])
        logging.log(logging.DATA, "finished")
        logging.flush()
        subdata['trialdata'][trial] = trialdata

        print(key_responses)

        #shuffle indices for the next trial
        #shuffle(indices)

    win.close()
         if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
             continueRoutine = True
             break  # at least one component has not yet finished
     
     # check for quit (the [Esc] key)
     if event.getKeys(["escape"]):
         core.quit()
     
     # refresh the screen
     if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
         win.flip()
         for triggeredComponent in trialComponents:
             if triggeredComponent.status == STARTED and triggeredComponent.frameNStart == frameN:
                 print str(triggeredComponent)
                 #writeTrigger(triggers['fixCross'])
                 logging.log(level=logging.DEBUG, msg='TRIGGER: fixCrossTrial')
                 TRIGGER_STATUS = True
             if TRIGGER_STATUS == True:
                 core.wait(0.005)
                 logging.log(level=logging.DEBUG, msg='TRIGGER: OFF')
                 TRIGGER_STATUS = False
                 #writeTrigger(0)
 
 #-------Ending Routine "trial"-------
 for thisComponent in trialComponents:
     if hasattr(thisComponent, "setAutoDraw"):
         thisComponent.setAutoDraw(False)
 
 
 # check responses
 if len(keyResponse.keys) == 0:  # No response was made
    expInfo['session'] +=1 # increment session number
except:#if not there then use a default set
    expInfo = {'subject':'1', 'session':'1'}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='Rhythmic tapping task', fixed=['date'], order=['subject','session'])
if dlg.OK:
    toFile('lastTappingParams.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

# Start log file
fileName = 'Tapping-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s'%dateStr)
logging.log(level=logging.INFO, msg='nBlocks: %d'%nBlocks)
logging.log(level=logging.INFO, msg='fixDur: %f'%fixDur)
logging.log(level=logging.INFO, msg='toneInterval: %f'%toneInterval)
logging.log(level=logging.INFO, msg='nTones: %d'%nTones)
logging.log(level=logging.INFO, msg='blockDurMin: %f'%blockDurMin)
logging.log(level=logging.INFO, msg='blockDurRange: %f'%blockDurRange)
logging.log(level=logging.INFO, msg='IBI: %f'%IBI)
logging.log(level=logging.INFO, msg='respKey: %s'%respKey)
logging.log(level=logging.INFO, msg='wanderKey: %s'%wanderKey)
logging.log(level=logging.INFO, msg='triggerKey: %s'%triggerKey)
logging.log(level=logging.INFO, msg='fullScreen: %s'%fullScreen)
logging.log(level=logging.INFO, msg='screenToShow: %s'%screenToShow)
def SendMessage(message):
    # send message preceded by SMI code ET_REM (generic remark) and surround multi-word remarks by quotes(?)
    myTracker.log(message)
    logging.log(level=logging.INFO,msg=message)
#    pass
    """
def run_block(fix):

    # Await scan trigger
    while True:
        scan_trigger_text.draw()
        win.flip()
        if 'o' in event.waitKeys():
            logging.log(logging.DATA, "start key press")
            break
        event.clearEvents()

    clock = core.Clock()
    t = clock.getTime()

    #set up the fixation
    ratings_and_onsets.append(['fixation', t])
    logging.log(logging.DATA, "fixation %f" % t)
    show_stim(fixation_text, fix)  # 8 sec blank screen with fixation cross

    #log fixation
    logging.log(logging.DATA, "fixation end %f" % t)
    t = clock.getTime()

    #reset the clock so the onsets are correct (if onsets have the 8 sec in them then you dont need this)
    clock.reset()
    ratings_and_onsets.append(['start', t])
    logging.log(logging.DATA, "START")

    #start the taste loop
    for trial in range(ntrials):
        #check for quit
        if check_for_quit(subdata, win):
            exptutils.shut_down_cleanly(subdata, win)
            sys.exit()
        #empty trial data
        trialdata = {}
        trialdata['onset'] = onsets[trial]

        #shuffle the positions

        visual_stim1 = visual.ImageStim(win,
                                        image=N.zeros((300, 300)),
                                        pos=positions[pos_ind[0]],
                                        size=(0.25, 0.25),
                                        units='height')
        visual_stim2 = visual.ImageStim(win,
                                        image=N.zeros((300, 300)),
                                        pos=positions[pos_ind[1]],
                                        size=(0.25, 0.25),
                                        units='height')

        #set which image is which
        x = int(N.random.choice(prob_index, 1, p=[0.34, 0.33, 0.33]))
        print(x)

        stim_images = stim_list[x]
        trial_prob = prob_list[x]
        trial_inv_prob = inv_prob_list[x]
        visual_stim1.setImage(
            stim_images[indices[0]])  #set which image appears
        visual_stim2.setImage(
            stim_images[indices[1]])  #set which image appears

        master_prob_list = [trial_prob, trial_inv_prob]

        #creating a dictory which will store the postion with the image and pump, the image and pump need to match
        mydict = {}
        #        mydict[positions_eng[pos_ind[1]]] = [stim_images[indices[1]], master_prob_list[indices[1]]]
        #        mydict[positions_eng[pos_ind[0]]] = [stim_images[indices[0]], master_prob_list[indices[0]]]
        mydict[positions_scan[pos_ind[1]]] = [
            stim_images[indices[1]], master_prob_list[indices[1]]
        ]
        mydict[positions_scan[pos_ind[0]]] = [
            stim_images[indices[0]], master_prob_list[indices[0]]
        ]

        print(mydict)

        #which is sweet?
        message = visual.TextStim(win, text='Which is Correct?', pos=(0, 5))
        print trial
        t = clock.getTime()

        #get the time of the image and log, this log is appending it to the csv file
        visual_stim1.draw()  #making image of the logo appear
        visual_stim2.draw()  #making image of the logo appear
        message.draw()
        RT = core.Clock()

        #this is logging when the message is shown
        logging.log(
            logging.DATA, "%s at position=%s and %s at position=%s" %
            (stim_images[indices[0]], positions_eng[pos_ind[0]],
             stim_images[indices[1]], positions_eng[pos_ind[1]]))
        logging.flush()

        while clock.getTime() < trialdata['onset']:
            pass
        win.flip()

        RT.reset()  # reaction time starts immediately after flip

        while clock.getTime() < (
                trialdata['onset'] + cue_time
        ):  #show the image, while clock is less than onset and cue, show cue
            pass

        keys = event.getKeys(keyList=['1', '2'], timeStamped=RT)
        message = visual.TextStim(
            win, text='')  #blank screen while the taste is delivered
        message.draw()
        win.flip()

        # get the key press logged, and time stamped

        if len(keys) > 0:
            logging.log(logging.DATA,
                        "keypress=%s at time= %f" % (keys[0][0], keys[0][1]))
            print("here are the keys:")
            print(keys)
            t = clock.getTime()
            logging.flush()

            #back up of the key press
            tempArray = [t, keys[0]]
            key_responses.append(tempArray)
            ratings_and_onsets.append(["keypress=%s" % keys[0][0], t])
            if keys[0][0] == '1':
                #draw images & what the participant chose
                rectangle_l = visual.Rect(win,
                                          pos=(-0.25, 0),
                                          size=(0.75, 0.75),
                                          units='height',
                                          fillColor=[0, 0, 0],
                                          lineColor=[1, -1, -1])
                rectangle_l.draw()
                visual_stim1.draw()
                visual_stim2.draw()

                #from the dictionary find the image code associated with the key press
                #taste=int(mydict['left'][1])
                image = (mydict['1'][0])
                trial_prob = (mydict['1'][1])
                taste = int(N.random.choice(pump_responses, 1, p=trial_prob))
                #if image=='sweet.jpg':
                #taste=int(N.random.choice(pump_responses, 1, p=[0.5, 0.5]))
                #elif image=='unsweet.jpg':
                #taste=int(N.random.choice(pump_responses, 1, p=[0.5, 0.5]))
                print(image)
                print(taste)
                #log the pump used, time, and key press
                print 'injecting via pump at address %s' % taste
                logging.log(
                    logging.DATA,
                    "injecting via pump at address %d and a keypress of %s and image of %s"
                    % (taste, keys[0][0], image))
                t = clock.getTime()
                ratings_and_onsets.append([
                    "injecting via pump at address %d" % taste, t, keys[0][0]
                ])
                #trigger pump with the numeral from the dictonary above
                ser.write('%dRUN\r' % taste)
                logging.flush()
            elif keys[0][0] == '2':
                rectangle_r = visual.Rect(win,
                                          pos=(0.25, 0),
                                          size=(0.75, 0.75),
                                          units='height',
                                          fillColor=[0, 0, 0],
                                          lineColor=[1, -1, -1])
                rectangle_r.draw()
                visual_stim1.draw()
                visual_stim2.draw()
                #from the dictonary get the image associated with the right key press
                image = (mydict['2'][0])
                trial_prob = (mydict['2'][1])
                taste = int(N.random.choice(pump_responses, 1, p=trial_prob))
                print(image)
                print(taste)
                #log the time, keypress, and pump
                print 'injecting via pump at address %s' % taste
                logging.log(
                    logging.DATA,
                    "injecting via pump at address %d and a keypress of %s and image of %s"
                    % (taste, keys[0][0], image))
                t = clock.getTime()
                ratings_and_onsets.append(
                    ["injecting via pump at address %d" % taste, t])
                #trigger the pump with the numeral from the dictionary
                ser.write('%dRUN\r' % taste)
                logging.flush()
        else:
            taste = 0
            t = clock.getTime()
            logging.log(logging.DATA, "Key Press Missed!")
            keys = keys.append(['MISS', t])
            logging.flush()
            message = visual.TextStim(win,
                                      text='Please answer quicker',
                                      pos=(0, 0),
                                      height=2)  #this lasts throught the taste
            message.draw()
            win.flip()

        while clock.getTime() < (trialdata['onset'] + cue_time +
                                 delivery_time):
            pass

        message = visual.TextStim(win, text='+', pos=(0, 0),
                                  height=2)  #this lasts throught the wait
        message.draw()
        win.flip()
        t = clock.getTime()
        ratings_and_onsets.append(["wait", t])

        trialdata['dis'] = [ser.write('0DIS\r'), ser.write('1DIS\r')]
        print(trialdata['dis'])

        while clock.getTime() < (trialdata['onset'] + cue_time +
                                 delivery_time + wait_time):
            pass

        message = visual.TextStim(win, text='', pos=(0, 0),
                                  height=2)  #this lasts throught the rinse
        message.draw()
        win.flip()

        print 'injecting rinse via pump at address %d' % 0
        t = clock.getTime()
        ratings_and_onsets.append(
            ['injecting rinse via pump at address %d' % 0, t])
        ser.write('%dRUN\r' % 0)
        logging.log(logging.DATA, "RINSE")
        logging.flush()

        while clock.getTime() < (trialdata['onset'] + cue_time +
                                 delivery_time + wait_time + rinse_time):
            pass

        message = visual.TextStim(win, text='+', pos=(0, 0),
                                  height=2)  #lasts through the jitter
        message.draw()
        win.flip()
        t = clock.getTime()
        ratings_and_onsets.append(["jitter", t])

        while clock.getTime() < (trialdata['onset'] + cue_time + delivery_time
                                 + wait_time + rinse_time + jitter[trial]):
            pass

        t = clock.getTime()
        ratings_and_onsets.append(['end time', t])
        logging.log(logging.DATA, "finished")
        logging.flush()
        subdata['trialdata'][trial] = trialdata

        print(key_responses)
        shuffle(indices)
        shuffle(pos_ind)
    win.close()
Exemple #41
0
def logThis( msg ):
    logging.log( msg, level=myLogLevel )
def do_run(run, trials):
    fileName = log_file.format(subj_id, run)
    #Ready Screen
    ready_screen.draw()
    win.flip()
    core.wait(ready_screen_dur)

    globalClock.reset()
    studyStart = globalClock.getTime()

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

    for trial in trials:
        image = "money.png"
        pictureStim.setImage(image)
        #decision phase
        timer.reset()
        event.clearEvents()
        resp_val = None
        resp_onset = None
        #ifresp = 0
        while timer.getTime() < decision_dur:
            pictureStim.draw()
            cardStim_left.draw()
            cardStim_right.draw()
            immed_left = trial['immed']
            delay_right = trial['delay']
            timeD_right = trial['time']
            immediate = '$%s today' % immed_left
            delayed = '$%s in %s days' % (delay_right, timeD_right)
            immed_text.setText(immediate)
            delay_text.setText(delayed)
            immed_text.draw()
            delay_text.draw()
            win.flip()
            resp = event.getKeys(keyList=responseKeys)
            if len(resp) > 0:
                resp_val = int(resp[0])
                resp_onset = globalClock.getTime()
                if resp_val == 1:
                    immed_text.setColor('red')
                if resp_val == 2:
                    delay_text.setColor('red')
                print "got here3"  #checkpoint
                pictureStim.draw()
                cardStim_left.draw()
                cardStim_right.draw()
                immed_text.draw()
                delay_text.draw()
                win.flip()
                core.wait(1)
                break
                print "got here4"  #checkpoint
        trials.addData('resp', resp_val)
        trials.addData('rt', resp_onset)
        print "got here5"  #checkpoint
        #reset rating number color
        immed_text.setColor('#FFFFFF')
        delay_text.setColor('#FFFFFF')
        print "got here7"  #checkpoint
        #ITI
        logging.log(level=logging.DATA, msg='ITI')  #send fixation log event
        timer.reset()
        iti_for_trial = float(trial['ITI'])
        while timer.getTime() < iti_for_trial:
            waiting.draw()
            win.flip()
        print "got here7"  #checkpoint

        #trials.saveAsText(fileName=log_file.format(subj_id, run_num)) #, dataOut='all_raw', encoding='utf-8'
        os.chdir(subjdir)
        trials.saveAsWideText(fileName)
        os.chdir(expdir)
    expInfo['session'] +=1 # increment session number
except:#if not there then use a default set
    expInfo = {'subject':'1', 'session':1}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='BopIt Task', fixed=['date'], order=['subject','session'])
if dlg.OK:
    toFile('lastBopItParams.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

# Start log file
fileName = 'BopIt-%s-%d-%s'%(expInfo['subject'],expInfo['session'],dateStr) #'BopIt-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s'%dateStr)
logging.log(level=logging.INFO, msg='isPractice: %i'%isPractice)
logging.log(level=logging.INFO, msg='respKeys: %s'%respKeys)
logging.log(level=logging.INFO, msg='triggerKey: %s'%triggerKey)
logging.log(level=logging.INFO, msg='wanderKey: %s'%wanderKey)
logging.log(level=logging.INFO, msg='nBlocks: %d'%nBlocks)
logging.log(level=logging.INFO, msg='nTrialsPerBlock: %d'%nTrialsPerBlock)
logging.log(level=logging.INFO, msg='fixDur_min: %f'%fixDur_min)
logging.log(level=logging.INFO, msg='fixDur_range: %f'%fixDur_range)
logging.log(level=logging.INFO, msg='toneDur: %f'%toneDur)
logging.log(level=logging.INFO, msg='respDur: %f'%respDur)
logging.log(level=logging.INFO, msg='preBlockDur: %f'%preBlockDur)
logging.log(level=logging.INFO, msg='IBI: %f'%IBI)
    ########################
    # SHOW READY SCREEN #
    ########################

    ready_screen.draw()
    win.flip()

    # wait for trigger from scanner (5 key press)
    event.waitKeys(keyList=('space'))

    # set clock
    globalClock = core.Clock()
    logging.setDefaultClock(globalClock)

    logging.log(level=logging.DATA, msg="** START RUN %i **" % current_run)

    trials.extraInfo = {'START': globalClock.getTime()}

    timer = core.Clock()

    while current_block < blocks_per_run:
        current_block += 1
        trial = trials.next()
        #for trial in trials:
        #print trial['cond'].encode('utf-8')

        cur_cond = trial['cond']

        prep_screen.setText(condition_text % prompt_map[cur_cond[:-4]])
        logging.log(level=logging.DATA, msg=condition_text % cur_cond)
Exemple #45
0
message=visual.TextStim(win, text='')

subdata['trialdata']={}
clock.reset()
event.clearEvents()

for trial in range(ntrials):
    if check_for_quit(subdata,win):
        exptutils.shut_down_cleanly(subdata,win)
        sys.exit()

    trialdata={}
    print 'trial %d'%trial
    trialdata['onset']=onsets[trial]
    print 'condition %d'%trialcond[trial]
    logging.log(logging.DATA,'Condition: %d'%trialcond[trial])
    print 'showing image: %s'%stim_images[trialcond[trial]]
    visual_stim.setImage(stim_images[trialcond[trial]])
    visual_stim.draw()
    while clock.getTime()<trialdata['onset']:#wait until the specified onset time to display image_file
        if check_for_quit(subdata,win):
            exptutils.shut_down_cleanly(subdata,win)
            sys.exit()
    win.flip()

    while clock.getTime()<(trialdata['onset']+cue_time):#show the image
        pass

    if hasPump:
        print 'injecting via pump at address %d'%pump[trial]
        logging.log(logging.DATA,'injecting via pump at address %d'%pump[trial])
 def on_error(client, error):
     if type(error) is KeyboardInterrupt:
         WsFeedbackReceiver.shouldExit = True
     else:
         logging.log(logging.WARNING, "on_error: WsFeedbackReceiver: {} {}".
                     format(type(error), str(error)))
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()

    win.flip()

    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)





    if run_number == 1:

        do_sound_test()



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

    # SHOW INSTRUCTIONS

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



    timer.reset()

    while timer.getTime() < instruct_dur:

    #for frame in range(instruct_dur):

        instruction_image.draw()

        instruction_text.draw()

        win.flip()



    while timer.getTime() < fixation_dur:

        #for frame in range(fixation_dur):

            fixation.draw()

            win.flip()



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

    # MAIN LOOP 

    # present trials



    for tidx, trial in enumerate(trials):

        trial_type = trial['type']

        theme = trial['theme']

        cond = trial['cond']

        image = "images/%s/%s_%s.png" % (cond, theme, trial_type)

        audio = "audio/%s_%s_%s.wav" % (theme, trial_type, cond)

        message = trial['message']

        

        pictureStim.setImage(image)

        messageStim.setText(message)

        

        message_audio = sound.Sound(audio)





        # send MESSAGE log event

        logging.log(level=logging.DATA, msg="MESSAGE: %s - %s - %s" % (cond, theme, trial_type))



        trials.addData('stim_onset', globalClock.getTime())



        # play sound file for message

        message_audio.play()

        # show mesage 

        timer.reset()

        while timer.getTime() < message_dur:

        #for frame in range(message_dur):

            pictureStim.draw()

            messageStim.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()

        # show rating and collect response  

        timer.reset()

        while timer.getTime() < rating_dur:

        #for frame in range(rating_dur):

            pictureStim.draw()

            messageStim.draw()

            

            for rate_stim in ratingStim:

                rate_stim.draw()

            

            anchor1.draw()

            anchor4.draw()

            win.flip()

            



            # get key response

            resp = event.getKeys(keyList = buttons)

        

            if len(resp) > 0 : 

                resp_value = resp[0]

                ratingStim[button_labels[resp_value]].setColor('red')

                

                # add response value to the trial handler logging

                trials.addData('resp',resp_value)

                trials.addData('rt', globalClock.getTime() - resp_onset)

                

                

            

        # reset rating number color

        for rate in ratingStim:

            rate.setColor('#FFFFFF')

       

        # ------------ FIXATION ------------

        # send FIXATION log event

        logging.log(level=logging.DATA, msg='FIXATION')

        # show fixation

        timer.reset()

        fixation_for_trial = fixations[run_number-1][tidx]

        while timer.getTime() < fixation_for_trial:

        #for frame in range(fixation_dur):

            fixation.draw()

            win.flip()

            





    # write logs



    # send END log event

    logging.log(level=logging.DATA, msg='******* END run %i *******' % run_number)
#    log_file.logger.flush()

    # save the trial infomation from trial handler

    log_filename2 = "%s_%i.csv" % (log_filename[:-4], run_number )

    trials.saveAsText(log_filename2, delim=',', dataOut=('n', 'all_raw'))



    event.waitKeys(keyList=('space'))
def send_error_response(client, response, errStr):
    logging.log(logging.WARNING, errStr)
    response.update({'status': 400, 'error': errStr})
    send_response(client, response)
params['skipPrompts'] = expInfo['skipPrompts']

# print params to Output
print 'params = {'
for key in sorted(params.keys()):
    print "   '%s': %s"%(key,params[key]) # print each value as-is (no quotes)
print '}'
    
# save experimental info
toFile('%s-lastExpInfo.pickle'%scriptName, expInfo)#save params to file for next time

#make a log file to save parameter/event  data
dateStr = ts.strftime("%b_%d_%H%M", ts.localtime()) # add the current time
filename = '%s-%s-%d-%s'%(scriptName,expInfo['subject'], expInfo['session'], dateStr) # log filename
logging.LogFile((filename+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='filename: %s'%filename)
logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s'%dateStr)
# log everything in the params struct
for key in sorted(params.keys()): # in alphabetical order
    logging.log(level=logging.INFO, msg='%s: %s'%(key,params[key])) # log each parameter

logging.log(level=logging.INFO, msg='---END PARAMETERS---')


# ========================== #
# ===== GET SCREEN RES ===== #
# ========================== #
    # TODO - update here with a specific stimuli for experiment sets
    videos = [vn for vn in os.listdir(STIM_DIR) if vn.endswith('.mov')]
    videos.sort()

    for vid in videos:

        do_fixation(5.0)

        play_video(os.path.join(STIM_DIR, vid))

        get_rating()

    do_fixation(10.0)

    logging.log(level=logging.DATA,
                msg='*********** TASK ENDED *************\tsys:{}'.format(
                    time.time()))

    # clean up
    logging.flush()
    win.close()
    core.quit()

# --------------------------------------------------------------------------------
#
# development note 2/2/17 - some videos throwing error discussed in
#   https://discourse.psychopy.org/t/error-while-trying-to-play-movie/1253/5
#   added patch to moviepy/audio/io/readers.py
#
# present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title="Flanker task", fixed=["date"], order=["subject", "session"])
if dlg.OK:
    toFile("lastFlankerParams.pickle", expInfo)  # save params to file for next time
else:
    core.quit()  # the user hit cancel so exit

# make a log file to save parameter/event  data
fileName = "Flanker-%s-%d-%s" % (
    expInfo["subject"],
    expInfo["session"],
    dateStr,
)  #'Sart-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName + ".log"), level=logging.INFO)  # , mode='w') # w=overwrite
logging.log(level=logging.INFO, msg="---START PARAMETERS---")
logging.log(level=logging.INFO, msg="subject: %s" % expInfo["subject"])
logging.log(level=logging.INFO, msg="session: %s" % expInfo["session"])
logging.log(level=logging.INFO, msg="date: %s" % dateStr)
logging.log(level=logging.INFO, msg="isPractice: %i" % isPractice)
logging.log(level=logging.INFO, msg="blockLengths: %s" % blockLengths)
logging.log(level=logging.INFO, msg="randomizeBlocks: %d" % randomizeBlocks)
logging.log(level=logging.INFO, msg="ITI_min: %f" % ITI_min)
logging.log(level=logging.INFO, msg="ITI_range: %f" % ITI_range)
logging.log(level=logging.INFO, msg="flankerDur: %f" % flankerDur)
logging.log(level=logging.INFO, msg="targetDur: %f" % targetDur)
logging.log(level=logging.INFO, msg="respDur: %d" % respDur)
logging.log(level=logging.INFO, msg="blankDur: %f" % blankDur)
logging.log(level=logging.INFO, msg="IBI: %f" % IBI)
logging.log(level=logging.INFO, msg="respKeys: %s" % respKeys)
logging.log(level=logging.INFO, msg="wanderKey: %s" % wanderKey)
Exemple #52
0
 # get current time
 t = trialClock.getTime()
 frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
 # update/draw components on each frame
 
 # *image* updates
 if t >= 0 and image.status == NOT_STARTED:
     # keep track of start time/frame for later
     image.tStart = t  # underestimates by a little under one frame
     image.frameNStart = frameN  # exact frame index
     image.setAutoDraw(True)
     #kamil
     #pport.Out32(pport_addrr, 255) # sets all pins to low
     #pport.Out32(pport_addrr+2, 1) # strobe on
     arduino.send_pulse_up()
     logging.log(level=logging.DATA, msg='Arduino pulse up')
      
 elif image.status == STARTED and t >= (0 + (2-win.monitorFramePeriod*0.75)): #most of one frame period left
     image.setAutoDraw(False)
 
 # *odpoved* updates
 if t >= 0 and odpoved.status == NOT_STARTED:
     # keep track of start time/frame for later
     odpoved.tStart = t  # underestimates by a little under one frame
     odpoved.frameNStart = frameN  # exact frame index
     odpoved.status = STARTED
     # keyboard checking is just starting
     odpoved.clock.reset()  # now t=0
     event.clearEvents(eventType='keyboard')
 if odpoved.status == STARTED:
     theseKeys = event.getKeys(keyList=['left', 'right'])
    expInfo['session'] +=1 # automatically increment session number
except:#if not there then use a default set
    expInfo = {'subject':'1', 'session':1}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='Numerical SART task', fixed=['date'], order=['subject','session'])
if dlg.OK:
    toFile('lastSimonParams.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

#make a log file to save parameter/event  data
fileName = 'Simon-%s-%d-%s'%(expInfo['subject'], expInfo['session'], dateStr) #'Sart-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='fileName: %s'%fileName)
logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s'%dateStr)
logging.log(level=logging.INFO, msg='isPractice: %i'%isPractice)
logging.log(level=logging.INFO, msg='skipInstructions: %i'%skipInstructions)
logging.log(level=logging.INFO, msg='tSessionMax: %d'%tSessionMax)
logging.log(level=logging.INFO, msg='nBlocks: %d'%nBlocks)
logging.log(level=logging.INFO, msg='nTrialsPerBlock: %d'%nTrialsPerBlock)
logging.log(level=logging.INFO, msg='ITI_min: %1.3f'%ITI_min)
logging.log(level=logging.INFO, msg='ITI_range: %1.3f'%ITI_range)
logging.log(level=logging.INFO, msg='stimDur: %1.3f'%stimDur)
logging.log(level=logging.INFO, msg='pauseDur: %1.3f'%pauseDur)
logging.log(level=logging.INFO, msg='tRespPerItem: %1.3f'%tRespPerItem)
logging.log(level=logging.INFO, msg='tRespRoundOff: %1.3f'%tRespRoundOff)
def do_run(trial_data, run_num):
    resp = []
    fileName = log_file.format(subj_id)

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

    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)

        #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()

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

        resp = []
        resp_val = None
        resp_onset = None

        trial_onset = globalClock.getTime()

        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])
            resp_onset = globalClock.getTime()
            rt = resp_onset - trial_onset
        else:
            resp_val = 0
            resp_onset = 'NA'
            #rt = 'NA'

        trials.addData('resp', int(resp_val))
        trials.addData('resp_onset', resp_onset)
        trials.addData('onset', trial_onset)
        trials.addData('ITIonset', ITI_onset)
        trials.addData('rt', rt)

        #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 = 'green'
                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 = 'green'
                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 = 'red'
                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 = 'red'
                trials.addData('outcome_val', int(outcome_txt))
            elif resp_val == 0:
                outcome_txt = '#'
                outcome_moneyTxt = ''
                outcome_color = 'white'

            #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 - trial_onset
            trials.addData('trialDuration', duration)
            event.clearEvents()
        print "got to check 3"

    os.chdir(subjdir)
    trials.saveAsWideText(fileName)
    os.chdir(expdir)
    if globalClock.getTime() < 850:
        endTime = (850 - globalClock.getTime())
    else:
        endTime = 10
    core.wait(endTime)
    print globalClock.getTime()
Exemple #55
0
    def flip(self, clearBuffer=True):
        """Flip the front and back buffers after drawing everything for your frame.
        (This replaces the win.update() method, better reflecting what is happening underneath).

        win.flip(clearBuffer=True)#results in a clear screen after flipping
        win.flip(clearBuffer=False)#the screen is not cleared (so represent the previous screen)
        """
        for thisStim in self._toDraw:
            thisStim.draw()

        

        if haveFB:
            #need blit the frambuffer object to the actual back buffer
            
            FB.glBindFramebufferEXT(FB.GL_FRAMEBUFFER_EXT, 0)#unbind the framebuffer as the render target

            #before flipping need to copy the renderBuffer to the frameBuffer
            '''
            GL.glActiveTexture(GL.GL_TEXTURE0)
            GL.glEnable(GL.GL_TEXTURE_2D)
            GL.glBindTexture(GL.GL_TEXTURE_2D, self.frameTexture)
            GL.glBegin( GL.GL_QUADS )
            GL.glTexCoord2f( 0.0, 0.0 ) ; GL.glVertex2f( -1.0,-1.0 )
            GL.glTexCoord2f( 0.0, 1.0 ) ; GL.glVertex2f( -1.0,1.0 )
            GL.glTexCoord2f( 1.0, 1.0 ) ; GL.glVertex2f( 1.0,1.0 )
            GL.glTexCoord2f( 1.0, 0.0 ) ; GL.glVertex2f( 1.0,-1.0 )
            GL.glEnd()
            '''

            GL.glActiveTexture(GL.GL_TEXTURE0)
            GL.glEnable(GL.GL_TEXTURE_2D)
            GL.glBindTexture(GL.GL_TEXTURE_2D, self.frameTexture)
            GL.glBegin( GL.GL_QUADS )

            GL.glTexCoord2f( 0.0, 0.0 ) ; GL.glVertex3f( -1.0,-1.0, 0.0 )
            GL.glTexCoord2f( 0.0, 1.0 ) ; GL.glVertex3f( -1.0,1.0, 0.0 )
            GL.glTexCoord2f( 1.0, 1.0 ) ; GL.glVertex3f( 1.0,1.0, 0.0 )
            GL.glTexCoord2f( 1.0, 0.0 ) ; GL.glVertex3f( 1.0,-1.0, 0.0 )

            GL.glEnd()
            

        if self.winType =="pyglet":
            #make sure this is current context
            self.winHandle.switch_to()

            GL.glTranslatef(0.0,0.0,-5.0)

            for dispatcher in self._eventDispatchers:
                dispatcher._dispatch_events()
            self.winHandle.dispatch_events()#this might need to be done even more often than once per frame?
            #pyglet.media.dispatch_events()#for sounds to be processed
            self.winHandle.flip()
            #self.winHandle.clear()
            GL.glLoadIdentity()


        #rescale/reposition view of the window
        if self.viewScale != None:
            GL.glMatrixMode(GL.GL_PROJECTION)
            GL.glLoadIdentity()
            GL.glOrtho(-1,1,-1,1,-1,1)
            GL.glScalef(self.viewScale[0], self.viewScale[1], 1)
        if self.viewPos != None:
            GL.glMatrixMode(GL.GL_MODELVIEW)
#            GL.glLoadIdentity()
            if self.viewScale==None: scale=[1,1]
            else: scale=self.viewScale
            norm_rf_pos_x = self.viewPos[0]/scale[0]
            norm_rf_pos_y = self.viewPos[1]/scale[1]
            GL.glTranslatef( norm_rf_pos_x, norm_rf_pos_y, 0.0)
        if self.viewOri != None:
            GL.glRotatef( self.viewOri, 0.0, 0.0, 0.0)

        if haveFB:
            #set rendering back to the framebuffer object
            FB.glBindFramebufferEXT(FB.GL_FRAMEBUFFER_EXT, self.frameBuffer)

        #reset returned buffer for next frame
        if clearBuffer: GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
        else: GL.glClear(GL.GL_DEPTH_BUFFER_BIT)#always clear the depth bit
        self._defDepth=0.0#gets gradually updated through frame

        #waitBlanking
        if self.waitBlanking:
            GL.glBegin(GL.GL_POINTS)
            GL.glColor4f(0,0,0,0)
            if sys.platform=='win32' and self.glVendor.startswith('ati'):
                pass
            else:
                GL.glVertex2i(10,10)#this corrupts text rendering on win with some ATI cards :-(
            GL.glEnd()
            GL.glFlush()

        #get timestamp
        now = logging.defaultClock.getTime()
        if self.recordFrameIntervals:
            self.frames +=1
            deltaT = now - self.lastFrameT
            self.lastFrameT=now
            if self.recordFrameIntervalsJustTurnedOn: #don't do anything
                self.recordFrameIntervalsJustTurnedOn = False
            else: #past the first frame since turned on
              self.frameIntervals.append(deltaT)
              if deltaT > self._refreshThreshold:
                   self.nDroppedFrames+=1
                   if self.nDroppedFrames<reportNDroppedFrames:
                       logging.warning('t of last frame was %.2fms (=1/%i)' %(deltaT*1000, 1/deltaT), t=now)
                   elif self.nDroppedFrames==reportNDroppedFrames:
                       logging.warning("Multiple dropped frames have occurred - I'll stop bothering you about them!")

        #log events
        for logEntry in self._toLog:
            #{'msg':msg,'level':level,'obj':copy.copy(obj)}
            logging.log(msg=logEntry['msg'], level=logEntry['level'], t=now, obj=logEntry['obj'])
        self._toLog = []

        #    If self.waitBlanking is True, then return the time that
        # GL.glFinish() returned, set as the 'now' variable. Otherwise
        # return None as before
        #
        if self.waitBlanking is True:
            return now
Exemple #56
0
# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "Instr"
InstrClock = core.Clock()
Ready = visual.TextStim(win=win, name='Ready',
    text='We have discovered that people\nwere stealing from the vending\nmachines! We have upgraded the\nmachine to make them harder to\nsteal from. However, when the\nmachine is overstocked a free snack \nwill fall out. \n\nThe lights on the front panel\nindicate whether the machine is\noverstocked. Watch the lights and\nlearn which snacks fall out. A\nmultiple choice question will test\nwhat you have learnt. Use the\nkeyboard [a b c d] to indicate the\ncorrect answer.\n\n\n\n\n         press space to begin',
    font='Helvetica Bold',
    pos=[0, 0], height=0.075, wrapWidth=None, ori=0, 
    color='LightGray', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=0.0);
Begin_resp = keyboard.Keyboard()
yellowSize = 0
blueSize = 0
logging.log(level=logging.DATA, msg = "version " + expInfo['version'])

# Initialize components for Routine "ITI"
ITIClock = core.Clock()
vend = visual.PatchStim(
    win=win, name='vend',
    tex='images/vend.png', mask=None,
    ori=0, pos=[0, 0], size=[1.5, 2], sf=None, phase=0.0,
    color=[1,1,1], colorSpace='rgb', opacity=1,
    texRes=512
, interpolate=True, depth=-1.0)

# Initialize components for Routine "trial"
trialClock = core.Clock()
vend_CS = visual.PatchStim(
    win=win, name='vend_CS',
def do_run(run_number, trials):

    timer = core.Clock()

    # 1. add ready screen and wait for trigger
    ready_screen.draw()
    win.flip()
    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()
    
    logging.log(level=logging.DATA, msg='Show Instructions')
    
    while timer.getTime() < instruct_dur:
    #for frame in range(instruct_dur):
        instruction_image.draw()
        instruction_text.draw()
        win.flip()
        


    # 2. fixation disdaqs
    #for frame in range(disdaq_dur):
    #   fixation.draw()
    #   win.flip()

    #######################
    # MAIN LOOP for trials
    # loop over stimuli
    for tidx,trial in enumerate(trials):
        
        logging.log(level=logging.DATA, msg='trial %i' % tidx)
        
        # test for REST trial
        if trial['value']=='REST':
            logging.log(level=logging.DATA, msg='REST BLOCK')
            timer.reset()
            while timer.getTime() < rest_dur:
            #for frame in range(rest_dur):
                fixation.draw()
                win.flip()
            continue
        
        value = trial['value']
        prime_label = trial['message']
        situation = trial['target']
        target = trial['target']

        valueStim.setText(prime_label)
        thinkStim.setText(prime_label)

        # 1. show prime
        
        logging.log(level=logging.DATA, msg='SHOW PRIME - %s' % prime_label)
        trials.addData('prime_onset', globalClock.getTime())

        primeStim.setText(prime_label)
        timer.reset()
        while timer.getTime() < prime_dur:
        #for frame in range(prime_dur):
            primeStim.draw()
            win.flip()

        # 2. show situation
        logging.log(level=logging.DATA, msg='Situation: %s' % situation)
        situationStim.setText(situation)
        timer.reset()
        trials.addData('stim_onset', globalClock.getTime())
        while timer.getTime() < situation_dur:
        #for frame in range(situation_dur):
            situationStim.draw()
            thinkStim.draw()
            win.flip()
        
        event.clearEvents()

        # 3. show rating and get response
        logging.log(level=logging.DATA, msg='Show response')
        trials.addData('resp_onset', globalClock.getTime())
        timer.reset()
        while timer.getTime() < rating_dur:
        #for frame in range(rating_dur):
            situationStim.draw()
            valueStim.draw()
            anchor1.draw()
            anchor4.draw()
            for resp in ratingStim:
                resp.draw()
            win.flip()

            # get key response
            resp = event.getKeys(keyList = buttons)
        
            if len(resp) > 0 : 
                resp_value = button_labels[resp[0]]
                ratingStim[resp_value].setColor('red')
                
                trials.addData('rating', resp_value+1)
                trials.addData('rt', timer.getTime())
        
        # reset rating number color
        for rate in ratingStim:
            rate.setColor('white')
        
        # 4. fixation
        trials.addData('fixation_onset', globalClock.getTime())
        logging.log(level=logging.DATA, msg='Fixation')

        timer.reset()
        while timer.getTime() < fixation_dur:
        #for frame in range(fixation_dur):
            fixation.draw()
            win.flip()
            
            
    # write logs

    # send END log event
    logging.log(level=logging.DATA, msg='******* END Run %i *******' % run_number)

#    log_file.logger.flush()
    
    # save the trial infomation from trial handler
    log_filename2 = "%s_%i.csv" % (log_filename[:-4], run_number )
    trials.saveAsText(log_filename2, delim=',', dataOut=('n', 'all_raw'))

    event.waitKeys(keyList=('space'))
Exemple #58
0
    def presentSound(self, wavfile):
        """
        Play a sound
        
        Parameters
        ----------
        wavfile : str 
            wave file to play (either absolute path or relative to the folder of the python file)
        """
        trialClock = core.Clock()
        wav = sound.Sound(wavfile, secs=-1, stereo=True, hamming=True, name="sound stimulus")
        wav.setVolume(1)
        trialDuration = wav.getDuration()
        keyb = keyboard.Keyboard()

        trialComponents = [wav]    
        self.resetTrialComponents(trialComponents)

        # reset timers
        t = 0
        _timeToFirstFrame = self.win.getFutureFlipTime(clock="now")
        trialClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
        frameN = -1
        continueRoutine = True

        while continueRoutine:
            # get current time
            t = trialClock.getTime()
            tThisFlip = self.win.getFutureFlipTime(clock=trialClock)
            tThisFlipGlobal = self.win.getFutureFlipTime(clock=None)
            frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
            # update/draw components on each frame
            
            if wav.status == NOT_STARTED and t >= 0.0-self.frameTolerance:
                # keep track of start time/frame for later
                wav.frameNStart = frameN  # exact frame index
                wav.tStart = t  # local t and not account for scr refresh
                wav.tStartRefresh = tThisFlipGlobal  # on global time
                wav.play()  # start the sound (it finishes automatically)
            
            # check for fMRI trigger to log
            if checkForFMRITrigger(self):
                logging.log(level = logging.EXP, msg = 'fMRI trigger')
            
            # check for quit (typically the Esc key)
            if self.endExpNow or self.defaultKeyboard.getKeys(keyList=["escape"]):
                core.quit()
            
            if wav.status == FINISHED and tThisFlipGlobal > wav.tStartRefresh + trialDuration-self.frameTolerance:
                continueRoutine = False     
            
            # refresh the screen
            if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
                self.win.flip()

        # -------Ending Routine -------
        wav.stop()  # ensure sound has stopped at end of routine
        self.thisExp.addData('wavfile', wavfile)
        self.thisExp.addData('wav.started', wav.tStart)
        self.thisExp.nextEntry()
        
        self.routineTimer.reset()
fixation = visual.GratingStim(win, color='black', tex=None, mask='circle',size=0.2)
message1 = visual.TextStim(win, pos=[0,+3],text="Memorize each sequence of 4 letters. Then an arrow will indicate whether the ordering is right-to-left or left-to-right. Next you'll see a letter - indicate its number in the given sequence and order.")
message2 = visual.TextStim(win, pos=[0,-3], text="When you're ready to begin, press any key.")

# make sequence text
centerText = visual.TextStim(win,pos=[0,0],text = sequences[0])
# make arrows
line = visual.Line(win,start=(-2,0),end=(2,0),lineColor='black')
leftArrow = visual.Polygon(win,edges=3,radius=0.5,pos=(-2,0),ori=30,lineColor='black',fillColor='black')
rightArrow = visual.Polygon(win,edges=3,radius=0.5,pos=(2,0),ori=-30,lineColor='black',fillColor='black')

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
logging.LogFile((fileName+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='Subject %s, Session %s'%(expInfo['subject'],expInfo['session']))
for i in range(0,len(sequences)):
    logging.log(level=logging.INFO, msg='sequence %d: %s'%(i,sequences[i]))

# ============================ #
# ======= SUBFUNCTIONS ======= #
# ============================ #

def PlaySequence(sequence):
    # get block start time
    tBlock = globalClock.getTime()*1000
    
    #draw fixation dot
    fixation.draw()
    win.logOnFlip(level=logging.EXP, msg='Fixation')
    win.flip()
Exemple #60
0
                          colorSpace='rgb255',
                          autoLog=False)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
### Wait for scanner.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
## Before advancing to task, wait for scanner to
## send TTL pulse. To abort task, hit 'escape' key.

KeyPress, = event.waitKeys(keyList=['equal', 'escape'])
if KeyPress == 'escape': QuitTask()

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
### Task.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
## Run the task. To abort task, hit 'escape' key.

## Initialize logging.
globalClock = core.Clock()
logging.setDefaultClock(globalClock)
logging.LogFile('%s-BREATHHOLD-CONTROL.log' % f,
                level=logging.EXP,
                filemode='w')

## Run task.
for block, sec in zip(blocks, timing):
    block(sec)

## Quit.
logging.log(level=logging.EXP, msg='Done')
QuitTask()