Esempio n. 1
0
    def __init__(self,
                 sub_val,
                 n_trial,
                 mode='uniform',
                 show_fb=False,
                 joy_id=0):
        super(OrientEncodeButtons, self).__init__(sub_val, n_trial, mode,
                                                  show_fb)
        self.L1 = 4
        self.L2 = 6
        self.R1 = 5
        self.R2 = 7

        self.welcome = visual.TextStim(
            self.win,
            pos=[0, -5],
            text='Thanks for your time. Press L2 or R2 to continue.')
        self.pause_msg = visual.TextStim(
            self.win,
            pos=[0, 0],
            text=
            'Take a short break. Press L2 or R2 when you are ready to continue.'
        )

        nJoys = joystick.getNumJoysticks()
        if nJoys < joy_id:
            print('Joystick Not Found')

        self.joy = joystick.Joystick(joy_id)
Esempio n. 2
0
 def setupJoystick(self):
     self.joy = getattr(self.config, 'joy', None)
     if self.joy is None:
         joystick.backend = BACKEND
         if not joystick.getNumJoysticks(
         ):  # to check if we have any connected
             self.joy = None
         self.joy = joystick.Joystick(
             self.config.joyID)  # id must be <= nJoys - 1
     self.joyHats = self.joy.getAllHats()
     self.joyButs = self.joy.getAllButtons().copy()
Esempio n. 3
0
    def __init__(self):
        """
        REQUIRES: visual.Window object is initialized
        MODIFIES: joystick.backend, nJoys, sensors, nAxes
        EFFECTS:  Initializes joystick using pyglet joystick backend. Sets
                  default max grip values.
        """
        joystick.backend = 'pyglet'

        self.nJoys = joystick.getNumJoysticks()

        JOYSTICK_ID = 0  # not sure what this is for
        self.sensors = joystick.Joystick(JOYSTICK_ID)
        self.nAxes = self.sensors.getNumAxes()
Esempio n. 4
0
joystick.backend = 'testmonitor'  # must match window type

#win = visual.Window((800.0, 800.0), allowGUI=False, winType=joystick.backend)

#win = visual.Window((800.0, 800.0), allowGUI=False, winType=joystick.backend, screen = 2)                                             # main

#win = visual.Window((800.0, 800.0), allowGUI=False, winType="pyglet")s

#win2 = visual.Window(size=(800, 800), monitor='testMonitor')

win = visual.Window(size=(800, 800), monitor=joystick.backend)

nJoysticks = joystick.getNumJoysticks()
if nJoysticks > 0:
    joy = joystick.Joystick(0)
    print('found ', joy.getName(), ' with:')

else:
    print("You don't have a joystick connected!?")

smooth = 3  #smoothing array averages this many inputs
xaxisMultiplier = -1  #depending on the controler x or y may need different signs
yaxisMultiplier = -1

sets = [1, 2,
        1]  #the different sets of trials, total trials are sets * targets
angles = [
    0, -60, 0
]  # angle distortion for each set, sets and angles must be the same size, positive is clockwise rotation        -60
distort = [False, True, False]  # true or false to use the visual distortion,
    frameDur = 1.0 / 60.0  # could not measure, so guess

# Initialize components for Routine "trial"
trialClock = core.Clock()
x, y = [None, None]
joystick = type('', (), {})()  # Create an object to use as a name space
joystick.device = None
joystick.device_number = 0
joystick.joystickClock = core.Clock()
joystick.xFactor = 1
joystick.yFactor = 1

try:
    numJoysticks = joysticklib.getNumJoysticks()
    if numJoysticks > 0:
        joystick.device = joysticklib.Joystick(0)
        if win.units == 'height':
            joystick.xFactor = 0.5 * win.size[0] / win.size[1]
            joystick.yFactor = 0.5
    else:
        joystick.device = fakejoysticklib.Joystick(0)
        logging.warning(
            "joystick_{}: Using keyboard+mouse emulation 'ctrl' + 'Alt' + digit."
            .format(joystick.device_number))
except Exception:
    pass

if not joystick.device:
    logging.error('No joystick/gamepad device found.')
    core.quit()
