Пример #1
0
def testWithNoKwargs():
    """
    testWithNoKwargs illustrates using the launchHubServer function with no
    parameters at all. Considerations:
        * A Keyboard, Mouse, Monitor, and Experiment device are created by default.
        * All devices use their default parameter settings. Therefore, not very useful in real studies.
        * ioHub DataStore is not enabled.
    """
    io=launchHubServer()

    # Get the default keyboard device created.
    keyboard=io.devices.keyboard

    print()
    print("** PRESS A KEY TO CONTINUE.....")

    # Check for new events every 1/4 second.
    # By using the io.wait() fucntion, the ioHub Process is checked for
    # events every 50 msec or so, and they are cached in the PsychoPy process
    # until the next getEvents() call is made. On Windows, messagePump() is also
    # called periodically so that any Window you have created does not lock up.
    #
    while not keyboard.getEvents():
        io.wait(0.25)

    print("A Keyboard Event was Detected; exiting Test.")

    io.quit()
Пример #2
0
def start_iohub(sess_code=None):
    import time, os

    # Create initial default session code
    if sess_code is None:
        sess_code='S_{0}'.format(long(time.mktime(time.localtime())))

    # Ask for session name / hdf5 file name
    save_to = fileSaveDlg(initFilePath=os.path.dirname(__file__),initFileName=sess_code,
                          prompt="Set Session Output File",
                          allowed="ioHub Datastore Files (*.hdf5)|*.hdf5")
    if save_to:
        # session code should equal results file name
        fdir, sess_code = os.path.split(save_to)
        sess_code=sess_code[0:min(len(sess_code),24)]
        if sess_code.endswith('.hdf5'):
            sess_code = sess_code[:-5]
        if save_to.endswith('.hdf5'):
            save_to = save_to[:-5]
    else:
        save_to = sess_code

    exp_code='wintab_evts_test'

    kwargs={'experiment_code':exp_code,
            'session_code':sess_code,
            'datastore_name':save_to,
            'wintab.WintabTablet':{'name':'tablet', 
                                   'mouse_simulation': {'enable':False,
                                                        'leave_region_timeout':2.0
                                                       }
                                  }
           }

    return launchHubServer(**kwargs)
Пример #3
0
def testEnabledDataStore():
        """
        testEnabledDataStore is the same as testUsingPsychoPyMonitorConfig above,
        but by adding an experiment_code parameter the ioHub DataStore will
        be enabled, using a auto generated session_code each time it is run.
        Experiment and session metadata is printed at the end of the demo.
        Considerations:
            * A Keyboard, Mouse, Monitor, and Experiment device are created by default.
            * If the psychopy_monitor_name is valid, the ioHub Display is updated to
              use the display size and viewing distance specified in the psychopy monitor config.
            * ioHub DataStore is enabled because experiment_code is provided.
              session_code will be auto generated using the current time.
        """
        psychopy_mon_name='testMonitor'
        exp_code='gap_endo_que'
        io=launchHubServer(psychopy_monitor_name=psychopy_mon_name, experiment_code=exp_code)

        display=io.devices.display

        print('Display Psychopy Monitor Name: ', display.getPsychopyMonitorName())
        print('Display Default Eye Distance: ', display.getDefaultEyeDistance())
        print('Display Physical Dimensions: ', display.getPhysicalDimensions())

        from pprint import pprint

        print('Experiment Metadata: ')
        pprint(io.getExperimentMetaData())
        print('\nSession Metadata: ')
        pprint(io.getSessionMetaData())

        io.quit()
Пример #4
0
def testUsingPsychoPyMonitorConfig():
    """
    testUsingPsychoPyMonitorConfig illustrates using the launchHubServer function
    and providing a PsychoPy monitor configuration file name.
    Considerations:
        * A Keyboard, Mouse, Monitor, and Experiment device are created by default.
        * If the psychopy_monitor_name is valid, the ioHub Display is updated to
          use the display size and viewing distance specified in the psychopy monitor config.
        * ioHub DataStore is not enabled.
    """

    io=launchHubServer(psychopy_monitor_name='testMonitor')

    # Get the default display device created.
    #
    display=io.devices.display

    # print(the display's physical characteristics, showing they have
    # been updated based on the settings in the PsychoPy monitor config.
    #
    print('Display Psychopy Monitor Name: ', display.getPsychopyMonitorName())
    print('Display Default Eye Distance: ', display.getDefaultEyeDistance())
    print('Display Physical Dimensions: ', display.getPhysicalDimensions())

    # That's it, shut doqn the ioHub Proicess and exit. ;)
    #
    io.quit()
Пример #5
0
def testUsingPsychoPyMonitorConfig():
    """
    testUsingPsychoPyMonitorConfig illustrates using the launchHubServer function
    and providing a PsychoPy monitor configuration file name.
    Considerations:
        * A Keyboard, Mouse, Monitor, and Experiment device are created by default.
        * If the psychopy_monitor_name is valid, the ioHub Display is updated to
          use the display size and viewing distance specified in the psychopy monitor config.
        * ioHub DataStore is not enabled.
    """

    io = launchHubServer(psychopy_monitor_name='testMonitor')

    # Get the default display device created.
    #
    display = io.devices.display

    # print(the display's physical characteristics, showing they have
    # been updated based on the settings in the PsychoPy monitor config.
    #
    print('Display Psychopy Monitor Name: ', display.getPsychopyMonitorName())
    print('Display Default Eye Distance: ', display.getDefaultEyeDistance())
    print('Display Physical Dimensions: ', display.getPhysicalDimensions())

    # That's it, shut doqn the ioHub Proicess and exit. ;)
    #
    io.quit()
Пример #6
0
def testEnabledDataStore():
    """
        testEnabledDataStore is the same as testUsingPsychoPyMonitorConfig above,
        but by adding an experiment_code parameter the ioHub DataStore will
        be enabled, using a auto generated session_code each time it is run.
        Experiment and session metadata is printed at the end of the demo.
        Considerations:
            * A Keyboard, Mouse, Monitor, and Experiment device are created by default.
            * If the psychopy_monitor_name is valid, the ioHub Display is updated to
              use the display size and viewing distance specified in the psychopy monitor config.
            * ioHub DataStore is enabled because experiment_code is provided.
              session_code will be auto generated using the current time.
        """
    psychopy_mon_name = 'testMonitor'
    exp_code = 'gap_endo_que'
    io = launchHubServer(psychopy_monitor_name=psychopy_mon_name,
                         experiment_code=exp_code)

    display = io.devices.display

    print('Display Psychopy Monitor Name: ', display.getPsychopyMonitorName())
    print('Display Default Eye Distance: ', display.getDefaultEyeDistance())
    print('Display Physical Dimensions: ', display.getPhysicalDimensions())

    from pprint import pprint

    print('Experiment Metadata: ')
    pprint(io.getExperimentMetaData())
    print('\nSession Metadata: ')
    pprint(io.getSessionMetaData())

    io.quit()
