def RunProbes(): # reset clock trialClock.reset() # set up stimuli message1.setText(probe1_string) message2.setText("1) %s\n2) %s\n3) %s\n4) %s\n5) %s" % probe1_options) message1.draw() message2.draw() win.logOnFlip(level=logging.EXP, msg='Probe 1') win.flip() # get response key1 = event.waitKeys(keyList=['1','2','3','4','5','q','Escape'],timeStamped=trialClock) # reset clock trialClock.reset() # set up stimuli message1.setText(probe2_string) message2.setText("1) %s\n2) %s\n3) %s\n4) %s\n5) %s" % probe2_options) message1.draw() message2.draw() win.logOnFlip(level=logging.EXP, msg='Probe 2') win.flip() # get response key2 = event.waitKeys(keyList=['1','2','3','4','5','q','Escape'],timeStamped=trialClock) # return results return (key1[0],key2[0])
def display_message(win, fix, txt, msg): """A function to display text to the experiment window. win: psychopy.visual.Window The window to write the message to. fix: psychopy.visual.Circle The fixation point to be removed from the screen. txt: psychopy.visual.TextStim The text object to present to the screen. msg: String The contents for the text object. """ txt.setText(msg) fix.setAutoDraw(False) txt.setAutoDraw(True) win.flip() event.waitKeys() txt.setAutoDraw(False) fix.setAutoDraw(True) win.flip()
def ShowPicInstruction( txt, duration, picFile, location, col=(0.0, 0.0, 0.0) ): instr = visual.TextStim( win, text=txt, pos=(0,-50), color=col, colorSpace='rgb', height=50 ) pic = visual.ImageStim( win ); pic.setImage( picFile ); h = pic.size picpos = ( 0, h[1]/2 + 20 ) textpos = ( 0, -1* instr.height/2 - 10) pic.setPos( picpos ); pic.draw( win ); instr.setPos( textpos ) instr.draw(win) win.flip() if duration < 0: event.waitKeys() else: core.wait( duration ) win.flip() #clear screen
def _present_choices(self, oleft, oright, trial): """Present the left and the right outcomes, first at the left and second at the right of fixation. After choice_screen_dur fixation cross is colored red for choice_screen_dur2, user has to respond while the cross is red. If user respond before or after then show the slow-down or too-slow message, otherwise color the outcome pressed yellow for remaining duration. Store all the events in dictionary trial, which is an argument to the method. Return value is the key pressed.""" trial['success'] = False # set to True if user responded on time. start_time = time.time() dist = NUMBER_FIXATION_DIST left_outcome = visual.TextStim(self.win, text=u"\u20AC" + str(oleft) , pos=(-dist, 0)) right_outcome = visual.TextStim(self.win, text=u"\u20AC" + str(oright), pos=(dist, 0)) self._render(left_outcome, right_outcome, self.fixation) # wait for choice_screen_dur and check if user presses left or right key try: key = event.waitKeys(maxWait=CHOICE_SCREEN_DUR, keyList=[LEFT_KEY, RIGHT_KEY, ESC_KEY])[0] except: key = "none" #usr responded too early show her slow down message and return if key in [LEFT_KEY, RIGHT_KEY]: trial['slow_down_msg_event'] = time.time() trial['too_fast'] = True self._render(slow_down_msg, duration=SLOW_DOWN_MSG_DUR) return key if key == ESC_KEY: self.win.close() core.quit() # turn the fixation cross red and wait for 1 sec for a user to respond trial['fixation_color_red_event'] = time.time() self.fixation.color = "red" self._render(left_outcome, right_outcome, self.fixation) try: key = event.waitKeys(maxWait=CHOICE_SCREEN_DUR2, keyList=[LEFT_KEY, RIGHT_KEY])[0] trial['key_pressed_event'] = time.time() except: key = "none" self.fixation.color = "black" # user did not responded, show too slow msg and return. if key == "none": trial['too_slow'] = True trial['too_slow_msg_event'] = time.time() self._render(too_slow_msg, duration=TOO_SLOW_MSG_DUR) return key #show the pressed key in yellow for the remaining time. if key == LEFT_KEY: left_outcome.color = "yellow" elif key == RIGHT_KEY: right_outcome.color = "yellow" self._render(left_outcome, right_outcome, self.fixation) time_elasped = time.time() - start_time core.wait(CHOICE_SCREEN_DUR + CHOICE_SCREEN_DUR2 - time_elasped) return key
def run_main_experiment(): time_start = core.getTime() time_play = time_start order = Exp.make_random_stim_order() Nonethird = np.floor(len(order)/3) Ntwothird = np.floor(2*len(order)/3) t = 0 for i in order: t = t+1 print(core.getTime() -time_start) if t in [Nonethird,Ntwothird]: set_msg('Short Break!','MAIN') set_msg('Press return to continue','KEY') win.flip() event.waitKeys(keyList=['return','space']) core.wait(1) s = sound_build.make_noisy_stim(i,Exp) scaled = np.int16(s/np.max(np.abs(s)) * 32767) write('test.wav', 44100, scaled) core.wait(time_play - core.getTime()) set_msg('Up or down?','MAIN') win.flip() playsound(s,vol) core.wait(0.1) #core.wait(0.5) #wait 500ms; but use a loop of x frames for more accurate timing in fullscreen thisResp = get_response() iscorrect = Exp.isRespCorrect(i,thisResp) # 1=correct, O=incorrect, -1=missed time_play = core.getTime() + iti dataFile.write('%i,%i,%i\n' %(i, thisResp,iscorrect)) dataFile.close()
def display_instructions(): set_msg('INTRODUCTION','TITLE') set_msg('AXB control','MAIN') set_msg('Press any key to continue','KEY') win.flip() core.wait(0.5) event.waitKeys()
def RunProbes(): # reset clock trialClock.reset() # set up stimuli message1.setText(probe1_string) message2.setText("1) %s\n2) %s\n3) %s\n4) %s\n5) %s" % probe1_options) message1.draw() message2.draw() win.logOnFlip(level=logging.EXP, msg="Probe 1") win.flip() # get response key1 = event.waitKeys(keyList=["1", "2", "3", "4", "5", "q", "Escape"], timeStamped=trialClock) # reset clock trialClock.reset() # set up stimuli message1.setText(probe2_string) message2.setText("1) %s\n2) %s\n3) %s\n4) %s\n5) %s" % probe2_options) message1.draw() message2.draw() win.logOnFlip(level=logging.EXP, msg="Probe 2") win.flip() # get response key2 = event.waitKeys(keyList=["1", "2", "3", "4", "5", "q", "Escape"], timeStamped=trialClock) # return results return (key1[0], key2[0])
def main(): data = {'start_time': timestamp()} data['play'] = True try: data['id'] = dialog_box()[0] except: return None win = visual.Window([800, 600], allowGUI=True, units='deg', color = "grey",fullscr=FULLSCREEN, monitor="testMonitor") dominant_stimulie = get_dominant_stimulie(data['id']) choices = random_choices4play(data['id'], NPLAY) blocks = [Visual(win, dominant_stimulie[0], choices["Visual"]), Auditory(win, dominant_stimulie[1], choices["Auditory"]), Semantic(win, dominant_stimulie[1], choices["Semantic"])] data['choices'] = choices data['total_win'] = 0 for block in blocks: corrects = block.play() for i in range(0, len(corrects)): if corrects[i]: data['total_win'] += choices[str(block)][i]['amount'] data['choices'][str(block)][i]['correctp'] = corrects[i] data['finish_time'] = timestamp() save_data(data) txt = u"You win 10 percent of \u20AC %s."%data['total_win'] visual.TextStim(win, text=txt, pos=(0,0)).draw() win.flip() event.waitKeys()
def pause(self): """ Pause block """ event.clearEvents() self.win.flip() event.waitKeys()
def _show_instructions(self): instructions = self.version['instructions'] for page in instructions['pages']: self.stim['text'].setText(instructions['text'][page]) self.stim['text'].draw() if page == 2: self.pics_left['donkey.bmp'].setOri(180.0) self.pics_left['donkey.bmp'].draw() self.pics_right['donkey.bmp'].draw() advance_keys = ['j',] elif page == 3: self.pics_right['piano.bmp'].setOri(180.0) self.pics_right['piano.bmp'].draw() self.pics_left['piano.bmp'].draw() advance_keys = ['f',] elif page == 4: self.mask_left.draw() self.mask_right.draw() advance_keys = ['space',] else: advance_keys = ['space',] self.win.flip() event.waitKeys(keyList = advance_keys)
def instrDraw(path): jpgList = os.listdir(path) for JPG in jpgList: ins = visual.ImageStim(win, image=path + JPG) ins.draw() win.flip() event.waitKeys()
def playclip(stimpath, stim): fixation() core.wait(0.3) #pparallel.setData(0) # sets all pin lo clip = visual.MovieStim(win=win, name= 'clip', filename= stimpath + stim, size = [800, 450], ori =0, pos=[0,0], opacity =1, depth = -1.0 ) pparallel.setData(trigger_stim) # sets all pin lo core.wait(0.005) pparallel.setData(0) stimOnset= trialClock.getTime() while clip.status != visual.FINISHED: clip.draw() win.flip() fixation() # get key press at the end of clip event.waitKeys(keyList=keyStop) respTime= trialClock.getTime() #mouse.clickReset() #button, time = mouse.getPressed(getTime=True) #print('mouse: ', button) #event.waitKeys(keyList= button) trials.addData('stimOnset', stimOnset) trials.addData('respTime',respTime)
def _show_instructions(self): instructions = self.version["instructions"] for page in instructions["pages"]: self.stim["text"].setText(instructions["text"][page]) self.stim["text"].draw() if page == 2: self.pics_left["donkey.bmp"].setOri(180.0) self.pics_left["donkey.bmp"].draw() self.pics_right["donkey.bmp"].draw() advance_keys = ["j"] elif page == 3: self.pics_right["piano.bmp"].setOri(180.0) self.pics_right["piano.bmp"].draw() self.pics_left["piano.bmp"].draw() advance_keys = ["f"] elif page == 4: self.mask_left.draw() self.mask_right.draw() advance_keys = ["space"] else: advance_keys = ["space"] self.win.flip() event.waitKeys(keyList=advance_keys)
def showpix(stimpath, stim, duration): fixation() pix = visual.ImageStim(win =win, image = stimpath + stim, pos = [0,0], size = [800, 450], opacity = 1, units = 'pix' ) pix.draw() # win.logOnFlip('parallel port trigger picture: %d' %trigger_stim , level=logging.EXP) win.flip() stimOnset= trialClock.getTime() pparallel.setData(0) # sets all pin lo pparallel.setData(trigger_stim) # sets all pin lo core.wait(0.005) pparallel.setData(0) core.wait(duration) #mouse.getPressed() fixation() # get key press at the end of clip event.waitKeys(keyList=keyStop) respTime= trialClock.getTime() trials.addData('stimOnset', stimOnset) trials.addData('respTime',respTime)
def nPaired (fi, nback_no, window, seq, dura, trial_no=None, adaptive=False): #data structures audicode=['C','D','E','F'] colorcode=['red','blue','green','yellow'] trial_no=len(seq) ready=visual.TextStim(window,'ready?', color=(1.0,1.0,1.0)) infoloop=['Press return/enter to continue', 'This is the paired 2-back test', 'You will see a series that contains both audio tones and coloured squares together', 'In this test, the same colour/tone pair is always presented together', 'Press L if the colour/tone pair matches the pair two steps back'] vstimlist=[];astimlist=[] target=[0,0] n=0 #create two stimuli lists and mark down target trials for i in seq: vstimlist.append(visual.Rect(window,width=100.0,height=100.0,lineColor=colorcode[i],fillColor=colorcode[i], pos=(0,0))) astimlist.append(sound.Sound(audicode[i],octave=4, sampleRate=44100, secs=dura,bits=8)) if n > nback_no-1: #if the event match with n events ago (n specified by 'nback_no') #mark it as a target trial if i==seq[n-nback_no]: target.append(1) else: target.append(0) n = n+1 infolooper(infoloop,window) #present basic test info for participant (what test, etc) ready.draw() window.flip() event.waitKeys(keyList=['return']) n=0 #play/draw stimuli and record response time for vtrial in vstimlist: response=None; hit=None; time=None vtrial.draw() astimlist[n].play() starttime=window.flip() #each stimulus is displayed for the duration specified response=event.waitKeys(maxWait=dura-(1/120.0),keyList=['l'],timeStamped=True) while(logging.defaultClock.getTime() - starttime) <= dura: pass if response!=None: if target[n]==1: #if target trials and get keypress, set 'hit' to true hit=True else: #if not target trials but get keypress, set 'hit' to false hit=False time=response[0][1]-starttime #record RT for any keypress window.flip() #output includes: condition, trial number, whether it's target, whether a hit, RT fi.writerow(['%s, %d, %s, %s, %s\n'%('paired', n+1, str(target[n]==1), str(hit), str(time))]) n = n+1 core.wait(0.5) #fi.writerow(['Testing sequence ', seq]) fi.writerow([])
def show_message_page(self, window, message, duration=2, block=False, release_key=None): visual.TextStim(win=window, text=message, pos=(0, 0), color='White').draw() window.update() if block: event.waitKeys(keyList=None if release_key is None else [release_key]) else: core.wait(duration)
def dummynote(self): # Draw Text visual.TextStim(self.window, text='Dummy Connection with EyeLink', color=self.txtcol).draw() self.window.flip() # Wait for key press event.waitKeys() self.window.flip()
def textscreen(text, win=stim['window'], exp=exp, auto=False): visual.TextStim(win, text=text, units='norm').draw() # fix window blendMode: win.blendMode = 'add' win.flip() if not auto: event.waitKeys() else: core.wait(0.1)
def endExp(): endtxt = open('Instructions\\end_instr.txt', 'r').read().split('#\n')[0] msgTxt.setText(endtxt) msgTxt.draw() win.flip() event.waitKeys(maxWait = 20) logging.flush() win.close() core.quit()
def send(self, txt, wait=False): print txt #if wait == True: #txt += "\nPress a key to continue." self.txt.setText(txt) self.txt.draw() self.win.flip() if wait == True: event.waitKeys()
def wait_for_key(keys): '''Wait for a key that is in a set of keys to be pressed before proceeding. Args: keys - A list or tuple of keys. ''' event.clearEvents() event.waitKeys(keyList=keys)
def break_checker(window, exp, df, exp_info, logfile, current_trial, qp_refresh_rate=3, plot_fun=None, plot_arg=None, dpi=120, img_name='temp.png', df_save_path='temp.xlsx', show_completed=False, show_correctness=False, use_forced_break=False): has_break = current_trial % exp['break after'] == 0 has_forced_break = current_trial == 214 or current_trial == 428 if has_break: save_df = trim_df(df) save_df.to_excel(df_save_path) if use_forced_break and has_forced_break: forced_break(win=window, auto=exp['debug'], exp_info=exp_info) if has_break or (has_forced_break and use_forced_break): # remind about the button press mappings show_resp_rules(exp=exp, auto=exp['debug']) if not show_completed: window.flip() if show_completed and (has_break or (has_forced_break and use_forced_break)): if show_correctness: upper_steps = df.query('step > 2') avg_corr = upper_steps.ifcorrect.mean() * 100 present_break(current_trial, exp=exp, win=window, auto=exp['debug'], correctness=avg_corr) else: present_break(current_trial, exp=exp, win=window, auto=exp['debug']) window.flip() if not exp['two screens']: # make sure feedback is only shown after the break on one screen qp_refresh_rate = 10000 # visual feedback on parameters probability if current_trial % qp_refresh_rate == 0 or has_break: try: fig = plot_fun(plot_arg) fig.savefig(img_name, dpi=dpi) plt.close(fig) window.winHandle.activate() except: pass if not exp['two screens']: win.blendMode = 'avg' exp_info.experimenter_plot(img_name) if not exp['two screens']: event.waitKeys(['f', 'j', 'space', 'return']) win.blendMode = 'add' # quest plus refresh adds ~ 1 s to ITI so we prefer that # it is not predictable when refresh is going to happen return sample([3, 4, 5], 1)[0] return qp_refresh_rate
def pause(text): pauseTS = visual.TextStim(win, text, height=th) pauseTS.draw() win.flip() core.wait(1) pauseTS.draw() visual.TextStim(win, 'Weiter mit beliebiger Taste ...', pos=(0, -200), height=th, wrapWidth=ww).draw() win.flip() event.waitKeys()
def display_break(self): message1 = visual.TextStim(self.win, wrapWidth=30, pos=[0,2], text='Take a short break') message2 = visual.TextStim(self.win, pos=[0,0],text='Hit any key when ready.') for f in range(self.break_duration_frames): message1.draw() self.win.flip() message1.draw() message2.draw() self.win.flip() event.waitKeys()
def Run(self): # the following will loop through the instructionText array for i in range(len(self.instructionText)): self.instructions.setText(self.instructionText[i]) self.instructions.draw() if(i < len(self.instructionText) - 1): self.cont.draw() self.win.flip() #to show our newly drawn 'stimuli' event.waitKeys()
def ShowInstruction( txt, duration, col=(0.0, 0.0, 0.0) ): instr = visual.TextStim( win, text=txt, pos=(0,0), color=col, colorSpace='rgb', height=50 ) instr.draw(win) win.flip() if duration < 0: event.waitKeys() else: core.wait( duration ) win.flip() # clear screen
def vNback (fi, nback_no, window, seq, dura, trial_no=None, adaptive=False): #visual nback test #data structures colorcode=['red','blue','green','yellow'] trial_no=len(seq) ready=visual.TextStim(window,'ready?', color=(1.0,1.0,1.0)) infoloop=['Press return/enter to continue', 'This is the visual 2-back test', 'You will see a series of coloured squares', 'Press L if the colour of a square matches the colour of a square two steps back'] stimlist=[] target=[0,0] n=0 #create stimuli list and mark down target trials for i in seq: #create stimuli based on the sequence passed in function argument stimlist.append(visual.Rect(window,width=100.0,height=100.0,lineColor=colorcode[i],fillColor=colorcode[i], pos=(0,0))) if n > nback_no-1: #if the event match with the one n events ago (n specified by 'nback_no') #mark it as a target trial if i==seq[n-nback_no]: target.append(1) else: target.append(0) n = n+1 infolooper(infoloop,window) #present basic test info for participant (what test, etc) ready.draw() window.flip() event.waitKeys(keyList=['return']) n=0 #draw stimuli and record response time for trial in stimlist: response=None; hit=None; time=None trial.draw() starttime=window.flip() #each stimulus is presented for the duration specified response=event.waitKeys(maxWait=dura-(1/120.0),keyList=['l'],timeStamped=True) while(logging.defaultClock.getTime() - starttime) <= dura: pass #RT will be recorded despite of trail types if response!=None: if target[n]==1: #if target trials abd get keypress, set 'hit' to true hit=True else: #if not target trials but get keypress, set 'hit' to false hit=False time=response[0][1]-starttime #record RT for any keypress #output includes: condition, trial number, whether it's target, whether a hit, RT fi.writerow(['%s, %d, %s, %s, %s\n'%('visual', n+1, str(target[n]==1), str(hit), str(time))]) n = n+1 window.flip() core.wait(0.3) #fi.writerow(['Testing sequence: ', seq]) fi.writerow([])
def recall(myClock, stimuli_list, expInfo, f): fixation.pos = (-300,250) continueTest = True attempt = 0 acc = 0 if expInfo['conditions'] == 'encoding': def saveResp(f, attempt, i, thisTrial, expInfo, resp): write_datalog(f, data='%i,%i,%s,%s,%s,%i,%f,%s,%s\n' %(attempt, i, thisTrial[0], thisTrial[1], resp[0], resp[1], resp[2], expInfo['subject'],expInfo['session'])) event.clearEvents() else: def saveResp(f, attempt, i, thisTrial, expInfo, resp): write_datalog(f, data='%i,%i,%s,%s,%s,%i,%f,%s,%f,%s,%s\n' %(attempt, i, thisTrial[0], thisTrial[1], resp[0], resp[1], resp[2], resp[3], resp[4], expInfo['subject'],expInfo['session'])) event.clearEvents() attempts = 3 while continueTest and acc < 70: countCORR = [] acc = 0 attempt +=1 shuffle(stimuli_list) for i, thisTrial in enumerate(stimuli_list): if i==21: msgTxt.setText('You are half way through this task, if you wish you may take a short break.\n\nPess SPACE to continue.') msgTxt.draw() win.flip() event.waitKeys(keyList=['space']) resp = ans_screen(myClock, thisTrial, expInfo['conditions'], question_length=12) else: resp = ans_screen(myClock, thisTrial, expInfo['conditions'], question_length=12) countCORR.append(resp[1]) saveResp(f, attempt, i, thisTrial, expInfo, resp) acc = float(sum(countCORR)) / float(len(countCORR)) * 100 write_datalog(f, data='%i,%s,%s,%s,%s,%i\n' %(attempt, 'accuracy', '', '', '', acc)) if expInfo['conditions'] == 'encoding': if acc >= 70 or attempt == 3: block_end(acc, attempts) continueTest = False else: attempts -= 1 block_end(acc, attempts) continueTest = True else: # expInfo['conditions'] == 'delayed' continueTest = False
def displaymessage(messages = "you didn't give a message for me to display!"): #""" This function displays a message in a small window. The message must be formatted as a list or single string""" # Load psychopy modules from psychopy import visual, event, core win = visual.Window(size=[500, 500]) text = visual.TextStim(win) # Messages welcome = 'hi and welcome to this experiment' print(welcome) instruction = 'really, there\'s not much to do. We just show a bunch of messages. Press RETURN to continue.' thanks = 'thank you and goodbye. We hope you enjoyed!' # Show welcome message text.setText(welcome) # set text text.draw() # prepare to show it win.flip() # actually show it response = event.waitKeys(keyList=None) # accepts all keys if response[0] == 'q': # response[0] is the name of the first pressed key core.quit() # quit if 'q' was pressed # Show instruction text.setText(instruction) text.draw() win.flip() response = event.waitKeys(keyList=['return', 'q']) # listen for return and q only if response[0] == 'q': core.quit() if type(messages) == str: text.setText(messages) text.draw() win.flip() response = event.waitKeys(keyList=None) # accepts all keys if response[0] == 'q': core.quit() elif type(messages) == list: for count in range(len(messages)): text.setText(messages[count]) text.draw() win.flip() response = event.waitKeys(keyList=None) # accepts all keys if response[0] == 'q': core.quit() else: print('messages is neither a list nor a string!') # Show debriefing text.setText(thanks) text.draw() win.flip() response = event.waitKeys(keyList=None) # accepts all keys if response[0] == 'q': core.quit()
def aNback (fi, nback_no, window, seq, dura, trial_no=None, adaptive=False): #data structures audicode=['C','D','E','F'] trial_no=len(seq) ready=visual.TextStim(window,'ready?', color=(1.0,1.0,1.0)) cross=visual.TextStim(window,'+',color='white') infoloop=['Press return/enter to continue', 'This is the auditory 2-back test', 'You will see a series of audio tones', 'Press L if the tone played matches the tone two steps back'] stimlist=[] target=[0,0] n=0 #create stimuli list and mark down target trials for i in seq: stimlist.append(sound.Sound(audicode[i],octave=4, sampleRate=44100, secs=dura,bits=8)) if n > nback_no-1: #if the event match with the one n events ago (n specified by argument 'nback_no') #mark it as a target trial if i==seq[n-nback_no]: target.append(1) else: target.append(0) n = n+1 infolooper(infoloop,window) #present basic test info for participant (what test, etc) ready.draw() window.flip() event.waitKeys(keyList=['return']) n=0 #play stimuli and record response time for trial in stimlist: response=None; hit=None; time=None cross.draw() trial.play() starttime=window.flip() #each stimulus is played for the duration specified response=event.waitKeys(maxWait=dura-(1/120.0),keyList=['l'],timeStamped=True) while(logging.defaultClock.getTime() - starttime) <= dura: pass if response!=None: if target[n]==1: #if target trials abd get keypress, set 'hit' to true hit=True else: #if not target trials but get keypress, set 'hit' to false hit=False time=response[0][1]-starttime #record RT for any keypress #output includes: condition, trial number, whether it's target, whether a hit, RT fi.writerow(['%s, %d, %s, %s, %s\n'%('auditory', n+1, str(target[n]==1), str(hit), str(time))]) n = n+1 window.flip() core.wait(0.5) #fi.writerow(['Testing sequence ', seq]) fi.writerow([])
##################### Instructions ############################### instructionMsg = visual.TextStim( winSub, pos=[0, 0], text= 'For each image, type the name of the the object then press enter. \n\nIf you can\'t name it, press enter. \n\nPress any key to begin.' ) instructionMsg.units = 'deg' instructionMsg.height = .5 instructionMsg.draw() winSub.flip() thisKey = None while thisKey == None: thisKey = event.waitKeys() if thisKey in quitKeys: core.quit() else: event.clearEvents() thisName = visual.TextStim(winSub, pos=[0, -200], units='pix', height=25) ################ set up task timers ############################ scanTimer = core.Clock() startTime = scanTimer.getTime() trialTimer = core.Clock() trialTime = trialTimer.getTime() imageTimer = core.Clock() responseTimer = core.Clock() ################# loop through the images #######################
#%% your loop here # start by copying your one trial here, then identify what needs to be # changed on every trial. Likely your stimuli, but you might want to change a few things # maybe start by making stimulus objects (e.g. myPic = visual.ImageStim(...)) baseInstructions = visual.TextStim(win, alignHoriz = 'center', height = .03, text='You will see a series of images and are required to make a judgement on them.\n\nSome of these items will be partially obsured. Do your best to make your judgements') myInstructions = visual.ImageStim(win, size = None, pos = (0,0), image ='indoor_instructions.jpg') endInstructions = visual.TextStim(win, alignHoriz = 'center', height = .03, text='Thanks for playing') # make a list or a pd.DataFrame that contains trial-specific info (stimulus, etc) # e.g. stim = ['1.jpg','2.jpg','3.jpg'] stim = ['001a.jpg', '002a.jpg', '003a.jpg'] #display instructions until a key is pressed baseInstructions.draw() win.flip() event.waitKeys() myInstructions.draw() win.flip() event.waitKeys() # make your loop for t in stim : #clear events event.clearEvents() # include your trial code in your loop but replace anything that should # change on each trial with a variable that uses your iterater # e.g. thisStimName = stim[t] # thisStim = visual.ImageStim(win, image=thisStimName ...)
[(6,10),(14,2),(2,14),(6,10),(14,2),(2,14)], [(14,2),(2,14),(6,10),(14,2),(2,14),(6,10)], [(2,14),(14,2),(6,10),(2,14),(14,2),(6,10)], [(6,10),(2,14),(14,2),(6,10),(2,14),(14,2)], [(14,2),(6,10),(2,14),(14,2),(6,10),(2,14)]] ### selected block order from initial dialogue input blockOrder = blockOrder[int(expInfo['order'])] rewardOrder = [4,4,8,8,20,20] ##----------------------- Begin experiment --------------------------------- # initial window, waits for input to begin the experiment start = visual.TextStim(win, text='Let go of the grip if you want to quit a trial \n\n'+'Press ENTER to begin',height=0.05) start.draw() win.flip() event.waitKeys(keyList=['return']) globalClock.reset() # to track the time since experiment started ##----------------------- Overall condition loop --------------------------- # start LabJack #if LabJack != 0: # LabJack.streamStart() # streamObj = LabJack.streamData() # wtw.handgrip.startBlockSignal(LabJack) #else: # streamObj = False # #if handgripNeeded: # hgQueue = Queue.LifoQueue() # create a queue
thisComponent.status = NOT_STARTED #-------Start Routine "Block"------- continueRoutine = True while continueRoutine and routineTimer.getTime() > 0: # get current time t = BlockClock.getTime() frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *image_2* updates image_2.setAutoDraw(True) win.flip() RTclock.reset() event.clearEvents(eventType='keyboard') theseKeys = event.waitKeys(max_rt, ('h', 'j', 'k', 'l'), timeStamped=RTclock) if theseKeys is None: key_response.corr = 0 key_response.keys = None key_response.rt = float('nan') Wrong_1.setAutoDraw(True) win.flip() core.wait(0.1) continueRoutine = False elif (len(theseKeys[0]) > 0): key_response.keys = theseKeys[0][ 0] # just the last key pressed key_response.rt = theseKeys[0][1] # was this 'correct'?
def main_experiment(): ## ################ Setup Streams #################### # Create trigger stream: # create LSL trigger outlet info_marker_stream = StreamInfo('PsychoPyMarkers', 'Marker', 1, 0, 'string') global out_marker out_marker = StreamOutlet(info_marker_stream) # create LSL arduino outlet global SerialArduino, SerialSRate SerialArduino = serial.Serial(port='COM4', baudrate=115200) SerialSRate = 80 # set LSL outlet for load cell global lc_out, clr_buf lc_out = InitLslArduino() clr_buf = 20 # setup TCP to PD global s_pitch, s_vol s_pitch = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s_pitch.connect(('localhost', 1002)) s_vol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s_vol.connect(('localhost', 1003)) ## ################ Get Max Force ################## global max_force chunk_ = [] max_force = [] max_force = input("What was the max force from the beginning:\n") max_force = int(max_force) print("Max force is {} Unit".format(max_force)) input("Start LabRecorder, press any key to continue") out_marker.push_sample(['max_force_{}'.format(max_force)]) # output to lsl ## ################ Setup Psychopy #################### # Set window and remove mouse during experiment: win_size = (1920, 1080) global win win = visual.Window(size=win_size, fullscr=True, allowGUI=False, monitor='testMonitor', units='norm', color=[-1, -1, -1]) # Experimental settings global design_mat, trial_num trial_num = 40 design_mat, trial_num = SetTrialDist(trial_num) global dur_hint, dur_bl, dur_fc, dur_trial dur_hint = 1 dur_bl = 1.5 dur_fc = (10, 15) # in deci seconds dur_trial = 6 # total 1 + 1.5 + 1.25 + 6 = 9.75 s per trial (40 trials -> 6,5 min) # stimulus settings global wdth_bar, hght_bar, scaling_factor, tar_pos, c_red, c_green wdth_bar = 0.01 hght_bar = 1 scaling_factor = 1 tar_pos = 0 # change scaling factor if different arduino setup c_red = [115, 38, 38] ## ################ Stimuli Psychopy ################# ## intro global exp_text exp_text = visual.TextStim(win, pos=[0, 0], color=(1, 1, 1)) ## main trial components global fixation fixation = visual.TextStim(win, pos=[0, 0], text='+', height=0.7, color=(0, 0, 0)) global bar_target bar_target = visual.Rect( win, width=wdth_bar, height=hght_bar + 4 * wdth_bar, pos=[tar_pos, 0], fillColor='grey', lineColor='black', ) global bar_force bar_force = visual.Rect(win, width=wdth_bar * 4, height=hght_bar, pos=[0, 0], fillColor=c_red, lineColor=c_red, fillColorSpace='rgb255', lineColorSpace='rgb255', autoDraw=False) #Set timer global timer timer = core.Clock() # init some vars for passive condition global ArdBuff, TrialBuff ArdBuff = [] TrialBuff = [None] * len(design_mat) #################### TRAINING BLOCK ################################### # INTRO num_training = 5 txt = "Trainingsblock Audio" presTextPsychoPy(txt) event.waitKeys() out_marker.push_sample(['block0']) # output to lsl txt = "Das auditive Feedback ändert sich. Passen Sie nun die Tonhöhe über den Druck an." presTextPsychoPy(txt) event.waitKeys() for i in range(num_training): presTrialVisAud(i) audio_train = True while audio_train: # explain task 2 repeat if nesecary event.clearEvents() txt = "Jetzt nur mit Ton." presTextPsychoPy(txt) event.waitKeys() for i in range(num_training): presTrialAud(i) txt = "Auditive Bedingung verstanden? Drücke r zum Wiederholen und c zum Fortsetzen" presTextPsychoPy(txt) key = event.waitKeys() if key == ['r']: audio_train = True elif key == ['c']: audio_train = False #################### BLOCK 1 ################################### # INTRO event.clearEvents() txt = "Block 1 (ca 6 min)" presTextPsychoPy(txt) event.waitKeys() out_marker.push_sample(['block1']) # output to lsl # explain task 1 txt = "Steuern Sie das Ziel so schnell wie möglich an." presTextPsychoPy(txt) event.waitKeys() for i in range(trial_num * 0, trial_num * 1 - 1): if design_mat[i, 1] == 1: presTrialVis(i) if design_mat[i, 1] == 2: presTrialVisAud(i) if design_mat[i, 1] == 3: presTrialAud(i) # end task 1 txt = "Geschafft" presTextPsychoPy(txt) event.waitKeys() #################### BLOCK 2 ################################### # INTRO txt = "Block 2 (ca 6 min)" presTextPsychoPy(txt) event.waitKeys() out_marker.push_sample(['block2']) # output to lsl # explain task 1 txt = "Steuern Sie das Ziel so schnell wie möglich an." presTextPsychoPy(txt) event.waitKeys() for i in range(trial_num * 1, trial_num * 2 - 1): if design_mat[i, 1] == 1: presTrialVis(i) if design_mat[i, 1] == 2: presTrialVisAud(i) if design_mat[i, 1] == 3: presTrialAud(i) # end task 1 txt = "Geschafft" presTextPsychoPy(txt) event.waitKeys() ## ################ FINISH UP #################### # Cleanup (always!) win.close() core.quit() print("DONE")
fullscr=True, waitBlanking=True, monitor='testMonitor', units='pix') # Create window # Open log file to write file_name = exp_info['participant'] + '_parity.csv' log_file = open(file_name, 'a') log_file.write('participant, task, stimulus, response, RT\n') # Heading # Instruction text_instruction = visual.TextStim( win, pos=[0, 0], text=texts['instr'][exp_info['language']]) # Text object text_instruction.draw() win.flip() # draw the instruction event.waitKeys() # wait for key press to continue # Experiment text_stimulus = visual.TextStim(win, pos=[0, 0], text='dummy') # Text object trial_clock = core.Clock() # Clock for measuring response time for stim in stims: # Example trial text_stimulus.setText(stim) text_stimulus.draw() win.flip() # draw the prepared window trial_clock.reset() # start measuring reaction time response = event.waitKeys()[0] # response RT = trial_clock.getTime() # store reaction time if response == 'escape': # stops experiment if esc is pressed core.quit() event.clearEvents()
height=None, color='black', text='Right Key = likely') instruct_trialbottomleft = visual.TextStim(win, pos=(-0.5, -0.75), height=None, color='black', text='Left Key = unlikely') #trial image stimulus yesno = visual.ImageStim(win, size=(1, 1), pos=(0, 0), image='pics/yes1.png') #draw all trial stimuli instruct_trialtop.draw() instruct_trialbottomright.draw() instruct_trialbottomleft.draw() yesno.draw() # then flip your window win.flip() # then record your responses leys = event.waitKeys(keyList=['right', 'left']) print(keys) #%% Required clean up # this cell will make sure that your window displays for a while and then # closes properly core.wait(2) win.close()
def run_session(self): path = os.path.join(self.res_dir, self.subject) if not os.path.exists(path): os.makedirs(path) psydat_path = os.path.join(path, 'psydat') if not os.path.exists(psydat_path): os.makedirs(psydat_path) # welcome msg = visual.TextStim(self.win, 'Welcome!' + '\n' + ' Press any key to start this session :)', color='black', units='deg', pos=(0, 0), height=0.8) msg.draw() self.win.mouseVisible = False self.win.flip() event.waitKeys() # read staircase parameters conditions = [ dict({'stimulus': key}, **value) for key, value in self.param.items() if key.startswith('stimulus') ] if conditions[0]['stairType'] == 'constant': stimuli = [] rot_all_disp = [] judge_all = [] for cond in conditions: for diff in np.linspace(cond['minVal'], 0, 3, endpoint=False): stimuli.append({'cond': cond, 'diff': diff}) for diff in np.linspace(0, cond['maxVal'], 3, endpoint=False): stimuli.append({'cond': cond, 'diff': diff}) stimuli.append({'cond': cond, 'diff': 0}) repeats_nmb = 20 stairs = data.TrialHandler(stimuli, repeats_nmb, method='random') else: sys.exit("The stimuli are not constant!") # write configuration files xpp = config_tools.WriteXpp(self.subject, self.idx) xpp_file = xpp.head(self.cfg_file, self.par_file) config_tools.write_xrl(self.subject, cfg_file=self.cfg_file, par_file=self.par_file, xpp_file=xpp_file) xlsname = path + '/' + self.idx + self.param[ 'noise_condition'] + '.xlsx' """ running staircase """ if isinstance(stairs, data.TrialHandler): count = 0 results = {cond['label']: [] for cond in conditions} for trial in stairs: count += 1 judge, react_time, trial_time_start = self.run_trial( trial['diff'], trial['cond'], count) valid_theta = np.round(np.load(self.hue_list), decimals=1) disp_standard = self.take_closest(valid_theta, cond['standard']) stair_test = cond['standard'] + trial['diff'] if stair_test < 0: stair_test += 360 disp_test = self.take_closest(valid_theta, stair_test) disp_intensity = disp_test - disp_standard if disp_intensity > 300: disp_intensity = (disp_test + disp_standard) - 360 xpp.task(count, cond, cond['diff'], float(disp_intensity), judge, react_time, trial_time_start) results[trial['label']].append((trial['diff'], judge)) if 'escape' in event.waitKeys(): config_tools.write_xrl(self.subject, break_info='userbreak') core.quit() config_tools.write_xrl(self.subject, xls_file=xlsname) # save results in xls-file workbook = xlsxwriter.Workbook(xlsname) for res_label, res_data in results.items(): worksheet = workbook.add_worksheet( cur_handler.extraInfo['label']) worksheet.write('A1', 'Reversal Intensities') worksheet.write('B1', 'Reversal Indices') worksheet.write('C1', 'All Intensities') worksheet.write('D1', 'All Responses') for i, (res_diff, res_resp) in enumerate(res_data): worksheet.write('C' + str(i + 2), res_diff) worksheet.write('D' + str(i + 2), res_resp) workbook.close() if isinstance(stairs, data.MultiStairHandler): # start running the staircase using the MultiStairHandler for the up-down method count = 0 for rot, cond in stairs: count += 1 direction = (-1)**(cond['label'].endswith('m') ) # direction as -1 if for minus stim rot = rot * direction # rotation for this trial judge, react_time, trial_time_start = self.run_trial( rot, cond, count) # check whether the theta is valid - if not, the rotation given by staircase should be corrected by # realizable values valid_theta = np.round(np.load(self.hue_list), decimals=1) disp_standard = self.take_closest( valid_theta, cond['standard']) # theta actually displayed stair_test = cond[ 'standard'] + stairs._nextIntensity * direction if stair_test < 0: stair_test += 360 disp_test = self.take_closest(valid_theta, stair_test) disp_intensity = disp_test - disp_standard if disp_intensity > 300: disp_intensity = (disp_test + disp_standard) - 360 stairs.addResponse(judge, abs(disp_intensity)) xpp.task(count, cond, rot, float(disp_intensity), judge, react_time, trial_time_start) if 'escape' in event.waitKeys(): config_tools.write_xrl(self.subject, break_info='userbreak') core.quit() config_tools.write_xrl(self.subject, xls_file=xlsname) stairs.saveAsExcel(xlsname) # save results misc.toFile( os.path.join( psydat_path, self.idx + self.param['noise_condition'] + '.psydat'), stairs) elif isinstance(stairs, list): # start running the staircase using custom interleaving stairs for the quest and psi methods count = 0 rot_all = [] rot_all_disp = [] judge_all = [] estimates = {s.extraInfo['label']: [] for s in stairs} for trial_n in range(self.trial_nmb): for handler_idx, cur_handler in enumerate(stairs): count += 1 direction = (-1)**( cur_handler.extraInfo['label'].endswith('m') ) # direction as -1 if for minus stim if cur_handler._nextIntensity >= 10.0: sys.exit( "Hue difference is out of range! Please enlarge the testing range or take more training!" ) rot = cur_handler._nextIntensity * direction # rotation for this trial if trial_n >= 5: # avoid repeating an intensity more than 3 times last_rots = [ np.round(r, decimals=1) for r in [ rot_all_disp[handler_idx][trial_n - 1], rot_all_disp[handler_idx][trial_n - 2], rot_all_disp[handler_idx][trial_n - 3] ] ] last_resp = [ judge_all[handler_idx][trial_n - 1], judge_all[handler_idx][trial_n - 2], judge_all[handler_idx][trial_n - 3] ] if last_rots[0] == last_rots[1] == last_rots[2] \ and last_resp[0] == last_resp[1] == last_resp[2]: if cur_handler._nextIntensity > 0.5: rot = (cur_handler._nextIntensity - 0.5) * direction print('Intensity decreases by 0.5!') if cur_handler._nextIntensity <= 0.5: rot = (cur_handler._nextIntensity + 0.5) * direction print('Intensity increases by 0.5!') cond = cur_handler.extraInfo judge, react_time, trial_time_start = self.run_trial( rot, cond, count) if len(rot_all) <= handler_idx: rot_all.append([]) rot_all[handler_idx].append(rot) if len(judge_all) <= handler_idx: judge_all.append([]) judge_all[handler_idx].append(judge) valid_theta = np.round(np.load(self.hue_list), decimals=1) disp_standard = self.take_closest(valid_theta, cond['standard']) stair_test = cond[ 'standard'] + rot # calculated test hue for this trial if stair_test < 0: stair_test += 360 disp_test = self.take_closest( valid_theta, stair_test) # actual displayed test hue for this trial disp_intensity = disp_test - disp_standard # actual displayed hue difference if disp_intensity > 300: disp_intensity = (disp_test + disp_standard) - 360 cur_handler.addResponse( judge, abs(disp_intensity) ) # only positive number is accepted by addResponse if len(rot_all_disp ) <= handler_idx: # add displayed intensities rot_all_disp.append([]) rot_all_disp[handler_idx].append(disp_intensity) if isinstance(cur_handler, data.PsiHandler): estimates[cur_handler.extraInfo['label']].append([ cur_handler.estimateLambda()[0], # location cur_handler.estimateLambda768()[1], # slope cur_handler.estimateThreshold(0.75) ]) elif isinstance(cur_handler, data.QuestHandler): estimates[cur_handler.extraInfo['label']].append([ cur_handler.mean(), cur_handler.mode(), cur_handler.quantile(0.5) ]) xpp.task(count, cond, rot, disp_intensity, judge, react_time, trial_time_start) if 'escape' in event.waitKeys(): config_tools.write_xrl(self.subject, break_info='userbreak') core.quit() config_tools.write_xrl(self.subject, xls_file=xlsname) # save results in xls-file workbook = xlsxwriter.Workbook(xlsname) for handler_idx, cur_handler in enumerate(stairs): worksheet = workbook.add_worksheet( cur_handler.extraInfo['label']) worksheet.write('A1', 'Reversal Intensities') worksheet.write('B1', 'Reversal Indices') worksheet.write('C1', 'All Intensities') worksheet.write('D1', 'All Responses') for i in range(len(rot_all[handler_idx])): # worksheet.write('C' + str(i + 2), rot_all[handler_idx][i]) worksheet.write('C' + str(i + 2), rot_all_disp[handler_idx][i]) worksheet.write('D' + str(i + 2), judge_all[handler_idx][i]) workbook.close() # print resulting parameters and estimates for each step res_file_path = os.path.join(path, self.idx + '_estimates.csv') res_writer = csv.writer(open(res_file_path, 'w')) for res_stim, res_vals in estimates.items(): for res_val_id, res_val in enumerate(res_vals): res_writer.writerow([ res_stim, res_val_id, res_val[0], res_val[1], res_val[2] ]) # save each handler into a psydat-file and save posterior into a numpy-file for cur_handler in stairs: file_name = os.path.join( psydat_path, self.idx + self.param['noise_condition'] + cur_handler.extraInfo['label']) misc.toFile(file_name + '.psydat', cur_handler) if isinstance(cur_handler, data.PsiHandler): cur_handler.savePosterior(file_name + '.npy')
def takeABreak(): message = visual.TextStim(window, "Take A Break....Hit Any Key To Resume") message.draw() window.flip() event.waitKeys()
def test_waitKeys_clearEvents_True(self): key = 'x' DelayedAddFakeKeysToBuffer(key).start() key_events = event.waitKeys(clearEvents=True) assert key_events == [key]
# Show a prompt on grey background at the beginning of the trial and wait for a keypress. bg = visual.GratingStim(win, tex=None, mask=None, size=2, units='norm', color=0) prompt = visual.TextStim(win, text=config.PROMPT_TEXT.format( trial * 100 // config.NTRIALS)) # prompt = visual.TextStim(win, text='HELLO', font='Consolas') bg.draw() prompt.draw() win.flip() event.waitKeys(clearEvents=True) # bg.draw(); win.flip(); event.waitKeys(clearEvents=True) # prompt.draw(); win.flip(); event.waitKeys(clearEvents=True) previousDigit = False # Start the cue loop. for cue in range(config.NCUES): # Create a random digit digit = randint(0, 9) # Ensure it is not the same as the previous digit while digit == previousDigit: digit = randint(0, 9)
height=0.5, name='No reward', ) # Message msg = visual.TextStim(win=win, pos=(0, 0), height=0.06, name='Message', ) # Quiz msg.text = 'QUIZ\nPress SPACE to start' msg.draw() win.flip() keys = event.waitKeys(keyList=('space', 'escape')) # check for quit: if "escape" in keys: core.quit() win.flip() core.wait(1) quiz(read_questions('quiz.txt'), win) # Determine reward probabilities try: n = int(info['Participant']) except ValueError: if random.random() < 0.5: rwrd_probs = {'pink': RWRD_PROB, 'blue': 1 - RWRD_PROB}
def check_exit(): #abort if esc was pressed if event.getKeys('escape'): win.close() core.quit() #create clock globalClock = core.Clock() logging.setDefaultClock(globalClock) #showing instructions first instruct_txt.draw() win.flip() #waiting for space bar to continue keys = event.waitKeys(keyList=['space'], timeStamped=globalClock) check_exit() #show waiting for scanner until keypress ScannerWait_txt.draw() win.flip() #wait for a 5 or t keypress to start keys = event.waitKeys(keyList=['t', '5'], timeStamped=globalClock) t0 = float(keys[0][0]) #creating variable for flip duration flip_duration = 21 # header for data log data = np.hstack(("StimType", "onset")) # Goal for this section: Check what time it is. If the time matches a value in the column "Time" # then present the text display from that same row for 1.25 seconds and then go back to blank #setting up the first stimulus outside the loop
def waitForKyes(self, win): win.flip() event.waitKeys() event.clearEvents() core.wait(.2)
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']] imagepath = os.path.join(expdir, 'Images') image = os.path.join(imagepath, "%s.png") % 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']) fixation.draw() win.flip() core.wait(iti_for_trial) trials.addData('ITIonset', ITI_onset) #decision phase timer.reset() event.clearEvents() decision_onset = globalClock.getTime() trials.addData('decision_onset', decision_onset) resp_val = None resp_onset = None while timer.getTime() < decision_dur: resp_text_accept.draw() resp_text_reject.draw() pictureStim.draw() partner_offer = trial['Offer'] partnerOffer = 'Proposal: $%s.00 out of $20.00' % partner_offer offer_text.setText(partnerOffer) offer_text.draw() win.flip() resp = event.getKeys(keyList=responseKeys) if len(resp) > 0: if resp == ['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 = float(resp[0]) resp_onset = globalClock.getTime() if resp_val == 2: resp_text_reject.setColor('red') core.wait(.25) if resp_val == 3: resp_text_accept.setColor('red') core.wait(.25) trials.addData('resp', resp_val) trials.addData('resp_onset', resp_onset) if resp == 0: resp_val = 'NA' print "got here" outcome_txt = outcome_map[resp_val] outcome_stim.setText(outcome_txt) #win.flip() outcome_stim.draw() core.wait(.25) trials.addData('resp', resp_val) #reset rating number color resp_text_accept.setColor('#FFFFFF') resp_text_reject.setColor('#FFFFFF') ''' #outcome phase timer.reset() #win.flip() outcome_onset = globalClock.getTime() pictureStim.draw() #win.flip() subjectReceives = trial['Offer'] partnerKeeps = trial['PartnerKeeps'] if resp_val == 3: outcome_txt = outcome_map[resp_val] % (subjectReceives, partnerKeeps) elif resp_val==2: outcome_txt = outcome_map[resp_val] else: outcome_txt = outcome_map[resp_val] outcome_stim.setText(outcome_txt) outcome_stim.draw() #trials.addData('outcome_txt', outcome_txt) trials.addData('outcome_onset', outcome_onset) win.flip() core.wait(outcome_dur) outcome_offset = globalClock.getTime() trials.addData('outcome_offset', outcome_offset) fixation.draw() win.flip() core.wait(.75) ''' trial_offset = globalClock.getTime() duration = trial_offset - decision_onset trials.addData('trialDuration', duration) event.clearEvents() print "got to check 3" #trials.saveAsText(fileName=log_file.format(subj_id),delim=',',dataOut='all_raw') 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()
flipHoriz=False, flipVert=False, texRes=128, interpolate=True, depth=0.0) ### introduction introtext=visual.TextStim( win, text='Fixiere immer den roten Punkt in der Mitte.\n\nVersuche wenig zu blinzeln.\n\n\nEs dauert nur 1 Minute!\n\nFixiere, und nach Tastendruck geht es los!', font='', pos=(0.0, 0.0), depth=0, rgb=None, color=(1.0, 1.0, 1.0), colorSpace='rgb', opacity=1.0, contrast=1.0, units='', ori=0.0, height=None, antialias=True, bold=False, italic=False, alignHoriz='center', alignVert='center', fontFiles=(), wrapWidth=None, flipHoriz=False, flipVert=False, name=None, autoLog=None) introtext.draw() fixation = visual.GratingStim(win, mask='circle', size=0.3, pos=[0,0], sf=0, rgb=[1,0,0]) fixation.draw() win.flip() event.waitKeys() # wait for a key press to continue win.flip() #total_counter=0 oddball_counter=0 frequent_counter=0 # contrast estimates con = [] for i in range(10): con.append(-math.cos( (2 * math.pi ) / 10. * i) ) con[i] = con[i] / 2 + 0.5 print(con[i]) for nstim in range(0,163): print(nstim)
def main(): subject = str(raw_input("Please enter subject number: ")) subject = subjectCheck(subject) #############Parameters!! if os.path.isfile('experimentconditions.csv'): #get conditions with open('experimentconditions.csv') as f: reader = csv.DictReader(f) for row in reader: calibration_time = float(row["calibration_time"]) display_time = float(row["display_time"]) stim_directory = row["stim_directory"] repetitions = int(row["repetitions"]) question = row["question"] keylist = ast.literal_eval(row["keylist"]) prompt = row["prompt"] else: #If you don't want to go through the condition generator, you can change these parameters directly. calibration_time = 11 display_time = 2 stim_directory = "C:/Users/expt102/Documents/gazepoint_code/gazepoint_psychopy/28px" repetitions = 0 question = "check this out" keylist = ['f', 'j'] prompt = "woah" ############File setup calibrationfile = open(subject + "_calibration_results.txt", 'wb') responsefile = open(subject + "responses.csv", 'wb') responsefields = ['subject', 'trial', 'image', 'response', 'rt'] responsewriter = csv.DictWriter(responsefile, responsefields) responsewriter.writeheader() trackingfile = open(subject + "_tracking_data.csv", 'wb') trackingfields = ['subject', 'trial', 'image', 'tracking data'] trackingwriter = csv.DictWriter(trackingfile, trackingfields) trackingwriter.writeheader() ############calibration gp = gazepoint_object() while True: calibration_results = gp.calibrate(calibration_time) calibrationfile.write(calibration_results) response = raw_input( "Experimenter: Was the calibration successful? y/[n]: ") if re.search("^y", response, re.IGNORECASE): break #get all the images tempfiles = [ f for f in listdir(stim_directory) if isfile(join(stim_directory, f)) ] images = [] for f in tempfiles: if re.search(".jpg$", f, re.IGNORECASE): images += [f] else: print f + " isn't a jpg image! It wasn't included." #Preload the images into stimuli stimuli_list = [] myWin = visual.Window((1000, 1000), monitor='testMonitor', allowGUI=False, color=(-1, -1, -1)) for stim in images: stimuli_list.append( visual.ImageStim(myWin, image=stim_directory + "/" + stim, pos=(0, 0), units='deg')) background = visual.Rect(myWin, lineWidth=0, fillColor="black", size=[800, 800], pos=[0, 0]) instructions = visual.TextStim( myWin, text="Welcome to the experiment or whatever", height=60, color='white', pos=[0, 0], units='pixels') background.draw() instructions.draw() myWin.flip() while True: event.waitKeys() break #Prep response variables question_stim = visual.TextStim(myWin, text=question, height=60, color='white', pos=[0, 0], units='pixels') prompt_stim = visual.TextStim(myWin, text=prompt, height=30, color='white', pos=[0, -60], units='pixels') #prep other variables trial = 1 timer = core.Clock() #Cycle thru each stim for stim in stimuli_list: gp.init_data() stim.draw() myWin.flip() tracking_results = gp.get_data(display_time) #Start response drawing background.draw() question_stim.draw() prompt_stim.draw() myWin.flip() #Start the response screen timer.reset() while True: response = event.waitKeys(keyList=keylist)[0] break rt = timer.getTime() responsewriter.writerow({ 'subject': subject, 'response': response, 'rt': rt, 'image': stim.image, 'trial': trial }) for row in tracking_results: trackingwriter.writerow({ 'subject': subject, 'tracking data': row, 'image': stim.image, 'trial': trial }) trial += 1 core.quit() sys.exit()
from psychopy import visual, core, event rts=[] keys=[] win = visual.Window(size=[500,500]) rt_clock = core.Clock() texti = visual.TextStim(win, "") for letter in ["A", "B", "C", "D", "E", "F", "G"]: texti.setText(letter) texti.draw(win) win.flip() rt_clock.reset() # so that RTs are time elapsed since stimulus presentation resp = event.waitKeys(maxWait = 3, timeStamped = rt_clock) if resp is not None: [(key, rt)] = resp keys.append(key) rts.append(rt) else: keys.append("miss") rts.append("miss") win.close()
print "got to check 2" ''' runs=[] for run in range(1): run_data = [] for t in range(8): sample = random.sample(range(len(trial_data)),1)[0] run_data.append(trial_data.pop(sample)) runs.append(run_data) ''' # main task loop # Instructions instruct_screen.draw() win.flip() event.waitKeys(keyList=('space')) instruct_screen2.draw() win.flip() event.waitKeys(keyList=('space')) 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()
) kb = keyboard.Keyboard() #Intructions for the participants Participant_Instruction = visual.TextStim(mywin, text=''' Welcome! Instructions: 1. You will be shown an experimental set of four shapes with colours. Please look at them carefully. 2. You will then be presented with another shape. You are required to ignore this. 3. A final image will be shown. Please report whether this image was present in the set of first four images. 4. Press 1 for "Yes" and 2 for "No"', ''') Participant_Instruction.draw() mywin.update() Subject_Response = event.waitKeys(keyList=['1', '2']) print(Subject_Response) #Initial Blank screen; to focus on the center start = visual.TextStim(mywin, text='+') start.draw() for frame in range(100): start.draw() mywin.update() #Trial 1 - Plausible suffix trial_1 = visual.TextStim(mywin, text='''Trial 1 Ready?''') for frame in range(150): trial_1.draw() mywin.update()
# this can save you processing time # use pos to position the object on the screen # draw image to window buffer face.draw() # flip window to reveal image win.flip() #%% recording a button press """ here's how you record a button press on your keyboard """ # waitKeys is a handy function that will run until a key is pressed keys = event.waitKeys() print(keys) # just for showing how it works! # you can also set an time limit for the response period keys = event.waitKeys(maxWait=2) print(keys) # just for showing how it works! # getKeys is like waitKeys, but it will only look for keys when it's called and # then the script keeps going # usually, you would use getKeys() in a while or for loop so it's called # frequently keys = [] while len(keys) < 1: keys = event.getKeys()
#pull up a screen that lets them start the experiment txt = "You now have {} seconds to name as many different {} as you can think of. Press any key when you are ready.".format( V["Insert time in secs (e.g. 120):"], V["category"]) info(txt) # initialize abort option endTrial = False # initialize clock clock = core.Clock() stopwatch = core.Clock() while not endTrial: # Wait for response... if clock.getTime() > int(V['Insert time in secs (e.g. 120):']): endTrial = True response = event.waitKeys() if response: # If backspace, delete last character if response[0] == 'backspace': text.setText(text.text[:-1]) # Insert space elif response[0] == 'space': text.setText(text.text + ' ') # Else if a letter, append to text: elif response[0] in chars: text.setText(text.text + response[0]) # If return, save word to panda and reset inputw elif response[0] == 'return':
maxVal=Nloads) # Create counter for each load level TrialCount = 1 count = [1] * Nloads MaxCount = 24 CurrentLoad = 1 EndFlag = 'EndedNormal' # Add the wait block continueRoutine = True WaitText.draw() win.flip() k = [''] KeyBoardCount = 0 while k[0] not in ['escape', 'esc'] and KeyBoardCount < 1: k = event.waitKeys() KeyBoardCount += 1 # Add a count down block CountDownTime = 1 CountDownText.text = '3' CountDownText.draw() win.flip() core.wait(CountDownTime) CountDownText.text = '2' CountDownText.draw() win.flip() core.wait(CountDownTime) CountDownText.text = '1' CountDownText.draw() win.flip()
def run_stimuli(stimuli_file): """ stimuli file is sem_stim_runi.csv file, including the stimuli for each run """ # read the stimuli # re-define, not use numbers, but use keywords all_trials, headers = load_conditions_dict(conditionfile=stimuli_file) headers += [ 'trial_pres_id', 'probe_onset', 'probe_durat', 'fixa1_onset', 'fixa1_durat', 'target_onset', 'target_durat', 'target_offset', 'fixa2_onset', 'fixa2_durat', 'RT', 'KeyPress' ] # read the fixation duration # all_fixa, fixa_headers = load_conditions_dict(conditionfile=fixa_file) # open the result file to write the heater write_header(filename, headers) # # # shuffle(all_trials) #- trial_pres_num = 1 # initialize a counter (so that we can have mini-blocks of 10) #trigger the scanner trigger_exp(curr_dic, 'trigger.jpg') keys_trigger = event.waitKeys(keyList=['5'], timeStamped=True) # remind the subjects that experiment starts soon. #ready() run_onset = keys_trigger[0][1] core.wait(5.5) # 2 TRs win.flip() print('run_onset', run_onset) for trial in all_trials: #''' trial is a ordered dictionary. The key is the first raw of the stimuli csv file''' # prepare fixation, clue, probe and target for dispaly fix2 = prep_cont('+', fix_pos, text_h, color=(1, -1, -1)) probe = prep_cont(trial['Probe'], probe_pos, text_h, win_text_col) target = prep_cont(trial['Target'], target_pos, text_h, win_text_col) #yes = prep_cont('Y',yes_pos,yes_no_h,win_text_col) #no = prep_cont('N',no_pos,yes_no_h,win_text_col) # draw probe and filp the window probe.draw() timetodraw = run_onset + 6 + trial_duration * (trial_pres_num - 1) while core.monotonicClock.getTime() < (timetodraw - (1 / 120.0)): pass probe_onset = win.flip() # draw fixa between probe and target and flip the window #fix.draw() for i in range(3): fix = visual.Circle(win, units='pix', radius=20, fillColor=[0, 0, 0], lineColor=[0, 0, 0], pos=[-120 + 120 * i, 0]) fix.draw() timetodraw = probe_onset + probe_durat while core.monotonicClock.getTime() < (timetodraw - (1 / 120.0)): pass fix1_onset = win.flip() # draw target and flip the window target.draw() #yes.draw() #no.draw() timetodraw = fix1_onset + fix1_durat while core.monotonicClock.getTime() < (timetodraw - (1 / 120.0)): pass event.clearEvents() target_onset = win.flip() keys = event.waitKeys(maxWait=target_durat, keyList=['1', '2', 'escape'], timeStamped=True) #yes.draw() #no.draw() time_after_targ = target_onset + target_durat while core.monotonicClock.getTime() < (time_after_targ - (1 / 120.0)): pass after_targ = win.flip() # If subjects do not press the key within maxwait time, RT is the timilimit and key is none and it is false if keys is None: keys = event.waitKeys(maxWait=timelimit_deci - target_durat, keyList=['1', '2', 'escape'], timeStamped=True) if keys is None: RT = 'None' keypress = 'None' #correct = 'False' target_offset = target_onset + timelimit_deci elif type(keys) is list: if keys[0][0] == 'escape': shutdown() else: keypress = keys[0][0] RT = keys[0][1] - target_onset #correct = (keys[0][0]==trial['correct_answer']) target_offset = keys[0][1] trial['RT'] = RT #trial['correct'] = correct trial['KeyPress'] = keypress #write_trial(filename,headers,trial) # If subjects press the key, record which key is pressed, RT and whether it is right # elif type(keys) is list: if keys[0][0] == 'escape': shutdown() else: keypress = keys[0][0] RT = keys[0][1] - target_onset #correct = (keys[0][0]==trial['correct_answer']) target_offset = keys[0][1] trial['RT'] = RT #trial['correct'] = correct trial['KeyPress'] = keypress fix2.draw() timetodraw = target_onset + timelimit_deci while core.monotonicClock.getTime() < (timetodraw - (1 / 120.0)): pass fix2_onset = win.flip() trial['trial_pres_id'] = trial_pres_num trial['fixa1_onset'] = fix1_onset - run_onset trial['fixa1_durat'] = fix1_durat trial['probe_onset'] = probe_onset - run_onset trial['probe_durat'] = probe_durat trial['fixa2_onset'] = fix2_onset - run_onset trial['fixa2_durat'] = fix2_durat trial['target_onset'] = target_onset - run_onset trial['target_offset'] = target_offset - run_onset trial['target_durat'] = target_durat trial['RT'] = RT #trial['correct'] = correct trial['KeyPress'] = keypress trial_pres_num += 1 # the number-th presentnted trial write_trial(filename, headers, trial) # calls the function that writes csv output
#initalize lists iti_list = [] received_rewards = [] total_rewards = [] correct_choices = [] trial_time = [] cp_with_slow_fast = [] cp_list = exp_param.cp.values[0:n_trials].tolist() #give instructions instruction_phase = True while instruction_phase: inst_msg.setAutoDraw(True) window.flip() inst_keys = event.waitKeys(keyList=['s']) instruction_phase = False inst_msg.setAutoDraw(False) window.flip() total_reward = 0 t = 0 totalMsg.text = str(total_reward) totalMsg.setAutoDraw(True) treasure_chest.setAutoDraw(True) break_screen = False #this is needed because t/2 is possible more than once if a slow trial is repeated expTime_clock.reset() #reset so that inst. time is not included
end2 = visual.TextStim(win=mywin, text='Please contact the experimenter.', pos=(0, -2)) ###show our instructions, and wait for a response### fixation.draw() instr1.draw() instr2.draw() instr3.draw() instr4.draw() instr5.draw() mywin.flip() ###wait for button press to start experiment### start_time = core.getTime() keys = event.waitKeys() while keys not in [['space']]: keys = event.waitKeys() ###first we will run the practice trials### for i_trial in range(len(trial_order_practice)): ITI = (randint(0, 500) * 0.001) + 0.5 ###wait a bit### mywin.flip() core.wait(ITI) ###present fixation cross### fixation.draw() mywin.flip() core.wait(1) ###now remove the fixation and wait for a bit### mywin.flip()
def disp_instr_cont(line): line.draw() win.flip() keys = event.waitKeys(keyList=['return', 'escape']) if keys[0][0] == 'escape': shutdown()
def run_trial(self, rot, cond, count): ref = self.patch_ref(theta=cond['ref'], pos=self.cfg['ref.pos']) # randomly assign patch positions: upper (+) or lower (-) patchpos = [self.cfg['standard.ylim'], self.cfg['test.ylim']] rndpos = patchpos.copy() np.random.shuffle(rndpos) sPatch = self.patch_stim(self.cfg['standard.xlim'], rndpos[0]) tPatch = self.patch_stim(self.cfg['test.xlim'], rndpos[1]) # set colors of two stimuli standard = cond['standard'] # standard should be fixed test = standard + rot sPatch.colors, tPatch.colors = self.choose_con(standard, test, cond['std']) # fixation cross fix = visual.TextStim(self.win, text="+", units='deg', pos=[0, 0], height=0.5, color='black', colorSpace=self.ColorSpace) # number of trial num = visual.TextStim(self.win, text="trial " + str(count), units='deg', pos=[12, -10], height=0.4, color='black', colorSpace=self.ColorSpace) trial_time_start = time.time() # present the standard and the test stimuli as well fix.draw() num.draw() ref.draw() sPatch.draw() tPatch.draw() self.win.flip() core.wait(self.trial_dur) fix.draw() self.win.flip() core.wait(0.2) # 0.2 sec gray background react_time_start = time.time() # refresh the window and show a colored checkerboard horiz_n = 30 vertic_n = 20 rect = visual.ElementArrayStim(self.win, units='norm', nElements=horiz_n * vertic_n, elementMask=None, elementTex=None, sizes=(2 / horiz_n, 2 / vertic_n), colorSpace=self.ColorSpace) rect.xys = [ (x, y) for x in np.linspace(-1, 1, horiz_n, endpoint=False) + 1 / horiz_n for y in np.linspace(-1, 1, vertic_n, endpoint=False) + 1 / vertic_n ] rect.colors = [ self.ColorPicker.newcolor(theta=x)[1] for x in np.random.randint(0, high=360, size=horiz_n * vertic_n) ] rect.draw() self.win.flip() core.wait(0.5) # 0.5 sec checkerboard judge = None react_time_stop = -1 kb = keyboard.Keyboard() get_keys = kb.getKeys(['up', 'down', 'escape' ]) # if response during the checkerboard if ('up' in get_keys and rndpos[1][0] > 0) or ('down' in get_keys and rndpos[1][0] < 0): judge = 1 # correct react_time_stop = time.time() elif ('up' in get_keys and rndpos[1][0] < 0) or ('down' in get_keys and rndpos[1][0] > 0): judge = 0 # incorrect react_time_stop = time.time() if 'escape' in get_keys: config_tools.write_xrl(self.subject, break_info='userbreak') core.quit() self.win.flip() fix.draw() self.win.flip() if judge is None: # if response after the checkerboard for wait_keys in event.waitKeys(): if (wait_keys == 'up' and rndpos[1][0] > 0) or (wait_keys == 'down' and rndpos[1][0] < 0): judge = 1 # correct react_time_stop = time.time() elif (wait_keys == 'up' and rndpos[1][0] < 0) or (wait_keys == 'down' and rndpos[1][0] > 0): judge = 0 # incorrect react_time_stop = time.time() elif wait_keys == 'escape': config_tools.write_xrl(self.subject, break_info='userbreak') core.quit() react_time = react_time_stop - react_time_start return judge, react_time, trial_time_start
keys = event.waitKeys(timeStamped=timer) resp = keys[0] rt = keys[1] if resp == 'z': respInt = 0 else: respInt = 1 for a in range(numFrames): onScreenTime.append(myTimesB[a] - myTimesA[a]) return (respInt, rt, onScreenTime) ############################################################ # Start Experiment event.waitKeys() block = 0 for trial in range(3): (flanker, target) = divmod(cond[order[trial]], 2) [resp, RT, keyrt, onScreenTime] = doTrial(flanker, target, crit[trial]) rt = decimal.Decimal(RT).quantize(decimal.Decimal('1e-3')) addData = (sessionID, block, trial, target, flanker, resp, rt, keyrt, crit[trial]) if useDB: insertDatTable(insertTableStatement, addData, dbConf) else: print(addData) ########################################################## hz = round(window.getActualFrameRate())
square = visual.Rect(win, size=40) square.setFillColor('blue') square.setLineColor('blue') square.setPos([30 * i - 240, 0]) square.draw() else: square = visual.Rect(win, size=40) square.setFillColor('red') square.setLineColor('red') square.setPos([30 * i - 240, 0]) square.draw() isFlip = False if trial[16] == '1': isFlip = True win.flip() response = event.waitKeys(keyList=['1', '0'])[0] winning = False if isFlip: if response == '1': winning = True else: if response == '0': winning = True if winning: correctFeedback.draw() else: incorrectFeedback.draw() win.flip() core.wait(1) win.close()