def setup_images(self): self.notargs = [] self.gotargs = [] self.deftargs = [] self.bkimg = ImageStim(self.win, image='resources/pond.jpg', units='norm', size=(2.0, 2.0)) for targ in range(self.geom['numtargs']): self.notargs.append( ImageStim(self.win, image='resources/rfrog2.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) self.gotargs.append( ImageStim(self.win, image='resources/gfrog2.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) self.deftargs.append( ImageStim(self.win, image='resources/lilypad.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) # set initial target stims to be the defaults self.targets = [] for targ in self.deftargs: self.targets.append(targ)
def RunTrial(self, image, pos): """Runs a particular trial, which includes displaying the image to the screen, and gathering the keypresses and their respective response times. image: The filename of the image to display pos: Coordinates (on 6x4 grid) where image will be displayed return: tuple of first keypress info: (keyPress, reactionTime) """ ShownImage = ImageStim(self.window) ShownImage.setPos(pos) ShownImage.setSize((self.imageWidth, self.imageWidth)) ShownImage.setImage(self.imgDir + '/%s' % (image)) ShownImage.draw(self.window) self.window.flip() clearEvents() self.clock.reset() keypresses = [] if (self.selfPaced == False): wait(self.trialDuration, self.trialDuration) keypresses = getKeys(keyList=[ self.leftButton, self.rightButton, self.pauseButton, "escape" ], timeStamped=self.clock) elif (self.selfPaced == True): keypresses = waitKeys(keyList=[ self.leftButton, self.rightButton, self.pauseButton, "escape" ], timeStamped=self.clock) self.window.flip() wait(self.ISI) if len(keypresses) < 1: return '', 0 return keypresses[0][0], keypresses[0][1]
class ImageScreen(Screen): def __init__(self, disp, text, text_width, image, image_size, text_pos=None, image_pos=None, wait_time=1, extra_image_stims=[] ): super(ImageScreen, self).__init__(disp, wait_time=wait_time) self.extra_image_stims = extra_image_stims self.wait_time = wait_time if self.wait_time == 0: self.continue_button.clickable = True if text_pos is None: _text_pos = self.coords(self.width/4, self.height/2) else: _text_pos = text_pos if image_pos is None: _image_pos = self.coords(3*self.width/4, self.height/2) else: _image_pos = image_pos self.text_stim = TextStim( win=self.window, text=text, pos=_text_pos, height=Screen.default_font_size, wrapWidth=text_width ) self.img_stim = ImageStim( win=self.window, image=image, pos=_image_pos, size=(image_size[0], image_size[1]) ) def draw(self, debug_mode=False): for img_stim in self.extra_image_stims: img_stim.draw() self.continue_button.draw() self.text_stim.draw() self.img_stim.draw() if not self.continue_button.clickable: if getAbsTime() - self.t0 > self.wait_time: self.continue_button.clickable = True def cleanup(self): for extra in self.extra_image_stims: del extra self.window.flip() self.window.flip() self.window.flip()
class ShowAndConfirm(): def __init__(self, win, image, button_text): self.win = win self.show = ImageStim(win, image=image, units='norm') self.confirm_button = Button(win, (0, -0.5), width=0.1, height=0.05, name='confirm_button', text=button_text) def run(self): while self.confirm_button.state != self.confirm_button.END: self.show.draw() self.confirm_button.process() self.confirm_button.draw() self.win.flip()
def main(): groups = create_stim_sequence(BLOCK1, BLOCK2, BLOCK3, TRIALREPEATS) print groups disp = Window(size=SIZE, monitor=MON, units='deg', color=BACKCOL, screen=1, fullscr=True) mouse = Mouse() fixmark = Circle(disp, radius=0.05, edges=32, pos=CENTER, lineColor=FIXCOL) images = [] for item in CIRCLES.keys(): image = ImageStim(disp, image=CIRCLES[item][1], pos=CIRCLES[item][0], size=CIRCLES[item][3]) images.append(image) fixmark.draw() draw_group(images) disp.flip() while True: button = mouse.getPressed() if button[0]: break for item in groups: flashes = [] for i in item: flash = ImageStim(disp, image=CIRCLES[i][2], pos=CIRCLES[i][0], size=CIRCLES[i][3]) flashes.append(flash) fixmark.draw() draw_group(images) draw_group(flashes) disp.flip() wait(FLASH) fixmark.draw() draw_group(images) wait(PAUSE) disp.flip() disp.close()
def RunTrial(self, image): """Runs a particular trial, which includes displaying the image to the screen, and gathering the keypresses and their respective response times. image: the image (filename) to display returns: [keyPress, reaction time] """ theImage = ImageStim(self.window) imagePath = os.path.normpath(self.imgDir + "/%s" % (image)) theImage.setImage(imagePath) imageSize = self.ScaleImage(imagePath, self.imageWidth) theImage.setSize(imageSize) theImage.draw(self.window) self.window.flip() clearEvents() self.clock.reset() keyPresses = [] if (self.selfPaced == False): wait(self.trialDuration, self.trialDuration) keyPresses = getKeys(keyList=[ self.leftButton, self.rightButton, self.pauseButton, 'escape' ], timeStamped=self.clock) elif (self.selfPaced == True): keyPresses = waitKeys(keyList=[ self.leftButton, self.rightButton, self.pauseButton, 'escape' ], timeStamped=self.clock) self.window.flip() wait(self.ISI) if (not keyPresses): return '', 0 return keyPresses[0][0], keyPresses[0][1]
def draw_image(self, image, pos=None, scale=None): """Draws an image on the screen arguments image -- a full path to an image file keyword arguments pos -- image center position, an (x,y) position tuple or None for a central position (default = None) scale -- scale factor for the image or None for no scaling (default = None) returns Nothing -- loads and draws an image surface on (PyGame) or adds SimpleImageStim to (PsychoPy) the self.screen property """ if pos == None: pos = (self.dispsize[0]/2, self.dispsize[1]/2) pos = pos2psychopos(pos,dispsize=self.dispsize) if scale == None: imgsize = None else: if pilimp: img = Image.open(image) imgsize = (img.size[0]*scale, img.size[1]*scale) else: imgsize = None print("WARNING! libscreen.Screen: PIL's Image class could not be loaded; image scaling with PsychoPy disptype is now impossible!") self.screen.append(ImageStim(pygaze.expdisplay, image=image, pos=pos, size=imgsize))
def setup_images(self): self.notargs = [] self.gotargs = [] self.deftargs = [] self.bkimg = ImageStim(self.win, image='resources/pond.jpg', units='norm', size=(2.0, 2.0)) for targ in range(self.geom['numtargs']): self.notargs.append(ImageStim(self.win, image='resources/rfrog2.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) self.gotargs.append(ImageStim(self.win, image='resources/gfrog2.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) self.deftargs.append(ImageStim(self.win, image='resources/lilypad.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) # set initial target stims to be the defaults self.targets = [] for targ in self.deftargs: self.targets.append(targ)
def imgbuf(rot_enum, tex_size, win): from psychopy.visual import ImageStim x, y = win.size size = ((x, tex_size) if rot_enum is 1 else (tex_size, y)) return ImageStim( win=win, size=size, units='pix', )
def __enter__(self): from psychopy.visual import ImageStim # eats some time from psychopy.visual import TextStim event.clearEvents() win = self.window.instance self.textstim = TextStim(win, text='') # image texture index order is iamge[y, x] self.instance = ImageStim( win=win, units='deg', #, filpVert=True, pos=self.component.position, size=self.component.size) #misc.pix2deg(win.size, win.monitor)*2) try: self.interval = self.window.get_isi() except Exception as e: raise ServiceRuntimeException( 'Could not acquire window object. Please try again') return self
def get_instance(self): from psychopy.visual import ImageStim # eats some time return ImageStim( win = self.window, image = Image.new('L', (self.tex_size, self.tex_size)), # units = 'pix', # size = self.monitor.getSizePix(), units = 'deg', size = misc.pix2deg(self.window.size, self.window.monitor)*2, )
def __init__(self, output_str, subject=None, output_dir=None, settings_file=None): super().__init__(output_str, subject=subject, output_dir=output_dir, settings_file=settings_file, run=run, eyetracker_on=False) logging.warn(self.settings['run']) self.buttons = self.settings['various'].get('buttons') self.image2 = ImageStim(self.win, self.settings['pile'].get('image2'), texRes=32, size=self.settings['pile'].get('dot_radius'))
def __init__(self, frames_dir, key='colored', **kwargs): """ :param frames_dir: path to mask files :param key: str key to identify the correct set of masks :param **kwargs: args to pass to visual.ImageStim """ mask_files = unipath.Path(frames_dir).listdir('*.png') self.masks = [ ImageStim(image=str(pth), **kwargs) for pth in mask_files ] self.cur_ix = 0
def __init__(self, **kwargs): """ :param **kwargs: args to pass to visual.ImageStim """ labtools_dir = unipath.Path(__file__).absolute().parent mask_files = unipath.Path(labtools_dir, 'dynamic_mask').listdir('*.png') self.masks = [ ImageStim(image=str(pth), **kwargs) for pth in mask_files ] self.cur_ix = 0
def create_trials(self): """creates trials by loading a list of jpg files from the img/ folder""" image_files = sorted( glob.glob( os.path.join(os.path.abspath(os.getcwd()), 'imgs', '*.jpg'))) self.image_stims = [ ImageStim(self.screen, image=imf) for imf in image_files ] self.trial_order = np.random.permutation(len(self.image_stims))
def create_trials(self): stim_file = 'faces_SINGLETRIAL.tsv' faces = pd.read_csv(stim_file, sep='\t').loc[:, 'face_id'].unique() print(faces) trial_nr = 0 for rep in [1, 2]: for rating in np.random.permutation(['dominance', 'attractiveness', 'trustworthiness']): if self.language == 'NL': cue_txt = f"Je gaat nu gezichten op {self.en2nl[rating]} beoordelen!" else: cue_txt = f"You're now going to rate faces on {rating}!" cue_trial = CueTrial( self, trial_nr=trial_nr, phase_durations=(4, 1), phase_names=('cue', 'fix'), txt=cue_txt ) self.trials.append(cue_trial) for face in np.random.permutation(faces): face = str(face).zfill(3) stim = op.join('..', '..', 'stimuli', 'london_face_dataset', 'neutral_front', f'{face}_03.jpg') self.display_text(f'Loading {trial_nr} / 240 ...', duration=0.001) trial = RatingTrial( session=self, trial_nr=trial_nr, face_stim=ImageStim(self.win, stim, size=(10, 10), units='deg'), phase_durations=(1.25, np.inf, 0.5), phase_names=('face', 'rating', 'fix'), rating=rating, parameters=dict(rating_type=rating, face_id=face, repetition=rep, session=self.session) ) self.trials.append(trial) trial_nr += 1 if rep == 1: if self.language == 'NL': cue_txt = f"Je bent op de helft!\nEven 30 seconden pauze; daarna gaan we weer beginnen." else: cue_txt = f"You're halfway!\nYou have a 30 second break; after that, we'll start again." pause_trial = CueTrial( self, trial_nr=trial_nr, phase_durations=(30, 1), phase_names=('cue', 'fix'), txt=cue_txt ) self.trials.append(pause_trial)
def whoAmI(response, done, qpos, image): """ Function that will be called to enter the user identification data - **Input**: :response: the user resonse (empty string at beginning) :done: boolean (True / False) -> False at beginning :qpos: text position for user response :image: the stimulus image - **outpu**: :response: the user response """ # --------------------------------------- # # WHILE THE WELCOME MESSAGE IS NOT PASSED # # --------------------------------------- # while len(response) == 0: # while the user has not taped anything yet response = '' # the response written by the user - On commence avec une chaîne vide respstim = TextStim(disp, text='', pos=qpos, height=size, color=color) # stimulus texte qstim = ImageStim(disp, image=image) qstim.draw() # dessiner la question disp.flip( ) # passer au screen au suivant -> on met la question par-dessus core.wait(loadTime ) # delay of 10 seconds before passing to the learning phase done = False # ----------------------------------- # # WHILE THE USER'S ANSWER IS NOT DONE # # Check for keypresses # # ----------------------------------- # while not done: # loop until done == True resplist = waitKeys(maxWait=float('inf'), keyList=None, timeStamped=True) key, presstime = resplist[ 0] # use only the first in the returned list of keypresses -> resplist[0] is the first element in the resplist list if len(key) == 1: # Check si la longeur de la réponse (len) = 1 response += key #Ajouter la lettre tapée à la réponse => on ne tient pas compte des touches pour les majuscules ni de la touche escape elif key == 'space': # Check if key is the space bar response += ' ' # ajoute un espace elif key == 'backspace' and len( response ) > 0: # Check if the key's name was backspace AND si la réponse a au moins une lettre response = response[0: -1] #remove last character of the response if key == 'return': # if the key was non of the above, check si c'est enter done = True # set done to True respstim.setText(response.capitalize( )) # actualiser la user response => 1ère lettre en majuscule qstim.draw() # réafficher la question stimulus (image) respstim.draw() # réafficher la réponse au stimulus disp.flip() # update the monitor core.wait( loadTime) # add a little lag to avoid little freez and/or bug return response.capitalize() # 1ère lettre en majuscule
def draw_overview_target(win, level, target_pos, text_pos, mouse_clicks_all_levels): target = ImageStim(win, 'target.png', size=420, pos=target_pos) level_text = TextStim(win, text=f'Level {level}', height=35, color=(0.2, 0.2, 0.8), pos=text_pos) target.draw() level_text.draw() target_x, target_y = target_pos curr_level_mouse_clicks = mouse_clicks_all_levels[level - 1] for target_hit_pos in curr_level_mouse_clicks: if target_hit_pos['mouse_in_target']: circle = Circle(win, radius=5, fillColor='yellow', lineColor='yellow') circle.setPos((target_hit_pos['mouse_x'] + target_x, target_hit_pos['mouse_y'] + target_y)) circle.draw()
def show_intro(win): start = TextStim( win, text="Hi there, player! This is you! Let's play!", height=35, color=(0.2, 0.2, 0.8), pos=(250, 230), ) player = ImageStim( win, 'creature.jpg', pos=(0, -100), size=(420, 420), ) intro_text = ( 'In this game you should shoot at the target with your mouse. ' + 'The target moves rapidly to a new position each time you shoot at it.' + 'There are 3 levels each faster than the previous one. Good luck!') instructions = TextStim( win, text=intro_text, height=35, color=(1, 0.2, 0.6), pos=(250, 0), ) start.draw() player.draw() win.flip() wait(3) instructions.draw() win.flip() wait(8)
def __init__(self, **kwargs): """ Create an ImageStim-like object that draws different images. Parameters ---------- kwargs: Arguments to pass to each psychopy.visual.ImageStim object """ self.is_flicker = kwargs.pop('flicker', True) util = Path(__file__).absolute().parent pngs = Path(util, 'dynamicmask').listdir(pattern='*.png') # workaround: psychopy checks type of image argument and expects str pngs = map(str, pngs) self.masks = [ImageStim(image=img, **kwargs) for img in pngs] self._ix = 1
def __init__(self, sub, run, output_str, stim_dir, scrambled, dummies, stim_file, ntrials=None, rt_cutoff=1, output_dir=None, settings_file=None): """ Initializes TestSession object. """ msg = ("When using this localizer, please acknowledge the original " "creators of the task (Stigliani et al.); for more info " "about how to cite the original authors, check " "http://vpnl.stanford.edu/fLoc\n") print(msg) if not op.isdir(stim_dir): msg = (f"Directory {stim_dir} does not exist!\n" f"To get the stimuli, simply run the following:\n" f"git clone https://github.com/FEED-UvA/fLoc.git") raise OSError(msg) self.stim_dir = stim_dir self.scrambled = scrambled self.dummies = dummies self.ntrials = ntrials self.rt_cutoff = rt_cutoff self.stim_file = stim_file df = pd.read_csv(stim_file, sep='\t') sub_id = f'sub-{sub}' self.stim_df = df.query('sub_id == @sub_id & run == @run') if self.ntrials is not None: # just for debugging self.stim_df = self.stim_df.iloc[:self.ntrials, :] self.stim_df.index = np.arange(0, len(self.stim_df), dtype=int) self.trials = [] self.current_trial = None super().__init__(output_str=output_str, settings_file=settings_file, output_dir=output_dir) self.current_stim = ImageStim(self.win, image=None) self.type2condition = dict(child='face', adult='face', body='body', limb='body', corridor='place', house='place', word='character', number='character', instrument='object', car='object', scrambled='scrambled', scrambled1='scrambled', scrambled2='scrambled', baseline='')
def userResponse(response, done, qpos, image, multi): """ Function that will be called every time the user needs to press a key to pass to the next display - **Input**: :response: the user resonse (empty string at beginning) :done: boolean (True / False) -> False at beginning :qpos: text position for user response :image: the stimulus image :multi: multiple display ? integer (1, 2 or 3) """ # --------------------------------------- # # WHILE THE WELCOME MESSAGE IS NOT PASSED # # --------------------------------------- # while len(response) == 0: # while the user has not taped anything yet response = '' # the response written by the user - On commence avec une chaîne vide respstim = TextStim(disp, text='', pos=qpos, height=size) # stimulus texte qstim = ImageStim(disp, image=image) qstim.draw() # dessiner la question if multi >= 2: # at least 2 diferent stimuli qstim2.draw() if multi == 3: # 3 diferent stimuli qstim3.draw() disp.flip( ) # passer au screen au suivant -> on met la question par-dessus core.wait(loadTime ) # delay of 10 seconds before passing to the learning phase done = False # ----------------------------------- # # WHILE THE USER'S ANSWER IS NOT DONE # # Check for keypresses # # ----------------------------------- # while not done: # loop until done == True resplist = waitKeys(maxWait=float('inf'), keyList=None, timeStamped=True) key, presstime = resplist[ 0] # use only the first in the returned list of keypresses -> resplist[0] is the first element in the resplist list response += key #Ajouter la lettre tapée à la réponse done = True # set done to True qstim.draw() # réafficher la question stimulus respstim.draw() # réafficher la réponse au stimulus disp.flip() # update the monitor core.wait( loadTime) # add a little lag to avoid little freez and/or bug
def __init__(self, disp, text, text_width, image, image_size, text_pos=None, image_pos=None, wait_time=1, extra_image_stims=None ): super(ImageScreen, self).__init__(disp, wait_time=wait_time) self.extra_image_stims = extra_image_stims if self.extra_image_stims is None: self.extra_image_stims = [] self.wait_time = wait_time if self.wait_time == 0: self.continue_button.clickable = True if text_pos is None: _text_pos = self.coords(self.width/4, self.height/2) else: _text_pos = text_pos if image_pos is None: _image_pos = self.coords(3*self.width/4, self.height/2) else: _image_pos = image_pos self.text_stim = TextStim( win=self.window, text=text, pos=_text_pos, height=Screen.default_font_size, wrapWidth=text_width ) self.img_stim = ImageStim( win=self.window, image=image, pos=_image_pos, size=(image_size[0], image_size[1]) )
def create_trials(self, sub, ses, run): df = pd.read_csv(self.stim_file, sep='\t').query('sub_id == @sub & ses == @ses & run == @run') df['face_id'] = [str(s).zfill(3) for s in df['face_id']] self.trials = [BaselineTrial(self, trial_nr=-1, phase_durations=(6,), phase_names=('fix',), verbose=True)] catches = np.random.permutation(['attractiveness', 'attractiveness', 'dominance', 'dominance', 'trustworthiness', 'trustworthiness']) i_catch = 0 for i in range(df.shape[0]): params = df.iloc[i, :] stim_dir = op.join(self.stim_dir, f"{params['expression']}_front") imgs = glob(op.join(stim_dir, f"{params['face_id']}_*.jpg")) if len(imgs) != 1: raise ValueError("Could not find stim (or too many).") img = ImageStim(self.win, imgs[0], size=(10, 10), units='deg') if int(params['catch']) == 0: phase_durations = [1.25, 3.75] phase_names = ['face', 'fix'] else: phase_durations = [1.25, 1.5, 2.5, 3.75] phase_names = ['face', 'fix', 'rating', 'fix'] i_catch += 1 params['rating_type'] = catches[i_catch - 1] if i == 20: phase_durations[-1] += 6.25 trial = FaceTrial( session=self, trial_nr=i, phase_durations=phase_durations, img=img, phase_names=phase_names, parameters=params.to_dict(), verbose=True, timing='seconds' ) self.trials.append(trial) self.trials.append(BaselineTrial(self, trial_nr=i+1, phase_durations=(6,), phase_names=('fix',), verbose=True))
def __init__(self, logfile, imgDir, subjectNum, screenType, numStim, numBlocks, trialDuration, ISI, selfPaced, runPractice, inputButtons, pauseButton): self.logfile = logfile self.imgDir = imgDir self.subjectNum = subjectNum self.numStim = numStim self.numBlocks = numBlocks self.trialDuration = trialDuration self.selfPaced = selfPaced self.ISI = ISI self.numCats = 4 self.trialsPer = int((self.numStim / self.numCats) / 2) self.runPractice = runPractice self.leftButton = inputButtons[0] self.rightButton = inputButtons[1] self.pauseButton = pauseButton #Set up window, center, left and right image sizes + positions if (screenType == 'Windowed'): screenSelect = False elif (screenType == 'Fullscreen'): screenSelect = True self.window = Window(fullscr=screenSelect, units='pix', color='White', allowGUI=False) self.imageWidth = self.window.size[1] / 5.5 self.centerImage = ImageStim(self.window) self.centerImage.setSize((self.imageWidth, self.imageWidth)) self.leftImage = ImageStim(self.window) self.leftImage.setPos((-1.5 * self.imageWidth, 0)) self.leftImage.setSize((self.imageWidth, self.imageWidth)) self.rightImage = ImageStim(self.window) self.rightImage.setPos((1.5 * self.imageWidth, 0)) self.rightImage.setSize((self.imageWidth, self.imageWidth)) self.clock = Clock() #Init score list for 4 categories: [correct,incorrect,response] self.scoreList = [] for i in range(0, 4): self.scoreList.append([0, 0, 0])
'', False, qpos, 'images/Degre.gif' ) # call the whoAmI -> double while loop to save the user taped response userResponse( '', False, qpos, 'images/Hello.gif' ) # call the userResponse -> double while loop to save the user taped response # ----------------------------------- # # SETTING FOR THE PRE-TEST # # WHILE THE PRE-TEST IS NOT SUCCEEDED # # ----------------------------------- # response = '' # the response attempted by the user - On commence avec une réponse vide while response != pretest: # while the answer is not correct response = '' # the response written by the user - On commence avec une chaîne vide respstim = TextStim(disp, text='', pos=qpos, height=size, color=color) # stimulus texte qstim = ImageStim(disp, image='images/TradVonat.gif') qstim.draw() # dessiner la question disp.flip() # passer au screen au suivant -> on met la question par-dessus core.wait( loadTime) # delay of 10 seconds before passing to the learning phase response, done = tapeAnswer( response, False, False) # While loop to taping the entire answer # ------------------------------------------------------- # # CHECK IF THE PRETEST IS SUCCEEDED OR NOT # # DISPLAY A MESSAGE TO THE USER ACCORDING TO THE ANSWER # # ------------------------------------------------------- # if response == pretest: # if the answer is correct userResponse( '', False, qpos, 'images/BravoVonat.gif' ) # call the userResponse -> double while loop to save the user taped response
class Display: def __init__(self, pars): self.win = initializers.setup_window() self.pars = pars self.geom = initializers.setup_geometry(self.win, self.pars) self.rotation_clocks = [None] * self.geom['numtargs'] self.type = ['default'] * self.geom['numtargs'] self.setup_sounds() self.setup_images() self.setup_text() def setup_sounds(self): self.cashsnd = Sound('resources/cash.wav') self.firesnd = Sound('resources/bbhit.wav') self.buzzsnd = Sound('resources/buzz.wav') def setup_images(self): self.notargs = [] self.gotargs = [] self.deftargs = [] self.bkimg = ImageStim(self.win, image='resources/pond.jpg', units='norm', size=(2.0, 2.0)) for targ in range(self.geom['numtargs']): self.notargs.append( ImageStim(self.win, image='resources/rfrog2.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) self.gotargs.append( ImageStim(self.win, image='resources/gfrog2.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) self.deftargs.append( ImageStim(self.win, image='resources/lilypad.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) # set initial target stims to be the defaults self.targets = [] for targ in self.deftargs: self.targets.append(targ) def setup_text(self): self.scoretxt = TextStim(self.win, text="Total Points: ", font='Helvetica', alignHoriz='left', alignVert='top', units='norm', pos=(-1, 1), height=0.2, color=[178, 34, 34], colorSpace='rgb255', wrapWidth=2) self.targtxt = [] for targ in range(self.geom['numtargs']): self.targtxt.append( TextStim(self.win, pos=self.geom['target_centers'][targ], color='White', units='height', height=0.05, text='')) def set_target_image(self, index, value='default'): if value == 'go': self.targets[index] = self.gotargs[index] elif value == 'no': self.targets[index] = self.notargs[index] elif value == 'default': self.targets[index] = self.deftargs[index] def set_target_text(self, index, value): self.targtxt[index].setText(value) def set_score(self, pts): self.scoretxt.setText('Total Points: ' + str(pts)) def onset(self, index, value): self.rotation_clocks[index] = Clock() self.type[index] = value def offset(self, index): self.rotation_clocks[index] = Clock() self.type[index] = 'default' def update(self): # for each target with clock running (i.e., rotating) ... for idx, clk in enumerate(self.rotation_clocks): if clk: rot_time = clk.getTime() rot_dur = self.pars['rot_dur'] if rot_time > rot_dur: rotfrac = -1 # rotation completed else: rotfrac = cos(pi * rot_time / self.pars['rot_dur']) # adjust target size to give illusion of rotation base_size = self.geom['target_size'] self.targets[idx].size = (abs(rotfrac) * base_size[0], base_size[1]) # set correct image on target based on rotation angle if rotfrac < 0: self.set_target_image(idx, self.type[idx]) def draw(self): self.update() self.bkimg.draw() self.scoretxt.draw() for stim in self.targets: stim.draw() for stim in self.targtxt: stim.draw() self.win.flip() def close(self): self.win.close()
class StimulusResource(Resource): should_stop = False def __enter__(self): from psychopy.visual import ImageStim # eats some time from psychopy.visual import TextStim event.clearEvents() win = self.window.instance self.textstim = TextStim(win, text='') # image texture index order is iamge[y, x] self.instance = ImageStim( win=win, units='deg', #, filpVert=True, pos=self.component.position, size=self.component.size) #misc.pix2deg(win.size, win.monitor)*2) try: self.interval = self.window.get_isi() except Exception as e: raise ServiceRuntimeException( 'Could not acquire window object. Please try again') return self @memoized_property def trials(self): from psychopy.data import TrialHandler # eats some time sqf = self.component.square_factor self.image = np.zeros((sqf, sqf)) conditions = [ Condition(x, y, v) for x, y, v in product(range(sqf), range(sqf), [-1, 1]) ] ts = [ Trial(self, cond, self.component.on_duration, self.interval) for cond in conditions ] return TrialHandler( ts, nReps=self.component.repetition, method=('random' if self.component.randomize else 'sequential')) @property def synced(self): self.clock.synchronize(self) return iter(self) def __iter__(self): trials = self.trials clock = self.clock.instance clock.reset() for trial in trials: self.update_trial(trial) logging.msg('Entering trial #%s...' % trials.thisN) trials.addData('on_time', clock.getTime()) yield trial.start() trials.addData('off_time', clock.getTime()) self.flip_blank() core.wait(self.component.off_duration) self.instance.opacity = 1.0 if self.should_stop: logging.msg('UserAbortException raised!') raise UserAbortException() def update_trial(self, trial): cond = trial.condition self.image[cond.y, cond.x] = cond.v self.instance.image = self.image self.instance.draw() self.image[cond.y, cond.x] = 0 # def update_phase(self, trial): # now = trial.tick() # self.instance.phase = np.mod(now * trial.condition.tf, 1) # self.instance.draw() # self.window.flip() def flip_text(self, text): self.textstim.setText(text) self.textstim.draw() self.window.flip() def flip_blank(self): self.instance.opacity = 0.0 self.instance.draw() self.window.flip()
def __init__( self, mouse: Mouse, window: Window, a_stimuli: List[str], b_stimuli: List[str], a_title: str, b_title: str, a_stimulus: str, b_stimulus: str, orientation: Optional[Literal["vertical", "horizontal"]] = "vertical", timeout: Optional[float] = None, instructions: Optional[str] = None, correct: Optional[Literal["a", "b"]] = None, global_progress: Optional[float] = None, ): assert orientation in ("vertical", "horizontal") if orientation == "horizontal": grid_offset = (57, 0) else: grid_offset = (240, 0) super().__init__(mouse, window, a_stimuli, b_stimuli, a_title, b_title, grid_offset) self.instructions = instructions self.timeout = timeout a_stimulus_image = ImageStim(window, a_stimulus) b_stimulus_image = ImageStim(window, b_stimulus) self.orientation = orientation if orientation == "horizontal": self.uncertain_2afc = HorizontalUncertainTwoAFCStim( mouse, window, a_stimulus_image, b_stimulus_image, pos=(0, -350), correct=correct, ) else: self.uncertain_2afc = VerticalUncertainTwoAFCStim( mouse, window, a_stimulus_image, b_stimulus_image, pos=(0, 0), correct=correct, ) self.timeout = timeout if timeout is None: self.timeout_progress_bar = None else: self.timeout_progress_bar = ProgressBar( window, pos=(0, -532), height=14, width=2 * (90 + a_stimulus_image.size[0])) if global_progress is None: self.global_progress_bar = None else: self.global_timeout_progress_bar = ProgressBar( window, pos=(0, -500), height=20, width=window.size[0]) self.global_timeout_progress_bar.update(global_progress)
framerate = float(cap.get(cv2.cv.CV_CAP_PROP_FPS)) # Compute the frame duration in milliseconds. framedur = 1000.0 / framerate # Get the frame size. width = cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH) height = cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT) # Reset the current stimscr. stimscr.clear() # For PsychoPy, prepare a new ImageStim. if DISPTYPE == 'psychopy': # Create a black frame, formatted as an all-zeros NumPy array. frame = numpy.zeros((height, width, 3), dtype=float) # Now create a PsychoPy ImageStim instance to draw the frame with. stim = ImageStim(pygaze.expdisplay, image=frame, size=(width, height)) # When DISPTYPE='psychopy', a Screen instance's screen property is a list # of PsychoPy stimuli. We would like to add the ImageStim we just created # to that list, and record at what index in the list it was added. # First we get the current length of the stimscr's list of stimuli, which # will be the index at which the new ImageStim will be assigned to. stim_index = len(stimscr.screen) # Then we add the ImageStim to the stimscr. Every time you call # disp.fill(stimscr) and then disp.show(), all stimuli in stimscr # (including the ImageStim) will be drawn. stimscr.screen.append(stim) # Wait until the participant presses any key to start. disp.fill(textscr) disp.show() kb.get_key(keylist=None, timeout=None, flush=True)
class MDTT(object): def __init__(self, logfile, imgDir, subjectNum, screenType, numStim, numBlocks, trialDuration, ISI, selfPaced, runPractice, inputButtons, pauseButton): self.logfile = logfile self.imgDir = imgDir self.subjectNum = subjectNum self.numStim = numStim self.numBlocks = numBlocks self.trialDuration = trialDuration self.selfPaced = selfPaced self.ISI = ISI self.numCats = 4 self.trialsPer = int((self.numStim / self.numCats) / 2) self.runPractice = runPractice self.leftButton = inputButtons[0] self.rightButton = inputButtons[1] self.pauseButton = pauseButton #Set up window, center, left and right image sizes + positions if (screenType == 'Windowed'): screenSelect = False elif (screenType == 'Fullscreen'): screenSelect = True self.window = Window(fullscr=screenSelect, units='pix', color='White', allowGUI=False) self.imageWidth = self.window.size[1] / 5.5 self.centerImage = ImageStim(self.window) self.centerImage.setSize((self.imageWidth, self.imageWidth)) self.leftImage = ImageStim(self.window) self.leftImage.setPos((-1.5 * self.imageWidth, 0)) self.leftImage.setSize((self.imageWidth, self.imageWidth)) self.rightImage = ImageStim(self.window) self.rightImage.setPos((1.5 * self.imageWidth, 0)) self.rightImage.setSize((self.imageWidth, self.imageWidth)) self.clock = Clock() #Init score list for 4 categories: [correct,incorrect,response] self.scoreList = [] for i in range(0, 4): self.scoreList.append([0, 0, 0]) def SplitRange(self, rangeMin, rangeMax, start=0): """Creates a pair of indexes separated by a value. The value itself can be between a min-max range. Neither index can be an index that is in a list of already used indexes. rangeMin: minimum amount that indexes can be separated by rangeMax: maximum amount that indexes can be separated by start: start index of used list return: a pair of indexes (index1,index2) (-1,-1) if range split failed """ #Search through list of used indexes to ensure no duplicates #Ignore start/end of list, as it's already used by primacy/recency for i in range(0, self.numStim): if (i in self.usedList): continue added = random.randint(rangeMin, rangeMax) startPt = added searchedRange = False #Loop through the min to max range of added values while not searchedRange: if ((i + added < self.numStim) and (i + added not in self.usedList)): self.usedList.append(i) self.usedList.append(i + added) return (i, i + added) if (added > rangeMin): added -= 1 else: added = rangeMax if (added == startPt): searchedRange = True return (-1, -1) def CreatePairsSpaced(self): """Creates a list, each element containing two indexes as well as a trial type. The trial type is based upon the spacing of the indexes as follows: adjacent (1): numbers next to eachother e.g. (3,4) or (8,9) eightish (2): numbers separated by between 7-9 e.g. (5,12) or (14,23) sixteenish (3): numbers separated by between 15-17 e.g. (3,18) or (8,25) primacy/recency: (4): start and end of list numbers e.g. (1,30) or (0,31) Occassionally, the list will fail to successfully split into index pairs. (SplitRange() returns (-1,-1) when this happens). The function will retry the index splitting until all indexes are used return: list containing elements each with: (index1,index2,trialType) """ startList = range(0, self.trialsPer) endList = range(self.numStim - self.trialsPer, self.numStim) trialOrder = range(0, (self.trialsPer * 3)) #3 categories besides P/R random.shuffle(startList) random.shuffle(endList) #Attempt to split 0-31 range into 4 index categories #Split fails if any one of the index pairs is (-1,-1) at end def AttemptSplit(): # 3 categories besides P/R trialOrder = range(0, (self.trialsPer * 3)) random.shuffle(trialOrder) self.usedList = [] attemptList = [] finalList = [] #Add edge index pairs (primacy/recency) for i in range(0, self.trialsPer): finalList.append((startList[i], endList[i], 4)) self.usedList.append(startList[i]) self.usedList.append(endList[i]) #Add spaced (separated) pairs of indexes to list for trial in trialOrder: if (trial % 3 == 0): #Adjacent (idxOne, idxTwo) = self.SplitRange(1, 1) attemptList.append((idxOne, idxTwo, 1)) elif (trial % 3 == 1): #Eightish (idxOne, idxTwo) = self.SplitRange(7, 9) attemptList.append((idxOne, idxTwo, 2)) elif (trial % 3 == 2): #Sixteenish (idxOne, idxTwo) = self.SplitRange(15, 17) attemptList.append((idxOne, idxTwo, 3)) #Ensures PR trials (type 4) occur first. Randomize successive trials random.shuffle(attemptList) finalList.extend(attemptList) return finalList #Try AttemptSplit() until index split is successful splitSuccess = False while (not splitSuccess): splitList = AttemptSplit() foundError = False for pair in splitList: if ((pair[0] == -1) or (pair[1] == -1)): foundError = True if (foundError == True): continue else: splitSuccess = True return splitList def RunTrialSingle(self, img): """Displays a single image at the center of the screen for a period of time, and captures keypresses and their respective reaction times. img: the image to Displays return: a list of keypresses and respective reaction times """ self.centerImage.setImage(self.imgDir + "/%s" % (img)) self.centerImage.draw(self.window) clearEvents() self.window.flip() self.clock.reset() keyPresses = [] if (self.selfPaced == False): wait(self.trialDuration, self.trialDuration) keyPresses = getKeys(keyList=[ self.leftButton, self.rightButton, self.pauseButton, "escape" ], timeStamped=self.clock) elif (self.selfPaced == True): keyPresses = waitKeys(keyList=[ self.leftButton, self.rightButton, self.pauseButton, "escape" ], timeStamped=self.clock) self.window.flip() wait(self.ISI) return keyPresses def RunTrialDual(self, leftImg, rightImg): """Displays two images on the screen for a period of time, and captures keypresses and their respective reaction times. leftimg: the image to display on the left rightimg: the image to display on the right return: a list of keypresses and respective reaction times """ self.leftImage.setImage(self.imgDir + "/%s" % (leftImg)) self.rightImage.setImage(self.imgDir + "/%s" % (rightImg)) self.leftImage.draw(self.window) self.rightImage.draw(self.window) clearEvents() self.window.flip() self.clock.reset() if (self.selfPaced == False): wait(self.trialDuration, self.trialDuration) keyPresses = getKeys(keyList=[ self.leftButton, self.rightButton, self.pauseButton, "escape" ], timeStamped=self.clock) elif (self.selfPaced == True): keyPresses = waitKeys(keyList=[ self.leftButton, self.rightButton, self.pauseButton, "escape" ], timeStamped=self.clock) self.window.flip() wait(self.ISI) return keyPresses def RunStudy(self, imageBlock, session): """Runs the study, i.e. the first half of each experimental block. Writes all relevant information about the study to a logfile. imageBlock: List of images to display during the study session: the number of the session (block number) that is running """ studyPrompt = ( "Test Session {}/{}: Are the following objects indoor or outdoor?\n\n('{}' to continue)" .format(session, 10, self.pauseButton)) studyText = TextStim(self.window, studyPrompt, color='Black') studyText.draw(self.window) self.window.flip() continueKey = waitKeys(keyList=[self.pauseButton, 'escape']) if (continueKey[0] == 'escape'): self.logfile.write("\n\n\nStudy Not Run Early\n\n\n") return self.logfile.write("\nBegin Study %d\n" % (session)) self.logfile.write("{h1:<6}{h2:<23}{h3:<10}{h4}\n".format( h1="Trial", h2="Image", h3="Response", h4="RT")) #Run trial for each image in the image block for i in range(0, len(imageBlock)): keyPresses = self.RunTrialSingle(imageBlock[i]) if (keyPresses == []): respKey = '' respRT = 0 else: respKey = keyPresses[0][0] respRT = keyPresses[0][1] if (respKey == "escape"): self.logfile.write("\n\n\nStudy block terminated early\n\n\n") break elif (respKey == self.pauseButton): self.Pause() self.logfile.write("{:^5}{:<23}{:^11}{:<1.3f}\n".format( i + 1, imageBlock[i], respKey, respRT)) return def RunTest(self, imageBlock, pairList, session): """Runs the test, i.e. the second half of each experimental block. Wites all relevant information about the test to a logfile imageBlock: List of images to display during the test pairList: List of paired image indexes w/ trial type session: the number of the session (block number) that is running """ testPrompt = ( "In this phase, the same series of objects will be shown\n\nWhich came first: Left or Right?\n\n('{}' to continue)" .format(self.pauseButton)) testText = TextStim(self.window, testPrompt, color='Black') testText.draw(self.window) self.window.flip() continueKey = waitKeys(keyList=[self.pauseButton, 'escape']) if (continueKey[0] == 'escape'): self.logfile.write("\n\n\nTest Not Run\n\n\n") return 0 self.logfile.write("\nBegin Test %d\n" % (session)) lghead = "{a:<7}{b:<7}{c:<23}{d:<23}{e:<7}{f:<7}{g:<10}{h:<7}{i}\n".format( a="Trial", b="TType", c="LeftImage", d="RightImage", e="LNum", f="RNum", g="CorResp", h="Resp", i="RT") self.logfile.write(lghead) #Randomize if pair is shown: (bef > aft) or (aft > bef) order sideOrder = range(0, len(pairList)) random.shuffle(sideOrder) correct = '' keyPresses = [] #Run dual image trial for each pair in the pairlist for i in range(0, len(pairList)): trialNum = i + 1 trialType = pairList[i][2] firstIdx = pairList[i][0] secondIdx = pairList[i][1] firstImg = imageBlock[pairList[i][0]] secondImg = imageBlock[pairList[i][1]] #Preserve the order images were shown in if (sideOrder[i] % 2 == 0): correct = self.leftButton leftIdx = firstIdx rightIdx = secondIdx leftImg = firstImg rightImg = secondImg keyPresses = self.RunTrialDual(leftImg, rightImg) #Reverse order images were shown elif (sideOrder[i] % 2 == 1): correct = self.rightButton leftIdx = secondIdx rightIdx = firstIdx leftImg = secondImg rightImg = firstImg keyPresses = self.RunTrialDual(leftImg, rightImg) #Get first response, or set to none if no response if (keyPresses == []): respKey = '' respRT = 0 else: respKey = keyPresses[0][0] respRT = keyPresses[0][1] #Break out of image block with escape, break out of program with f5 if (respKey == 'escape'): self.logfile.write("\n\nTest block terminated early\n\n") break elif (respKey == self.pauseButton): self.Pause() #Keep track of score if (respKey): self.scoreList[pairList[i][2] - 1][2] += 1 if (respKey == correct): self.scoreList[pairList[i][2] - 1][0] += 1 else: self.scoreList[pairList[i][2] - 1][1] += 1 #Write info to logfile lgspace = "{:^5}{:^9}{:<23}{:<23}{:<7}{:<10}{:<8}{:<6}{:<1.3f}\n" lgform = (lgspace.format(trialNum, trialType, leftImg, rightImg, leftIdx, rightIdx, correct, respKey, respRT)) self.logfile.write(lgform) return 1 def Pause(self): """Pauses the task, and displays a message waiting for a spacebar input from the user before continuing to proceed. """ pauseMsg = "Experiment Paused\n\nPress '{}' to continue".format( self.pauseButton) pauseText = TextStim(self.window, text=pauseMsg, color='Black', height=40) pauseText.draw(self.window) self.window.flip() waitKeys(keyList=[self.pauseButton]) clearEvents() def SegmentPracticeImages(self, images): ''' Return the indexes for the test, it will index the image list from study: [[index_left_image, index_right_image, trialType]] ''' # Since we know that the images are already randomized, we can just iterate over them # In order for the code to work, we want 4 practice images per practice block if len(images) != 4: print "Assertion error: length of practice images is not equal to 4" self.window.close() sys.exit() # Trial type of 4 means long distance large_dist = (0, 3, 4) if random.random() > .5 else (3, 0, 4) mid_dist_1 = (0, 2, 2) if random.random() > .5 else (2, 0, 2) mid_dist_2 = (1, 3, 2) if random.random() > .5 else (3, 1, 2) adjacent = (0, 1, 1) if random.random() > .5 else (1, 0, 1) adjacent_2 = (1, 2, 1) if random.random() > .5 else (2, 1, 1) adjacent = adjacent if random.random() > .5 else adjacent_2 all = [large_dist, mid_dist_1, mid_dist_2, adjacent] random.shuffle(all) return all def ShowPromptAndWaitForSpace(self, prompt, keylist=['space', 'escape']): ''' Show the prompt on the screen and wait for space, or the keylist specified returns the key pressed ''' keylist = [self.pauseButton, 'escape'] text = TextStim(self.window, prompt, color='Black') text.draw(self.window) self.window.flip() continueKey = waitKeys(keyList=keylist) if len(continueKey) != 0 and continueKey[0] == 'escape': self.logfile.write("Terminated early.") self.logfile.close() sys.exit() return continueKey def RunSinglePractice(self, practiceBlock, imgs): ''' Read in the images we want, and run the practice block for this subject Run encoding and test, and write to the logs Return: float: ratio correct ''' random.shuffle(imgs) ### Encoding # imgs = [[img, trialType, Study(x,y), Test(x,y)]] testIdxs = self.SegmentPracticeImages(imgs) self.ShowPromptAndWaitForSpace( " Indoor or Outdoor?\n\n('{}' to continue)".format( self.pauseButton)) self.logfile.write("\nBegin Practice Study {}\n".format(practiceBlock)) self.logfile.write("{h1:<6}{h2:<23}{h3:<10}{h4}\n".format( h1="Trial", h2="Image", h3="Response", h4="RT")) # Run the trial for each encoding trial for i in range(0, len(imgs)): keyPresses = self.RunTrialSingle(imgs[i]) if (keyPresses == []): respKey = '' respRT = 0 else: respKey = keyPresses[0][0] respRT = keyPresses[0][1] if (respKey == "escape"): self.logfile.write("\n\n\nStudy block terminated early\n\n\n") break elif (respKey == self.pauseButton): self.Pause() self.logfile.write("{:^5}{:<23}{:^11}{:<1.3f}\n".format( i + 1, imgs[i], respKey, respRT)) ### Test self.ShowPromptAndWaitForSpace( " Which came first? Left or right? ('{}' to continue)".format( self.pauseButton)) self.logfile.write("\nBegin Practice Test {}\n".format(practiceBlock)) self.logfile.write( "{a:<7}{b:<7}{c:<23}{d:<23}{e:<7}{f:<7}{g:<10}{h:<7}{i}\n".format( a="Trial", b="TType", c="LeftImage", d="RightImage", e="LNum", f="RNum", g="CorResp", h="Resp", i="RT")) # Keep track of the total number they got correct totalCorrect = 0 for trialNum, idxes in enumerate(testIdxs): leftImgIdx, rightImgIdx, trialType = idxes leftImg = imgs[leftImgIdx] rightImg = imgs[rightImgIdx] keyPresses = self.RunTrialDual(leftImg, rightImg) correct = self.leftButton if leftImgIdx < rightImgIdx else self.rightButton #Get first response, or set to none if no response if (keyPresses == []): respKey = '' respRT = 0 else: respKey = keyPresses[0][0] respRT = keyPresses[0][1] #Break out of image block with escape, break out of program with f5 if (respKey == 'escape'): self.logfile.write("\n\nPractice block terminated early\n\n") self.logfile.close() sys.exit() #Write info to logfile lgspace = "{:^5}{:^9}{:<23}{:<23}{:<7}{:<10}{:<8}{:<6}{:<1.3f}\n" lgform = (lgspace.format(trialNum + 1, trialType, leftImg, rightImg, leftImgIdx, rightImgIdx, correct, respKey, respRT)) self.logfile.write(lgform) if respKey == correct: totalCorrect += 1 # Return the percentage correct return totalCorrect / len(imgs) def RunPractice(self): ''' Runs three rounds of practice trials. If the participant gets a certain amount correct, they move on to the real test. ''' dirFiles = os.listdir(self.imgDir) practiceImages = [img for img in dirFiles if "PR_" in img] if len(practiceImages) == 0: print "No practice images found" self.window.close() sys.exit() random.shuffle(practiceImages) # Split the practice images into three sets practiceImages = np.array_split(practiceImages, 3) # Run each practice session for i in range(3): practicePrompt = "Let's practice\n\n('{}' to continue)".format( self.pauseButton) self.ShowPromptAndWaitForSpace(practicePrompt) results = self.RunSinglePractice( i + 1, [img for img in practiceImages[i]]) # If they get a certain percentage correct, then stop the practice self.ShowPromptAndWaitForSpace( "You got {}% correct! ('{}' to continue)".format( int(results * 100), self.pauseButton)) if results > .6: return def RunExp(self): """Runs through an instance of the MDT-T experiment, which includes arranging the images into lists/sublists, running through a given number of study/test blocks, and writing the scores to a logfile. """ #Print task ending message to the screen; wait for user to press escape def EndExp(): exitPrompt = ("This concludes the session. Thank you for " "participating!\n\nPress Escape to quit") exitText = TextStim(self.window, exitPrompt, color='Black') exitText.draw(self.window) self.window.flip() waitKeys(keyList=['escape']) self.window.close() # Run practice if self.runPractice: self.RunPractice() #Put image files from folder into list imageList = [] for img in os.listdir(self.imgDir): if ( img[-4:] == ".jpg" and "PR_" not in img ): # Make sure that PR (practice image) is not included for study/tests imageList.append(img) random.shuffle(imageList) #Divide imagelist into <numBlocks> # of lists, put into one list #Each sublist contains <numStim> # of stimuli imageBlockList = [] for i in range(0, self.numBlocks): block = [] for j in range(i * self.numStim, self.numStim + (i * self.numStim)): block.append(imageList[j]) imageBlockList.append(block) #Run through each study/test block blockOrder = range(0, self.numBlocks) random.shuffle(blockOrder) writeScores = True for i in range(0, len(blockOrder)): pairList = self.CreatePairsSpaced() self.RunStudy(imageBlockList[i], i + 1) testFinished = self.RunTest(imageBlockList[i], pairList, i + 1) if not testFinished: writeScores = False continue EndExp() #Return logfile and scorelist if all study/test blocks gone through if writeScores: return (self.logfile, self.scoreList) else: return (-1, -1)
Please press any key to continue.""", wrapWidth=30, units='deg', pos=[0, -2], height=.6, color='White') intromes.draw() descriptionmes.draw() win.flip() waitKeys() #Setting up the examples and questions: sample_aid_short = ImageStim( win, image= "C:\Users\lasch\OneDrive\Documents\Wright State\Research\Cara_experiment_code\intShort.png", pos=[-7, 0]) sample_aid_long = ImageStim( win, image= "C:\Users\lasch\OneDrive\Documents\Wright State\Research\Cara_experiment_code\intLong.png", pos=[7, 0]) aid = TextStim( win, text= """Examples of long and short bars with automated aid \n \nPress any key to continue""", wrapWidth=40, units='deg', pos=[0, 10], height=1,
#save a log file logFile = logging.LogFile(fileName + '.log', level=logging.DEBUG) logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file #create a window mywin = Window(screen_size, units='pix', color=background_color, fullscr=full_screen) #create some stimuli """ 2 separate blocks: learning (difficulty either increases or decreases) & transfer (difficulty are all shuffled) blocks 1 group of subjects starts with easy to hard (odd participants) and the other group starts with hard to easy (even participants) in the learning block both leanring block and transfer are 30 trials, so 60 trials in total """ directory_stimuli = os.path.join(os.getcwd(), 'stimuli', 'example_3') # directory where images can be found patch_image = ImageStim(win=mywin, size=image_size) # create image object n_trials = 30 if (expInfo['participant'] % 2) == 0: # order difficulty even participants order_difficulty = ['hard', 'medium', 'easy'] else: # order difficulty odd participants order_difficulty = ['easy', 'medium', 'hard'] """ create a dataframe with information about the stimuli corrisponding to their file number: - the first half of images are from category 'A', the second from 'B' - for the first half of images the correct response is 'a', for the second is 'b' - difficulty goes from easy to medium to hard, every 5 images for both category example: image 1 (patch1.png) is from category A, so the correct response is 'a' and the difficulty is easy """
class Display: def __init__(self, pars): self.win = initializers.setup_window() self.pars = pars self.geom = initializers.setup_geometry(self.win, self.pars) self.rotation_clocks = [None] * self.geom['numtargs'] self.type = ['default'] * self.geom['numtargs'] self.setup_sounds() self.setup_images() self.setup_text() def setup_sounds(self): self.cashsnd = Sound('resources/cash.wav') self.firesnd = Sound('resources/bbhit.wav') self.buzzsnd = Sound('resources/buzz.wav') def setup_images(self): self.notargs = [] self.gotargs = [] self.deftargs = [] self.bkimg = ImageStim(self.win, image='resources/pond.jpg', units='norm', size=(2.0, 2.0)) for targ in range(self.geom['numtargs']): self.notargs.append(ImageStim(self.win, image='resources/rfrog2.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) self.gotargs.append(ImageStim(self.win, image='resources/gfrog2.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) self.deftargs.append(ImageStim(self.win, image='resources/lilypad.jpg', size=self.geom['target_size'], pos=self.geom['target_centers'][targ])) # set initial target stims to be the defaults self.targets = [] for targ in self.deftargs: self.targets.append(targ) def setup_text(self): self.scoretxt = TextStim(self.win, text="Total Points: ", font='Helvetica', alignHoriz='left', alignVert='top', units='norm', pos=(-1, 1), height=0.2, color=[178, 34, 34], colorSpace='rgb255', wrapWidth=2) self.targtxt = [] for targ in range(self.geom['numtargs']): self.targtxt.append(TextStim(self.win, pos=self.geom['target_centers'][targ], color='White', units='height', height=0.05, text='')) def set_target_image(self, index, value='default'): if value == 'go': self.targets[index] = self.gotargs[index] elif value == 'no': self.targets[index] = self.notargs[index] elif value == 'default': self.targets[index] = self.deftargs[index] def set_target_text(self, index, value): self.targtxt[index].setText(value) def set_score(self, pts): self.scoretxt.setText('Total Points: ' + str(pts)) def onset(self, index, value): self.rotation_clocks[index] = Clock() self.type[index] = value def offset(self, index): self.rotation_clocks[index] = Clock() self.type[index] = 'default' def update(self): # for each target with clock running (i.e., rotating) ... for idx, clk in enumerate(self.rotation_clocks): if clk: rot_time = clk.getTime() rot_dur = self.pars['rot_dur'] if rot_time > rot_dur: rotfrac = -1 # rotation completed else: rotfrac = cos(pi * rot_time / self.pars['rot_dur']) # adjust target size to give illusion of rotation base_size = self.geom['target_size'] self.targets[idx].size = (abs(rotfrac) * base_size[0], base_size[1]) # set correct image on target based on rotation angle if rotfrac < 0: self.set_target_image(idx, self.type[idx]) def draw(self): self.update() self.bkimg.draw() self.scoretxt.draw() for stim in self.targets: stim.draw() for stim in self.targtxt: stim.draw() self.win.flip() def close(self): self.win.close()