Пример #7
0
def testWithNoKwargs():
    """
    testWithNoKwargs illustrates using the launchHubServer function with no
    parameters at all. Considerations:
        * A Keyboard, Mouse, Monitor, and Experiment device are created by default.
        * All devices use their default parameter settings. Therefore, not very useful in real studies.
        * ioHub DataStore is not enabled.
    """
    io = launchHubServer()

    # Get the default keyboard device created.
    keyboard = io.devices.keyboard

    print()
    print("** PRESS A KEY TO CONTINUE.....")

    # Check for new events every 1/4 second.
    # By using the io.wait() fucntion, the ioHub Process is checked for
    # events every 50 msec or so, and they are cached in the PsychoPy process
    # until the next getEvents() call is made. On Windows, messagePump() is also
    # called periodically so that any Window you have created does not lock up.
    #
    while not keyboard.getEvents():
        io.wait(0.25)

    print("A Keyboard Event was Detected; exiting Test.")

    io.quit()
Пример #8
0
def startHubProcess():
    io = launchHubServer()
    assert io != None

    io_proc = Computer.getIoHubProcess()
    io_proc_pid = io_proc.pid
    assert io_proc != None and io_proc_pid > 0

    return io
Пример #9
0
    def __connect_eyetracker(self, sample_rate: int=300) -> Any:    
        iohub_config: dict = {'eyetracker.hw.tobii.EyeTracker':
            {'name': 'tracker',
            'runtime_settings': {'sampling_rate': sample_rate}}
            }
        
        io: Any = launchHubServer(**iohub_config)    

        return io
Пример #10
0
def startHubProcess():
    io = launchHubServer()
    assert io != None

    io_proc = Computer.getIoHubProcess()
    io_proc_pid = io_proc.pid
    assert io_proc != None and io_proc_pid > 0

    return io
Пример #11
0
def connect_eyetracker(sample_rate = 300):
    print("CONNECTING EYETRACKER...")
    iohub_config = {'eyetracker.hw.tobii.EyeTracker':
                   {'name': 'tracker', 
                   'runtime_settings': {'sampling_rate': sample_rate}}}
                   
    
    io = launchHubServer(**iohub_config)  
    print("SUCCESS!")  
    return io
Пример #12
0
def run():
    global numEventRequests
    io = launchHubServer(experiment_code='delay_test')

    lastFlipTime = 0.0

    # create fullscreen pyglet window at current resolution, as well as required resources / drawings
    psychoWindow, psychoStim = createPsychoGraphicsWindow(io)

    # create stats numpy arrays, set experiment process to high priority.
    # Init Results numpy array
    results= zeros((totalEventRequestsForTest,3),dtype='f4')

    numEventRequests=0

    # clear the ioHub event Buffer before starting the test.
    # This is VERY IMPORTANT, given an existing bug in ioHub.
    # You would want to do this before each trial started until the bug is fixed.
    io.clearEvents('all')

    # draw and flip to the updated graphics state.
    flipTime = drawAndFlipPsychoWindow(psychoStim, psychoWindow, io, None)
    ifi = flipTime - lastFlipTime
    lastFlipTime = flipTime

    # START TEST LOOP >>>>>>>>>>>>>>>>>>>>>>>>>>
    while numEventRequests < totalEventRequestsForTest:
        # send an Experiment Event to the ioHub server process
        io.sendMessageEvent("This is a test message %.3f" % flipTime)

        # check for any new events from any of the devices, and return the events list and the time it took to
        # request the events and receive the reply
        events, callDuration = checkForEvents(io)
        if events:
            # events were available
            results[numEventRequests][0] = callDuration  # ctime it took to get events from ioHub
            results[numEventRequests][1] = len(events)  # number of events returned
            results[numEventRequests][2] = ifi * 1000.0  # calculating inter flip interval.
            numEventRequests += 1  # incrementing tally counterfgh
            # draw and flip to the updated graphics state.

        flipTime = drawAndFlipPsychoWindow(psychoStim, psychoWindow, io, events)
        ifi = flipTime - lastFlipTime
        lastFlipTime = flipTime

    # END TEST LOOP <<<<<<<<<<<<<<<<<<<<<<<<<<

    psychoWindow.close()

    # plot collected delay and retrace detection results.
    plotResults(results)
    printResults(results)
Пример #13
0
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)
Пример #14
0
    def __init__(self):
        # Set up iohub and internal clock. Use existing ioHubServer if it exists.
        from psychopy import iohub, core, sys
        self._sys = sys
        self._core = core
        self._timeAtLastReset = core.getTime()

        self._EventConstants = iohub.EventConstants
        existing_iohub = iohub.ioHubConnection.ACTIVE_CONNECTION
        self._io = existing_iohub if existing_iohub else iohub.launchHubServer()

        import numpy
        self._np = numpy
    def __init__(self):
        # Set up iohub and internal clock. Use existing ioHubServer if it exists.
        from psychopy import iohub, core, sys
        self._sys = sys
        self._core = core
        self._timeAtLastReset = core.getTime()

        self._EventConstants = iohub.EventConstants
        existing_iohub = iohub.ioHubConnection.ACTIVE_CONNECTION
        self._io = existing_iohub or iohub.launchHubServer()

        import numpy
        self._np = numpy
Пример #16
0
    def init_devices(self):
        # Initialize test screen
        if self.test_screen is not None:
            self.close_test_screen = False
        else:
            self.test_screen = visual.Window(fullscr=True,
                                             units='pix',
                                             winType='pyglet')
            self.test_screen.winHandle.activate()

        self.test_screen.mouseVisible = False

        # Initialize keyboard input
        self.io = iohub.launchHubServer()
        self.keyboard = self.io.devices.keyboard
Пример #17
0
    def init_eyetracker(self):

        if not self.eyetracker_on:
            raise ValueError("Cannot initialize eyetracker if eyetracker_on=False!")

        EYETRACKER_NAME = 'eyetracker.hw.sr_research.eyelink.EyeTracker'
        # default_native_data_file_name: et_data
        self.iohub = launchHubServer(
            psychopy_monitor_name=self.monitor.name,
            datastore_name='test_et',
            **{EYETRACKER_NAME: {
                'enable_interface_without_connection': True
            }}
        )

        self.tracker = self.iohub.getDevice('eyetracker.hw.sr_research.eyelink.EyeTracker')
def EyeTrackerInitialization():

    iohub_config = {
        'eyetracker.hw.sr_research.eyelink.EyeTracker': {
            'name': 'tracker',
            'model_name': 'EYELINK 1000 DESKTOP',
            'runtime_settings': {
                'sampling_rate': 500,
                'track_eyes': 'RIGHT'
            }
        }
    }
    io = launchHubServer(**iohub_config)

    # Get the eye tracker device.
    tracker = io.devices.tracker

    return tracker
Пример #19
0
	def __init__(self, rows, cols, buttons, maxTime, myWin, thisExp):
		self.maxTime = maxTime
		self.buttonGrid = ButtonGrid(myWin, buttons, rows=0, cols=6)
		self.buttonGrid.autoDraw = False
		self.io = iohub.launchHubServer()
		self.trialN = 0
		self.myWin = myWin
		self.thisExp = thisExp
		self.instr = visual.TextStim(win=self.myWin, name='instr',
						text=u'+',
						font='Comic Sans',
						pos=(0, 0), height=180, wrapWidth=None, ori=0, 
						color='white', colorSpace='rgb', opacity=1,
						depth=0.0);

		self.freq = SigTo(value=440, time=0.001, init=440)
		self.sine = SineLoop(freq=[self.freq, self.freq], feedback=0.08, mul=.3)
		self.freqTarget = {'C': 261.626 ,'Cis': 277.183,'D' : 293.665,'Dis' : 311.127,'E' : 329.628,'F' : 349.228,'Fis' : 369.994,'G' : 391.995,'Gis' : 415.305,'A' : 440,'B' : 466.164,'H': 493.883}
