def runSetupProcedure( self, starting_state=EyeTrackerConstants.DEFAULT_SETUP_PROCEDURE): """ The runSetupProcedure allows the eye tracker interface to perform such things as participant placement validation, camera setup, calibration, and validation type activities. For the EyeGaze implementation, the DEFAULT_SETUP_PROCEDURE starting state is supported, which launches the external EyeGaze calibrate.exe calibration routine. When the calibration program completes, control is returned to the PsychoPy Process. Args: None Returns: None """ try: #calibration_properties=self.getConfiguration().get('calibration',None) if self._eyegaze_control and self.isRecordingEnabled() is False: # pEyeGaze # when using the external calibrate.exe to # run calibration, need todisconnect from the tracker # and reconnect after calibration is done. self.setConnectionState(False) import subprocess, gevent, os #p = subprocess.Popen(('calibrate.exe', ''), env={"PATH": "/usr/bin"}) from psychopy.iohub import module_directory runthis = os.path.join(module_directory(localfunc), 'calibrate_lc.bat') p = subprocess.Popen((runthis, '')) while p.poll() is None: gevent.sleep(0.05) self.setConnectionState(True) # circle_attributes=calibration_properties.get('circle_attributes') # targetForegroundColor=circle_attributes.get('outer_color') # [r,g,b] of outer circle of targets # targetBackgroundColor=circle_attributes.get('inner_color') # [r,g,b] of inner circle of targets # screenColor=calibration_properties.get('screen_background_color') # [r,g,b] of screen # targetOuterDiameter=circle_attributes.get('outer_diameter') # diameter of outer target circle (in px) # targetInnerDiameter=circle_attributes.get('inner_diameter') # diameter of inner target circle (in px) except Exception, e: return printExceptionDetailsToStdErr() #("IOHUB_DEVICE_EXCEPTION",
def runSetupProcedure(self, starting_state=EyeTrackerConstants.DEFAULT_SETUP_PROCEDURE): """ The runSetupProcedure allows the eye tracker interface to perform such things as participant placement validation, camera setup, calibration, and validation type activities. For the EyeGaze implementation, the DEFAULT_SETUP_PROCEDURE starting state is supported, which launches the external EyeGaze calibrate.exe calibration routine. When the calibration program completes, control is returned to the PsychoPy Process. Args: None Returns: None """ try: # calibration_properties=self.getConfiguration().get('calibration',None) if self._eyegaze_control and self.isRecordingEnabled() is False: # pEyeGaze # when using the external calibrate.exe to # run calibration, need todisconnect from the tracker # and reconnect after calibration is done. self.setConnectionState(False) import subprocess, gevent, os # p = subprocess.Popen(('calibrate.exe', ''), env={"PATH": "/usr/bin"}) from psychopy.iohub import module_directory runthis = os.path.join(module_directory(localfunc), "calibrate_lc.bat") p = subprocess.Popen((runthis, "")) while p.poll() is None: gevent.sleep(0.05) self.setConnectionState(True) # circle_attributes=calibration_properties.get('circle_attributes') # targetForegroundColor=circle_attributes.get('outer_color') # [r,g,b] of outer circle of targets # targetBackgroundColor=circle_attributes.get('inner_color') # [r,g,b] of inner circle of targets # screenColor=calibration_properties.get('screen_background_color') # [r,g,b] of screen # targetOuterDiameter=circle_attributes.get('outer_diameter') # diameter of outer target circle (in px) # targetInnerDiameter=circle_attributes.get('inner_diameter') # diameter of inner target circle (in px) except Exception, e: return printExceptionDetailsToStdErr() # ("IOHUB_DEVICE_EXCEPTION",
def select_eye_tracker(): eye_tracker_config_files = { 'MouseGaze': 'eyetracker_configs/mousegaze_config.yaml', 'GazePoint': 'eyetracker_configs/gazepoint_config.yaml', 'SR Research': 'eyetracker_configs/eyelink_config.yaml', 'Tobii': 'eyetracker_configs/tobii_config.yaml', } info = { 'Eye Tracker Type': ['Select', 'MouseGaze', 'GazePoint', 'SR Research', 'Tobii'] } dlg_info = dict(info) infoDlg = gui.DlgFromDict(dictionary=dlg_info, title='Select Eye Tracker') if not infoDlg.OK: return False while list(dlg_info.values())[0] == u'Select' and infoDlg.OK: dlg_info = dict(info) infoDlg = gui.DlgFromDict(dictionary=dlg_info, title='SELECT Eye Tracker To Continue...') if not infoDlg.OK: return False configurationDirectory = module_directory(run) base_config_file = os.path.normcase( os.path.join(configurationDirectory, 'base_iohub_config.yaml')) eyetrack_config_file = os.path.normcase( os.path.join(configurationDirectory, eye_tracker_config_files[list(dlg_info.values())[0]])) combined_config_file_name = os.path.normcase( os.path.join(configurationDirectory, 'iohub_config.yaml')) mergeConfigurationFiles(base_config_file, eyetrack_config_file, combined_config_file_name) return list(dlg_info.values())[0]
# All trials have been run, so end the experiment. # flip_time=window.flip() self.hub.sendMessageEvent(text='EXPERIMENT_COMPLETE',sec_time=flip_time) # Disconnect the eye tracking device. # tracker.setConnectionState(False) # The experiment is done, all trials have been run. # Clear the screen and show an 'experiment done' message using the # instructionScreen text. # instuction_text="Press Any Key to Exit Demo" instructions_text_stim.setText(instuction_text) instructions_text_stim.draw() flip_time=window.flip() self.hub.sendMessageEvent(text="SHOW_DONE_TEXT",sec_time=flip_time) self.hub.clearEvents('all') # wait until any key is pressed kb.waitForPresses() ### End of experiment logic ####### Launch the Experiment ####### runtime=ExperimentRuntime(module_directory(ExperimentRuntime.run), "experiment_config.yaml") runtime.start()
infoDlg = gui.DlgFromDict(dictionary=dlg_info, title='SELECT Eye Tracker To Continue...') if not infoDlg.OK: return -1 base_config_file=os.path.normcase(os.path.join(configurationDirectory, 'iohub_config.yaml.part')) eyetrack_config_file=os.path.normcase(os.path.join(configurationDirectory, eye_tracker_config_files[dlg_info.values()[0]])) combined_config_file_name=os.path.normcase(os.path.join(configurationDirectory, 'iohub_config.yaml')) ExperimentRuntime.mergeConfigurationFiles(base_config_file, eyetrack_config_file,combined_config_file_name) runtime=ExperimentRuntime(configurationDirectory, "experiment_config.yaml") runtime.start((dlg_info.values()[0],)) # Get the current directory, using a method that does not rely on __FILE__ # or the accuracy of the value of __FILE__. # configurationDirectory=module_directory(main) # Run the main function, which starts the experiment runtime # main(configurationDirectory)
# ain.enableEventReporting(False) # Delay 1/4 second before next trial # actualDelay=self.hub.wait(0.250) # All trials have been run. End demo.... # Wait 250 msec before ending the experiment actualDelay=self.hub.wait(0.250) print "Delay requested %.6f, actual delay %.6f, Diff: %.6f"%(0.250,actualDelay,actualDelay-0.250) ### End of experiment logic ############################################################################### if __name__ == "__main__": import sys def main(configurationDirectory): """ Creates an instance of the ExperimentRuntime class, and launches the experiment logic in run(). """ runtime=ExperimentRuntime(configurationDirectory, "experiment_config.yaml") runtime.start(sys.argv) # run the main function, which starts the experiment runtime main(module_directory(main))
if not infoDlg.OK: return -1 base_config_file = os.path.normcase( os.path.join(configurationDirectory, 'iohub_config.yaml.part')) eyetrack_config_file = os.path.normcase( os.path.join(configurationDirectory, eye_tracker_config_files[list(dlg_info.values())[0]])) combined_config_file_name = os.path.normcase( os.path.join(configurationDirectory, 'iohub_config.yaml')) ExperimentRuntime.mergeConfigurationFiles(base_config_file, eyetrack_config_file, combined_config_file_name) runtime = ExperimentRuntime(configurationDirectory, "experiment_config.yaml") runtime.start((list(dlg_info.values())[0], )) # Get the current directory, using a method that does not rely on __FILE__ # or the accuracy of the value of __FILE__. # configurationDirectory = module_directory(main) # Run the main function, which starts the experiment runtime # main(configurationDirectory)
############################################### # load a support_settings_values.yaml def loadYamlFile(yaml_file_path, print_file=False): yaml_file_contents = load(file(yaml_file_path, 'r'), Loader=Loader) # if print_file: # print 'yaml_file_contents:' # print 'file: ',yaml_file_path # print 'contents:' # pprint(yaml_file_contents) return yaml_file_contents _current_dir = module_directory(isValidString) def buildConfigParamValidatorMapping(device_setting_validation_dict, param_validation_func_mapping, parent_name): for param_name, param_config in device_setting_validation_dict.iteritems(): current_param_path = None if parent_name is None: current_param_path = param_name else: current_param_path = "%s.%s" % (parent_name, param_name) keyword_validator_function = None if isinstance(param_name, basestring): keyword_validator_function = CONFIG_VALIDATION_KEY_WORD_MAPPINGS.get(
# Delay 1/4 second before next trial # actualDelay = self.hub.wait(0.250) # All trials have been run. End demo.... # Wait 250 msec before ending the experiment actualDelay = self.hub.wait(0.250) print("Delay requested %.6f, actual delay %.6f, Diff: %.6f" % (0.250, actualDelay, actualDelay - 0.250)) ### End of experiment logic ############################################################################### if __name__ == "__main__": import sys def main(configurationDirectory): """ Creates an instance of the ExperimentRuntime class, and launches the experiment logic in run(). """ runtime = ExperimentRuntime(configurationDirectory, "experiment_config.yaml") runtime.start(sys.argv) # run the main function, which starts the experiment runtime main(module_directory(main))
def run(self,*args): """ The run method contains your experiment logic. It is equal to what would be in your main psychopy experiment script.py file in a standard psychopy experiment setup. That is all there is too it really. """ global subj_id global con from psychopy.iohub import module_directory exp_script_dir = module_directory(self.run) #exp_conditions = importConditions(os.path.join(exp_script_dir, # 'trial_conditions.xlsx')) #TrialHandler(trialList, nReps, method=’random’, dataTypes=None, extraInfo=None, seed=None, originPath=None, name=’‘, autoLog=True) #trials = TrialHandler(exp_conditions, 1) # 1 - number of repetitions, how do we use conditions lets try to comment out # Inform the ioDataStore that the experiment is using a # TrialHandler. The ioDataStore will create a table # which can be used to record the actual trial variable values (DV or IV) # in the order run / collected. # #self.hub.createTrialHandlerRecordTable(trials) #Use Esc to quit, it will be called at some stages during the experiment def _checkQuit(key): if key[0]=='escape': os._exit(1) core.quit() ########### #### Experiment functions ########### def to_output(subject_id, decision, trigger_value, i_d, output_file_dir, reaction_time, reaction_time_decision_scren): import os.path global con is_exist = False if os.path.exists(output_file_dir): is_exist = True # Add header to the output file if it is the first time to write to it... if not is_exist: output_data_headers = ['Subject_id','Condition', 'Decision', 'Trigger','Item number', 'c1','c2','c3','c4','c5','c6', 'm1','m2','m3','m4','m5','m6', 'Reaction time', 'Reaction time since decision screen start'] # Python 2 with open(output_file_dir, 'ab') as f: # Python 3 #with open(output_file_dir, 'a', newline = '') as f: writer = csv.writer(f) if not is_exist: writer.writerows([output_data_headers]) writer.writerows([[subject_id, con, decision, trigger_value, i_d[0],i_d[1],i_d[2],i_d[3],i_d[4],i_d[5], i_d[6],i_d[7],i_d[8],i_d[9],i_d[10],i_d[11],i_d[12], reaction_time, reaction_time_decision_scren]]) def to_output_eyetracking(subject_id, x, y, gazetime, trigger, output_eye_file_dir): import os.path is_exist = False if os.path.exists(output_eye_file_dir): is_exist = True # Add header to the output file if it is the first time to write to it... if not is_exist: output_data_headers = ['Subject_id', 'x', 'y', 'gazetime', 'Trigger'] # Python 2 with open(output_eye_file_dir, 'ab') as f: # Python 3 #with open(output_file_dir, 'a', newline = '') as f: writer = csv.writer(f) if not is_exist: writer.writerows([output_data_headers]) writer.writerows([[subject_id, x, y, gazetime, trigger]]) def row_to_condition(row): txt=row #array_column_names #print(txt.split(';')) a = np.empty(len(txt.split(';'))) a = txt.split(';') #print('a', a) return a def read_input_file(csv_dir, item_number): global subject_id i=0 with open(csv_dir, 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter='\n', quotechar='|') #print(spamreader) for row in spamreader: i=i+1 if (i==item_number): #print('row', row) return row return 0 def monitor_coordinate_check(win): for i in range(90): texti = str(-450+10*i) #-display_resolution[1]/2 pixel_line_y = visual.ShapeStim(win, units='pix', lineWidth=1.5,lineColor=(55,255,255),lineColorSpace='rgb255', vertices=((-750, -450+10*i),(750, -450+10*i)),closeShape=False, pos=(0, 0), size=1.2) pixel_name_y = visual.TextStim(win, text='y='+texti, height=10, units='pix', pos = [0,-450+10*i],color=[255,55,255],colorSpace='rgb255') texti = str(-800+i*20) #-display_resolution[0]/2 pixel_line_x = visual.ShapeStim(win, units='pix', lineWidth=1.5,lineColor=(155,255,55),lineColorSpace='rgb255', vertices=((-800+i*20, -450),(-800+i*20, 450)),closeShape=False, pos=(0, 0), size=1) #what size param pixel_name_x = visual.TextStim(win, text=texti, height=9, units='pix', pos = [-800+i*20,0],color=[255,55,55],colorSpace='rgb255') pixel_line_x.draw() pixel_line_y.draw() pixel_name_x.draw() pixel_name_y.draw() win.flip() def draw_input(win, item_array_text, item_array_x, item_array_y): global con item_left = item_array_text[1:7] item_right = item_array_text[7:13] print(item_array_text, item_left, item_right) random.Random(con).shuffle(item_left) random.Random(con).shuffle(item_right) print(item_array_text, item_left, item_right) item_array_text_shuffled = item_left + item_right print(item_array_text_shuffled) for i in range(len(item_array_x)): #print(item_array_x[i], item_array_y[i], i, len(item_array_x), len(item_array_text), item_array_text) whitebox = visual.ShapeStim(win, units='pix', lineWidth=1.5, lineColor=(255,255,255),lineColorSpace='rgb255', vertices=((item_array_x[i]+20, item_array_y[i]+20), (item_array_x[i]+20, item_array_y[i]-20), (item_array_x[i]-20, item_array_y[i]-20), (item_array_x[i]-20, item_array_y[i]+20)), closeShape=True, fillColor = (255,255,255), fillColorSpace='rgb255', pos=(0, 0), size=1) #what size param #uncomment white box in case want to create different background on values #whitebox.draw() item_value = visual.TextStim(win, text=item_array_text_shuffled[i], height=14, units='pix', #here we use i+1 because the first number is numbers item pos = [item_array_x[i],item_array_y[i]],color=[0,0,0],colorSpace='rgb255') item_value.draw() win.flip(clearBuffer=False) def logs_windows(log_text, log_key_to_proceed): start_message = visual.TextStim(win, text=log_text, pos = [0,0], height=35,color=[255,255,255],colorSpace='rgb255',wrapWidth=win.size[0]*.9) start_message.draw() win.flip() core.wait(0.2) key=event.waitKeys(keyList=[log_key_to_proceed]) return key def instructions_blank_screen(win, output_eye_dir): #uncomment in case want to draw gaze dot '''timer = core.Clock() timer.add(0.5) while timer.getTime()<0: print('precise timing bl', timer.getTime())''' draw_gaze_dot(win, 1001, 0.5, output_eye_dir) self.hub.clearEvents('all') def instructions_fixation_cross(win, output_eye_dir): #inst_dir = 'Instructions\\fixation_cross.jpg' #instr=visual.ImageStim(win,image=inst_dir, units='pix', size = display_resolution) #instr.draw() fixation_cross = visual.TextStim(win, text='+', pos = [-595,345], height=54,color=[-1,-1,-1],colorSpace='rgb') fixation_cross.autoDraw = True win.flip() #uncomment in case we want to see the fixation draw_gaze_dot(win, 2001, 0.5, output_eye_dir) #change 0.5 seconds #uncomment in case of coordinate monitor greed #monitor_coordinate_check(win) #comment in case of monitor coordinate check #win.flip() fixation_cross.autoDraw = False self.hub.clearEvents('all') def draw_table_lines(win): global con print('con', con) table_rectangle = visual.ShapeStim(win, units='pix', lineWidth=1.5, lineColor=(25,25,25),lineColorSpace='rgb255', vertices=((-225, 375), (200,375),(200,-395),(-225,-395)), closeShape=True, pos=(0, 0), size=1) table_rectangle2 = visual.ShapeStim(win, units='pix', lineWidth=1.5, lineColor=(25,25,25),lineColorSpace='rgb255', vertices=((235, 375), (650,375),(650,-395),(235,-395)), closeShape=True, pos=(0, 0), size=1) line1 = visual.ShapeStim(win, units='pix', lineWidth=1.5, lineColor=(25,25,25),lineColorSpace='rgb255', vertices=((-225, 327), (200,327)), pos=(0, 0), size=1) line2 = visual.ShapeStim(win, units='pix', lineWidth=1.5, lineColor=(25,25,25),lineColorSpace='rgb255', vertices=((235, 327), (650,327)), pos=(0, 0), size=1) line_dotted1 = visual.Line(win, start=(-660, 280), end=(650, 280),lineColor=(25,25,25),lineColorSpace='rgb255') line_dotted2 = visual.Line(win, start=(-660, 148), end=(650, 148),lineColor=(25,25,25),lineColorSpace='rgb255') line_dotted3 = visual.Line(win, start=(-660, 40), end=(650, 40),lineColor=(25,25,25),lineColorSpace='rgb255') line_dotted4 = visual.Line(win, start=(-660, -70), end=(650, -70),lineColor=(25,25,25),lineColorSpace='rgb255') line_dotted5 = visual.Line(win, start=(-660, -175), end=(650, -175),lineColor=(25,25,25),lineColorSpace='rgb255') line_dotted6 = visual.Line(win, start=(-660, -284), end=(650, -284),lineColor=(25,25,25),lineColorSpace='rgb255') text = ['Number of participating countries', 'Costs to average household per \n month', 'Share of emission represented by \nparticipating countries', 'Distribution of cost from \nimplementing the agreement', 'Sanctions for missing emission \nreduction targets', 'Monitoring: Emission reductions \nwill be monitored by'] #shuffle text, put text items in an array random.Random(con).shuffle(text) for i in range(6): start_message = visual.TextStim(win, text=text[i], pos = [-640,215-i*112], height=24,color=[25,25,25],colorSpace='rgb255' ,wrapWidth=win.size[0]*.9, alignHoriz='left') start_message.draw() agreement_message =('Agreement 1','Agreement 2') agreement_message1 = visual.TextStim(win, text=agreement_message[0], pos = [-15,355], height=24,color=[25,25,25],colorSpace='rgb255',wrapWidth=win.size[0]*.9) agreement_message1.draw() agreement_message2 = visual.TextStim(win, text=agreement_message[1], pos = [440,355], height=24,color=[25,25,25],colorSpace='rgb255',wrapWidth=win.size[0]*.9) agreement_message2.draw() table_rectangle.draw() table_rectangle2.draw() line1.draw() line2.draw() line_dotted1.draw() line_dotted2.draw() line_dotted3.draw() line_dotted4.draw() line_dotted5.draw() line_dotted6.draw() def instructions_choice_decision(win, item_list_text, output_eye_dir): #uncomment in case we want to compare with table from the presentation experiment requirements #inst_dir = 'Instructions\\choice_decision.jpg' #instr=visual.ImageStim(win,image=inst_dir, units='pix', size = display_resolution) #instr.draw() item_array_x = np.array([-15, -15, -15, -15,-15, -15, 445, 445, 445, 445, 445, 445]) item_array_y = np.array([215,105,-5,-115,-225,-335,215,105,-5,-115,-225,-335]) draw_table_lines(win) draw_input(win, item_list_text, item_array_x, item_array_y) (choice, time_all, time_trial) = draw_gaze_dot(win, 3001, 10000, output_eye_dir) #comment in case want to see gazedot return (choice, time_all, time_trial) def draw_trigger(win, tracker, trigger, item_number, output_file_dir, output_eye_dir): global input_file_dir choice = 0 flip_time=win.flip() self.hub.sendMessageEvent(text="TRIAL_START",sec_time=flip_time) self.hub.clearEvents('all') tracker.setRecordingState(True) #setting it every time here - why tracker.setTriggerValue(trigger) input_to_make_decision = read_input_file(input_file_dir, item_number) input_to_make_decision_split = ''.join(input_to_make_decision) input_to_make_decision_split = row_to_condition(input_to_make_decision_split) #default gazetime and eyedata x,y,gazetime = 'did not catch', 'eyedata, possibly blinked', 30 if (trigger == 1001): instructions_blank_screen(win, output_eye_dir) if (trigger == 2001): instructions_fixation_cross(win, output_eye_dir,) if (trigger == 3001): choice, choice_time_whole, choice_time_decision_screen = instructions_choice_decision(win, input_to_make_decision_split, output_eye_dir) to_output(subject_id, choice, trigger, input_to_make_decision_split, output_file_dir, choice_time_whole, choice_time_decision_screen) flip_time=win.flip() self.hub.sendMessageEvent(text="TRIAL_END %d"%t,sec_time=flip_time) tracker.setRecordingState(False) self.hub.clearEvents('all') return choice def draw_gaze_dot(win, trigger, time, output_eye_dir): #try to paint gaze position #if we are not using draw gaze dot, then we would not use 'c', 'm' to transfer through the blank and fixation_cross #screens. stime = getTime() #print(stime) while getTime()-stime < time: gpos = tracker.getPosition() #print('start time', stime, 'actual time', getTime(), 'difference', getTime()-stime, 'until <',time) if (gpos != None): start_message = visual.TextStim(win, text='+', pos = [gpos[0],gpos[1]], height=10,color=[-1,-1,-1],colorSpace='rgb',wrapWidth=win.size[0]) start_message.draw() #start_message = visual.TextStim(win, text=str(gpos), pos = [gpos[1],gpos[0]], height=35,color=[-1,-1,-1],colorSpace='rgb',wrapWidth=win.size[0]*.9) #start_message.draw() win.flip(clearBuffer=False) to_output_eyetracking(subject_id, gpos[0], gpos[1], getTime(), trigger, output_eye_dir) core.wait(0.001) else: to_output_eyetracking(subject_id, 'did not catch eye data, possibly blinked', 'or corrupted', getTime(), trigger, output_eye_dir) #getTime gives current time, here should probably print getTime from inside while self.hub.clearEvents('all') if (trigger == 3001): key = event.getKeys(keyList=['c', 'm']) if key!=[]: print('choice key', key, trigger, getTime()) return (key[0], getTime(), getTime()-stime) self.hub.clearEvents('all') print('events after clear events', event.getKeys(keyList=['c', 'm'])) return 0 selected_eyetracker_name=args[0] # Let's make some short-cuts to the devices we will be using in this 'experiment'. tracker=self.hub.devices.tracker display=self.hub.devices.display kb=self.hub.devices.keyboard mouse=self.hub.devices.mouse # Start by running the eye tracker default setup procedure. tracker.runSetupProcedure() # Create a psychopy window, full screen resolution, full screen mode... display_coord_type=display.getCoordinateType() display_resolution=display.getPixelResolution() # it is recommended to use pixle as unit espically if you are using eye tracker, because the eyetracker returns the readings in pixel win=visual.Window(display_resolution,monitor=display.getPsychopyMonitorName(),units='pix',fullscr=True,screen= display.getIndex(), waitBlanking=False) #color="white" # Hide the 'system mouse cursor'. # would need it for later mouse.setSystemCursorVisibility(False) event.Mouse(visible=False) #------------------------------------------------------------Experiment begins ---------------------------------------------------------------------------------------------- #get time in nice format to name the csv file localtime=time.asctime(time.localtime(time.time())) localtime=localtime[11:16]+'pm-'+localtime[4:10] localtime=localtime.replace(":","_").replace(" ","_") #create csv file csv_eye_output='Exp Results\\'+subject_id+'_eyetracking_output'+localtime+'.csv' csv_experiment_output ='Exp Results\\'+subject_id+'_decision_output'+localtime+'.csv' tracker.setRecordingState(True) #draw instruction before experiment start inst_dir = 'Instructions\\Inst_2.jpg' instr=visual.ImageStim(win,image=inst_dir, units='pix', size = display_resolution) instr.draw() '''inst1 = visual.TextStim(win, text='Instruction', pos = [0,0], height=24, color=[-1,-1,-1], colorSpace='rgb', alignHoriz='center', alignVert='center', wrapWidth=win.size[0]*.9)''' flip_time=win.flip() self.hub.sendMessageEvent(text="EXPERIMENT_START",sec_time=flip_time) self.hub.clearEvents('all') key=event.waitKeys(keyList=['space']) #------------------------------------------------------------Experiment trial testing ---------------------------------------------------------------------------------------------- # Send some information to the ioHub DataStore as experiment messages # including the eye tracker being used for this session. # self.hub.sendMessageEvent(text="IO_HUB EXPERIMENT_INFO START") self.hub.sendMessageEvent(text="ioHub Experiment started {0}".format(getCurrentDateTimeString())) self.hub.sendMessageEvent(text="Experiment ID: {0}, Session ID: {1}".format(self.hub.experimentID,self.hub.experimentSessionID)) self.hub.sendMessageEvent(text="Stimulus Screen ID: {0}, Size (pixels): {1}, CoordType: {2}".format(display.getIndex(),display.getPixelResolution(),display.getCoordinateType())) self.hub.sendMessageEvent(text="Calculated Pixels Per Degree: {0} x, {1} y".format(*display.getPixelsPerDegree())) self.hub.sendMessageEvent(text="Eye Tracker being Used: {0}".format(selected_eyetracker_name)) self.hub.sendMessageEvent(text="IO_HUB EXPERIMENT_INFO END") print('get current date time', "{0}".format(getCurrentDateTimeString())) print('experiment ID', self.hub.experimentID,'experiment session ID', self.hub.experimentSessionID) print('display', "{0}".format(display.getIndex()), 'pixel resolution', "{0}".format(display.getPixelResolution()), 'coordinate type', "{0}".format(display.getCoordinateType())) print('pixels degree', "{0}".format(display.getPixelsPerDegree()), 'selected eyetracker', selected_eyetracker_name) self.hub.clearEvents('all') for t in range(2): #number of trials is 10 self.hub.sendMessageEvent(text="TRIAL_START") self.hub.clearEvents('all') #uncomment for trials, here item number 1 is used only for testing purposes item_number = random.randrange(2, 11, 1) #item_number = 2 trigger_value=1001 draw_trigger(win, tracker, trigger_value, item_number,csv_experiment_output, csv_eye_output) #the row indexing starts from 2 trigger_value=2001 draw_trigger(win, tracker, trigger_value, item_number, csv_experiment_output, csv_eye_output) trigger_value=3001 draw_trigger(win, tracker, trigger_value, item_number, csv_experiment_output, csv_eye_output) flip_time=win.flip() self.hub.sendMessageEvent(text='TRIAL_END',sec_time=flip_time) self.hub.clearEvents('all') #------------------------------------------------------------Experiment ends ---------------------------------------------------------------------------------------------- # Disconnect the eye tracking device. # So the experiment is done, all trials have been run. # Clear the screen and show an 'experiment done' message using the # instructionScreen state. What for the trigger to exit that state. # (i.e. the space key was pressed) # flip_time=win.flip() self.hub.sendMessageEvent(text='EXPERIMENT_COMPLETE',sec_time=flip_time) tracker.setRecordingState(False) tracker.setConnectionState(False) logs_windows("Thank you for your participation! Press ''escape'' to exit", 'escape') print('checkquit escape') _checkQuit(key) self.hub.sendMessageEvent(text="SHOW_DONE_TEXT") tex1=eventtxt.Eventtotext() print('tex1=eventtxt.Eventtotext()', tex1) #use try: would give an error in case of the not connected eye tracker at later stages tex1.convertToText(exp_script_dir,subject_id,localtime) self.hub.clearEvents('all') #self.hub.clearEvents('all', exp_script_dir) # MANAGER ERROR WHEN SENDING MSG:[Errno 9] Bad file descriptor #Warning: TimeoutExpired, Killing ioHub Server process. #ioHubExperimentRuntime.shutdown() #print(ioHubExperimentRuntime) win.close() self.hub.quit()
exptFiles.extend(glob.glob('./expt_*.yaml')) os.chdir(modDir) exptConfigInfo = {'Experiment config file = ': exptFiles} exptConfigInfo = dict(exptConfigInfo) exptConfigDlg = gui.DlgFromDict(dictionary=exptConfigInfo, title='Select experiment config file') if not exptConfigDlg.OK: return -1 while exptConfigInfo.values()[0] == u'Select' and exptConfigDlg.OK: exptConfigInfo = dict(exptConfigInfo) exptConfigDlg = gui.DlgFromDict( dictionary=exptConfigInfo, title='SELECT experiment config file to continue...') if not exptConfigDlg.OK: return -1 # Start the experiment # --------------------------------------------------------------------- runtime = ExperimentRuntime(configDir, exptConfigInfo.values()[0]) runtime.start((dlg_info.values()[0], modDir)) # Get the current directory, using a method that does not rely on __FILE__ # or the accuracy of the value of __FILE__. modDir = module_directory(main) # Run the main function, which starts the experiment runtime main(modDir)
def run(self, *args): from psychopy.iohub import module_directory global exp_script_dir exp_script_dir = module_directory(self.run) """ The run method contains your experiment logic. It is equal to what would be in your main psychopy experiment script.py file in a standard psychopy experiment setup. That is all there is too it really. """ def get_time(): #get time in nice format to name the csv file localtime = time.asctime(time.localtime(time.time())) localtime = localtime[11:16] + 'pm-' + localtime[4:10] localtime = localtime.replace(":", "_").replace(" ", "_") return localtime def empty_screen(win): text = visual.TextStim(win, text='*', height=40, units='pix', pos=[500, 430], color=[255, 255, 255], colorSpace='rgb255') text.draw() win.flip() event.waitKeys(keyList=['f2']) def read_input_file(csv_dir): data = [] with open(csv_dir, 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: data.append(row[0].split(",")) return data def instruction_screen(win, img_name): img = visual.ImageStim(win, image=img_name, units='pix') img.draw() win.flip() k = event.waitKeys(keyList=['f2', 'right']) if k[0] == 'f2': experiment_ends(win) elif k[0] == 'right': pass def get_next_idx(current_idx, key): if key == 'right': if current_idx == 5: return 0 else: return current_idx + 1 else: if current_idx == 0: return 5 else: return current_idx - 1 def check_code_values(code_text): import string number_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] letter_list = list(string.ascii_lowercase) + ['*'] messages = '' success = True if code_text[0] not in letter_list: messages += 'Code 1 has to be letter.\n' success = False if code_text[1] not in letter_list: messages += 'Code 2 has to be letter.\n' success = False if code_text[2] not in letter_list: messages += 'Code 3 has to be letter.\n' success = False if code_text[3] not in letter_list: messages += 'Code 4 has to be letter.\n' success = False if code_text[4] not in number_list: messages += 'Code 5 has to be number.\n' success = False if code_text[5] not in number_list: messages += 'Code 6 has to be numbder.\n' success = False return success, messages def trial_experiment(win, trial_data): for round_data in trial_data: fixation_cross(win) time.sleep(0.5) round_results = do_round(win, round_data, is_trial=True) print('results', round_results, 'data', round_data) draw_payoff(win, round_data, round_results, trial_id=None) win.flip() def experiment_begins(win): text = "Sie haben die Probedurchgänge nun abgeschlossen. Nun beginnt das eigentliche Experiment, welches auszahlungsrelevant wird. \nDer nächste Teil wird ca. 5 Minuten dauern. Sie können in diesen 5 Minuten keine Pausen einlegen.\ \nFalls Sie noch Fragen haben, melden Sie sich bitte jetzt beim Experimentator.\n\nFalls Sie keine Fragen mehr haben, drücken Sie bitte die Pfeiltaste nach rechts, um das Experiment zu beginnen." text_obj = visual.TextStim(win, text=text, height=30, alignHoriz='center', units='pix', pos=[0, 0], color=[255, 255, 255], colorSpace='rgb255', wrapWidth=win.size[0] * .7) text_obj.draw() win.flip() event.waitKeys(keyList=['right']) def main_experiment(win, main_data): experiment_results = [] for round_data in main_data: round_results = do_round(win, round_data, False) experiment_results.append(round_results) win.flip() time.sleep(0.5) selected_round_idx = random.randint(0, len(experiment_results) - 1) selected_round_results = experiment_results[selected_round_idx] selected_round_data = [] for round_data in main_data: if int(round_data[0]) == int( selected_round_results['picked_item']): selected_round_data = round_data draw_payoff(win, selected_round_data, selected_round_results, trial_id=selected_round_idx + 1) to_output(subj_id, condition, exp_time, experiment_results, csv_experiment_output) k = event.waitKeys(keyList=['f2', 'up', 'down']) if k[0] == 'f2': experiment_ends(win) elif k[0] == 'up' or 'down': pass def to_output(subj_id, experiment_number, condition, localtime, results, output_file_dir): import os.path is_exist = False if os.path.exists(output_file_dir): is_exist = True # Add header to the output file if it is the first time to write to it... if not is_exist: output_data_headers = [ 'trial', 'subject_id', 'condition', 'starting_time', 'item_picked', 'pressup', 'pressup_time', 'correct_answer' ] # Python 2 with open(output_file_dir, 'ab') as f: # Python 3 #with open(output_file_dir, 'a', newline = '') as f: writer = csv.writer(f) if not is_exist: writer.writerows([output_data_headers]) for i in range(0, len(results)): row = [] row.append(results[i]['pressup']) row.append(results[i]['pressup_time']) row.append(results[i]['correct_answer']) row.insert(0, str(experiment_number * 1000 + i + 1)) row.insert(1, str(subj_id)) row.insert(2, str(condition)) #here you are actually outputing local time in the date format and not in the seconds row.insert(3, str(localtime)) row.insert(4, results[i]['picked_item']) #print('rows', row) writer.writerows([row]) def get_display_order(order_file_dir, condition): all_orders = [] with open(order_file_dir, 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: r = row[0].split(",") all_orders.append(r) return all_orders[int(condition[1]) - 1] def draw_screen(win, round_data, intervened, is_trial): global display_order global condition titles = ['Entscheider', 'Empfänger', 'Bestrafung', 'Ausgaben'] if is_trial: Probedurchgang = visual.TextStim(win, text='Probedurchgang', pos=[0, 400], units='pix', height=20, color=[255, 255, 255], colorSpace='rgb255', wrapWidth=win.size[0] * .5) Probedurchgang.draw() line = visual.Line(win, start=(-700, 0), end=(700, 0)) # draw the tables tableA = visual.ShapeStim(win, units='pix', lineWidth=3.5, lineColor=(255, 255, 255), lineColorSpace='rgb255', vertices=((-600, -50), (600, -50), (600, -430), (-600, -430), (-600, -50)), closeShape=False, pos=(0, 0), size=1) tableB = visual.ShapeStim(win, units='pix', lineWidth=3.5, lineColor=(255, 255, 255), lineColorSpace='rgb255', vertices=((-600, -240), (600, -240)), closeShape=False, pos=(0, 0), size=1) tableC = visual.ShapeStim(win, units='pix', lineWidth=3.5, lineColor=(255, 255, 255), lineColorSpace='rgb255', vertices=((0, -50), (0, -430)), closeShape=False, pos=(0, 0), size=1) label_1 = visual.TextStim(win, text=titles[int(display_order[0]) - 1], height=20, units='pix', pos=[-360, -150]) label_2 = visual.TextStim(win, text=titles[int(display_order[1]) - 1], height=20, units='pix', pos=[-360, -350]) label_3 = visual.TextStim(win, text=titles[int(display_order[2]) - 1], height=20, units='pix', pos=[360, -150]) label_4 = visual.TextStim(win, text=titles[int(display_order[3]) - 1], height=20, units='pix', pos=[360, -350]) number_1 = visual.TextStim(win, text=round_data[int(display_order[0])], height=20, units='pix', pos=[-120, -150]) number_2 = visual.TextStim(win, text=round_data[int(display_order[1])], height=20, units='pix', pos=[-120, -350]) number_3 = visual.TextStim(win, text=round_data[int(display_order[2])], height=20, units='pix', pos=[120, -150]) number_4 = visual.TextStim(win, text=round_data[int(display_order[3])], height=20, units='pix', pos=[120, -350]) line.draw() tableB.draw() tableC.draw() label_1.draw() label_2.draw() label_3.draw() label_4.draw() number_1.draw() number_2.draw() number_3.draw() number_4.draw() win.flip() def fixation_cross(win): fixation_cross = visual.TextStim(win, text='+', pos=[0, 0], units='pix', height=50, color=[255, 255, 255], colorSpace='rgb255', wrapWidth=win.size[0] * .5) fixation_cross.draw() win.flip() def do_round(win, round_data, is_trial): global display_order global condition pressup = 0 correct_answer = 0 print('round_data', round_data, 'is trial', is_trial) results = { 'correct_answer': [], 'picked_item': round_data[0], 'points': 0., 'pressup': '0', 'pressup_time': '99' } results['correct_answer'] = '0' clock = core.Clock() draw_screen(win, round_data, pressup, is_trial) e = event.waitKeys(keyList=['up', 'down', 'f2']) print('get into len(e) > 0 if', e) self.hub.clearEvents('all') if len(e) > 0: print('get into len(e) > 0 if', e, len(e)) if e[0] in ['up'] and not pressup: pressup = 1 results['pressup'] = '1' results['pressup_time'] = getTime() elif e[0] in ['down'] and not pressup: pressup = 0 results['pressup'] = '0' results['pressup_time'] = getTime() #print('round data 9', round_data[13]) if e[0] == 'up' and round_data[13] == '1': # up is '1' in the input file, hence when we have '1' in the input and up it is correct_answer # if it is '0' and down -: false correct_answer = 1 results['correct_answer'] = '1' results['points'] = 0.1 elif e[0] == 'down' and round_data[13] == '0': correct_answer = 1 results['correct_answer'] = '1' results['points'] = 0.1 draw_screen(win, round_data, pressup, is_trial) print(results) if e[0] == 'f2': experiment_ends(win) return results def draw_payoff(win, selected_round_data, selected_round_results, trial_id=None): global display_order correct_answer_points = int(selected_round_data[4]) if not trial_id: Probedurchgang = visual.TextStim(win, text='Probedurchgang', pos=[0, 400], units='pix', height=20, color=[255, 255, 255], colorSpace='rgb255', wrapWidth=win.size[0] * .5) Probedurchgang.draw() if selected_round_results['correct_answer'] == '0': payoff_text_1 = "Sie haben in dieser Runde falsch entschieden.\n\nSie erhalten daher kein Geld für diese Runde.\n" else: payoff_text_1 = "Sie haben in dieser Runde richtig entschieden. \n\nSie erhielten daher 0,10€ zusätzlich für diesen Durchgang." payoff_text_1_obj = visual.TextStim(win, text=payoff_text_1, height=25, units='pix', pos=[0, 250], wrapWidth=win.size[0] * .7, alignHoriz='center') payoff_text_1_obj.draw() continue_text = "Bitte drücken Sie die Pfeiltaste nach rechts (-->)" continue_text_obj = visual.TextStim(win, text=continue_text, height=25, units='pix', pos=[0, 50], wrapWidth=win.size[0] * .7, alignHoriz='center') continue_text_obj.draw() # draw the tables titles = ['Entscheider', 'Empfänger', 'Bestrafung', 'Ausgaben'] tableA = visual.ShapeStim(win, units='pix', lineWidth=3.5, lineColor=(255, 255, 255), lineColorSpace='rgb255', vertices=((-600, -50), (600, -50), (600, -430), (-600, -430), (-600, -50)), closeShape=False, pos=(0, 0), size=1) tableB = visual.ShapeStim(win, units='pix', lineWidth=3.5, lineColor=(255, 255, 255), lineColorSpace='rgb255', vertices=((-600, -240), (600, -240)), closeShape=False, pos=(0, 0), size=1) tableC = visual.ShapeStim(win, units='pix', lineWidth=3.5, lineColor=(255, 255, 255), lineColorSpace='rgb255', vertices=((0, -50), (0, -430)), closeShape=False, pos=(0, 0), size=1) label_1 = visual.TextStim(win, text=titles[int(display_order[0]) - 1], height=20, units='pix', pos=[-360, -150]) label_2 = visual.TextStim(win, text=titles[int(display_order[1]) - 1], height=20, units='pix', pos=[-360, -350]) label_3 = visual.TextStim(win, text=titles[int(display_order[2]) - 1], height=20, units='pix', pos=[360, -150]) label_4 = visual.TextStim(win, text=titles[int(display_order[3]) - 1], height=20, units='pix', pos=[360, -350]) number_1 = visual.TextStim(win, text=selected_round_data[int( display_order[0])], height=20, units='pix', pos=[-120, -150]) number_2 = visual.TextStim(win, text=selected_round_data[int( display_order[1])], height=20, units='pix', pos=[-120, -350]) number_3 = visual.TextStim(win, text=selected_round_data[int( display_order[2])], height=20, units='pix', pos=[120, -150]) number_4 = visual.TextStim(win, text=selected_round_data[int( display_order[3])], height=20, units='pix', pos=[120, -350]) line = visual.Line(win, start=(-700, 0), end=(700, 0)) tableB.draw() tableC.draw() label_1.draw() label_2.draw() label_3.draw() label_4.draw() number_1.draw() number_2.draw() number_3.draw() number_4.draw() line.draw() win.flip() k = event.waitKeys(keyList=['f2', 'right']) if k[0] == 'f2': experiment_ends(win) elif k[0] == 'right': pass def calculate_code(win, payoff): text = "Der erste Teil des Experiments ist hiermit beendet. \n\nIn den ersten 30 Durchgängen haben Sie " + str( payoff ) + ' Durchgänge richtig beantwortet. \nSie erhalten also ' + str( format(payoff * 0.10, '.2f') ) + '€ zusätzlich ausgezahlt am Ende des Experiments.\ \n\n\n\n Bitte drücken Sie die Pfeiltaste nach rechts (-->)' text_obj = visual.TextStim(win, text=text, height=30, pos=[0, 200], units='pix', wrapWidth=win.size[0] * .7, alignHoriz='center') text_obj.draw() win.flip() k = event.waitKeys(keyList=['f2', 'right']) if k[0] == 'f2': experiment_ends(win) elif k[0] == 'right': pass def calculate_code_second(win, payoff_first, payoff_second): text = "Das Experiment ist hiermit beendet.\n\nIn den zweiten 30 Durchgängen haben Sie " + str( payoff_second ) + ' Durchgänge richtig beantwortet. Sie erhalten also hierfür also ' + str( format(payoff_second * 0.10, '.2f') ) + '€.\ \n' + "Da Sie im ersten Teil " + str( format(payoff_first * 0.10, '.2f') ) + "€ verdient haben, wird Ihnen der Experimentator nun " + str( format((payoff_first + payoff_second) * 0.10, '.2f')) + "€ zusätzlich auszahlen.\ \n\n\nBitte bleiben Sie an Ihrem Platz sitzen und melden sich. Sie werden dann von Ihrem Platz abgeholt." text_obj = visual.TextStim(win, text=text, height=30, pos=[0, 200], units='pix', wrapWidth=win.size[0] * .7, alignHoriz='center') text_obj.draw() win.flip() def experiment_ends(win): # Disconnect the eye tracking device. global exp_script_dir, subj_id, localtime, tracker, experiment_end # So the experiment is done, all trials have been run. # Clear the screen and show an 'experiment done' message using the # instructionScreen state. What for the trigger to exit that state. # (i.e. the space key was pressed) # flip_time = win.flip() self.hub.sendMessageEvent(text='EXPERIMENT_COMPLETE', sec_time=flip_time) tracker.setRecordingState(False) tracker.setConnectionState(False) self.hub.sendMessageEvent(text="SHOW_DONE_TEXT") print("SHOW_DONE_TEXT") tex1 = eventtxt.Eventtotext() print('tex1=eventtxt.Eventtotext()', tex1) #use try: would give an error in case of the not connected eye tracker at later stages tex1.convertToText(exp_script_dir, subj_id, localtime) self.hub.clearEvents('all') #self.hub.clearEvents('all', exp_script_dir) # MANAGER ERROR WHEN SENDING MSG:[Errno 9] Bad file descriptor #Warning: TimeoutExpired, Killing ioHub Server process. #ioHubExperimentRuntime.shutdown() print('ioHubExperimentRuntime') win.close() self.hub.quit() print('end of exp logic') experiment_end = 1 ### End of experiment logic #****************Collect Information about the Subject**************************** global tracker, subj_id, localtime selected_eyetracker_name = args[0] # Let's make some short-cuts to the devices we will be using in this 'experiment'. tracker = self.hub.devices.tracker display = self.hub.devices.display kb = self.hub.devices.keyboard mouse = self.hub.devices.mouse # Start by running the eye tracker default setup procedure. tracker.runSetupProcedure() # Create a psychopy window, full screen resolution, full screen mode... display_coord_type = display.getCoordinateType() display_resolution = display.getPixelResolution() # it is recommended to use pixle as unit espically if you are using eye tracker, because the eyetracker returns the readings in pixel win = visual.Window(display_resolution, monitor=display.getPsychopyMonitorName(), units='pix', fullscr=True, screen=display.getIndex(), waitBlanking=False) #color="white" # Hide the 'system mouse cursor'. # would need it for later mouse.setSystemCursorVisibility(False) event.Mouse(visible=False) #------------------------------------------------------------Experiment begins ---------------------------------------------------------------------------------------------- #get time in nice format to name the csv file localtime = time.asctime(time.localtime(time.time())) localtime = localtime[11:16] + 'pm-' + localtime[4:10] localtime = localtime.replace(":", "_").replace(" ", "_") tracker.setRecordingState(True) global order_file_dir, input_file_dir, input_file_dir2, output_file_dir, subj_id, condition, csv_experiment_output #subj_id, condition = get_subject_info() exp_dir = os.getcwd() exp_time = get_time() #create csv file csv_eye_output = 'Exp Results\\' + subj_id + '_eyetracking_output' + localtime + '.csv' csv_experiment_output = 'Exp Results\\' + subj_id + '_decision_output' + localtime + '.csv' order_file_dir = exp_dir + '\\' + order_file_dir input_file_dir = exp_dir + '\\' + input_file_dir input_file_dir2 = exp_dir + '\\' + input_file_dir2 output_file_dir = exp_dir + '\\' + output_file_dir # Create a psychopy window, full screen resolution, full screen mode... win = visual.Window(fullscr=True) # Waiting for the user to press F2 empty_screen(win) #**********************************instructions_text start************************************* instruction_screen(win, welcome_screen) #**********************************Reading Data************************************** # get order of display... global display_order display_order = get_display_order(order_file_dir, condition) # get data... all_data = read_input_file(input_file_dir) trial_data = all_data[1:4] fixed_data = all_data[4:9] shuffled_data = all_data[9:] random.shuffle(shuffled_data) main_data = fixed_data + shuffled_data trial_experiment(win, trial_data) experiment_begins(win) #------------------------------------------------------------ Main Experiment Starts ---------------------------------------------------------------------------------------------- experiment_results_first = [] t = 0 sum_correct_first = 0 for round_data in main_data: t += 1 tracker.setTriggerValue(1100) flip_time = win.flip() time.sleep(0.5) tracker.setTriggerValue(1200) fixation_cross(win) time.sleep(0.5) tracker.setTriggerValue(1000 + t) round_results = do_round(win, round_data, is_trial=False) sum_correct_first = sum_correct_first + int( round_results['correct_answer']) experiment_results_first.append(round_results) try: print('exp end', experiment_end) if (experiment_end == 1): sys.exit('The experiment was stopped') except NameError: print("global name 'experiment_end' is not defined") win.flip() flip_time = win.flip() tracker.setTriggerValue(1500) print('sum', sum_correct_first) to_output(subj_id, 1, condition, exp_time, experiment_results_first, csv_experiment_output) #------------------------------------------------------------ Main Experiment Ends ---------------------------------------------------------------------------------------------- calculate_code(win, sum_correct_first) instruction_screen(win, 'second_part_1.jpg') instruction_screen(win, 'second_part_2.jpg') #------------------------------------------------------------ Main Experiment 2 Starts ---------------------------------------------------------------------------------------------- # get data... all_data = read_input_file(input_file_dir2) trial_data = all_data[1:4] fixed_data = all_data[4:9] shuffled_data = all_data[9:] random.shuffle(shuffled_data) main_data = fixed_data + shuffled_data experiment_results_second = [] t = 0 sum_correct_second = 0 for round_data in main_data: t += 1 tracker.setTriggerValue(2100) flip_time = win.flip() time.sleep(0.5) tracker.setTriggerValue(2200) fixation_cross(win) time.sleep(0.5) tracker.setTriggerValue(2000 + t) round_results = do_round(win, round_data, is_trial=False) sum_correct_second = sum_correct_second + int( round_results['correct_answer']) experiment_results_second.append(round_results) win.flip() flip_time = win.flip() tracker.setTriggerValue(2500) calculate_code_second(win, sum_correct_first, sum_correct_second) #print('sum', sum_correct) to_output(subj_id, 2, condition, exp_time, experiment_results_second, csv_experiment_output) #------------------------------------------------------------ Main Experiment 2 Ends ---------------------------------------------------------------------------------------------- #=============== Draw Last Screen (Payoff) ================== #draw_payoff(win, selected_round_data, selected_round_results, trial_id=selected_round_idx+1)''' event.waitKeys(keyList=['f2']) #------------------------------------------------------------Experiment ends ---------------------------------------------------------------------------------------------- experiment_ends(win)
def writeDataRow(output_file,*args): """ Save a row of data to the output file, in tab delimited format. See comment for writeOutputFileHeader function for order of saved columns. """ all_data=[] for cvals in args: all_data.extend([str(cv) for cv in cvals]) output_file.write('\t'.join(all_data)) output_file.write('\n') if __name__ == '__main__': # Select the hdf5 file to process. data_file_path= displayDataFileSelectionDialog( starting_dir=os.path.join( module_directory( writeOutputFileHeader), 'results')) if data_file_path is None: print("File Selection Cancelled, exiting...") sys.exit(0) dpath,dfile=os.path.split(data_file_path) # Lets time how long it takes to read and save to .txt format # start_time=getTime() # Create an instance of the ExperimentDataAccessUtility class # for the selected DataStore file. This allows us to access data # in the file based on Device Event names and attributes, as well # as access the experiment session metadata saved with each session run.
def writeDataRow(output_file, *args): """ Save a row of data to the output file, in tab delimited format. See comment for writeOutputFileHeader function for order of saved columns. """ all_data = [] for cvals in args: all_data.extend([str(cv) for cv in cvals]) output_file.write('\t'.join(all_data)) output_file.write('\n') if __name__ == '__main__': # Select the hdf5 file to process. data_file_path = displayDataFileSelectionDialog(starting_dir=os.path.join( module_directory(writeOutputFileHeader), 'results')) if data_file_path is None: print("File Selection Cancelled, exiting...") sys.exit(0) dpath, dfile = os.path.split(data_file_path) # Lets time how long it takes to read and save to .txt format # start_time = getTime() # Create an instance of the ExperimentDataAccessUtility class # for the selected DataStore file. This allows us to access data # in the file based on Device Event names and attributes, as well # as access the experiment session metadata saved with each session run. dataAccessUtil = ExperimentDataAccessUtility(dpath,
flip_time = window.flip() self.hub.sendMessageEvent(text='EXPERIMENT_COMPLETE', sec_time=flip_time) # Disconnect the eye tracking device. # tracker.setConnectionState(False) # The experiment is done, all trials have been run. # Clear the screen and show an 'experiment done' message using the # instructionScreen text. # instuction_text = "Press Any Key to Exit Demo" instructions_text_stim.setText(instuction_text) instructions_text_stim.draw() flip_time = window.flip() self.hub.sendMessageEvent(text="SHOW_DONE_TEXT", sec_time=flip_time) self.hub.clearEvents('all') # wait until any key is pressed kb.waitForPresses() ### End of experiment logic ####### Launch the Experiment ####### runtime = ExperimentRuntime(module_directory(ExperimentRuntime.run), "experiment_config.yaml") runtime.start()
IOHUB_IP_ADDRESS_V4=isValidIpAddress, IOHUB_DATE=isValidDateString) ############################################### # load a support_settings_values.yaml def loadYamlFile(yaml_file_path,print_file=False): yaml_file_contents=load(file(yaml_file_path,'r'), Loader=Loader) # if print_file: # print 'yaml_file_contents:' # print 'file: ',yaml_file_path # print 'contents:' # pprint(yaml_file_contents) return yaml_file_contents _current_dir=module_directory(isValidString) def buildConfigParamValidatorMapping(device_setting_validation_dict,param_validation_func_mapping,parent_name): for param_name,param_config in device_setting_validation_dict.iteritems(): current_param_path=None if parent_name is None: current_param_path=param_name else: current_param_path="%s.%s"%(parent_name,param_name) keyword_validator_function=None if isinstance(param_name,basestring): keyword_validator_function=CONFIG_VALIDATION_KEY_WORD_MAPPINGS.get(param_name,None) if keyword_validator_function: param_validation_func_mapping[parent_name]=keyword_validator_function,param_config