Esempio n. 6
0
"""

from psychopy import visual, event, core
from psychopy.hardware import joystick


# Preparing Joystick
joystick.backend='pyglet'  # must match the Window

# preparing window
my_win = visual.Window(size = (1920, 1080), units = 'pix', pos=(0,0), screen = 1)

# Basic parameters for controller(joystick/wheel)
nJoys = joystick.getNumJoysticks()  # to check if we have any
id = 0
joy = joystick.Joystick(id)  # id must be <= nJoys - 1

mouse = event.Mouse(visible = True, win = my_win)

# Basic parameters for visual objects(stimulu/indication)
imageList = ['Slide1.png', 'Slide2.png', 'Slide3.png', 'Slide4.png', 'Slide5.png']

IndiX = [0, -231, -231+270, -231+540]
IndiY = [115, 115-46, 115-92, 115-138, -115]

# Timer setting
MAX_DURATION = 5
experiment_timer = core.Clock()

# Reset everything with initial
experiment_timer.reset()
Esempio n. 7
0
my_win = visual.Window(size=(2560, 1440),
                       pos=(0, 0),
                       color=base03,
                       colorSpace='rgb255',
                       monitor=mon,
                       units='pix',
                       screen=0,
                       fullscr=1)

# Preparing Joystick & Mouse ----
# - Joysticks setting
joystick.backend = 'pyglet'
nJoys = joystick.getNumJoysticks()  # Check if I have any joysticks
id = 0  # I'll use the first one as input
joy = joystick.Joystick(id)  # ID has to be nJoys - 1
# - Mouse setting
mouse = event.Mouse(visible=True, win=my_win)
mouse.clickReset()  # Reset to its initials

# Preparing pics ----
img_start = 'ACC_ImgFolder/Practice_Start.png'
img_rest = 'ACC_ImgFolder/Practice_Rest.png'
img_ty = 'ACC_ImgFolder/Practice_End.png'

img_ins1 = 'ACC_ImgFolder/Practice_Ins1.png'
img_ins2 = 'ACC_ImgFolder/Practice_Ins2.png'

practice_ins = [img_ins1, img_ins2]

instruction_dict = {
Esempio n. 8
0
endExpNow = False
frameTolerance = 0.001
#joystick.backend='pyglet'
win = visual.Window(size=(1024, 768), fullscr=True, screen=0, winType='pyglet', allowGUI=True, allowStencil=False,
    monitor='testMonitor', color=[0,0,0], colorSpace='rgb',blendMode='avg', useFBO=True, units='height')
win.winHandle.push_handlers(keyState)
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0
nJoys = joystick.getNumJoysticks()
print("nJOys = ", nJoys)
id = 0
joy = joystick.Joystick(id)
nAxes = joy.getNumAxes()

defaultKeyboard = keyboard.Keyboard()

# Initialize variables
Instructions1Clock = core.Clock()
ITIClock = core.Clock()
BackgroundInfoClock = core.Clock()
ISIClock = core.Clock()
RoleCueClock = core.Clock()
VideoClock = core.Clock()
Q1Clock = core.Clock()
EndScreenClock = core.Clock()
routineTimerList = []
routineTimerListRed = []
Esempio n. 9
0
def setup_joystick():
    return joystick.Joystick(0)
Esempio n. 10
0
def run_try():
    #def run_try(SID, raID, scan, resk, run_num='1'):

    #setup the joystick
    joystick.backend = 'pyglet'
    schedules = [
        f for f in os.listdir(os.path.dirname(__file__))
        if f.endswith('.schedule')
    ]
    if not g.session_params['auto_advance']:
        myDlg = gui.Dlg(title="DR")
        myDlg.addField('Run Number',
                       choices=schedules,
                       initial=str(g.run_params['run']))
        myDlg.show()  # show dialog and wait for OK or Cancel
        if myDlg.OK:  # then the user pressed OK
            thisInfo = myDlg.data
        else:
            print 'QUIT!'
            return -1  #the user hit cancel so exit
        g.run_params['run'] = thisInfo[0]
    StimToolLib.general_setup(g)
    nJoysticks = joystick.getNumJoysticks()
    if nJoysticks > 0:
        g.joy = joystick.Joystick(0)
    else:
        g.win.close()
        #try:
        StimToolLib.error_popup("You don't have a joystick connected?")
        #except StimToolLib.QuitException:
        #    return -1

    #g.resk = resk

    g.timer_msg = visual.TextStim(g.win,
                                  text="",
                                  units='pix',
                                  pos=[0, -50],
                                  color=[1, 1, 1],
                                  height=30,
                                  wrapWidth=int(1600))
    schedule_file = os.path.join(os.path.dirname(__file__),
                                 g.run_params['run'])
    #param_file = os.path.join(os.path.dirname(__file__),'T1000_DR_Schedule' + str(g.run_params['run']) + '.csv')
    block_types, junk, block_lengths, junk = StimToolLib.read_trial_structure(
        schedule_file, g.win, g.msg)
    block_lengths = block_lengths[0]

    start_time = data.getDateStr()

    param_file = g.run_params['run'][
        0:
        -9] + '.params'  #every .schedule file can (probably should) have a .params file associated with it to specify running parameters (including part of the output filename)
    StimToolLib.get_var_dict_from_file(
        os.path.join(os.path.dirname(__file__), param_file), g.run_params)
    g.prefix = StimToolLib.generate_prefix(g)
    fileName = os.path.join(g.prefix + '.csv')

    #g.prefix = 'DR-' + g.session_params['SID'] + '-Admin_' + g.session_params['raID'] + '-run_' + str(g.run_params['run']) + '-' + start_time
    #fileName = os.path.join(os.path.dirname(__file__), 'data/' + g.prefix +  '.csv')
    g.output = open(fileName, 'w')

    sorted_events = sorted(event_types.iteritems(), key=operator.itemgetter(1))
    g.output.write('Administrator:,' + g.session_params['admin_id'] +
                   ',Original File Name:,' + fileName + ',Time:,' +
                   start_time + ',Parameter File:,' + schedule_file +
                   ',Event Codes:,' + str(sorted_events) + '\n')
    g.output.write(
        'trial_number,trial_type,event_code,absolute_time,response_time,response,result\n'
    )

    g.car = visual.ImageStim(g.win,
                             os.path.join(os.path.dirname(__file__),
                                          'media/car2.bmp'),
                             units='cm',
                             interpolate=True,
                             mask=os.path.join(os.path.dirname(__file__),
                                               'media/car_mask.bmp'))
    g.bar_green = visual.ImageStim(g.win,
                                   os.path.join(os.path.dirname(__file__),
                                                'media/bar_green.png'),
                                   pos=(g.bar_x, 0),
                                   units='pix')
    g.bar_blue = visual.ImageStim(g.win,
                                  os.path.join(os.path.dirname(__file__),
                                               'media/bar_blue.png'),
                                  pos=(g.bar_x, 0),
                                  units='pix')
    g.stop_sign = visual.ImageStim(g.win,
                                   os.path.join(os.path.dirname(__file__),
                                                'media/stop.png'),
                                   pos=(0, g.stop_y),
                                   units='cm',
                                   interpolate=True)
    g.target = visual.ImageStim(g.win,
                                os.path.join(os.path.dirname(__file__),
                                             'media/circle_white.png'),
                                pos=[6, 0],
                                units='cm')
    g.sound_correct = sound.Sound(value=os.path.join(os.path.dirname(__file__),
                                                     'media/correctsound.wav'),
                                  volume=0.08)
    g.sound_error = sound.Sound(value=os.path.join(os.path.dirname(__file__),
                                                   'media/errorsound.wav'),
                                volume=0.08)
    g.sound_double_error = sound.Sound(value=os.path.join(
        os.path.dirname(__file__), 'media/doubleerrorsound.wav'),
                                       volume=0.08)
    g.sound_beep1 = sound.Sound(value=os.path.join(os.path.dirname(__file__),
                                                   'media/beep1.wav'),
                                volume=0.08)
    g.sound_beep2 = sound.Sound(value=os.path.join(os.path.dirname(__file__),
                                                   'media/beep2.wav'),
                                volume=0.08)
    g.sound_timeout = sound.Sound(value=os.path.join(os.path.dirname(__file__),
                                                     'media/timeoutsound.wav'),
                                  volume=0.08)

    g.time_text.append(
        visual.TextStim(g.win,
                        text="10s",
                        units='pix',
                        height=25,
                        color=[1, 1, 1],
                        pos=[g.bar_x + 45, 550]))
    g.time_text.append(
        visual.TextStim(g.win,
                        text="0s",
                        units='pix',
                        height=25,
                        color=[1, 1, 1],
                        pos=[g.bar_x + 45, 0]))

    g.fix = visual.TextStim(g.win,
                            text="X",
                            units='pix',
                            height=50,
                            color=[1, 1, 1],
                            pos=[0, 0],
                            bold=True)

    StimToolLib.task_start(StimToolLib.DRIVE_CODE, g)
    g.win.flip()
    g.trial = 0  #initialize trial number
    #StimToolLib.show_title(g.win, g.title)
    for i in range(len(block_types)):
        do_one_block(block_types[i], int(block_lengths[i]))
Esempio n. 11
0
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0  # could not measure, so guess

# Initialize components for Routine "trial"
trialClock = core.Clock()
button_resp = type('', (), {})()  # Create an object to use as a name space
button_resp.device = None
button_resp.device_number = 0

try:
    numJoysticks = joysticklib.getNumJoysticks()
    if numJoysticks > 0:
        button_resp.device = joysticklib.Joystick(0)
        try:
            joystickCache
        except NameError:
            joystickCache = {}
        if not 0 in joystickCache:
            joystickCache[0] = joysticklib.Joystick(0)
        button_resp.device = joystickCache[0]
    else:
        button_resp.device = virtualjoybuttonslib.VirtualJoyButtons(0)
        logging.warning(
            "joystick_{}: Using keyboard emulation 'ctrl' + 'Alt' + digit.".
            format(button_resp.device_number))
except Exception:
    pass
Esempio n. 12
0
        rm = pandas.rolling_mean(df,rw)[rw-1:] #moving average
        ma = rm['samples'][rm.index[-1]] #gets last pupil sample
        return ma
        
    def sample_update(self,s0,s1):  #collect new sample only if more than 1.8000 msec has gone by since old sample
        su = (s1 - s0) > .0018
        return su
    
    def cue_update(self,c0,c1): #create new cue only if more than 2000 msec has gone by since old sample
        cu = (c1 - c0) > 0.2000
        return cu
        
mouse = event.Mouse(win=win)
gamepad_available = False #debug - turn on if task is ready for implimentation
if gamepad_available:
    gamepad = joystick.Joystick(0)

# Initialize components for Routine "Block_Instructions"
Block_InstructionsClock = core.Clock()
Block_image = visual.ImageStim(win=win, name='Block_image',
    image='sin', mask=None,
    ori=0, pos=[0, 0], size=None,
    color=[1,1,1], colorSpace='rgb', opacity=1,
    flipHoriz=False, flipVert=False,
    texRes=128, interpolate=True, depth=-1.0)

# Initialize components for Routine "Fixation"
FixationClock = core.Clock()

fixation_cross = visual.ImageStim(win=win, name='fixation_cross',
    image="Instructions/fixation.png", mask=None,
Esempio n. 13
0
    def __init__(self):
        #
        # Experiment necessities
        #
        joystick.backend = 'pygame'

        #
        # Set up Subject info
        #
        self.subjectID = '999'  #temporary subject number.
        self.run = '1'
        self.expName = 'Grip Force'
        self.expInfoDic = {'participant': '', 'session': '001', 'run': ''}
        self.dlg = gui.DlgFromDict(dictionary=self.expInfoDic,
                                   title=self.expName)
        if self.dlg.OK == False: core.quit()  # user pressed cancel
        self.subjectID = self.expInfoDic['participant']
        self.run = self.expInfoDic['run']
        print self.subjectID
        print self.run
        self.myWin = visual.Window(
            (800.0, 800.0),
            allowGUI=True,
            winType='pygame',
            fullscr=True,
            units='cm',
            monitor='testMonitor')  # This is the experiment window to draw in
        self.nJoysticks = joystick.getNumJoysticks()
        self.joy = joystick.Joystick(0)
        #
        # Experiment variables
        #
        self.eRate = 0.01
        self.earningTIme = 20
        if self.run in ['006', '007', '008']:
            self.curConstant = 21
        else:
            self.curConstant = 26
        self.cur_weight = 35
        self.winDur = 0.15  # time window for grip smoothing
        self.duration = 30
        self.origin = -8
        self.CV = 1
        self.blockWaitDur = 5
        self.blockFixDur = 15  #plus 5 for the phrase
        self.numBlocks = 3  #number of blocks in each run
        self.numTrials = 8  #number of trials (within each block) ####
        self.trialLen = 14
        self.trialWait = 3
        self.path = './data/HV_' + str(self.subjectID) + '.Rew/'
        self.myMouse = event.Mouse(visible=0)
        self.testRuns = ['006', '007', '008']
        #
        self.targSpot = visual.Circle(self.myWin,
                                      pos=(0, 0),
                                      size=(1.5, 1.5),
                                      opacity=1.0,
                                      fillColor='DodgerBlue',
                                      lineColor='DodgerBlue',
                                      lineWidth=0,
                                      autoLog=False)
        #
        self.originSpot = visual.PatchStim(self.myWin,
                                           tex="none",
                                           mask="circle",
                                           pos=(0, self.origin),
                                           size=(2, 2),
                                           color='black',
                                           autoLog=False)
        #
        self.fixationCross = visual.TextStim(win=self.myWin,
                                             text='+',
                                             wrapWidth=10.0,
                                             font='Arial',
                                             pos=[0, 0],
                                             height=2.0,
                                             color='white',
                                             opacity=1,
                                             depth=0.0)
        self.fixationCrossB = visual.TextStim(win=self.myWin,
                                              text='+',
                                              wrapWidth=10.0,
                                              font='Arial',
                                              pos=[0, 0],
                                              height=2.0,
                                              color='black',
                                              opacity=1,
                                              depth=0.0)
        #
        self.block = 0
        self.loadEarning(self.block)

        self.instPhraseL1 = str('Track the blue circle')
        self.instPhraseL2 = str('')
        self.instPhraseL3 = str('Press space')
        self.breakPhraseL1 = str("Nice job, take a breather.")

        self.breakPhraseL3 = str(
            "You will now see a cross.  It will turn black when you are about to start"
        )

        self.InstructionL1 = visual.TextStim(win=self.myWin,
                                             text=self.instPhraseL1,
                                             wrapWidth=10.0,
                                             font='Arial',
                                             pos=[0, 2],
                                             height=1.0,
                                             color=[1.000, 1.000, 1.000],
                                             colorSpace='rgb',
                                             opacity=1,
                                             depth=0.0)

        self.InstructionL2 = visual.TextStim(win=self.myWin,
                                             text=self.instPhraseL2,
                                             wrapWidth=10.0,
                                             font='Arial',
                                             pos=[0, 0],
                                             height=1.0,
                                             color=[1.000, 1.000, 1.000],
                                             colorSpace='rgb',
                                             opacity=1,
                                             depth=0.0)

        self.InstructionL3 = visual.TextStim(win=self.myWin,
                                             text=self.instPhraseL3,
                                             wrapWidth=10.0,
                                             font='Arial',
                                             pos=[0, -2],
                                             height=1.0,
                                             color=[1.000, 1.000, 1.000],
                                             colorSpace='rgb',
                                             opacity=1,
                                             depth=0.0)

        self.breakL1 = visual.TextStim(win=self.myWin,
                                       text=self.breakPhraseL1,
                                       wrapWidth=10.0,
                                       font='Arial',
                                       pos=[0, 2],
                                       height=1.0,
                                       color=[1.000, 1.000, 1.000],
                                       colorSpace='rgb',
                                       opacity=1,
                                       depth=0.0)

        self.breakL3 = visual.TextStim(win=self.myWin,
                                       text=self.breakPhraseL3,
                                       wrapWidth=10.0,
                                       font='Arial',
                                       pos=[0, -2],
                                       height=1.0,
                                       color=[1.000, 1.000, 1.000],
                                       colorSpace='rgb',
                                       opacity=1,
                                       depth=0.0)

        print self.run

        if self.run == '001':
            makedirs(self.path)
            self.genSubjSine()
            self.Amps, self.Pers = self.genRandSine()
            self.bAmps = self.Amps
            self.bPers = self.Pers
            self.saveSine()

        elif self.run in ['003', '004']:
            subjAmps, subjPers = self.readSubjSine()
            seqAmps = [subjAmps for i in range(self.numTrials)]
            seqPers = [subjPers for i in range(self.numTrials)]
            self.bAmps = [seqAmps for i in range(3)]
            self.bPers = [seqPers for i in range(3)]
            self.saveSine()

        else:
            self.bAmps = [0, 0, 0]
            self.bPers = [0, 0, 0]
            self.numblocks = 2
            self.subjAmps, self.subjPers = self.readSubjSine()
            self.Amps, self.Pers = self.genRandSine()
            self.bAmps[0] = self.Amps[0]
            self.bPers[0] = self.Pers[0]
            self.bAmps[1] = [self.subjAmps for i in range(self.numTrials)]
            self.bPers[1] = [self.subjPers for i in range(self.numTrials)]
            self.bAmps[2] = self.Amps[1]
            self.bPers[2] = self.Pers[1]
            self.saveSine()
Esempio n. 14
0
def do_one_slide(slide, isound, directory, g):
    #event.clearEvents()
    image = visual.ImageStim(g.win,
                             image=os.path.join(directory, slide[0]),
                             units='pix')

    # Adust the size so it's always full screen.
    try:
        image.size = [
            g.session_params['screen_x'], g.session_params['screen_y']
        ]
    except:
        pass
    s = isound
    advance_time = float(slide[2])
    #if it's -1, don't advance, if it's 0, advance at the end of the sound, if it's positive, advance after that amount of time
    wait_z = False
    if advance_time == -1:
        advance_time = float('inf')
    elif advance_time == 0:
        try:
            advance_time = s.getDuration()
        except AttributeError:  #in case there is a None in stead of a sound, just set duration to 0.5
            advance_time = 0.5
    elif advance_time == -2:  #wait for a 'z' to advance
        advance_time = float('inf')
        wait_z = True

    image.draw()
    g.win.flip()
    k = None  #initialize k
    if s:
        s.play()
        advance_time = advance_time - s.getDuration(
        )  #since we're waiting for the duration of s, decrease advance_time by that amount--allows for e.g. advance_time of 5s with a sound of 3s->wait 2s after the sound ends
        k = event.waitKeys(
            keyList=['z', 'a', 'escape'], maxWait=s.getDuration()
        )  #force the subject to listen to all of the instructions--allow 'z' to skip them or 'a' to force back
    if not k:  #if skipped instructions, don't wait to advance afterword
        if g.session_params[
                'allow_instructions_back']:  #only allow back if it's specified in the session parameters
            kl = [
                g.session_params['left'], g.session_params['right'], 'escape',
                'z', 'a'
            ]
        else:
            kl = [g.session_params['right'], 'escape', 'z', 'a']
        if wait_z:  #only advance for a 'z'
            kl = ['z', 'a']

        timeout = False
        now = g.clock.getTime()
        try:
            g.joystick = joystick.Joystick(0)

            #wait for button to be released so program doesn't just run through all instructions by holding down a button
            #            while g.joystick.getButton(g.session_params['joy_forward']) or g.joystick.getButton(g.session_params['joy_backward']):
            #                if g.clock.getTime() > now + advance_time:
            #                    timeout=True
            #                    break
            #                image.draw()
            #                event.clearEvents() #do this each frame to avoid getting clogged with joystick and key events
            #                g.win.flip()

            while 1:
                #if not g.session_params['joystick']: break # Break out of this if wer're not using a joystick
                if g.clock.getTime() > now + advance_time:
                    timeout = True
                    break
                k = event.getKeys(keyList=kl)
                if k != []:
                    break
                if g.joystick.getButton(g.session_params['joy_forward']
                                        ) or g.joystick.getButton(
                                            g.session_params['joy_backward']):
                    break
                image.draw()
                event.clearEvents()
                g.win.flip()


#            while not g.joystick.getButton(g.session_params['joy_forward']) and not g.joystick.getButton(g.session_params['joy_backward']):
#                if g.clock.getTime() > now + advance_time:
#                    timeout=True
#                    break
#                k=event.getKeys(keyList = kl)
#                if k!=[]:
#                    break
#                image.draw()
#                event.clearEvents()
#                g.win.flip()
        except (AttributeError, IndexError):
            k = event.waitKeys(keyList=kl, maxWait=advance_time)

    if s:  #stop the sound if it's still playing
        s.stop()

    try:
        if g.joystick.getButton(g.session_params['joy_forward']) or timeout:
            retval = 1
        elif g.joystick.getButton(g.session_params['joy_backward']):
            retval = -1
    except (AttributeError, UnboundLocalError, IndexError):
        joystick_not_used = True

    if k == None or k == []:  #event timeout
        print('')
    elif k[0] == 'z':
        retval = 1
    elif k[0] == 'a':
        retval = -1
    elif k[0] == g.session_params['right']:
        print(k[0])
        retval = 1
    elif k[0] == g.session_params['left']:
        retval = -1
    elif k[0] == 'escape':
        raise QuitException()
    return retval
Esempio n. 15
0
def setup_joystick():
    if joystick.getNumJoysticks() > 0:
        return joystick.Joystick(0)
    else:
        return None
Esempio n. 16
0
    def __init__(self):
        #
        # Experiment necessities
        #
        joystick.backend = 'pygame'

        #
        # Set up Subject info
        #
        self.subjectID = '999'  #temporary subject number.
        self.run = '1'
        self.expName = 'Grip Force'
        self.expInfoDic = {
            "condition": '',
            'SameDiff': '',
            'participant': '',
            'run': ''
        }
        self.dlg = gui.DlgFromDict(dictionary=self.expInfoDic,
                                   title=self.expName)
        if self.dlg.OK == False: core.quit()  # user pressed cancel
        self.subjectID = self.expInfoDic['participant']
        self.run = self.expInfoDic['run']
        self.cond = self.expInfoDic['condition']
        self.congruent = self.expInfoDic['SameDiff']
        print self.subjectID
        print self.run
        self.myWin = visual.Window(
            (800.0, 800.0),
            allowGUI=True,
            winType='pygame',
            fullscr=True,
            units='cm',
            monitor='testMonitor')  # This is the experiment window to draw in
        self.nJoysticks = joystick.getNumJoysticks()
        self.joy = joystick.Joystick(0)
        #
        # Experiment variables
        #
        # Adding in the jitter here for run 1
        self.setWeight = 25
        self.cur_weight = self.setWeight
        self.curConstant = 25
        self.winHeight = 20
        self.eRate = 0.01
        self.earningTIme = 20
        #        if self.run in ['006','007','008']:  ### Necessary for scanner at the NIH.  Need to adjust for the Oxford scanners.
        #            self.curConstant = 21
        #        else:
        #            self.curConstant = 25

        self.winDur = 0.15  # time window for grip smoothing
        self.duration = 30
        self.origin = -8
        self.CV = 1
        self.blockWaitDur = 5
        self.blockFixDur = 15  #plus 5 for the phrase
        self.numBlocks = 3  #number of blocks in each run
        self.numTrials = 8  #number of trials (within each block) ####
        self.trialLen = 14
        self.trialWait = 3
        self.path = './data.Gates/HV_' + str(
            self.subjectID) + '.' + self.cond + '/'
        self.myMouse = event.Mouse(visible=0)
        self.testRuns = ['006', '007', '008']
        self.targetWidth = 1.0
        self.targSize = (self.targetWidth, self.targetWidth)
        #

        self.targSpot1 = visual.Circle(self.myWin,
                                       pos=(0, 0),
                                       size=self.targSize,
                                       opacity=1.0,
                                       fillColor='SkyBlue',
                                       lineColor='SkyBlue',
                                       lineWidth=0,
                                       autoLog=False)

        self.targSpot2 = visual.Circle(self.myWin,
                                       pos=(0, 0),
                                       size=self.targSize,
                                       opacity=1.0,
                                       fillColor='Tomato',
                                       lineColor='Tomato',
                                       lineWidth=0,
                                       autoLog=False)

        self.targSpot3 = visual.Circle(self.myWin,
                                       pos=(0, 0),
                                       size=self.targSize,
                                       opacity=1.0,
                                       fillColor='SpringGreen',
                                       lineColor='SpringGreen',
                                       lineWidth=0,
                                       autoLog=False)

        self.targSpot4 = visual.Circle(self.myWin,
                                       pos=(0, 0),
                                       size=self.targSize,
                                       opacity=1.0,
                                       fillColor='Yellow',
                                       lineColor='Yellow',
                                       lineWidth=0,
                                       autoLog=False)

        self.targSpot5 = visual.Circle(self.myWin,
                                       pos=(0, 0),
                                       size=self.targSize,
                                       opacity=1.0,
                                       fillColor='HotPink',
                                       lineColor='HotPink',
                                       lineWidth=0,
                                       autoLog=False)

        #
        self.originSpot = visual.PatchStim(self.myWin,
                                           tex="none",
                                           mask="circle",
                                           pos=(0, self.origin),
                                           size=(2, 2),
                                           color='black',
                                           autoLog=False)
        #
        self.fixationCross = visual.TextStim(win=self.myWin,
                                             text='+',
                                             wrapWidth=10.0,
                                             font='Arial',
                                             pos=[0, 0],
                                             height=2.0,
                                             color='white',
                                             opacity=1,
                                             depth=0.0)
        self.fixationCrossB = visual.TextStim(win=self.myWin,
                                              text='+',
                                              wrapWidth=10.0,
                                              font='Arial',
                                              pos=[0, 0],
                                              height=2.0,
                                              color='black',
                                              opacity=1,
                                              depth=0.0)
        #
        self.block = 0
        self.loadEarning(self.block)

        self.instPhraseL1 = str('Hit the gates in the right order.')
        self.instPhraseL2 = str('')
        self.instPhraseL3 = str('Press space')
        self.breakPhraseL1 = str("Nice job, take a breather.")
        self.breakPhraseL3 = str(
            "You will now see a cross.  It will turn black when you are about to start"
        )

        self.InstructionL1 = visual.TextStim(win=self.myWin,
                                             text=self.instPhraseL1,
                                             wrapWidth=10.0,
                                             font='Arial',
                                             pos=[0, 2],
                                             height=1.0,
                                             color=[1.000, 1.000, 1.000],
                                             colorSpace='rgb',
                                             opacity=1,
                                             depth=0.0)

        self.InstructionL2 = visual.TextStim(win=self.myWin,
                                             text=self.instPhraseL2,
                                             wrapWidth=10.0,
                                             font='Arial',
                                             pos=[0, 0],
                                             height=1.0,
                                             color=[1.000, 1.000, 1.000],
                                             colorSpace='rgb',
                                             opacity=1,
                                             depth=0.0)

        self.InstructionL3 = visual.TextStim(win=self.myWin,
                                             text=self.instPhraseL3,
                                             wrapWidth=10.0,
                                             font='Arial',
                                             pos=[0, -2],
                                             height=1.0,
                                             color=[1.000, 1.000, 1.000],
                                             colorSpace='rgb',
                                             opacity=1,
                                             depth=0.0)

        self.breakL1 = visual.TextStim(win=self.myWin,
                                       text=self.breakPhraseL1,
                                       wrapWidth=10.0,
                                       font='Arial',
                                       pos=[0, 3],
                                       height=2.0,
                                       color=[1.000, 1.000, 1.000],
                                       colorSpace='rgb',
                                       opacity=1,
                                       depth=0.0)

        self.breakL3 = visual.TextStim(win=self.myWin,
                                       text=self.breakPhraseL3,
                                       wrapWidth=10.0,
                                       font='Arial',
                                       pos=[0, -3],
                                       height=2.0,
                                       color=[1.000, 1.000, 1.000],
                                       colorSpace='rgb',
                                       opacity=1,
                                       depth=0.0)

        print self.run
        self.rnum = int(self.run)

        self.subjGateLocation = [0.15, 0.35, 0.65, 0.7, 0.9]
        self.TargetOrder = [3, 0, 4, 1, 2]

        if self.run == '001':
            while isdir(self.path) == True:
                print(self.path + ' exists! Looking for solution...')
                self.path = self.path[0:-1] + '+/'
            mkdir(self.path)
            self.bGates = [0] * 3
            randLoc = self.genRandomGates()
            self.bGates[0] = randLoc[0]
            self.bGates[2] = randLoc[2]
            self.bGates[1] = [
                self.subjGateLocation for i in range(self.numTrials)
            ]
            self.saveGates(self.bGates)

            with open(self.path + self.subjectID + '.Congruent.txt',
                      'w') as congFile:
                congWriter = csv.writer(congFile)
                congWriter.writerow([self.congruent])


#            self.randGateLocations = self.genRandomGates()
#            self.bGates = self.randGateLocations
#            self.saveGates(self.bGates)
#        elif self.run in ['003','004']:                                            #This bit makes the purly sequence blocks.  This is commented to let us do just R-S-R blocks.
#            self.bGates = [0]*3
#                for i in range(3):
#                    self.bGates[i] = [self.subjGateLocation for i in range(self.numTrials)]
#            self.saveGates()
        elif all([self.congruent == 'Diff', self.run == '003']):
            self.bGates = [0] * 3
            self.bGates[0] = [
                self.subjGateLocation for i in range(self.numTrials)
            ]
            self.bGates[1] = [
                self.subjGateLocation for i in range(self.numTrials)
            ]
            self.bGates[2] = [
                self.subjGateLocation for i in range(self.numTrials)
            ]
            self.saveGates(self.bGates)

        else:
            self.bGates = [0] * 3
            randLoc = self.genRandomGates()
            self.bGates[0] = randLoc[0]
            self.bGates[2] = randLoc[2]
            self.bGates[1] = [
                self.subjGateLocation for i in range(self.numTrials)
            ]
            self.saveGates(self.bGates)
Esempio n. 17
0
joystick = type('', (), {})()  # Create an object to use as a name space
joystick.device = None
joystick.device_number = 0
joystick.joystickClock = core.Clock()
joystick.xFactor = 1
joystick.yFactor = 1

try:
    numJoysticks = joysticklib.getNumJoysticks()
    if numJoysticks > 0:
        try:
            joystickCache
        except NameError:
            joystickCache = {}
        if not 0 in joystickCache:
            joystickCache[0] = joysticklib.Joystick(0)
        joystick.device = joystickCache[0]
        if win.units == 'height':
            joystick.xFactor = 0.5 * win.size[0] / win.size[1]
            joystick.yFactor = 0.5
    else:
        joystick.device = virtualjoysticklib.VirtualJoystick(0)
        logging.warning(
            "joystick_{}: Using keyboard+mouse emulation 'ctrl' + 'Alt' + digit."
            .format(joystick.device_number))
except Exception:
    pass

if not joystick.device:
    logging.error('No joystick/gamepad device found.')
    core.quit()
    def __init__(self):
        #
        # Experiment necessities
        #
        joystick.backend = 'pygame'
        
        
        #
        # Set up Subject info
        #
        self.subjectID = '999' #temporary subject number.
        self.run = '1'
        self.expName = 'Grip Force'
        self.expInfoDic = {'SameDiff':'','condition':'','participant':'','run':''}
        self.dlg = gui.DlgFromDict(dictionary=self.expInfoDic, title=self.expName)
        if self.dlg.OK == False: core.quit()  # user pressed cancel
        self.subjectID = self.expInfoDic['participant']
        self.run = self.expInfoDic['run']
        self.cond = self.expInfoDic['condition']
        self.congruent = self.expInfoDic['SameDiff']
        print self.subjectID
        print self.run
        print self.cond
        print self.congruent
        self.myWin = visual.Window((800.0,800.0),allowGUI=True,winType='pygame',fullscr=True,units='cm',monitor='testMonitor') # This is the experiment window to draw in
        self.nJoysticks = joystick.getNumJoysticks()
        self.joy = joystick.Joystick(0)
        #
        # Experiment variables
        #
        # Adding in the jitter here for run 1
        self.setWeight = 25
        self.cur_weight = self.setWeight
        self.curConstant = 25
        
        self.eRate = 0.005
        self.earningTIme = 20
#        if self.run in ['006','007','008']:  ### Necessary for scanner at the NIH.  Need to adjust for the Oxford scanners.
#            self.curConstant = 21
#        else:
#            self.curConstant = 25
        

        
        self.winDur = 0.15 # time window for grip smoothing
        self.duration = 30
        self.origin = -8
        self.CV = 1
        self.blockWaitDur = 5
        self.blockFixDur = 15 #plus 5 for the phrase
        self.numBlocks = 3 #number of blocks in each run
        self.numTrials = 8              #number of trials (within each block) ####
        self.trialLen = 14 
        self.trialWait = 3
        self.path = './data.Stable/HV_'+str(self.subjectID)+'.'+str(self.cond)+'/'
        self.myMouse = event.Mouse(visible=0)
        self.testRuns = ['006','007','008']
        #
        self.targSpot = visual.Circle(self.myWin,
        pos=(0,0), size=(1.5,1.5),opacity=1.0,fillColor='DodgerBlue',lineColor='DodgerBlue',lineWidth=0,autoLog=False)
        #
        self.originSpot = visual.PatchStim(self.myWin,tex="none", mask="circle",
        pos=(0,self.origin), size=(2,2),color='black', autoLog=False)
        #
        self.fixationCross = visual.TextStim(win=self.myWin, text='+', wrapWidth=10.0, font='Arial',
        pos=[0, 0], height=2.0, color='white',opacity=1, depth=0.0)
        self.fixationCrossB = visual.TextStim(win=self.myWin, text='+', wrapWidth=10.0, font='Arial',
        pos=[0, 0], height=2.0, color='black', opacity=1, depth=0.0)
        #
        self.block = 0
        self.loadEarning(self.block)
            
        self.instPhraseL1= str('Track the blue circle')
        self.instPhraseL2= str('')
        self.instPhraseL3= str('Press space')
        self.breakPhraseL1 = str("Nice job, take a breather.")
        self.breakPhraseL3 = str("You will now see a cross.  It will turn black when you are about to start")        
            
        self.InstructionL1 = visual.TextStim(win=self.myWin, text=self.instPhraseL1, wrapWidth=10.0, font='Arial',
        pos=[0, 2], height=1.0, color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1, depth=0.0)
        
        self.InstructionL2 = visual.TextStim(win=self.myWin, text=self.instPhraseL2, wrapWidth=10.0, font='Arial',
        pos=[0, 0], height=1.0, color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1, depth=0.0)
        
        self.InstructionL3 = visual.TextStim(win=self.myWin, text=self.instPhraseL3, wrapWidth=10.0, font='Arial',
        pos=[0, -2], height=1.0, color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1, depth=0.0)
            
        self.breakL1 = visual.TextStim(win=self.myWin, text=self.breakPhraseL1, wrapWidth=10.0, font='Arial',
        pos=[0, 2], height=1.0, color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1, depth=0.0)
        
        self.breakL3 = visual.TextStim(win=self.myWin, text=self.breakPhraseL3, wrapWidth=10.0, font='Arial',
        pos=[0, -2], height=1.0, color=[1.000,1.000,1.000], colorSpace='rgb', opacity=1, depth=0.0)
        
        

            
        print self.run
        self.FBprops = [[0.45,0.45,0.46],[0.46,0.46,0.47],[0.49,0.50,0.50],[0.50,0.51,0.52],[0.53,0.54,0.55],[0.53,0.54,0.55],[0.53,0.54,0.55],[0.53,0.54,0.55]]
        self.rnum = int(self.run)
        #self.contFB = self.FBprops[self.rnum-1]
        
        if self.run == '001':
            while isdir(self.path) == True:
               print(self.path + ' exists! Looking for solution...')
               self.path=self.path+'+'
            mkdir(self.path)
            self.genSubjSine()
            self.Amps,self.Pers = self.genRandSine()
            self.bAmps = self.Amps
            self.bPers = self.Pers
            self.saveSine()
            with open(self.path+self.subjectID+'.Congruent.txt','w') as congFile:
                congWriter = csv.writer(congFile)
                congWriter.writerow([self.congruent])
        
        elif self.run == '003' or all([self.congruent == 'Same',self.run == '007']):                                            #This bit makes the purly sequence blocks.  This is commented to let us do just R-S-R blocks.
            subjAmps,subjPers = self.readSubjSine()
            seqAmps = [subjAmps for i in range(self.numTrials)]
            seqPers = [subjPers for i in range(self.numTrials)]        
            self.bAmps = [seqAmps for i in range(3)]
            self.bPers = [seqPers for i in range(3)]
            self.saveSine()
            
            
        else:
            self.bAmps = [0,0,0]
            self.bPers = [0,0,0]
            self.numblocks = 2
            self.subjAmps,self.subjPers = self.readSubjSine()
            self.Amps,self.Pers = self.genRandSine()
            self.bAmps[0] = self.Amps[0]
            self.bPers[0] = self.Pers[0]
            self.bAmps[1] = [self.subjAmps for i in range(self.numTrials)]
            self.bPers[1] = [self.subjPers for i in range(self.numTrials)]
            self.bAmps[2] = self.Amps[1]
            self.bPers[2] = self.Pers[1]
            self.saveSine()