Пример #20
0
def t5():
    # Open the window and hide the cursor
    w = visual.Window(screen=1, fullscr=True, units='pix')
    m = event.Mouse(visible=False, win=w)
    m.setExclusive(True)

    # Turn on IOHub
    io = iohub.launchHubServer()
    kb = io.devices.keyboard

    # Delay a while
    t_end = core.getTime() + 10
    while core.getTime() < t_end:
        core.wait(0.010)

    # Turn off iohub, release the cursor and close the window
    io.quit()
    m.setExclusive(False)
    w.close()
Пример #21
0
def startIOHub():
    """
    Starts the ioHub process, saving events to events.hdf5, recording data from
    all standard devices as well as the ioSync MCU device.
    """
    global io
    import time
    psychopy_mon_name = 'testMonitor'
    exp_code = 'events'
    sess_code = 'S_{0}'.format(int(time.mktime(time.localtime())))
    iohub_config = {
        "psychopy_monitor_name": psychopy_mon_name,
        "mcu.iosync.MCU": dict(serial_port='auto',
                               monitor_event_types=['AnalogInputEvent',
                                                    'DigitalInputEvent']),
        "experiment_code": exp_code,
        "session_code": sess_code
    }
    return launchHubServer(**iohub_config)
Пример #22
0
    def init_eyetracker(self):
        """ Initializes eyetracker.

        After initialization, tracker object ("device" in iohub lingo)
        can be accessed from self.tracker
        """
        if not self.eyetracker_on:
            raise ValueError(
                "Cannot initialize eyetracker if eyetracker_on=False!")

        EYETRACKER_NAME = 'eyetracker.hw.sr_research.eyelink.EyeTracker'
        self.iohub = launchHubServer(
            psychopy_monitor_name=self.monitor.name,
            **{
                EYETRACKER_NAME: {
                    'enable_interface_without_connection': False,
                }
            })

        self.tracker = self.iohub.devices.eyetracker
Пример #23
0
def testEnabledDataStoreAutoSessionCode():
        """
        testEnabledDataStoreAutoSessionCode is the same as testEnabledDataStore
        above, but session_code is provided by the script instead of being
        auto-generated. The ioHub DataStore will be enabled, using the
        experiment and session_code provided each time it is run. Experiment
        and session metadata is printed at the end of the demo.

        Considerations:
            * A Keyboard, Mouse, Monitor, and Experiment device are created by
              default.
            * If the psychopy_monitor_name is valid, the ioHub Display is
              updated to use the display size and viewing distance specified
              in the psychopy monitor config.
            * ioHub DataStore is enabled because experiment_code and
              session_code are provided.
        """
        import time
        from pprint import pprint

        psychopy_mon_name = 'testMonitor'
        exp_code = 'gap_endo_que'
        sess_code = 'S_{0}'.format(int(time.mktime(time.localtime())))
        print('Current Session Code will be: ', sess_code)

        io = launchHubServer(psychopy_monitor_name=psychopy_mon_name,
                             experiment_code=exp_code,
                             session_code=sess_code)

        display = io.devices.display

        print('Display Psychopy Monitor Name: ', display.getPsychopyMonitorName())
        print('Display Default Eye Distance: ', display.getDefaultEyeDistance())
        print('Display Physical Dimensions: ', display.getPhysicalDimensions())

        print('Experiment Metadata: ')
        pprint(io.getExperimentMetaData())
        print('\nSession Metadata: ')
        pprint(io.getSessionMetaData())

        io.quit()
Пример #24
0
def testEnabledDataStoreAutoSessionCode():
    """
        testEnabledDataStoreAutoSessionCode is the same as testEnabledDataStore
        above, but session_code is provided by the script instead of being
        auto-generated. The ioHub DataStore will be enabled, using the
        experiment and session_code provided each time it is run. Experiment
        and session metadata is printed at the end of the demo.

        Considerations:
            * A Keyboard, Mouse, Monitor, and Experiment device are created by
              default.
            * If the psychopy_monitor_name is valid, the ioHub Display is
              updated to use the display size and viewing distance specified
              in the psychopy monitor config.
            * ioHub DataStore is enabled because experiment_code and
              session_code are provided.
        """
    import time
    from pprint import pprint

    psychopy_mon_name = 'testMonitor'
    exp_code = 'gap_endo_que'
    sess_code = 'S_{0}'.format(int(time.mktime(time.localtime())))
    print('Current Session Code will be: ', sess_code)

    io = launchHubServer(psychopy_monitor_name=psychopy_mon_name,
                         experiment_code=exp_code,
                         session_code=sess_code)

    display = io.devices.display

    print('Display Psychopy Monitor Name: ', display.getPsychopyMonitorName())
    print('Display Default Eye Distance: ', display.getDefaultEyeDistance())
    print('Display Physical Dimensions: ', display.getPhysicalDimensions())

    print('Experiment Metadata: ')
    pprint(io.getExperimentMetaData())
    print('\nSession Metadata: ')
    pprint(io.getSessionMetaData())

    io.quit()
Пример #25
0
def start_iohub(sess_code=None):
    import time, os

    # Create initial default session code
    if sess_code is None:
        sess_code = 'S_{0}'.format(long(time.mktime(time.localtime())))

    # Ask for session name / hdf5 file name
    save_to = fileSaveDlg(initFilePath=os.path.dirname(__file__),
                          initFileName=sess_code,
                          prompt="Set Session Output File",
                          allowed="ioHub Datastore Files (*.hdf5)|*.hdf5")
    if save_to:
        # session code should equal results file name
        fdir, sess_code = os.path.split(save_to)
        sess_code = sess_code[0:min(len(sess_code), 24)]
        if sess_code.endswith('.hdf5'):
            sess_code = sess_code[:-5]
        if save_to.endswith('.hdf5'):
            save_to = save_to[:-5]
    else:
        save_to = sess_code

    exp_code = 'wintab_evts_test'

    kwargs = {
        'experiment_code': exp_code,
        'session_code': sess_code,
        'datastore_name': save_to,
        'wintab.WintabTablet': {
            'name': 'tablet',
            'mouse_simulation': {
                'enable': False,
                'leave_region_timeout': 2.0
            }
        }
    }

    return launchHubServer(**kwargs)
Пример #26
0
def startIOHub():
    """
    Starts the ioHub process, saving events to events.hdf5, recording data from
    all standard devices as well as the ioSync MCU device.
    """
    global io
    import time
    psychopy_mon_name = 'testMonitor'
    exp_code = 'events'
    sess_code = 'S_{0}'.format(long(time.mktime(time.localtime())))
    iohub_config = {
        "psychopy_monitor_name":
        psychopy_mon_name,
        "mcu.iosync.MCU":
        dict(serial_port='auto',
             monitor_event_types=['AnalogInputEvent', 'DigitalInputEvent']),
        "experiment_code":
        exp_code,
        "session_code":
        sess_code
    }
    return launchHubServer(**iohub_config)
