/
sentencecomp_8sec_allresps.py
executable file
·496 lines (209 loc) · 7.19 KB
/
sentencecomp_8sec_allresps.py
1
"""sentencecomp.py - code to run the sentence comprehension task for the reading remediation study"""from psychopy import visual, core, event, logging,guiimport numpy as Nimport pickleimport datetimeimport sysimport osimport inspectimport hashlibfrom socket import gethostnamefrom exptutils import *# study-specific routinesdef load_sentences(filename): f=open(filename) ll=f.readlines() f.close() s={} s['sentence']=[] s['cond']=[] s['onset']=[] for l in ll: l_s=l.split('\t') #print l_s s['sentence'].append(' '.join(l_s[2:]).strip('\n')) s['cond'].append(l_s[1]) s['onset'].append(l_s[0]) return s# set study-specific variablesexpt_title='Sentence Comprehension Task'stimdur=8.0 # stimulus durationisi=2.0 # inter-stimulus intervalblocklen=20 # null break after this many trials # this is actually four blocks of stimuliblock_break=16.0total_duration=424.0inst_time=2.0 # time that instructions are shownverbose=Trueversion=0.1trigger_key='5'discard_time_to_wait=0.0fullscr=True # change to True for full screen display# initialize subdata dictionary# this stores all of the info about the studysubdata={}subdata['completed']=0subdata['cwd']=os.getcwd()subdata['hostname']=gethostname()# save a copy of the script in the data filescriptfile= inspect.getfile(inspect.currentframe())f=open(scriptfile)subdata['script']=f.readlines()f.close()clock=core.Clock()datestamp=datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")subdata['datestamp']=datestampsubdata['expt_title']=expt_titlesubdata['trigger_times']=[]# stimulus lists are in files in directory called "stimlists"stimfiles=get_lists_from_directory('stimlists')#onsetfiles=get_lists_from_directory('onsetlists')# read in variables from user dialoginfo = {'subcode':'', 'ExpVersion': version, 'Site': ['Houston', 'Austin'],'Yes':['left','right'],'Simulated rt (secs)':'','Stimulus file': stimfiles}info=get_info_from_dialog(info,expt_title,fixed=['ExpVersion'])if info==[]: shut_down_cleanly(subdata,win)while info['subcode']=='': print 'must enter a valid subject code!' info=get_info_from_dialog(stimfiles) if info==[]: shut_down_cleanly(subdata,win)# set up logging informationsubcode=info['subcode']logging.console.setLevel(logging.INFO)if not os.path.exists('Output'): os.mkdir('Output')logging.LogFile('Output/%s_%s_%s.log'%(subcode,expt_title.replace(' ','_'),datestamp),level=logging.INFO)# load the sentencesif info['Stimulus file']=='practice.txt': practice_mode=1else: practice_mode=0subdata['practice_mode']=practice_modesubdata['sentence_info']=load_sentences('stimlists/%s'%info['Stimulus file'])sentences=[i.strip() for i in subdata['sentence_info']['sentence']]# load the onsetsonsets=[float(i) for i in subdata['sentence_info']['onset']]cond=subdata['sentence_info']['cond']# set up the subdata dictionary# which is used to store all of the datasubdata['info']=infosubdata['onsets']=onsetssubdata['resp']={}subdata['rt']={}subdata['cond']={}subdata['stimons']={}if info['Simulated rt (secs)']=='': subdata['simulate_response']=0.0else: subdata['simulate_response']=float(info['Simulated rt (secs)']) # set to nonzero to generate simulated responses with this mean RT# set up the window win=visual.Window([1024,768],fullscr=fullscr)#win.setColor('black')#win.flip()#win.flip()# wait for trigger or start keyevent.clearEvents()if subdata['simulate_response']>0: message=visual.TextStim(win, text='SIMULATION MODE: Waiting for trigger (or press s)',wrapWidth=800)else: message=visual.TextStim(win, text='Waiting for trigger (or press s)',wrapWidth=800)message.setAutoDraw(True) #automatically draw every framewin.flip()start=Falsewhile start==False: k=event.waitKeys() if k[0]=='s' or k[0]==trigger_key: start=True message.setText('') win.flip() if discard_time_to_wait>0: core.wait(discard_time_to_wait) if k[0]=='q': shut_down_cleanly(subdata,win)# show instructionmessage.setText('Makes Sense?')win.flip()core.wait(inst_time)clock.reset()subdata['start_time']=clock.getTime()keep_going=1if info['Yes']=='left': inst_text=['YES','NO']else: inst_text=['NO','YES']inst_l=visual.TextStim(win,text=inst_text[0],pos=(-0.5,-0.5))inst_l.setAutoDraw(False)inst_r=visual.TextStim(win,text=inst_text[1],pos=(0.4,-0.5))inst_r.setAutoDraw(False)trial_buffer = 0.01for s in range(len(sentences)): if keep_going==0: shut_down_cleanly(subdata,win) if subdata['simulate_response']>0: simrt=N.random.randn()*0.05 + subdata['simulate_response'] print 'simrt: ',simrt else: simrt = 100000000.0 message.setText(sentences[s]) # wait for the onset time for the next stimulus inst_l.draw() inst_r.draw() while clock.getTime() < onsets[s]: pass win.flip() subdata['stimons'][s]=clock.getTime() subdata['rt'][s]=[] subdata['resp'][s]=[] subdata['cond'][s]=cond[s] # look for response and/or end of trial # record multiple responses event.clearEvents() thisResp=None stimShowing=True respctr=-1 try: trial_end=onsets[s+1] - trial_buffer except: trial_end=total_duration print onsets[s], trial_end, total_duration while clock.getTime() < trial_end: allkeys=event.getKeys() if allkeys: if allkeys[0]=='q': keep_going=0 subdata['broke_on_trial']=s break elif allkeys[0]==trigger_key: # trigger subdata['trigger_times'].append(clock.getTime()) else: respctr+=1 subdata['rt'][s].append(clock.getTime() - subdata['stimons'][s]) subdata['resp'][s].append(allkeys[0]) DATA='RESPONSE: %s (%f)'%(subdata['resp'][s][respctr],subdata['rt'][s][respctr]) logging.data(DATA) logging.flush() if verbose: print DATA elif clock.getTime() > (subdata['stimons'][s] + simrt) and thisResp==None: subdata['rt'][s].append(clock.getTime() - subdata['stimons'][s]) subdata['resp'][s].append('s') DATA='RESPONSE: %s (%f)'%(subdata['resp'][s][respctr],subdata['rt'][s][respctr]) logging.data(DATA) logging.flush() if verbose: print DATA thisResp=1 if clock.getTime() > (subdata['stimons'][s] + stimdur) and stimShowing==True: message.setText('') win.flip() stimShowing=False while clock.getTime() < total_duration: passsubdata['finish_time']=clock.getTime()# close down and save datasubdata['completed']=1shut_down_cleanly(subdata,win)event.clearEvents()