def Run(self): trials = csv.DictReader(self.trialFileName, delimiter="\t") #Reads the trial structure, the sizes of rectangles etc. dataFile = csv.DictWriter(self.data, fieldnames=["RT","KeyPress"]) #This is the data file that the participant data will be written dataFile.writeheader() for trial in trials: for i in range(int(trial["TrialNumber"])): #Determines how many trials each block have sizes = [int(trial["WidthofStimulus1"]), int(trial["WidthofStimulus2"])] random.shuffle(sizes) #This is for randomizing the presentation side of each stimulus timeFrame = core.StaticPeriod(win=expWin) #To determine time period for each trial timeFrame.start(0.5) stimulus1 = visual.Rect(expWin, height=100, width=sizes[0], lineWidth=2, lineColor="black", fillColor="red", pos=(-300,0)) stimulus1.draw() #Stimuli presentations stimulus2 = visual.Rect(expWin, height=100, width=sizes[1], lineWidth =2, lineColor="black", fillColor="black", pos=(300,0)) stimulus2.draw() if "," in trial["Names"]: #If two stimuli that belong to different categories are presented both of their category name is presented name1 = trial["Names"][1:trial["Names"].find(",")] #Extracting names of categories from the file name2 = trial["Names"][trial["Names"].find(",")+1:-1] if sizes[0] != int(trial["WidthofStimulus1"]): name1, name2 = name2, name1 #Determines whether shuffling change the order, if it did it changes category names as well disp1 = visual.TextStim(expWin, color=txtColor, text=name1, pos=(-300,-100)) disp2 = visual.TextStim(expWin, color=txtColor, text=name2, pos= (300, -100)) disp1.draw() #Category names are displayed disp2.draw() else: disp = visual.TextStim(expWin, color=txtColor, text=trial["Names"], pos=(0,-100)) disp.draw() expWin.flip() timeFrame.complete()
def __init__(self, win, daq, parameters, file_save, classifier, lmodel, fake): self.window = win self.frame_rate = self.window.getActualFrameRate() self.parameters = parameters self.daq = daq self.static_clock = core.StaticPeriod(screenHz=self.frame_rate) self.experiment_clock = core.Clock() self.buffer_val = parameters['task_buffer_len'] self.alp = alphabet(parameters) self.rsvp = _init_copy_phrase_display(self.parameters, self.window, self.daq, self.static_clock, self.experiment_clock) self.file_save = file_save trigger_save_location = f"{self.file_save}/{parameters['triggers_file_name']}" self.trigger_file = open(trigger_save_location, 'w') self.session_save_location = f"{self.file_save}/{parameters['session_file_name']}" self.wait_screen_message = parameters['wait_screen_message'] self.wait_screen_message_color = parameters[ 'wait_screen_message_color'] self.num_sti = parameters['num_sti'] self.len_sti = parameters['len_sti'] self.timing = [ parameters['time_target'], parameters['time_cross'], parameters['time_flash'] ] self.color = [ parameters['target_letter_color'], parameters['fixation_color'], parameters['stimuli_color'] ] self.task_info_color = parameters['task_color'] self.stimuli_height = parameters['sti_height'] self.is_txt_sti = parameters['is_txt_sti'] self.eeg_buffer = parameters['eeg_buffer_len'] self.copy_phrase = parameters['text_task'] self.spelled_letters_count = int(parameters['spelled_letters_count']) if self.spelled_letters_count > len(self.copy_phrase): logging.debug("Already spelled letters exceeds phrase length.") self.spelled_letters_count = 0 self.max_seq_length = parameters['max_seq_len'] self.max_seconds = parameters['max_minutes'] * 60 # convert to seconds self.fake = fake self.lmodel = lmodel self.classifier = classifier self.down_sample_rate = parameters['down_sampling_rate']
def initializePatches(win, expInfo): """ This function initializes the Gabor-patches Input: win: window object instance expInfo: Structure with background information about experiment Return: patchClock: clock object instance for patch timing patch1: object instance for first Gabor-patch patch2: object instance for second Gabor-patch """ patchClock = core.Clock() ISI = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI') patch1 = visual.GratingStim(win=win, name='patch1', units='cm', tex='sin', mask='raisedCos', ori=0, pos=[0, 0], size=10, sf=0.4, phase=0.0, color=[1, 1, 1], colorSpace='rgb', opacity=1.0, texRes=512, interpolate=True, depth=-1.0) patch2 = visual.GratingStim(win=win, name='patch2', units='cm', tex='sin', mask='raisedCos', ori=0, pos=[0, 0], size=10, sf=0.4, phase=0.0, color=[1, 1, 1], colorSpace='rgb', opacity=1.0, texRes=512, interpolate=True, depth=-2.0) return (patchClock, patch1, patch2)
def __init__(self, win, daq, parameters, file_save, fake): super(RSVPCopyPhraseCalibrationTask, self).__init__() self.window = win self.frame_rate = self.window.getActualFrameRate() self.parameters = parameters self.daq = daq self.static_clock = core.StaticPeriod(screenHz=self.frame_rate) self.experiment_clock = core.Clock() self.buffer_val = parameters['task_buffer_len'] self.alp = alphabet(parameters) self.rsvp = _init_copy_phrase_display_task(self.parameters, self.window, self.daq, self.static_clock, self.experiment_clock) self.file_save = file_save trigger_save_location = f"{self.file_save}/{parameters['triggers_file_name']}" self.session_save_location = f"{self.file_save}/{parameters['session_file_name']}" self.trigger_file = open(trigger_save_location, 'w') self.wait_screen_message = parameters['wait_screen_message'] self.wait_screen_message_color = parameters[ 'wait_screen_message_color'] self.num_sti = parameters['num_sti'] self.len_sti = parameters['len_sti'] self.timing = [ parameters['time_target'], parameters['time_cross'], parameters['time_flash'] ] self.color = [ parameters['target_letter_color'], parameters['fixation_color'], parameters['stimuli_color'] ] self.task_info_color = parameters['task_color'] self.stimuli_height = parameters['sti_height'] self.is_txt_sti = parameters['is_txt_sti'] self.eeg_buffer = parameters['eeg_buffer_len'] self.copy_phrase = parameters['text_task'] self.max_seq_length = parameters['max_seq_len'] self.fake = fake self.enable_breaks = parameters['enable_breaks']
def __init__(self, win, daq, parameters, file_save): super(RSVPCalibrationTask, self).__init__() self.window = win self.frame_rate = self.window.getActualFrameRate() self.parameters = parameters self.daq = daq self.static_clock = core.StaticPeriod(screenHz=self.frame_rate) self.experiment_clock = core.Clock() self.buffer_val = parameters['task_buffer_len'] self.alp = alphabet(parameters) self.rsvp = init_calibration_display_task(self.parameters, self.window, self.daq, self.static_clock, self.experiment_clock) self.file_save = file_save trigger_save_location = f"{self.file_save}/{parameters['trigger_file_name']}" self.trigger_file = open(trigger_save_location, 'w', encoding='utf-8') self.wait_screen_message = parameters['wait_screen_message'] self.wait_screen_message_color = parameters[ 'wait_screen_message_color'] self.stim_number = parameters['stim_number'] self.stim_length = parameters['stim_length'] self.timing = [ parameters['time_target'], parameters['time_cross'], parameters['time_flash'] ] self.color = [ parameters['target_letter_color'], parameters['fixation_color'], parameters['stim_color'] ] self.task_info_color = parameters['task_color'] self.stimuli_height = parameters['stim_height'] self.is_txt_stim = parameters['is_txt_stim'] self.eeg_buffer = parameters['eeg_buffer_len'] self.enable_breaks = parameters['enable_breaks']
def __init__(self, win, daq, parameters, file_save, signal_model, language_model, fake, is_word, auc_filename): super(RSVPIconToIconTask, self).__init__() self.window = win self.frame_rate = self.window.getActualFrameRate() self.parameters = parameters self.daq = daq self.static_clock = core.StaticPeriod(screenHz=self.frame_rate) self.experiment_clock = core.Clock() self.buffer_val = parameters['task_buffer_len'] self.image_path = parameters['path_to_presentation_images'] # Alphabet is comprised of the image base names self.alp = alphabet(parameters, include_path=False) self.rsvp = _init_icon_to_icon_display_task( self.parameters, self.window, self.daq, self.static_clock, self.experiment_clock, is_word) self.file_save = file_save self.is_word = is_word trigger_save_location = f'{self.file_save}/{parameters["trigger_file_name"]}' self.trigger_file = open(trigger_save_location, 'w+') self.session_save_location = f'{self.file_save}/{parameters["session_file_name"]}' self.wait_screen_message = parameters['wait_screen_message'] self.wait_screen_message_color = parameters[ 'wait_screen_message_color'] self.stim_number = parameters['stim_number'] self.stim_length = parameters['stim_length'] self.timing = [ parameters['time_target'], parameters['time_cross'], parameters['time_flash'] ] self.color = [ parameters['target_letter_color'], parameters['fixation_color'], parameters['stim_color'] ] self.task_info_color = parameters['task_color'] self.stimuli_height = parameters['stim_height'] self.eeg_buffer = parameters['eeg_buffer_len'] self.max_seconds = parameters['max_minutes'] * 60 # convert to seconds self.max_seq_length = parameters['max_seq_len'] self.max_seq_per_trial = parameters['max_seq_per_trial'] self.fake = fake self.language_model = language_model self.signal_model = signal_model self.auc_filename = auc_filename self.task_height = parameters['task_height'] self.is_txt_stim = False self.min_num_seq = parameters['min_seq_len'] self.word_matching_text_size = parameters['word_matching_text_size'] self.collection_window_len = parameters[ 'collection_window_after_trial_length'] self.data_save_path = parameters['data_save_loc'] match_type = 'Word' if self.is_word else 'Icon' self.session_description = f'Icon to {match_type} Matching'
def Test(): # Ensure that relative paths start from the same directory as this script _thisDir = os.path.dirname(os.path.abspath(__file__)) os.chdir(_thisDir) # Store info about the experiment session expName = u'Test1' # from the Builder filename that created this script expInfo = {'participant': '', 'session': '001'} dlg = gui.DlgFromDict(dictionary=expInfo, title=expName) if dlg.OK == False: core.quit() # user pressed cancel expInfo['date'] = data.getDateStr() # add a simple timestamp expInfo['expName'] = expName # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc filename = _thisDir + os.sep + 'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date']) # An ExperimentHandler isn't essential but helps with data saving thisExp = data.ExperimentHandler(name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath=None, savePickle=True, saveWideText=True, dataFileName=filename) #save a log file for detail verbose info logFile = logging.LogFile(filename + '.log', level=logging.EXP) logging.console.setLevel( logging.WARNING) # this outputs to the screen, not a file endExpNow = False # flag for 'escape' or other condition => quit the exp # Start Code - component code to be run before the window creation # Setup the Window win = visual.Window( size=(1200, 1920), fullscr=True, screen=0, allowGUI=False, allowStencil=False, monitor='testMonitor', color=[0, 0, 0], colorSpace='rgb', blendMode='avg', useFBO=True, ) # store frame rate of monitor if we can measure it successfully expInfo['frameRate'] = win.getActualFrameRate() if expInfo['frameRate'] != None: frameDur = 1.0 / round(expInfo['frameRate']) else: frameDur = 1.0 / 60.0 # couldn't get a reliable measure so guess # Initialize components for Routine "trial" trialClock = core.Clock() ISI = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI') text = visual.TextStim(win=win, ori=0, name='text', text=u'Any text\n\nincluding line breaks', font=u'Arial', pos=[0, 0], height=0.1, wrapWidth=None, color=u'white', colorSpace=u'rgb', opacity=1, depth=-1.0) text_2 = visual.TextStim(win=win, ori=0, name='text_2', text=u'Text2', font=u'Arial', pos=[0, 0], height=0.1, wrapWidth=None, color=u'white', colorSpace=u'rgb', opacity=1, depth=-2.0) # Create some handy timers globalClock = core.Clock() # to track the time since experiment started routineTimer = core.CountdownTimer( ) # to track time remaining of each (non-slip) routine #------Prepare to start Routine "trial"------- t = 0 trialClock.reset() # clock frameN = -1 routineTimer.add(4.000000) # update component parameters for each repeat # keep track of which components have finished trialComponents = [] trialComponents.append(ISI) trialComponents.append(text) trialComponents.append(text_2) for thisComponent in trialComponents: if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED #-------Start Routine "trial"------- continueRoutine = True while continueRoutine and routineTimer.getTime() > 0: # get current time t = trialClock.getTime() frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *text* updates if t >= 0.0 and text.status == NOT_STARTED: # keep track of start time/frame for later text.tStart = t # underestimates by a little under one frame text.frameNStart = frameN # exact frame index text.setAutoDraw(True) elif text.status == STARTED and t >= ( 0.0 + (2 - win.monitorFramePeriod * 0.75) ): #most of one frame period left text.setAutoDraw(False) # *text_2* updates if t >= 2 and text_2.status == NOT_STARTED: # keep track of start time/frame for later text_2.tStart = t # underestimates by a little under one frame text_2.frameNStart = frameN # exact frame index text_2.setAutoDraw(True) elif text_2.status == STARTED and t >= ( 2 + (2 - win.monitorFramePeriod * 0.75) ): #most of one frame period left text_2.setAutoDraw(False) # *ISI* period if t >= 0.0 and ISI.status == NOT_STARTED: # keep track of start time/frame for later ISI.tStart = t # underestimates by a little under one frame ISI.frameNStart = frameN # exact frame index ISI.start(0.5) elif ISI.status == STARTED: #one frame should pass before updating params and completing ISI.complete() #finish the static period # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine routineTimer.reset( ) # if we abort early the non-slip timer needs reset break continueRoutine = False # will revert to True if at least one component still running for thisComponent in trialComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # check for quit (the Esc key) if endExpNow or event.getKeys(keyList=["escape"]): core.quit() # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() #-------Ending Routine "trial"------- for thisComponent in trialComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) win.close()
def __init__(self, win, daq, parameters, file_save, signal_model, language_model, fake): super(RSVPCopyPhraseTask, self).__init__() self.window = win self.frame_rate = self.window.getActualFrameRate() self.parameters = parameters self.daq = daq self.static_clock = core.StaticPeriod(screenHz=self.frame_rate) self.experiment_clock = core.Clock() self.buffer_val = parameters['task_buffer_len'] self.alp = alphabet(parameters) self.rsvp = _init_copy_phrase_display(self.parameters, self.window, self.daq, self.static_clock, self.experiment_clock) self.file_save = file_save trigger_save_location = f"{self.file_save}/{parameters['trigger_file_name']}" self.trigger_file = open(trigger_save_location, 'w') self.session_save_location = f"{self.file_save}/{parameters['session_file_name']}" self.wait_screen_message = parameters['wait_screen_message'] self.wait_screen_message_color = parameters[ 'wait_screen_message_color'] self.stim_number = parameters['stim_number'] self.stim_length = parameters['stim_length'] self.time_cross = parameters['time_cross'] self.time_target = parameters['time_target'] self.time_flash = parameters['time_flash'] self.timing = [self.time_target, self.time_cross, self.time_flash] self.color = [ parameters['target_color'], parameters['fixation_color'], parameters['stim_color'] ] self.task_info_color = parameters['task_color'] self.stimuli_height = parameters['stim_height'] self.is_txt_stim = parameters['is_txt_stim'] self.eeg_buffer = parameters['eeg_buffer_len'] self.copy_phrase = parameters['task_text'] self.spelled_letters_count = int(parameters['spelled_letters_count']) if self.spelled_letters_count > len(self.copy_phrase): self.logger.debug('Already spelled letters exceeds phrase length.') self.spelled_letters_count = 0 self.max_inq_length = parameters['max_inq_len'] self.max_seconds = parameters['max_minutes'] * 60 # convert to seconds self.max_inq_per_trial = parameters['max_inq_per_trial'] self.fake = fake self.language_model = language_model self.signal_model = signal_model self.down_sample_rate = parameters['down_sampling_rate'] self.filter_low = self.parameters['filter_low'] self.filter_high = self.parameters['filter_high'] self.fitler_order = self.parameters['filter_order'] self.notch_filter_frequency = self.parameters['notch_filter_frequency'] self.min_num_inq = parameters['min_inq_len'] self.collection_window_len = parameters['trial_length'] self.static_offset = parameters['static_trigger_offset'] self.show_feedback = parameters['show_feedback'] self.feedback_color = parameters['feedback_message_color'] if self.show_feedback: self.feedback = VisualFeedback(self.window, self.parameters, self.experiment_clock)
color='white', alignHoriz='center') instrTextR = visual.TextStim(win, text='press any key\n to start', font='Cambria', pos=posCentR, height=dg2px(.5), wrapWidth=dg2px(4), color='white', alignHoriz='center') # Initialize components for Routine "trial" trialClock = core.Clock() moveClock = core.Clock() maskMoveClock = core.Clock() ISI = core.StaticPeriod(win=win, screenHz=frameRate, name='ISI') # circular windows: winL = visual.Polygon(win, edges=36, size=[winSz, winSz], pos=posCentL, lineWidth=winThickness, lineColor='white') winR = visual.Polygon(win, edges=36, size=[winSz, winSz], pos=posCentR, lineWidth=winThickness, lineColor='white') # fixation: fixL = visual.ShapeStim(win,
zip_list = list(zip(perm_list, target_list)) random.shuffle(zip_list) n_trials = len(perm_list) # window task_win = visual.Window(size=[win_width, win_height], color=(0.3, 0.3, 0.3), colorSpace='rgb', units='pix', screen=scrn, fullscr=full_scrn) # timing devices global_clock = core.Clock() local_clock = core.Clock() ISI = core.StaticPeriod(screenHz=refresh_rate, win=task_win) # stimuli fixation = visual.TextStim(text='+', height=100, alignHoriz='center', alignVert='center', win=task_win) #left_cue = visual.TextStim(text='Not Connected', height=20, alignHoriz='left', alignVert='bottom', win=task_win) #right_cue = visual.TextStim(text='Connected', height=20, alignHoriz='right', alignVert='bottom', win=task_win) left_cue = visual.TextStim(text='Not Connected', antialias=True, pos=[-300, -200], height=20, win=task_win) right_cue = visual.TextStim(text='Connected',
win=win, ori=0, name='Instructions', text="This concludes the study. Let the researcher know you're done." "\n\nPress any key to end experiment.", font='Arial', pos=[0, 0], height=0.09, wrapWidth=None, color='white', colorSpace='rgb', opacity=1, depth=0.0) # print visual.getMsPerFrame(myWin=win) trial_wait = core.StaticPeriod(screenHz=60) trial_clock = core.Clock() K_block = 0 AK_block = 0 comb_task_file_name = CPT_data.create_data_file(expInfo, "Combined Task Summary", header="ParticipantID," "Date," "Session," "Sex," "Hand," "Age," "EdYr," "ActLvl,"
name='instruction', text='default text', font='Arial', units='norm', pos=[0, 0], height=0.1, wrapWidth=1.25, ori=0, color='white', colorSpace='rgb', opacity=1, depth=0.0) # Initialize components for Routine "ISI" ISIClock = core.Clock() isi = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='isi') # Initialize components for Routine "P" PClock = core.Clock() screen_shot = visual.ImageStim(win=win, name='screen_shot', units='pix', image='sin', mask=None, ori=0, pos=[0, 0], size=[768, 432], color=[1, 1, 1], colorSpace='rgb', opacity=1, flipHoriz=False,
color=[-1.000, -1.000, -1.000], colorSpace='rgb', blendMode='avg', useFBO=True, ) # store frame rate of monitor if we can measure it successfully expInfo['frameRate'] = win.getActualFrameRate() if expInfo['frameRate'] != None: frameDur = 1.0 / round(expInfo['frameRate']) else: frameDur = 1.0 / 60.0 # couldn't get a reliable measure so guess # Initialize components for Routine "black" blackClock = core.Clock() black_background = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='black_background') # Initialize components for Routine "trial" trialClock = core.Clock() Background = visual.ImageStim( win=win, name='Background', image='/Users/valeraigla/Google Drive/Uwe/00 NO_DOTS.png', mask=None, ori=0, pos=[0, 0], size=[2.0, 2.0], color=[1, 1, 1], colorSpace='rgb', opacity=1,
filename = os.path.join(script_dir, "trials_list.csv") trialList = csv.DictReader(open(filename)) timer = core.Clock() #to keep track of time timestr = time.strftime("%Y%m%d%H%M") # Log file to save timings datafileName = 'data/' + expInfo['subjID'] + '_run' + str( expInfo['session']) + '_log_' + timestr dataFile_Stim = open(datafileName + '.csv', 'w') dataFile_Stim.write( 'trial,session,subjID,modality,trialType,stimulus,stimOnset,stimOffset,expectedDuration\n' ) # Some Global Properties and Components staticITI = core.StaticPeriod(win=win, screenHz=60) checkH1 = visual.ImageStim(win, image=os.path.join(script_dir, "checkerboardH1.png"), pos=(0, 0)) checkH2 = visual.ImageStim(win, image=os.path.join(script_dir, "checkerboardH2.png"), pos=(0, 0)) checkV1 = visual.ImageStim(win, image=os.path.join(script_dir, "checkerboardV1.png"), pos=(0, 0)) checkV2 = visual.ImageStim(win, image=os.path.join(script_dir,
opacity=1, depth=-1.0) image = visual.ImageStim(win=win, name='image', image='sin', mask=None, ori=0, pos=[0, 0], size=None, color=[1, 1, 1], colorSpace='rgb', opacity=1, texRes=128, interpolate=False, depth=-2.0) ISI = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI') # Initialize components for Routine "feedback" feedbackClock = core.Clock() #inicializace promenne msqFeedback = '' textFeedBack = visual.TextStim(win=win, ori=0, name='textFeedBack', text='nonsense', font='Arial', pos=[0, 0], height=0.1, wrapWidth=None, color='white', colorSpace='rgb',
colorSpace='rgb', opacity=0, flipHoriz=False, flipVert=False, texRes=128, interpolate=True, depth=-2.0) if actually_send_triggers: from psychopy import parallel parallel_trigger = parallel.ParallelPort(address='0xd050') # eeg_trigger = parallel.ParallelPort(address='0xcff8') parallel_trigger.setData(0) # eeg_trigger.setData(0) prepare_time = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='prepare_time') stop_signal = visual.Rect(win=win, name='stop_signal', width=[60, 60][0], height=[60, 60][1], ori=0, pos=[0, 2], lineWidth=1, lineColor=[0, 0, 1], lineColorSpace='rgb', fillColor=[0, 0, 1], fillColorSpace='rgb', opacity=1.0, depth=-19.0, interpolate=True)
for i in range(5): pic.image = 'pic/Nback_%s.png' % i pic.draw() win.flip() event.waitKeys(keyList=['space']) event.clearEvents() M_text.text = '按【空格键】进入N-back练习' M_text.draw() win.flip() key = event.waitKeys(keyList=['space', 'escape']) if 'space' in key: event.clearEvents() break event.clearEvents() ISI = core.StaticPeriod(screenHz=60) ISI.start(1) # start a period of 0.5s ISI.complete() clk = core.Clock() for j in range(4): for k in range(13): clk.reset() event.clearEvents() index = 52 * 1 + 13 * j + k M_text.color = [1, 1, 1] if data['trial'][index] == 1: M_text.text = '%s-Back' % data_tr['item'][index] M_text.draw() win.flip() core.wait(4)
itertools.product(np.linspace(-w / 2, w / 2, 21), np.linspace(-h / 2, h / 2, 10))) grid_size = len(grid) circles = [ visual.GratingStim(win, tex='sin', mask='gauss', size=grating_size, sf=3, autoDraw=True) for i in range(grid_size) ] center = visual.Circle(win, radius=0.5, lineColor='white', autoDraw=True) stopwatch = core.Clock() ITI = core.StaticPeriod(win=win) counter = 0 event.clearEvents() stopwatch.reset() [circles[i].setPos(grid[i]) for i in range(grid_size)] choice = list(np.random.randint(0, grid_size, 8)) chosen_one = np.random.choice(choice) def set_stim(choice, chosen_one): [circles[i].setColor('black') for i in range(grid_size)] [circles[i].setColor('blue') for i in choice] mouse.setPos((0.0, 0.0))
texRes=128, interpolate=True, depth=-2.0) image_blank = visual.ImageStim( win=win, name='image_blank',units='pix', image='instructions/blank.png', mask=None, ori=0, pos=(0, 0), size=[1024,768], color=[1,1,1], colorSpace='rgb', opacity=1, flipHoriz=False, flipVert=False, texRes=128, interpolate=True, depth=-3.0) instructions_pic = visual.ImageStim( win=win, name='instructions_pic',units='pix', image='sin', mask=None, ori=0, pos=[0, 0], size=[1024,768], color=[1,1,1], colorSpace='rgb', opacity=1, flipHoriz=False, flipVert=False, texRes=128, interpolate=True, depth=-4.0) ISI_2 = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI_2') image_IAPS = visual.ImageStim( win=win, name='image_IAPS',units='pix', image='sin', mask=None, ori=0, pos=(0, 0), size=[1024,1024], color=[1,1,1], colorSpace='rgb', opacity=.9, #IAPSOPACITY flipHoriz=False, flipVert=False, texRes=128, interpolate=True, depth=-6.0) debug_text2 = visual.TextStim(win=win, name='debug_text2', text='stimClassDesc', font='Arial', pos=(0, -2), height=0.1, wrapWidth=None, ori=0, color='black', colorSpace='rgb', opacity=1, depth=-7.0); ISI_1 = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI_1') # if int(expInfo['participant']) == 0:
def run(self): # set up presentation window color, and size bgcolor = 'grey' txtcolor = 'white' #self.win = visual.Window(fullscr=True, color=bgcolor, units='pix') self.win = visual.Window( (1200, 900), color=bgcolor, units='pix' ) # temporary presentation window setup, exchange for line above when running actual experiment # set up timing related stuff self.frame_dur = 1.0 / self.fps self.clock = core.Clock() # trial timer self.expclock = core.Clock() # whole experiment timer # inter trial interval setup self.isi = core.StaticPeriod() #self.isi.start(.5) # various stimulus presentation boxes for text and images self.word1 = visual.TextStim(self.win, color=txtcolor, height=30, wrapWidth=900) self.word2 = visual.TextStim(self.win, color=txtcolor, height=30, wrapWidth=900) self.title = visual.TextStim(self.win, pos=(0, 200), color=txtcolor, height=30, wrapWidth=900) self.fixation = visual.ShapeStim(self.win, vertices=((0, -15), (0, 15), (0, 0), (-15, 0), (15, 0)), lineWidth=5, pos=[0, 0], closeShape=False, lineColor="black") self.image_l = visual.ImageStim(self.win, pos=(0, 0), size=[300, 300]) self.grating = visual.GratingStim(self.win, units="pix", size=[200, 200], mask="gauss", contrast=1.0) #I created a template grating similar to other shapes so that we can use it and manipulate only necessary things in the code below # actually run the experiment routines with open(self.trials_fname, 'r') as trial_file, open(self.log_fname, 'w', newline='') as log_file: # read trial structure trials = csv.DictReader(trial_file, delimiter='\t') # set up log file log_fields = trials.fieldnames + ['keypress', 'RT', 'ACC', 't'] log = csv.DictWriter(log_file, fieldnames=log_fields) log.writeheader() blocks = {} for trial in trials: if trial['block'] not in blocks.keys(): blocks[trial['block']] = [trial] else: blocks[trial['block']].append(trial) for block_number in sorted(blocks.keys()): trials = blocks[block_number] #if trials[0]['randomize'] == 'yes': # random.shuffle(trials) for trial in trials: self.clock.reset() # reset trial clock trial = self.present_trial(trial) # present the trial log.writerow(trial) # log the trial data self.win.close()
def draw_room(win, room_img, tokens: list, values: list, speed, spinningTime, responseTime, loss, spinning=False, arrowPressed=None) -> str: """Draws the square when tokens are not spinning and when its spinning.""" lossAmt = loss if room_img == "Picture2.jpg": message = "Room 1" else: message = "Room 2" roomTitle = visual.TextStim(win, text=message, color="black", units="pix", height=35, wrapWidth=1000, pos=(0, 300)) room = visual.ImageStim(win, image=room_img, units="pix") right = visual.ImageStim(win, image=rightArrow_img, units="pix", size=(100, 100), pos=(200, -250)) left = visual.ImageStim(win, image=leftArrow_img, units="pix", size=(100, 100), pos=(-200, -250)) #lossBox = visual.Rect(win, width = 130, height = 130, pos=(400,300), lineColor="black", lineWidth=6) lossValue = visual.TextStim(win, text="$" + str(round(lossAmt, 2)), color="black", units="pix", height=35, wrapWidth=1000, pos=(400, 300)) value1 = values[0] value2 = values[1] value3 = values[2] value4 = values[3] value5 = values[4] circle1 = tokens[0] circle2 = tokens[1] circle3 = tokens[2] circle4 = tokens[3] circle5 = tokens[4] kb = keyboard.Keyboard() if spinning == False: kb.clearEvents() timer = core.StaticPeriod() while True: lossValue = visual.TextStim(win, text="$" + str(round(lossAmt, 2)), color="black", units="pix", height=35, wrapWidth=1000, pos=(400, 300)) room.draw() roomTitle.draw() #lossBox.draw() lossValue.draw() right.draw() left.draw() circle1.draw() circle2.draw() circle3.draw() circle4.draw() circle5.draw() win.flip() keyPressed = kb.getKeys(keyList=['left', 'right'], clear=True) #keyPressed = event.getKeys(keyList=['left', 'right']) timer.start(0.5) if len(keyPressed) == 1: print(type(keyPressed[0].name)) break else: lossAmt -= 0.01 timer.complete() return [keyPressed[0].name, lossAmt] #key that was pressed, cents that was lost else: spinTime = core.CountdownTimer(spinningTime) while spinTime.getTime() > 0: for i in range(0, 360, 5): spinSpeed = core.CountdownTimer( speed) #Controls the speed at which the circles spin while spinSpeed.getTime() > 0: angle1 = i * math.pi / 180 circle1.pos = ((50 * math.sin(angle1)) * 2, (50 * math.cos(angle1)) * 2) value1.pos = ((50 * math.sin(angle1)) * 2, (50 * math.cos(angle1)) * 2) angle2 = (i + 72) * math.pi / 180 circle2.pos = ((50 * math.sin(angle2)) * 2, (50 * math.cos(angle2)) * 2) value2.pos = ((50 * math.sin(angle2)) * 2, (50 * math.cos(angle2)) * 2) angle3 = (i + 144) * math.pi / 180 circle3.pos = ((50 * math.sin(angle3)) * 2, (50 * math.cos(angle3)) * 2) value3.pos = ((50 * math.sin(angle3)) * 2, (50 * math.cos(angle3)) * 2) angle4 = (i + 216) * math.pi / 180 circle4.pos = ((50 * math.sin(angle4)) * 2, (50 * math.cos(angle4)) * 2) value4.pos = ((50 * math.sin(angle4)) * 2, (50 * math.cos(angle4)) * 2) angle5 = (i + 288) * math.pi / 180 circle5.pos = ((50 * math.sin(angle5)) * 2, (50 * math.cos(angle5)) * 2) value5.pos = ((50 * math.sin(angle5)) * 2, (50 * math.cos(angle5)) * 2) room.draw() roomTitle.draw() #lossBox.draw() lossValue.draw() if arrowPressed == "right": rightBox = visual.Rect(win, width=130, height=130, pos=(200, -250), lineColor="black", lineWidth=6) rightBox.draw() else: leftBox = visual.Rect(win, width=130, height=130, pos=(-200, -250), lineColor="black", lineWidth=6) leftBox.draw() right.draw() left.draw() circle1.draw() circle2.draw() circle3.draw() circle4.draw() circle5.draw() win.flip()
pos=(0, 7)) bar2 = visual.ImageStim(mywin, bar_matrix2, size=(width_vbar, height_vbar), pos=(7, 0)) bar3 = visual.ImageStim(mywin, bar_matrix3, size=(width_hbar, height_hbar), pos=(0, -7)) bar4 = visual.ImageStim(mywin, bar_matrix4, size=(width_vbar, height_vbar), pos=(-7, 0)) #draw the stimuli and update the window timer = core.StaticPeriod(screenHz=60) while True: bar1.draw() bar2.draw() bar3.draw() bar4.draw() fixation1.draw() fixation2.draw() fixation3.draw() timer.complete() dots1.draw() dots_slave.draw()
screen=0, allowGUI=False, allowStencil=False, monitor='testMonitor', color='black', colorSpace='rgb', blendMode='avg', waitBlanking=True, winType='pyglet') win.recordFrameIntervals = True frameRate = win.getActualFrameRate() print(frameRate) # Initialize Clock clock = core.StaticPeriod(screenHz=frameRate) experiment_clock = core.MonotonicClock(start_time=None) rsvp = CopyPhraseDisplay(win, clock, experiment_clock, marker_writer=NullMarkerWriter(), static_task_text=text_task, static_task_color=color_task, info_text=text_text, info_color=color_text, info_pos=pos_text, info_height=txt_height, info_font=font_text, task_color=['white'], task_font=font_task,
def run(self): # set up presentation window color, and size bgcolor = 'white' txtcolor = 'black' self.win = visual.Window(fullscr=True, color=bgcolor) #self.win = visual.Window((1200, 900), color=bgcolor) # temporary presentation window setup, exchange for line above when running actual experiment # set up timing related stuff self.frame_dur = 1.0 / self.fps self.clock = core.Clock() # trial timer self.expclock = core.Clock() # whole experiment timer # inter trial interval setup self.isi = core.StaticPeriod() self.isi.start(.5) # various stimulus presentation boxes for text and images self.text = visual.TextStim(self.win, color=txtcolor) self.message = visual.TextStim(self.win, color=txtcolor) self.message.wrapWidth = 1.5 self.title = visual.TextStim(self.win, pos=(0, .8), color=txtcolor) self.title.wrapWidth = 1.5 self.image = visual.ImageStim(self.win) # actually run the experiment routines with open(self.trials_fname, 'rU') as trial_file, open(self.log_fname, 'w', newline='') as log_file: # read trial structure trials = csv.DictReader(trial_file, delimiter='\t') # set up log file log_fields = trials.fieldnames + ['keypress', 'RT', 'ACC', 't' ] + list(self.pp_info.keys()) log = csv.DictWriter(log_file, fieldnames=log_fields, delimiter='\t') log.writeheader() # preload block and instructions blocks = {} self.instructions = {} for trial in trials: trial.update(self.pp_info) if (trial['trialAudio'] != '') and ( trial['trialAudio'] not in self.instructions.keys()): self.instructions[trial['trialAudio']] = audio.read( self.instructions_folder + trial['trialAudio']) if trial['block'] not in blocks.keys(): blocks[trial['block']] = [trial] else: blocks[trial['block']].append(trial) for i in range(5, 0, -1): self.text.text = '+' * (2 * i - 1) self.text.draw() self.win.flip() core.wait(1) # present the trials random.seed(self.pp_info['number']) for block_number in sorted(blocks.keys()): trials = blocks[block_number] if trials[0]['randomize'] == 'yes': random.shuffle(trials) for trial in trials: self.clock.reset() # reset trial clock trial = self.present_trial(trial) # present the trial log.writerow(trial) # log the trial data self.win.close()