Пример #27
0
    def __init__(self, root, filter=None, sample_rate=300, calibrate=True):
        super(EyeTracker, self).__init__(filter)
        self.daemon = True  #??? TODO any issue with this closing down psychopy?
        #https://stackoverflow.com/questions/40391812/running-code-when-closing-a-python-daemon
        try:
            from psychopy.iohub import launchHubServer
        except Exception as e:
            raise EyeTrackingError("IMPORT FAILED.", cause=e)

        #self.io = connect_eyetracker(sample_rate = sample_rate)

        iohub_config = {
            'eyetracker.hw.tobii.EyeTracker': {
                'name': 'tracker',
                'runtime_settings': {
                    'sampling_rate': sample_rate
                }
            }
        }
        self.io = launchHubServer(**iohub_config)
        self.tracker = self.io.devices.tracker
        self.sample_rate = sample_rate
        self.tk_root = root
        #self.tk_root.bind("<Configure>", self.tk_update) #TODO some thought here, cannot bind multiple <Configure>..?

        # transform eye tracking coordinates to tk window coordinates
        self.tk_position = (self.tk_root.winfo_x(), self.tk_root.winfo_y())
        self.tk_screen_size2 = (
            root.winfo_screenwidth() / 2, root.winfo_screenheight() / 2
        )  #psychopy coordinate system is 0,0 screen center

        if calibrate:
            if not self.tracker.runSetupProcedure():
                print("WARNING: EYETRACKER CALIBRATION FAILED")

        self.closed = threading.Event()
        name = "{0}:{1}".format(EyeTracker.__name__, str(0))
        self.register(name)
Пример #28
0
fetching and processing events from hardware; mice, keyboards, eyetrackers).

Inital Version: May 6th, 2013, Sol Simpson
Abbrieviated: May 2013, Jon Peirce
Updated July, 2013, Sol, Added timeouts
"""

from __future__ import division

import sys

from psychopy import visual, core
from psychopy.iohub import launchHubServer

# create the process that will run in the background polling devices
io = launchHubServer()

# some default devices have been created that can now be used
display = io.devices.display
keyboard = io.devices.keyboard
mouse = io.devices.mouse

# Hide the 'system mouse cursor'.
mouse.setSystemCursorVisibility(False)

# We can use display to find info for the Window creation, like the resolution
# (which means PsychoPy won't warn you that the fullscreen does not match your requested size)
display_resolution = display.getPixelResolution()

# ioHub currently supports the use of a single full-screen PsychoPy Window
win = visual.Window(display_resolution, units="pix", fullscr=True, allowGUI=False, screen=0)
Пример #29
0
 def setup(cls):
     if cls.io is not None:
         cls.io.quit()
     cls.io = iohub.launchHubServer()
     cls.keyboard = cls.io.devices.keyboard
Demonstrate iohub module versus event module with a flip-loop.
iohub registers responses during win.flip(), thus always scores
responses as faster than event.getKeys() which timestamps according
to the time that the function is called.

Jonas Kristoffer Lindeløv, 2015.
"""
import psychopy

psychopy.useVersion("1.81.02")

from psychopy import iohub, visual, event

win = visual.Window()
textStim = visual.TextStim(win, text="press now", height=0.1, wrapWidth=100)
io = iohub.launchHubServer()
keyboard = io.devices.keyboard

# Comparing iohub.
while True:
    # Animate and show results
    textStim.ori += 0.1
    textStim.draw()
    win.flip()

    # Get responses
    event_getkeys = event.getKeys(timeStamped=True)
    io_getpresses = keyboard.getPresses()

    # Update text if a matching response was found
    if len(event_getkeys) and len(io_getpresses):
from psychopy.iohub import launchHubServer, getCurrentDateTimeString


#Particicpant Info and Other Settings
info = {}
info['participant'] = '0'
info['dateStr'] = data.getDateStr() #will create str of current date/time
dlg = gui.DlgFromDict(info) #dialog box
if not dlg.OK: #did they push ok?
    core.quit()



###############----ioHub Start and Hardware----#############

io = launchHubServer(iohub_config_name = 'iohub_config.yaml', experiment_code = info['participant'])

#Declare our Hardware
try:
    tracker=io.devices.tracker
except Exception:
    # No eye tracker config found in iohub_config.yaml
    from psychopy.iohub.util import MessageDialog
    md = MessageDialog(title="No Eye Tracker Configuration Found",
                       msg="Update the iohub_config.yaml file by "
                       "uncommenting\nthe appropriate eye tracker "
                       "config lines.\n\nPress OK to exit demo.",
                       showButtons=MessageDialog.OK_BUTTON,
                       dialogType=MessageDialog.ERROR_DIALOG,
                       allowCancel=False,
                       display_index=0)
Пример #32
0
import time
from psychopy import core
from psychopy.iohub import launchHubServer
getTime=core.getTime

try:
    psychopy_mon_name='testMonitor'
    exp_code='events'
    sess_code='S_{0}'.format(long(time.mktime(time.localtime())))
    iohub_config={
    "psychopy_monitor_name":psychopy_mon_name,
    "mcu.iosync.MCU":dict(serial_port='auto',monitor_event_types=['DigitalInputEvent',]),
    "experiment_code":exp_code, 
    "session_code":sess_code
    }
    io=launchHubServer(**iohub_config)
    mcu=io.devices.mcu
    kb=io.devices.keyboard
        
    core.wait(0.5)
    mcu.enableEventReporting(True)
    io.clearEvents("all")
    while not kb.getEvents():   
        mcu_events=  mcu.getEvents()
        for mcu_evt in mcu_events:
            print'{0}\t{1}'.format(mcu_evt.time,mcu_evt.state)
        core.wait(0.002,0)
    io.clearEvents('all')
except Exception:
    import traceback
    traceback.print_exc()    
