def start_iohub(sess_info): ''' Starts the iohub server process, using data from the dict returned by showSessionInfoDialog() to create the hdf5 file name. If the file already exists, the existing file is renamed so that it is not overwritten by the current sessions data. iohub device configuration information is read from an 'iohub_config.yaml' file which must be in the same folder as this file. The created ioHubConnection object is returned after the iohub server has started and is ready for interaction with the experiment runtime. :param sess_info: dict returned from showSessionInfoDialog() :return: ioHubConnection object ''' import os, shutil save_to = os.path.join(os.path.dirname(__file__), u'results', sess_info['Session Code']) save_to = os.path.normpath(save_to) if not save_to.endswith('.hdf5'): save_to = save_to + u'.hdf5' fdir, sess_code = os.path.split(save_to) if not os.path.exists(fdir): os.mkdir(fdir) #TODO: Ask if file should be overwritten, or new session code entered. si = 1 save_dest = save_to while os.path.exists(save_dest): sname, sext = sess_code.rsplit(u'.', 1) save_dest = os.path.join(fdir, u"{}_{}.{}".format(sname, si, sext)) si += 1 if save_dest is not save_to: shutil.move(save_to, save_dest) sess_code = sess_code[0:min(len(sess_code), 24)] if sess_code.endswith(u'.hdf5'): sess_code = sess_code[:-5] if save_to.endswith(u'.hdf5'): save_to = save_to[:-5] kwargs = { 'experiment_code': EXP_NAME, 'session_code': sess_code, 'datastore_name': save_to, 'iohub_config_name': 'iohub_config.yaml' } return launchHubServer(**kwargs)
def start_iohub(session_code, experiment_name): ''' Starts the iohub server process, using data from the dict returned by showSessionInfoDialog() to create the hdf5 file name. If the file already exists, the existing file is renamed so that it is not overwritten by the current sessions data. iohub device configuration information is read from an 'iohub_config.yaml' file which must be in the same folder as this file. The created ioHubConnection object is returned after the iohub server has started and is ready for interaction with the experiment runtime. :param sess_info: dict returned from showSessionInfoDialog() :return: ioHubConnection object ''' import os, shutil save_to = os.path.join(os.path.dirname(__file__),u'data', session_code) save_to = os.path.normpath(save_to) if not save_to.endswith('.hdf5'): save_to = save_to+u'.hdf5' fdir, sess_code = os.path.split(save_to) if not os.path.exists(fdir): os.mkdir(fdir) #TODO: Ask if file should be overwritten, or new session code entered. si = 1 save_dest = save_to while os.path.exists(save_dest): sname, sext = sess_code.rsplit(u'.',1) save_dest = os.path.join(fdir, u"{}_{}.{}".format(sname,si,sext)) si+=1 if save_dest is not save_to: shutil.move(save_to,save_dest) sess_code=sess_code[0:min(len(sess_code),24)] if sess_code.endswith(u'.hdf5'): sess_code = sess_code[:-5] if save_to.endswith(u'.hdf5'): save_to = save_to[:-5] kwargs={'experiment_code':experiment_name, 'session_code':sess_code, 'datastore_name':save_to, 'iohub_config_name': 'iohub_config.yaml' } return launchHubServer(**kwargs)
Created on Thu Oct 17 22:46:06 2013 @author: Sol """ from __future__ import print_function from psychopy import visual, core from psychopy.data import TrialHandler, importConditions from psychopy.iohub.client import launchHubServer from psychopy.iohub.devices import Computer from psychopy.iohub.constants import EventConstants getTime = Computer.getTime psychopy_mon_name = 'testMonitor' exp_code = 'io_stroop' io = launchHubServer( psychopy_monitor_name=psychopy_mon_name, experiment_code=exp_code) io.sendMessageEvent(category='EXP', text='Experiment Started') kb = io.devices.keyboard mouse = io.devices.mouse win = visual.Window(allowGUI=False, fullscr=True) gabor = visual.GratingStim( win, tex='sin', mask='gauss', texRes=256, size=[ 200.0, 200.0], sf=[ 4, 0], ori=0, name='gabor1') letter = visual.TextStim(win, pos=(0.0, 0.0), text='X') retrace_count = 0
# will be saved, but device events are still available at runtime. runtime_settings = dict() runtime_settings['sampling_rate'] = 500 runtime_settings['track_eyes'] = 'RIGHT' iohub_config = { 'eyetracker.hw.sr_research.eyelink.EyeTracker': { 'name': 'tracker', #'simulation_mode': True, 'model_name': 'EYELINK 1000 DESKTOP', 'runtime_settings': runtime_settings }, } # Uncomment experiment_code setting to enable saving data to hdf5 file. #iohub_config['experiment_code'] = 'et_simple' io = launchHubServer(**iohub_config) # Get some iohub devices for future access. keyboard = io.devices.keyboard display = io.devices.display tracker = io.devices.tracker # run eyetracker calibration r = tracker.runSetupProcedure() # Initialize window win = visual.Window([800, 600], color=(-1, -1, -1), colorSpace='rgb', allowGUI=True, monitor='testMonitor',
# Number if 'trials' to run in demo TRIAL_COUNT = 2 # Maximum trial time / time timeout T_MAX = 10.0 iohub_tracker_class_path = 'eyetracker.hw.sr_research.eyelink.EyeTracker' eyetracker_config = dict() eyetracker_config['name'] = 'tracker' eyetracker_config['model_name'] = 'EYELINK 1000 DESKTOP' eyetracker_config['simulation_mode'] = True eyetracker_config['runtime_settings'] = dict(sampling_rate=1000, track_eyes='RIGHT') # Since no experiment or session code is given, no iohub hdf5 file # will be saved, but device events are still available at runtime. io = launchHubServer(**{iohub_tracker_class_path: eyetracker_config}) # Get some iohub devices for future access. keyboard = io.getDevice('keyboard') display = io.getDevice('display') tracker = io.getDevice('tracker') # run eyetracker calibration tracker.runSetupProcedure() win = visual.Window(display.getPixelResolution(), units='pix', fullscr=True, allowGUI=False) gaze_ok_region = visual.Circle(win, radius=200, units='pix')
from psychopy.iohub.client import launchHubServer from psychopy import core # Start the ioHub process. 'io' can now be used during the # experiment to access iohub devices and read iohub device events. io = launchHubServer() clock = core.Clock() print "Press any Key to Exit Example....." while clock.getTime() < 30: # Wait until a keyboard event occurs keys = io.devices.keyboard.getKeys(keys=[ 'd', ], clear=False) #check constantly if not keys: print(len(keys)) else: keyname = keys[-1] keyout = keyname.key print(len(keyout)) print("Exiting experiment....") # Stop the ioHub Server io.quit()
elif TRACKER == 'tobii': tracker_config = {'eyetracker.hw.tobii.EyeTracker': eyetracker_config} else: print( "{} is not a valid TRACKER name; please use 'eyelink', 'gazepoint', or 'tobii'." .format(TRACKER)) # Number if 'trials' to run in demo TRIAL_COUNT = 2 # Maximum trial time / time timeout T_MAX = 5.0 if tracker_config: # Since no experiment or session code is given, no iohub hdf5 file # will be saved, but device events are still available at runtime. io = launchHubServer(**tracker_config) # Get some iohub devices for future access. keyboard = io.getDevice('keyboard') display = io.getDevice('display') tracker = io.getDevice('tracker') # run eyetracker calibration tracker.runSetupProcedure() win = visual.Window(display.getPixelResolution(), units='pix', fullscr=True, allowGUI=False) gaze_ok_region = visual.Circle(win, radius=200, units='pix')
# Number if 'trials' to run in demo TRIAL_COUNT = 2 # Maximum trial time / time timeout T_MAX = 10.0 iohub_tracker_class_path = 'eyetracker.hw.sr_research.eyelink.EyeTracker' eyetracker_config = dict() eyetracker_config['name'] = 'tracker' eyetracker_config['model_name'] = 'EYELINK 1000 DESKTOP' #eyetracker_config['simulation_mode'] = True eyetracker_config['runtime_settings'] = dict(sampling_rate=1000, track_eyes='RIGHT') # Since no experiment or session code is given, no iohub hdf5 file # will be saved, but device events are still available at runtime. io = launchHubServer(**{iohub_tracker_class_path: eyetracker_config}) # Get some iohub devices for future access. keyboard = io.devices.keyboard display = io.devices.display tracker = io.devices.tracker # run eyetracker calibration r = tracker.runSetupProcedure() win = visual.Window(display.getPixelResolution(), units='pix', fullscr=True, allowGUI=False ) gaze_ok_region = visual.Circle(win, radius=200, units='pix')
win.close() core.quit() participant = 'dl' dataFile = openDataFile(participant) win = visual.Window([200, 100], mon='SonyG500') if eyeTracker: dataFileEye = openDataFile2(participant) iohub_tracker_class_path = 'eyetracker.hw.theeyetribe.EyeTracker' eyetracker_config = dict() eyetracker_config['name'] = 'tracker' io = launchHubServer(psychopy_monitor_name='sonye200', experiment_code=dataFileEye, **{iohub_tracker_class_path: eyetracker_config}) tracker = io.devices.tracker else: io = launchHubServer(psychopy_monitor_name='sonye200') display = io.devices.display keyboard = io.devices.keyboard PPD_X, PPD_Y = display.getPixelsPerDegree() def degToPix(deg): return round(deg * PPD_X)
onset=line[1], end=line[2] if not isinstance(line[2], str) else None)) return percept_list if __name__ == '__main__': from psychopy import visual, clock from psychopy.iohub import client # launch a win instance to intercept the keypresses # so that they are not sent to the console win = visual.Window() # Start the ioHub process. 'io' can now be used during the # experiment to access iohub devices and read iohub device events io = client.launchHubServer() io.devices.mouse.reporting = False print('Press [SPACE] to continue... ') waitKeyPress(io, key=' ', timeout=10) all_percepts = [] trial_timer = clock.CountdownTimer(start=3) pb = get_percept_report(io, clear=True) current_percept = pb[-1] while trial_timer.getTime() > 0: win.flip() pb = get_percept_report(io)
# Store info about the experiment session expName = 'test-tracker' # 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 import pandas as pd full_data = pd.DataFrame(columns=["subj", "item", "time", "x", "y"]) full_data["item"] = full_data["item"].astype(str) from psychopy.iohub.client import launchHubServer io = launchHubServer(iohub_config_name="callab.yaml") tracker = io.devices.tracker # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc filename = _thisDir + os.sep + u'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)
def init(init_file=None): """ this is the init function that is called with an appropriate json init-file :Parameters: init_file : str a json formatted init file containing parameters about the experimental set-up :return: expInfo : dict dictionary gathering information about the experiment win : psychopy.visual.win window in which the experiment will be run kb : psychopy.hardware.keyboard the keyboard configuration that will be used with the appropriate listeners """ # dictionary with the parameters from the init file init = utils.load_init(init_file) # set-up the Display and monitor # make a monitor with monitor constants from the init file mon = makeMonitor(init['monitor_constants']) # and make a window using that monitor win = visual.Window( monitor=mon, color=init['experiment']['bkgcolor'], size=mon.getSizePix(), units='deg', screen=1, # 0 is the monitor of the experiment control fullscr=True, allowGUI=False, waitBlanking=False, winType='pyglet') # for iohub to function well # start to fill the ioHub_config ioHub_config = dict( experiment_code=init['experiment']['name'], experiment_info=dict(total_sessions_to_run=2), session_info=dict(user_variables=dict( modalities=init['experiment']['modalities'], observer=init['experiment']['observer'], dummy_mode=init['experiment']['dummy_mode'], hw=dict(parallel_port=init['devices']['parallel_port']), parameters=init['experiment']['stim'])), psychopy_monitor_name=mon.name, data_store=dict(enable=False), mouse=dict(enable=False)) # transform the velocity of the gratings to the plaid (vertical) velocity v = init['experiment']['stim']['vel'] theta = init['experiment']['stim']['ori'] * math.pi / 180 sf = init['experiment']['stim']['sf'] ioHub_config['session_info']['user_variables']['parameters'][ 'velocity'] = [0, v / math.sin(theta) * sf] # make sure the eyetracker is available as eyelink try: et_init_file = init['devices']['eyetracker'] et_init = eyetracker_setup(win, et_init_file) except KeyError: print('no eyetracker configuration file given, using default Eyelink') et_init = eyetracker_setup(win) if 'GAZE' in [m.upper() for m in init['experiment']['modalities']]: ioHub_config.update(et_init) # Are we running in dummy_mode ? try: dummy_mode = init['experiment']['dummy_mode'] except KeyError: dummy_mode = False # for a given subject the data directory is # <session_type><subject_id> # and all files are named as # <session_type><subject_id>_<session_number>_<modality>.<ext> if not dummy_mode: session_id, subject_path = utils.register_subject( datapath=init['data']['path'], modalities=init['modalities']) else: session_id = 'tmp' subject_path = Path(Path.cwd(), 'subject_data') subject_path.mkdir() shutil.copy(init_file, Path(subject_path).joinpath(session_id + '_init.yaml')) ioHub_config['session_code'] = session_id ioHub_config['data_store'].update( dict( enable=True, filename=session_id, parent_dir=str( subject_path ) # serialisation of json strings requires casting to string )) logfile = Path(subject_path).joinpath(session_id + '_log.tsv') triggerfile = Path(subject_path).joinpath(session_id + '_triggers.tsv') ioHub_config['session_info']['user_variables']['logfile'] = str(logfile) ioHub_config['session_info']['user_variables']['triggerfile'] = str( triggerfile) # setting up the eye-tracker if 'GAZE' in [m.upper() for m in init['experiment']['modalities']]: ioHub_config['session_info']['user_variables'][ 'guiding_eye'] = get_guiding_eye() # Start the ioHub process. 'io' can now be used during the # experiment to access iohub devices and read iohub device events # important devices for us are # io.getDevice('keyboard') # io.getDevice('eyelink') io = client.launchHubServer(**ioHub_config) # the four different conditions, key to our experiment nBlocks = init['experiment']['structure']['nBlocks'] conditions = [ dict( cond='nAmb_nKp', img='img/NoPRESS.jpg', ), dict( cond='nAmb_Kp', img='img/PRESS.jpg', ), dict( cond='Amb_nKp', img='img/NoPRESS.jpg', ), dict( cond='Amb_Kp', img='img/PRESS.jpg', ) ] # the subject learns the different conditions (only first three of them) learning_phase = TrialHandler(conditions[:-1], nReps=nBlocks['learn'], method='sequential') # the subject goes through 4 blocks of a single trial 'Amb_Kp', will be used to estimate the parameters for the perceptual transitions estimation_phase = TrialHandler([conditions[3]], nReps=nBlocks['estim'], method='sequential') # this is the final phase of the experiments with blocks of randomly shuffled conditions testing_phase = TrialHandler(conditions, nReps=nBlocks['test'], method='random') exp_structure = TrialHandler([ dict(name="learn", trials=learning_phase, img='img/Consigne.jpg', text="Phase d'habituation I"), dict(name="estim", trials=estimation_phase, img='', text="Phase d'habituation II"), dict(name="test", trials=testing_phase, img='', text="Phase d'expérimentation") ], nReps=1, method='sequential') # generate the different stimuli plaid_stims = stims.plaids(win, **init['experiment']['stim']) plaid_stims.update(dict(fix=stims.fixation(win))) return io, win, exp_structure, plaid_stims
# {'name': 'tracker', # #'simulation_mode': True, # 'model_name': 'EYELINK 1000 DESKTOP', # 'runtime_settings': runtime_settings # }, # # } # Config the GazePoint 3 tracker for use. iohub_config = {'eyetracker.hw.gazepoint.gp3.EyeTracker': {'name': 'tracker', 'device_timer': {'interval': 0.005}}} # Uncomment experiment_code setting to enable saving data to hdf5 file. iohub_config['experiment_code'] = 'et_simple' io = launchHubServer(**iohub_config) # Get some iohub devices for future access. keyboard = io.devices.keyboard display = io.devices.display tracker = io.devices.tracker infoDlg("Eye Tracker Setup", "Press OK to start\neye tracker setup / calibration procedure.") # run eyetracker calibration r = tracker.runSetupProcedure() if isinstance(r,dict): # iohub-GP3 interface setup call returns the GP3 calibration results. # Ex: {u'LX5': 0.0, u'LX4': 0.0, u'LX3': 0.0, u'LX2': 0.0, u'LX1': 0.0, # u'CALX1': 0.5, u'CALX3': 0.85, u'CALX2': 0.85, u'CALX5': 0.15, # u'CALX4': 0.15, u'LV5': 0, u'LV4': 0, u'LV1': 0, u'LV3': 0,
#import queue #from general import init from psychopy import core from psychopy.iohub.client import launchHubServer infoBuffer = {} # Placeholder for information stored by the initial dialog (dialog.py) ser = '' # Placeholder: serial connection to Arduino to which the buttons are connected stored here by init.initSer() #q = queue.Queue() # queue for threads timer = core.Clock() # init the timer ITI500 = timer.getTime() Mapping = {} # Placeholder: mapping of response keys and effect colors stored here by init.initMapping() io = launchHubServer() # Start the ioHub process. 'io' can now be used during the experiment to access iohub devices and read iohub device events.