Пример #33
0
Demo of using the iohub mouse.
"""

import sys

from psychopy import visual, core
from psychopy.iohub import launchHubServer

win = visual.Window((1920, 1080),
                    units='height',
                    fullscr=True,
                    allowGUI=False,
                    screen=0)

# create the process that will run in the background polling devices
io = launchHubServer(window=win)

# some default devices have been created that can now be used
keyboard = io.devices.keyboard
mouse = io.devices.mouse
mouse.setPosition((0.0, .250))
#win.setMouseVisible(False)

# Create some psychopy visual stim
fixSpot = visual.GratingStim(win,
                             tex="none",
                             mask="gauss",
                             pos=(0, 0),
                             size=(.03, .03),
                             color='black',
                             autoLog=False)
logFile = logging.LogFile(filename+'.log', level=logging.DEBUG)
logging.console.setLevel(logging.WARNING)  # this outputs to the screen, not a file

# 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)

#-------------------------------------------------------------------------------
# iohub stuff
#-------------------------------------------------------------------------------

# create the process that will run in the background polling devices
io=launchHubServer(experiment_code='target-sequences', psychopy_monitor_name='default')

# some default devices have been created that can now be used
display = io.devices.display
keyboard = io.devices.keyboard
mouse=io.devices.mouse

# Hide the 'system mouse cursor'.
mouse.setSystemCursorVisibility(False)
mouse.enableEventReporting(True)

# We can use display to find info for the Window creation, like the resolution
# (which means PsychoPy won't warn you that the fullscreen does not match your requested size)
display_resolution=display.getPixelResolution()

#-------------------------------------------------------------------------------
Пример #35
0
    # Create a circle to use for the Gaze Cursor. Current units assume pix.
    #
    gaze_dot = visual.GratingStim(window, tex=None, mask="gauss", pos=(0, 0),
                                  size=(0.1, 0.1), color='green')

    # Create a Text Stim for use on /instruction/ type screens.
    # Current units assume pix.
    instructions_text_stim = visual.TextStim(window, text='', pos=[0, 0], units='pix', height=24, color=[-1, -1, -1],
                                             wrapWidth=window.size[0]*.9)


    exp_conditions = importConditions('trial_conditions.xlsx')
    trials = TrialHandler(exp_conditions, 1)

    io_hub = launchHubServer(window=window, experiment_code='gc_cursor', **devices_config)
    # 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.
    #
    io_hub.createTrialHandlerRecordTable(trials)

    # Let's make some short-cuts to the devices we will be using in this demo.
    tracker = None
    try:
        tracker = io_hub.devices.tracker
    except Exception:
        print(" No eye tracker config found in iohub_config.yaml")
        io_hub.quit()
        core.quit()

    display = io_hub.devices.display
Пример #36
0
from __future__ import print_function

from psychopy import iohub
from psychopy.visual.window import Window
from psychopy.visual.circle import Circle

io = iohub.launchHubServer()
mouse = io.devices.mouse

win = Window(units='pix', fullscr=True)
circle = Circle(win, size=300)
circle.draw()
win.flip()

mouse.clearEvents()

while True:
    e = mouse.getEvents(event_type=(iohub.EventConstants.MOUSE_BUTTON_PRESS))

    if e:
        x, y = e[0].x_position, e[0].y_position

        if circle.contains((x, y), units='pix'):
            print('Received button press!')
            break

win.close()
io.quit()
Пример #37
0
Displays event information from ioHub Keyboard Events. 

Inital Version: May 6th, 2013, Sol Simpson
Updated June 22nd: Added demo timeout. SS
"""
from psychopy import core, visual
from psychopy.iohub import launchHubServer, EventConstants

# launchHubServer is a fucntion that can be used to create an instance of the
#   ioHub Process within a procedural PsychoPy Script and without the need for
#   external configuration files. It is useful when devices like the Keyboard,
#   Mouse, Display, and Experiment are all that is needed. By default the
#   Display device will use pixel units and display index 0 of a multimonitor setup.
#   The returned 'io' variable gives access to the ioHub Process.
#
io = launchHubServer(experiment_code='key_evts',
                     psychopy_monitor_name='default')

# Devices that have been created on the ioHub Process and will be monitored
# for events during the experiment can be accessed via the io.devices.* attribute.
#
# save some 'dots' during the trial loop
#
display = io.devices.display
keyboard = io.devices.keyboard
mouse = io.devices.mouse

# Hide the 'system mouse cursor'.
mouse.setSystemCursorVisibility(False)

# Get settings needed to create the PsychoPy full screen window.
#   - display_resolution: the current resolution of diplsay specified by the screen_index.
Пример #38
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test for using iohub mouse with multiple windows on multiple monitors.

To enable multi window support for the iohub Mouse device:

launchHubServer(window=win, Mouse=dict(enable_multi_window=True))

In this mode, if the mouse is over a psychopy window, mouse position is returned
as the pix position within the window, with origin (0,0) at window center. mouse event
window_id will equal a psychopy window handle (pyglet only).

Note: If testing using 'cm' or 'deg' units, use your actual monitor configurations
or update the `monitors.Monitor` created below to match your setup.

If the mouse is not over a psychopy window, desktop mouse position is returned with
window_id = 0.
"""
import sys

from psychopy import visual, core, monitors
from psychopy.iohub import launchHubServer
from psychopy.iohub.constants import EventConstants

# True = print mouse events to stdout, False = do not
PRINT_MOUSE_EVENTS = False

# Test creating a monitor before starting iohub
mon0 = monitors.Monitor('monitor0')
mon0.setDistance(60.0)
Пример #39
0
"""
Created on Thu Oct 17 22:46:06 2013

@author: Sol
"""
from __future__ import print_function
from builtins import str
from psychopy import visual,core
from psychopy.data import TrialHandler,importConditions
from psychopy.iohub import launchHubServer,Computer,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
def loggedFlip(letter_char,letter_color):
    global retrace_count
    gabor.draw()
Пример #40
0
iohubkwargs = {
    'psychopy_monitor_name':
    psychopy_mon_name,
    'experiment_code':
    exp_code,
    'session_code':
    sess_code,
    'serial.Serial':
    dict(name='serial',
         port=SERIAL_PORT,
         baud=BAUDRATE,
         event_parser=dict(byte_diff=True))
}

# start the iohub server and set up display and PST box devices
io = launchHubServer(**iohubkwargs)
display = io.devices.display
pstbox = io.devices.serial

# Prepare the PST box.
#
# Bit 7 = 128 -> Enable/Disable streaming.
# Bit 6 =  64 -> Lower bits control lamp state.
# Bit 5 =  32 -> Enable/Disable button queries.
# Bit 0-4 = 1-16 -> Enable/Disable Lamp 0-4.
#
# Source: https://psychtoolbox-3.googlecode.com/svn/beta/Psychtoolbox/PsychHardware/CMUBox.m
print('Switching response box to streaming mode and switching on lamp #3...')
pstbox.write(chr(np.uint8(128 + 32 + 64 + 4)))
core.wait(0.25)
print('...done.')
Пример #41
0
from psychopy import visual, core
from psychopy.iohub import launchHubServer, EventConstants


def normalizedValue2Coord(normed_position,normed_magnitude,display_coord_area):
        x,y=normed_position[0]*normed_magnitude,normed_position[1]*normed_magnitude
        w,h=display_coord_area
        return x*(w/2.0),y*(h/2.0)

if __name__ == '__main__':
    # Start the ioHub Event Server, requesting an XInput Gamepad Device to be
    #   created along with the default devices. Since the configuration dict
    #   for the Gamepad is empty, all default values will be used.
    #
    kwargs={'psychopy_monitor_name':'default','xinput.Gamepad':{}}
    io=launchHubServer(**kwargs)
    
    display = io.devices.display
    mouse = io.devices.mouse
    display = io.devices.display
    keyboard = io.devices.keyboard
    gamepad = io.devices.gamepad
    
    display_resolution=display.getPixelResolution()
    psychopy_monitor=display.getPsychopyMonitorName()
    unit_type=display.getCoordinateType()
    screen_index=display.getIndex()
    dl,dt,dr,db=display.getCoordBounds()
    coord_size=dr-dl,dt-db
        
    myWin=visual.Window(display_resolution, monitor=psychopy_monitor, 
Пример #42
0
Displays event information from ioHub Keyboard Events. 

Inital Version: May 6th, 2013, Sol Simpson
"""
from psychopy import visual
from psychopy.iohub import launchHubServer,EventConstants 


# launchHubServer is a fucntion that can be used to create an instance of the 
#   ioHub Process within a procedural PsychoPy Script and without the need for
#   external configuration files. It is useful when devices like the Keyboard,
#   Mouse, Display, and Experiment are all that is needed. By default the
#   Display device will use pixel units and display index 0 of a multimonitor setup.
#   The returned 'io' variable gives access to the ioHub Process.
#
io=launchHubServer(experiment_code='key_evts',psychopy_monitor_name='default')

# Devices that have been created on the ioHub Process and will be monitored
# for events during the experiment can be accessed via the io.devices.* attribute.
#
# save some 'dots' during the trial loop
#
display = io.devices.display
keyboard = io.devices.keyboard
mouse=io.devices.mouse

# Hide the 'system mouse cursor'.
mouse.setSystemCursorVisibility(False)

# Get settings needed to create the PsychoPy full screen window.
#   - display_resolution: the current resolution of diplsay specified by the screen_index.
Пример #43
0
Inital Version: May 6th, 2013, Sol Simpson
Abbrieviated: May 2013, Jon Peirce
Updated July, 2013, Sol, Added timeouts
"""

from __future__ import division
from __future__ import print_function

import sys

from psychopy import visual, core
from psychopy.iohub import launchHubServer

# create the process that will run in the background polling devices
io = launchHubServer()

# some default devices have been created that can now be used
display = io.devices.display
keyboard = io.devices.keyboard
mouse = io.devices.mouse

# Hide the 'system mouse cursor'.
mouse.setSystemCursorVisibility(False)

# We can use display to find info for the Window creation, like the resolution
# (which means PsychoPy won't warn you that the fullscreen does not match your requested size)
display_resolution = display.getPixelResolution()

# ioHub currently supports the use of a single full-screen PsychoPy Window
win = visual.Window(display_resolution,
Пример #44
0
# standard
from __future__ import print_function, division

from psychopy.iohub import launchHubServer

_IO_HUB = launchHubServer()
Пример #45
0
# -*- coding: utf-8 -*-

"""
keyboard_rt.run.py

Keyboard Reaction Time Calculation shown within a line length matching task.

Initial Version: May 6th, 2013, Sol Simpson
"""
from __future__ import absolute_import, division, print_function

from psychopy import  core,  visual
from psychopy.iohub import launchHubServer
from math import fabs

io = launchHubServer(psychopy_monitor_name='default')
display = io.devices.display
win = visual.Window(display.getPixelResolution(), monitor='default',
    units='pix', fullscr=True, allowGUI=False)

# save some 'dots' during the trial loop
keyboard = io.devices.keyboard

# constants for use in example
line_size_match_delay = 5 + int(core.getTime() * 1000) % 5
full_length = win.size[0] / 2
latest_length = 0

static_bar = visual.ShapeStim(win=win, lineColor='Firebrick',
    fillColor='Firebrick',
    vertices=[[0, 0], [full_length, 0], [full_length, 5], [0, 5]],
Пример #46
0
    psychopy_mon_name = 'testMonitor'
    exp_code = 'events'
    sess_code = 'S_{0}'.format(long(time.mktime(time.localtime())))
    iohub_config = {
        "psychopy_monitor_name":
        psychopy_mon_name,
        "mcu.iosync.MCU":
        dict(serial_port='auto', monitor_event_types=[
            'DigitalInputEvent',
        ]),
        "experiment_code":
        exp_code,
        "session_code":
        sess_code
    }
    io = launchHubServer(**iohub_config)
    mcu = io.devices.mcu
    kb = io.devices.keyboard

    core.wait(0.5)
    mcu.enableEventReporting(True)
    io.clearEvents("all")
    while not kb.getEvents():
        mcu_events = mcu.getEvents()
        for mcu_evt in mcu_events:
            print '{0}\t{1}'.format(mcu_evt.time, mcu_evt.state)
        core.wait(0.002, 0)
    io.clearEvents('all')
except:
    import traceback
    traceback.print_exc()
Пример #47
0
SERIAL_PORT = 'COM5'
BAUDRATE = 19200

# ioHub configuration.
psychopy_mon_name = 'Monitor_01'
exp_code = 'pstbox'
sess_code = 'S_{0}'.format(int(time.mktime(time.localtime())))
iohubkwargs = {
    'psychopy_monitor_name': psychopy_mon_name,
    'experiment_code': exp_code,
    'session_code': sess_code,
    'serial.Pstbox': dict(name='pstbox', port=SERIAL_PORT, baud=BAUDRATE)
}

# Start the iohub server and set up devices.
io = launchHubServer(**iohubkwargs)
computer = Computer
display = io.devices.display
pstbox = io.devices.pstbox

print('Switching on lamp #3...')
pstbox.setLampState([0, 0, 1, 0, 0])
print('...done.')

# Create a window.
win = visual.Window(
    display.getPixelResolution(),
    units='pix', fullscr=True, allowGUI=False,
    screen=0
)
Пример #48
0
def main(fCue, fStim, fInterval, fTest, fPause, recLength, recWidth,
         cubeLength, cubeWidth, tPerBlock, stimType, arraySize, targPresent,
         numTrials):

    fStim = fStim
    fTest = fTest
    fPause = fPause
    recLength = recLength
    recWidth = recWidth
    cubeLength = cubeLength
    cubeWidth = cubeWidth
    tPerBlock = tPerBlock
    stimType = stimType
    arraySize = arraySize
    targPresent = targPresent
    numTrials = numTrials

    # Ensure that relative paths start from the same directory as this script
    _thisDir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(_thisDir + u'\%s%s%s' % (targPresent[0], stimType, arraySize[0]))

    # Store info about the experiment session
    expName = 'VST.py'
    expInfo = {'session': '001', 'participant': ''}
    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 + 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)
    # 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

    # 300 x 2 x 10 x 1 matrix
    # 300 entries, xy for each shape, 10 shape locations
    f = open('genCoorVST.pckl', 'rb')
    genCoor = pickle.load(f)
    f.close()
    win = visual.Window([1600, 900], units='height', fullscr=True)
    clock = core.Clock()

    # KEYBOARD STUFF
    # Start iohub process. The iohub process can be accessed using `io`.
    io = launchHubServer()
    # A `keyboard` variable is used to access the iohub Keyboard device.
    keyboard = io.devices.keyboard
    events = keyboard.getKeys()

    # INITIALIZE
    # trialN       : number of trial
    # trialResp    : their response on each trial
    # correctResp  : if their response was correct
    # responseTime : the amount of time it took for them to respond on each trial
    m = 0
    trialN = [-1 for x in range(numTrials)]
    trialResp = [9 for x in range(numTrials)]
    correctResp = [9 for x in range(numTrials)]
    responseTime = [0 for x in range(numTrials)]
    respChar = [['r', 'i'], ['f', 'j']]
    numSet = 100
    rectangles = not stimType
    shapeN = [[], []]

    # COLORS
    recColors = ['#0000ff', '#ff0000']
    cubeColors = [['#0000ff', '#9999ff', '#000066'],
                  ['#ff0000', '#ff9999', '#660000']]

    # STIMULI
    center = [0, 0]
    posTheta = [0, math.pi / 4, math.pi / 2, 3 * math.pi / 4]
    posCubes = [0, 1]
    pauseText = visual.TextStim(win,
                                text="Press the Spacebar to Continue",
                                font=u'Arial',
                                pos=(0, 0),
                                height=0.1,
                                wrapWidth=None,
                                ori=0,
                                color=u'white',
                                colorSpace='rgb',
                                opacity=1,
                                depth=0.0)

    # rotates [x,y] by theta
    def rotate(xy, center, theta):
        #pts = {} Rotates points(nx2) about center by angle theta in radians
        return numpy.dot(
            xy - center,
            numpy.array([[math.cos(theta), math.sin(theta)],
                         [-math.sin(theta), math.cos(theta)]])) + center

    def rotateRec(center, theta):
        center = center
        theta = theta
        p1 = [center[0] - recWidth, center[1] - recLength]
        p2 = [center[0] - recWidth, center[1] + recLength]
        p3 = [center[0] + recWidth, center[1] + recLength]
        p4 = [center[0] + recWidth, center[1] - recLength]
        rVert = rotate(numpy.array([p1, p2, p3, p4]), center, theta)
        return rVert

    # creates a three-sided cube
    def cubeCreator(centerV, cubeType):
        center = centerV
        cubeType = cubeType
        if cubeType == 0:
            p1 = [center[0], center[1]]
            p2 = [center[0], center[1] - cubeLength]
            p3 = [center[0] - cubeWidth, center[1] - cubeLength / 2]
            p4 = [center[0] - cubeWidth, center[1] + cubeLength / 2]
            sideOne = [p1, p2, p3, p4]

            q1 = [center[0], center[1]]
            q2 = [center[0], center[1] - cubeLength]
            q3 = [center[0] + cubeWidth, center[1] - cubeLength / 2]
            q4 = [center[0] + cubeWidth, center[1] + cubeLength / 2]
            sideTwo = [q1, q2, q3, q4]

            r1 = [center[0], center[1]]
            r2 = [center[0] - cubeWidth, center[1] + cubeLength / 2]
            r3 = [center[0], center[1] + cubeLength]
            r4 = [center[0] + cubeWidth, center[1] + cubeLength / 2]
            sideThree = [r1, r2, r3, r4]
        else:
            m1 = [center[0], center[1]]
            m2 = [center[0], center[1] + cubeLength]
            m3 = [center[0] + cubeWidth, center[1] + cubeLength / 2]
            m4 = [center[0] + cubeWidth, center[1] - cubeLength / 2]
            sideOne = [m1, m2, m3, m4]

            n1 = [center[0], center[1]]
            n2 = [center[0], center[1] + cubeLength]
            n3 = [center[0] - cubeWidth, center[1] + cubeLength / 2]
            n4 = [center[0] - cubeWidth, center[1] - cubeLength / 2]
            sideTwo = [n1, n2, n3, n4]

            s1 = [center[0], center[1]]
            s2 = [center[0] - cubeWidth, center[1] - cubeLength / 2]
            s3 = [center[0], center[1] - cubeLength]
            s4 = [center[0] + cubeWidth, center[1] - cubeLength / 2]
            sideThree = [s1, s2, s3, s4]
            # k cubes x 3 sides x 4 vertices x 2 coordinates
        cVert = [sideOne, sideTwo, sideThree]
        return cVert

    def randShuf(inputList):
        shufList = inputList[:]
        while True:
            random.shuffle(shufList)
            for a, b in zip(inputList, shufList):
                if a == b:
                    break
                else:
                    return shufList

    def recDraw(frames, nStim, stimulus, changeT, order):
        frames = frames
        for k in range(nStim):
            stimulus[k].draw()
        print('stimType%d_arraySize%d_trial%d_targPresent%d_order%d.png' %
              (stimType, arraySize[t], t, targPresent[t], order))
        time.sleep(0.03)
        win.getMovieFrame(buffer='back')
        win.flip()
        win.saveMovieFrames(
            'stimType%d_arraySize%d_trial%d_targPresent%d_order%d.png' %
            (stimType, arraySize[t], t, targPresent[t], order))

    def cubeDraw(frames, nStim, stimulus, changeT, order):
        frames = frames
        for j in range(nStim):
            for k in range(3):
                stimulus[j][k].draw()
                stimulus[j][k].draw()
        print('stimType%d_arraySize%d_trial%d_targPresent%d_order%d.png' %
              (stimType, arraySize[t], t, targPresent[t], order))
        time.sleep(0.03)
        win.getMovieFrame(buffer='back')
        win.flip()
        win.saveMovieFrames(
            'stimType%d_arraySize%d_trial%d_targPresent%d_order%d.png' %
            (stimType, arraySize[t], t, targPresent[t], order))

    for t in range(numTrials):
        if (t % tPerBlock == 0) & (t > 1):
            waiting = []
            while not ' ' in waiting:
                pauseText.draw()
                win.flip()
                waiting = keyboard.getKeys()
        random.shuffle(recColors[0][0])
        trialN[t] = t + 1
        nStim = arraySize[t]
        shapes = [[] for i in range(nStim)]
        recStim = [[] for i in range(nStim)]
        recVert = [[] for i in range(nStim)]
        cubeV = [[] for i in range(nStim)]
        # 3 because 3 sides
        targCube = [[] for i in range(3)]
        cubeStim = [[[], [], []] for i in range(nStim)]
        stimIndex = nStim - 1

        # START WORKING HERE
        # Choose random trial and get center coordinates of objects
        # ASSUMING ARRAYSIZE[T] IS A VECTOR OF ARRAY SIZES
        # genCoor (300 x 2 x 10 x 1)
        #          300 sets, (X pos, Y pos), 10 points
        # x any y pos of arraySize[t] locations
        randInt = random.randint(0, numSet - 1)
        for j in range(0, nStim):
            xCoor = genCoor[randInt, 0, j]
            yCoor = genCoor[randInt, 1, j]
            shapes[j] = [xCoor[0], yCoor[0]]

        if rectangles:
            # create a unique rectangle that will only been seen once or not at all
            random.shuffle(posTheta)
            coinFlip = (random.random() > .5)
            targTheta = posTheta[0]
            targColor = coinFlip
            targRectVert = rotateRec([0, 0], targTheta)

            # creates unique rectangle for cue
            targRect = ShapeStim(win,
                                 vertices=targRectVert,
                                 fillColor=recColors[targColor],
                                 size=.5)

            # creates numRect rectangles with random orientations and random colors
            for k in range(nStim):
                coinFlip = (random.random() > .5)
                random.shuffle(posTheta)
                while posTheta[0] == targTheta and coinFlip == targColor:
                    coinFlip = (random.random() > .5)
                    random.shuffle(posTheta)
                recVert[k] = rotateRec(shapes[k], posTheta[0])
                recStim[k] = ShapeStim(win,
                                       vertices=recVert[k],
                                       fillColor=recColors[coinFlip],
                                       size=.5)
                coinFlip = (random.random() > .5)
                random.shuffle(posTheta)

        else:
            # create a unique cube that will only been seen once or not at all
            random.shuffle(posCubes)
            coinFlip = (random.random() > .5)
            targOrientation = posCubes[coinFlip]
            random.shuffle(cubeColors[coinFlip])
            targCubeColors = cubeColors[coinFlip][:]
            targCubeVert = cubeCreator([0, 0], targOrientation)

            # creates unique cube for cue
            for b in range(3):
                targCube[b] = ShapeStim(win,
                                        vertices=targCubeVert[b],
                                        fillColor=targCubeColors[b],
                                        size=.5)

            for j in range(nStim):
                coinFlip = (random.random() > .5)
                random.shuffle(posCubes)
                random.shuffle(cubeColors[0])
                random.shuffle(cubeColors[1])
                while posCubes[0] == targOrientation and cubeColors[
                        coinFlip] == targCubeColors:
                    coinFlip = (random.random() > .5)
                    random.shuffle(posCubes)
                    random.shuffle(cubeColors[0])
                    random.shuffle(cubeColors[1])

                cubeVert = cubeCreator(shapes[j], posCubes[0])
                cubeV[j] = cubeCreator(shapes[j], posCubes[0])

                # creates each side
                for i in range(3):
                    cubeStim[j][i] = ShapeStim(
                        win,
                        vertices=cubeVert[i],
                        fillColor=cubeColors[coinFlip][i],
                        size=.5)

        # STIM PRESENTATION

        #
        # presents target
        if rectangles:
            recDraw(fStim, 1, [targRect], targPresent[t], 0)
        else:
            cubeDraw(fStim, 1, [targCube], targPresent[t], 0)

        ## presents interval
        #for frameN in range(fPause + 1):
        #    win.flip()

        # presents stim
        if targPresent[t]:
            if rectangles:
                # inserts target rectangle into line-up
                targRect = rotateRec(shapes[0], targTheta)
                recStim[0] = ShapeStim(win,
                                       vertices=targRect,
                                       fillColor=recColors[targColor],
                                       size=.5)

                recDraw(fStim, nStim, recStim, targPresent[t], 1)
            else:
                # inserts target cube into line-up
                for b in range(3):
                    cubeStim[0][b] = ShapeStim(win,
                                               vertices=cubeV[0][b],
                                               fillColor=targCubeColors[b],
                                               size=.5)

                cubeDraw(fStim, nStim, cubeStim, targPresent[t], 1)
        else:
            if rectangles:
                recDraw(fStim, nStim, recStim, targPresent[t], 1)
            else:
                cubeDraw(fStim, nStim, cubeStim, targPresent[t], 1)

        if trialResp[t] == targPresent[t]:
            correctResp[t] = 1
        else:
            correctResp[t] = 0

    # OUTPUT
    print()
    print('Correct response trials')
    print(correctResp)
    print('Percent correct')
    print(sum(correctResp) / numTrials)
    print('Response Time')
    print(responseTime)
    print('Average response time')
    print(sum(responseTime) / numTrials)

    thisExp.addData('correct responses', correctResp)
    thisExp.nextEntry()
    thisExp.addData('response times', responseTime)
    thisExp.nextEntry()
    # these shouldn't be strictly necessary (should auto-save)
    thisExp.saveAsWideText(filename + '.csv')
    thisExp.saveAsPickle(filename)
    logging.flush()
    # make sure everything is closed down
    thisExp.abort()  # or data files will save again on exit

    origLUT = numpy.round(win.backend._origGammaRamp *
                          65535.0).astype("uint16")
    origLUT = origLUT.byteswap() / 255.0
    win.backend._origGammaRamp = origLUT

    win.close()
    core.quit()
Пример #49
0
def generate_variables(game):
    # game logic
    game.show_feedback = False
    game.show_cue = False
    game.header_written = False
    game.feedback_score_history = [0]
    game.feedback_requesting_bool = False
    game.trial_stage = 'splash'  # splash, zscore, cue, wait, feedback, iti
    game.feedback_status = 'idle'  # idle, calculated

    # input/output
    io = launchHubServer()
    game.keyboard = io.devices.keyboard
    game.monitor = monitors.Monitor('projector',
                                    width=game.SCREEN_WIDTH,
                                    distance=game.SCREEN_DISTANCE)
    game.monitor.setSizePix(game.SCREEN_DIMS)
    game.screen = visual.Window(game.SCREEN_DIMS,
                                monitor=game.monitor,
                                fullscr=game.FULLSCREEN,
                                units='deg',
                                color=game.BG_COLOR,
                                colorSpace='rgb')

    # visual stims
    game.max_score_circ = visual.Circle(game.screen,
                                        edges=64,
                                        lineWidth=1,
                                        lineColor=game.BG_COLOR,
                                        lineColorSpace='rgb',
                                        fillColor=game.SCORE_COLOR,
                                        fillColorSpace='rgb255',
                                        radius=0.5 *
                                        game.SCORE_DIAMETER_MAX_INDICATOR,
                                        interpolate=True)
    game.max_score_circ_mask = visual.Circle(game.screen,
                                             edges=64,
                                             lineWidth=1,
                                             lineColor=game.BG_COLOR,
                                             lineColorSpace='rgb',
                                             fillColor=game.BG_COLOR,
                                             fillColorSpace='rgb',
                                             radius=0.5 *
                                             game.SCORE_DIAMETER_MAX,
                                             interpolate=True)
    game.score_circ = visual.Circle(game.screen,
                                    edges=64,
                                    lineWidth=1,
                                    lineColor=game.SCORE_COLOR,
                                    lineColorSpace='rgb255',
                                    fillColor=game.SCORE_COLOR,
                                    fillColorSpace='rgb255',
                                    radius=0.5 * game.SCORE_DIAMETER_MIN,
                                    interpolate=True)
    game.score_circ_mask = visual.Circle(game.screen,
                                         edges=64,
                                         lineWidth=1,
                                         lineColor=game.BG_COLOR,
                                         lineColorSpace='rgb',
                                         fillColor=game.BG_COLOR,
                                         fillColorSpace='rgb',
                                         radius=0.5 *
                                         game.SCORE_DIAMETER_MIN_INDICATOR,
                                         interpolate=True)
    game.fixation = visual.Circle(game.screen,
                                  lineWidth=1,
                                  lineColor=game.FIXATION_COLOR,
                                  lineColorSpace='rgb',
                                  fillColor=game.FIXATION_COLOR,
                                  fillColorSpace='rgb',
                                  radius=0.5 * game.FIXATION_DIAMETER,
                                  interpolate=True)
    game.cue = visual.Circle(game.screen,
                             lineWidth=1,
                             lineColor=game.SCORE_COLOR,
                             lineColorSpace='rgb255',
                             fillColor=game.SCORE_COLOR,
                             fillColorSpace='rgb255',
                             radius=0.5 * game.FIXATION_DIAMETER,
                             interpolate=True)

    game.splash_msg = visual.TextStim(
        game.screen,
        text=game.SPLASH_MSG_BASE.format(current=str(1), total=str(game.RUNS)))

    game.reward_msg = visual.TextStim(game.screen, text='', pos=(0, 2.5))

    game.debug_msg = visual.TextStim(game.screen, text='', pos=(-0.25, -0.25))

    game.debug_msg_base = ('last volume: {last_vol}\n' +
                           'last classifier: {last_clf}\n')

    # timers
    game.trial_clock = core.Clock()
    game.feedback_update_clock = core.Clock()
    game.self_pace_start_clock = core.Clock()
    game.trial_count = 0
    game.run_count = -1

    # reward
    game.run_reward_history = []
    game.total_reward = 0