allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "setup"
setupClock = core.Clock()
taskVer = int(expInfo['taskVer'])
if taskVer == 1:
    order = [0, 1, 2]

# Initialize components for Routine "instr"
instrClock = core.Clock()
instrText = visual.TextStim(
    win=win,
    name='instrText',
    text="'Space' for blue, nothing for orange. 'S' to start.",
    font='Arial',
    pos=(0, 0),
Example #2
0
# -------Start Routine "trial"-------
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = trialClock.getTime()
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame
    # start/stop sound_1
    if t >= 0.0 and sound_1.status == NOT_STARTED:
        # keep track of start time/frame for later
        sound_1.tStart = t  # not accounting for scr refresh
        sound_1.frameNStart = frameN  # exact frame index
        win.timeOnFlip(sound_1, 'tStartRefresh')  # time at next scr refresh
        win.callOnFlip(sound_1.play)  # screen flip

    # check for quit (typically the Esc key)
    if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
        core.quit()

    # check if all components have finished
    if not continueRoutine:  # a component has requested a forced-end of Routine
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in trialComponents:
        if hasattr(thisComponent,
                   "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished

    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()
Example #3
0
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "instructions"
instructionsClock = core.Clock()
text = visual.TextStim(win=win,
                       name='text',
                       text='Hello, welcome!\nasdf',
                       font='Arial',
                       pos=(0, 0),
                       height=0.1,
                       wrapWidth=None,
                       ori=0,
                       color='white',
                       colorSpace='rgb',
                       opacity=1,
                       languageStyle='LTR',
Example #4
0
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "demo"
demoClock = core.Clock()
Instructions = visual.TextStim(
    win=win,
    name='Instructions',
    text=
    'This is a demo to pracitce counterbalancing. \n\nImagine our researcher wants to present one block of cat images and one block of dog images. \n\nThey have made a classic error in counterbalancing... \n\nLook at the structure of the flow, the way the routines are set is not very flexible. \n\nHave a run through and then work through the exercises.\n\nPress space to start',
    font='Arial',
    pos=(0, 0),
    height=0.02,
    wrapWidth=None,
    ori=0,
    color='black',
    colorSpace='rgb',
Example #5
0
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "trial"
trialClock = core.Clock()
polygon = visual.ShapeStim(win=win,
                           name='polygon',
                           vertices='star7',
                           size=(0.01, 0.01),
                           ori=0,
                           pos=(0, 0),
                           lineWidth=0.01,
                           lineColor='black',
                           lineColorSpace='rgb',
                           fillColor='black',
                           fillColorSpace='rgb',
                           opacity=1,
Example #6
0
# Setup the Window
win = visual.Window(
    size=[1280, 720], fullscr=True, screen=0, 
    winType='pyglet', allowGUI=False, allowStencil=False,
    monitor='testMonitor', color=[-1.000,-1.000,-1.000], colorSpace='rgb',
    blendMode='avg', useFBO=True, 
    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "look_at_me"
look_at_meClock = core.Clock()
fixation = visual.TextStim(win=win, name='fixation',
    text='+',
    font='Arial',
    pos=(0, 0), height=0.2, wrapWidth=None, ori=0, 
    color='black', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=0.0);
press_to_go = keyboard.Keyboard()

# Initialize components for Routine "trial"
trialClock = core.Clock()
targets = visual.ImageStim(
Example #7
0
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING)

endExpNow = False
frameTolerance = 0.001


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')
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0

defaultKeyboard = keyboard.Keyboard()

introClock = core.Clock()
Instructions = visual.TextStim(win=win, name='Instructions',
    text='In this part of the study you will be given a regulation strategy to use while viewing various pictures.\n\nThen you will use a rating scale to categorize your emotions.\n\nYou will first be completing a few practice rounds.\n\nWhen you are ready, press space to start!',
    font='Arial',pos=(0, 0), height=0.07, wrapWidth=1.5, color='white');
space = keyboard.Keyboard()

isiClock = core.Clock()
Iti = visual.TextStim(win=win, text='default',font='Arial', pos=(0, 0), height=0.1, color='white');

BeginInstrClock = core.Clock()
text = visual.TextStim(win=win, text='You will now complete the full task. \n\nPress space to begin!', font='Arial', pos=(0, 0), height=0.08, wrapWidth=1.5,color='white');

CueClock = core.Clock()
cue = visual.TextStim(win=win, text='default', font='Arial', pos=(0, 0), height=0.1, color='white');
Example #8
0
instructionstext = visual.TextStim(
    win=win,
    name='instructionstext',
    text=
    'Choose the color of letters ignoring the word\n\nleft = red\nright = blue\ndown = green\n',
    font='Arial',
    pos=(0, 0),
    height=0.1,
    wrapWidth=None,
    ori=0,
    color='white',
    colorSpace='rgb',
    opacity=1,
    languageStyle='LTR',
    depth=0.0)
key_resp = keyboard.Keyboard()

# Initialize components for Routine "task1"
trail1Clock = core.Clock()
target1 = visual.TextStim(win=win,
                          name='target1',
                          text='default text',
                          font='Arial',
                          pos=(0, 0),
                          height=0.1,
                          wrapWidth=None,
                          ori=0,
                          color='white',
                          colorSpace='rgb',
                          opacity=1,
                          languageStyle='LTR',
Example #9
0
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# ========= END WINDOW =========

# ========== BEGIN COMPONENTS ==========

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

instructionsClock = core.Clock()
instructions_text = visual.TextStim(win=win,
                                    name='instructions_text',
                                    text='Welcome!',
                                    font='Arial',
                                    pos=(0, 0),
                                    height=0.1,
                                    wrapWidth=None,
                                    ori=0,
                                    color='white',
                                    colorSpace='rgb',
                                    opacity=1,
                                    languageStyle='LTR',
                                    depth=0.0)
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "setup"
setupClock = core.Clock()
setupText = visual.TextStim(win=win,
                            name='setupText',
                            text='Move mouse.Space continue',
                            font='Arial',
                            pos=(0, 0),
                            height=0.05,
                            wrapWidth=None,
                            ori=0,
                            color='white',
                            colorSpace='rgb',
                            opacity=1,
                            languageStyle='LTR',
def PainCatastrophizingScale(outputPath, subjectNum, questPath):

    questformPath = '/Users/loued/Documents/PythonScripts/Experiment1_Scripts/QuestionnaireForms_PsychoPy/'
    os.chdir(questformPath)

    #Timing
    clock = core.Clock()
    #Keyboard
    kb = keyboard.Keyboard()
    kb.clock.reset()

    #Screen
    mywin = visual.Window([900, 900], [0, 0],
                          monitor="testMonitor",
                          units="height",
                          allowStencil=True)

    x = pd.read_csv('PainCatastrophizingScale.csv')
    y = [x.T.to_dict()]

    #survey = Form.Form(mywin, items=y, size=(1.0, 0.7), pos=(0.0, 0.0))
    Instructions = visual.TextStim(
        win=mywin,
        text=
        ("Chacun d'entre nous aura Ć  subir des expĆ©riences douloureuses.\nCela peut ĆŖtre la douleur associĆ©e aux maux de tĆŖte, Ć  un mal de dent, ou encore la douleur musculaire.\nDans le prĆ©sent questionnaire, nous vous demandons de dĆ©crire le genre de pensĆ©es et d'Ć©motions que vous avez quand vous avez de la douleur.\nVous trouverez ci-dessous treize Ć©noncĆ©s dĆ©crivant diffĆ©rent pensĆ©es et Ć©motions qui peuvent ĆŖtre associĆ©es Ć  la douleur.\n Veuillez indiquer Ć  quel point vous avez ces pensĆ©es et Ć©motions, selon l'Ć©chelle ci-dessous."
         ),
        font='',
        height=0.04,
        pos=(0, 0.85),
        units='norm',
        wrapWidth=2)

    survey = Form.Form(mywin,
                       items='PainCatastrophizingScale.csv',
                       size=(1.0, 0.7),
                       pos=(0.0, 0.0),
                       autoLog=True)

    while not survey.formComplete():
        Instructions.draw()
        survey.draw()
        mywin.flip()
        #    key = event.waitKeys()
        mouse = event.Mouse()
        #    keys = event.getKeys()
        buttons = mouse.getPressed()
        buttons, times = mouse.getPressed(getTime=True)
    #for i in range(1,30):
    #    keys = event.waitKeys()
    #    Resp[i] = str(keys[0])
    #    print(keys)
    #
    #for i in range(1,30):
    #    rate = survey.getData()
    #    Resp[i] = str(keys[0])
    #    print(keys)

    x = survey.getData()

    Questions = pd.DataFrame(list(x.get('questions')))
    Questions = Questions.rename(columns={0: 'Questions'})

    Answers = pd.DataFrame(list(x.get('ratings')))
    Answers = Answers.rename(columns={0: 'Answers'})
    Answers = Answers.astype('int32')

    Questions = pd.concat([Questions, Answers], axis=1)

    Questions = Questions.append(
        {
            'Questions': 'Total',
            'Answers': Questions.Answers.sum()
        },
        ignore_index=True)

    os.chdir(questPath)
    Questions.to_csv(subjectNum + 'PCS_Scale_Response.csv')
    mywin.close()
        counter = i

        core.wait(dur / 1000)
        oddBallStim1.setAutoDraw(False)
        myWin.flip()

    # oddBallStim1.setRadius(oddBallMinRadius)

    if type[ix] == 0:
        judgment = oddBallStim1
    elif type[ix] == 1:
        judgment = oddBallStim2
    else:
        judgment = oddBallStim3

    kb = keyboard.Keyboard()

    # during your trial
    kb.clock.reset()  # when you want to start the timer from
    kb.start()
    waiting = True
    display_message(
        myWin, display_text,
        "Press and hold [SPACE] to report the duration of the stimulus")
    judgment.setAutoDraw(True)
    myWin.flip()
    oddBallClock.reset()
    counter = i
    kb = keyboard.Keyboard(clock=oddBallClock)

    waiting = True
Example #13
0
def test6_pyglet(bit):
    """
    Abandoned!!! Not dynamic yet!!!
    Same test as test6, but using pyglet directly instead of Psychopy
    """
    import pyglet
    from pyglet.gl import gl
    from psychopy.hardware import keyboard
    import time

    kb = keyboard.Keyboard()

    # colors
    def changegun(c, d):
        new = c.astype(float)
        new[0] = new[0] + d  # R
        new[1] = new[1] - d  # G
        new[2] = new[2] - d  # B
        return new

    Crgb = ColorPicker().Crgb
    color = Crgb.astype(int)

    newcolor1 = changegun(color, 1)
    newcolor2 = changegun(color, -1)

    color1_1 = [color, color, color, newcolor1, newcolor1,
                newcolor1]  # upper in condition 1
    color1_2 = [color, color, color, newcolor2, newcolor2,
                newcolor2]  # upper in condition 2

    color2_1 = [
        changegun(color, 0.),
        changegun(color, 0.2),
        changegun(color, 0.4),
        changegun(color, 0.6),
        changegun(color, 0.8),
        changegun(color, 1.0)
    ]

    color2_2 = [
        changegun(color, 0.),
        changegun(color, -0.2),
        changegun(color, -0.4),
        changegun(color, -0.6),
        changegun(color, -0.8),
        changegun(color, -1.0)
    ]

    # convert to [0, 1]

    Crgb = Crgb / (2**8 - 1)

    rgb1_1 = [x / (2**8 - 1) for x in color1_1]  # upper in condition 1
    rgb1_2 = [x / (2**8 - 1) for x in color1_2]  # upper in condition 2

    rgb2_1 = [x / (2**8 - 1) for x in color2_1]
    rgb2_2 = [x / (2**8 - 1) for x in color2_2]

    background = (Crgb[0], Crgb[1], Crgb[2], 1)  # RGB and alpha value

    # set up context and window
    # platform = pyglet.window.get_platform()
    # display = platform.get_default_display()
    # screen = display.get_default_screen()

    # template = pyglet.gl.Config(red_size=bit, green_size=bit, blue_size=bit)
    # config = screen.get_best_config(template)
    # context = config.create_context(None)

    # config = pyglet.gl.Config(red_size=bit, green_size=bit, blue_size=bit)
    config = pyglet.gl.Config(buffer_size=bit * 3)

    winsize = 1900
    window = pyglet.window.Window(caption='OpenGL',
                                  resizable=True,
                                  config=config,
                                  fullscreen=True)

    frameN = 0
    while True:
        if frameN % 2:
            rgb1 = rgb1_1
            rgb2 = rgb2_1
            color1 = color1_1
            color2 = color2_1
        else:
            rgb1 = rgb1_2
            rgb2 = rgb2_2
            color1 = color1_2
            color2 = color2_2

        @window.event
        def on_draw():
            # clears the background with the background color
            gl.glClearColor(*background)
            gl.glClear(gl.GL_COLOR_BUFFER_BIT)

            # draw in a loop
            boundary = winsize - 100
            gap = (winsize - boundary) / 2
            i_width = boundary / len(rgb1)
            i_height = boundary / 2

            # the first line
            for idx, rgb in enumerate(rgb1):
                gl.glColor3f(*rgb)

                gl.glBegin(
                    gl.GL_QUADS
                )  # start drawing a rectangle in counter-clockwise (CCW) order

                gl.glVertex2f(gap + idx * i_width,
                              gap + i_height)  # bottom left point
                gl.glVertex2f(gap + (idx + 1) * i_width,
                              gap + i_height)  # bottom right point
                gl.glVertex2f(gap + (idx + 1) * i_width,
                              gap + boundary)  # top right point
                gl.glVertex2f(gap + idx * i_width,
                              gap + boundary)  # top left point

                gl.glEnd()

                label = pyglet.text.Label(str(color1[idx]),
                                          font_size=7,
                                          x=gap + idx * i_width,
                                          y=gap + boundary + 20)
                label.draw()

            # # # the second line
            for idx, rgb in enumerate(rgb2):
                gl.glColor3f(*rgb)

                gl.glBegin(
                    gl.GL_QUADS
                )  # start drawing a rectangle in counter-clockwise (CCW) order

                gl.glVertex2f(gap + idx * i_width, gap)  # bottom left point
                gl.glVertex2f(gap + (idx + 1) * i_width,
                              gap)  # bottom right point
                gl.glVertex2f(gap + (idx + 1) * i_width,
                              gap + i_height)  # top right point
                gl.glVertex2f(gap + idx * i_width,
                              gap + i_height)  # top left point
                gl.glEnd()

                label = pyglet.text.Label(str(color2[idx]),
                                          font_size=7,
                                          x=gap + idx * i_width,
                                          y=gap - 20)
                label.draw()

        frameN += 1
        pyglet.app.run()

        kb.clock.reset()
        if kb.getKeys():  # press any key to quit
            core.quit()
        else:
            time.sleep(1)  # change every 1 sec
Example #14
0
def test6(bit, diff=1):
    """
    Dynamic version of test5.

    :param bit: 8 or 10
    :param diff: difference in RGB255 scale
    :return:
    """
    from psychopy.hardware import keyboard
    import time
    # mon = monitors.Monitor(name='VIEWPixx LITE', width=38, distance=57)
    #

    color = ColorPicker().Crgb
    color = color.astype(int)

    def changegun(c, d):
        new = c.astype(float)
        new[0] = new[0] + d  # R
        new[1] = new[1] - d  # G
        new[2] = new[2] - d  # B
        return new

    newcolor1 = changegun(color, diff)
    newcolor2 = changegun(color, -diff)

    color1_1 = [color, color, color, newcolor1, newcolor1,
                newcolor1]  # upper in condition 1
    color1_2 = [color, color, color, newcolor2, newcolor2,
                newcolor2]  # upper in condition 2

    color2_1 = [
        changegun(color, 0.),
        changegun(color, 0.2),
        changegun(color, 0.4),
        changegun(color, 0.6),
        changegun(color, 0.8),
        changegun(color, 1.0)
    ]

    color2_2 = [
        changegun(color, 0.),
        changegun(color, -0.2),
        changegun(color, -0.4),
        changegun(color, -0.6),
        changegun(color, -0.8),
        changegun(color, -1.0)
    ]

    # convert to [-1, 1]
    Crgb = ColorPicker().Crgb / (2**8 - 1) * 2 - 1

    rgb1_1 = [x / (2**8 - 1) * 2 - 1 for x in color1_1]  # upper in condition 1
    rgb1_2 = [x / (2**8 - 1) * 2 - 1 for x in color1_2]  # upper in condition 2

    rgb2_1 = [x / (2**8 - 1) * 2 - 1 for x in color2_1]
    rgb2_2 = [x / (2**8 - 1) * 2 - 1 for x in color2_2]

    win = visual.Window(fullscr=True,
                        color=Crgb,
                        colorSpace='rgb',
                        bpc=(bit, bit, bit),
                        depthBits=bit,
                        units='norm')
    kb = keyboard.Keyboard()

    boundary = 0.8
    num = len(color1_1)

    colorbar1 = visual.ElementArrayStim(win,
                                        units='norm',
                                        nElements=num,
                                        elementMask=None,
                                        elementTex=None,
                                        sizes=(boundary * 2 / num,
                                               boundary / 2),
                                        colorSpace='rgb')
    colorbar2 = visual.ElementArrayStim(win,
                                        units='norm',
                                        nElements=num,
                                        elementMask=None,
                                        elementTex=None,
                                        sizes=(boundary * 2 / num,
                                               boundary / 2),
                                        colorSpace='rgb')

    colorbar1.xys = [
        (x, boundary / 4)
        for x in np.linspace(-boundary, boundary, num, endpoint=False) +
        boundary / num
    ]
    colorbar2.xys = [
        (x, -boundary / 4)
        for x in np.linspace(-boundary, boundary, num, endpoint=False) +
        boundary / num
    ]

    frameN = 0
    while True:
        if frameN % 2:
            rgb1 = rgb1_1
            rgb2 = rgb2_1
            color1 = color1_1
            color2 = color2_1
        else:
            rgb1 = rgb1_2
            rgb2 = rgb2_2
            color1 = color1_2
            color2 = color2_2

        colorbar1.colors = rgb1
        colorbar2.colors = rgb2

        colorbar1.draw()
        colorbar2.draw()

        for idx, x in enumerate(
                np.linspace(-boundary, boundary, num, endpoint=False) +
                boundary / num):
            text1 = visual.TextStim(
                win, text=str(color1[idx]), pos=(x, 0.7),
                height=0.028)  # position set in weird way but works
            text2 = visual.TextStim(win,
                                    text=str(color2[idx]),
                                    pos=(x, -0.7),
                                    height=0.028)
            text1.draw()
            text2.draw()

        win.flip()
        frameN += 1

        kb.clock.reset()
        if kb.getKeys():  # press any key to quit
            core.quit()
        else:
            time.sleep(1)  # change every 1 sec
Example #15
0
frameTolerance = 0.001  # how close to onset before 'same' frame

# Setup the Window
win = visual.Window(size=(1024, 768),
                    fullscr=False,
                    color='black',
                    units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] is not None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0  # could not measure, so guess

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for MentalRotation test
MentalRotation_clock = core.Clock()
MentalRotation_circle = visual.Circle(win=win,
                                      name='MentalRotation_circle',
                                      size=0.03,
                                      radius=0.2,
                                      pos=(0.0, 0.0),
                                      lineColor='#ffffff',
                                      fillColor='#ffffff')
MentalRotation_circle.model_name = None
MentalRotation_circle.cname = 'MentalRotation_circle'

MentalRotation_image = visual.ImageStim(win=win,
                                        name='MentalRotation_image',
Example #16
0
        counter = i

        core.wait(dur / 1000)
        oddBallStim1.setAutoDraw(False)
        myWin.flip()

    # oddBallStim1.setRadius(oddBallMinRadius)

    if type[ix] == 0:
        judgment = oddBallStim1
    elif type[ix] == 1:
        judgment = oddBallStim2
    else:
        judgment = oddBallStim3

    kb = keyboard.Keyboard()

    # during your trial
    kb.clock.reset()  # when you want to start the timer from
    kb.start()
    waiting = True
    display_message(
        myWin, display_text,
        "Press and hold [SPACE] to report the duration of the stimulus")
    myWin.flip()
    oddBallClock.reset()
    counter = i
    kb = keyboard.Keyboard(bufferSize=2)
    kb.clock.reset()

    waiting = True
Example #17
0
# Setup the Window
win = visual.Window(size=(1024, 768),
                    fullscr=True,
                    screen=0,
                    winType='pyglet',
                    allowGUI=False,
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[1, 1, 1],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "Wait"
WaitClock = core.Clock()
wait_text = visual.TextStim(win=win,
                            name='wait_text',
                            text='Train..',
                            font='AppleMyungjo',
                            pos=(0, 0),
                            height=0.05,
                            wrapWidth=None,
                            ori=0,
                            color='black',
                            colorSpace='rgb',
                            opacity=1,
                            languageStyle='LTR',
Example #18
0
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "trial"
trialClock = core.Clock()
key_resp = keyboard.Keyboard()
stdline = visual.Line(win=win,
                      name='stdline',
                      units='pix',
                      start=(-(100, 2)[0] / 2.0, 0),
                      end=(+(100, 2)[0] / 2.0, 0),
                      ori=0.0,
                      pos=(-500, 0),
                      lineWidth=1.0,
                      colorSpace='rgb',
                      lineColor='white',
                      fillColor='white',
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "WelcomeScreen"
WelcomeScreenClock = core.Clock()
textWelcome = visual.TextStim(
    win=win,
    name='textWelcome',
    text=
    'Welcome to Our Experinment\n\nPlease have a seat and go over the instructions with the reseracher\n',
    font='Arial',
    pos=(0, 0),
    height=0.1,
    wrapWidth=None,
    ori=0,
    color='white',
    colorSpace='rgb',
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "instruction1"
instruction1Clock = core.Clock()
instr1 = visual.TextStim(
    win=win,
    name='instr1',
    text='In this experiment blah blah\nSpace to continue',
    font='Arial',
    pos=(0, 0),
    height=0.05,
    wrapWidth=None,
    ori=0,
    color='white',
    colorSpace='rgb',
    opacity=1,
Example #21
0
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "instruction"
instructionClock = core.Clock()
instr_text = visual.TextStim(win=win,
                             name='instr_text',
                             text='Any text\n\nincluding line breaks',
                             font='Arial',
                             pos=(0, 0),
                             height=0.1,
                             wrapWidth=None,
                             ori=0,
                             color='white',
                             colorSpace='rgb',
                             opacity=1,
                             languageStyle='LTR',
Example #22
0
    filename = OUTPATH + u'%s_%s_%s' % (expInfo['Participant'], date, expName) + '.csv'
    if not os.path.isfile(filename):
        csvOutput(["Direction","Letter Height (degrees)","Eccentricity (degrees)"]) 

#WINDOW CREATION
mon = monitors.Monitor('TV')
mon.setWidth(200)
win = visual.Window(
    size=(3840, 2160), fullscr=False, screen=-1, 
    winType='pyglet', allowGUI=True, allowStencil=False,
    monitor= mon, color='grey', colorSpace='rgb',
    blendMode='avg', useFBO=True, 
    units='cm')

#CREATE DEFAULT KEYBOARD
defaultKeyboard = keyboard.Keyboard()
keyPress = keyboard.Keyboard()

#EXPERIMENTAL VARIABLES
letters = list("EPB")
anglesH = [0, 5, 10, 15, 20, 25, 30, 35, 40]
anglesV = [5, 10, 15, 20, 25, 30]
directionsG = [0, 2]
directionsNG = [0, 1, 2, 3]
distToScreen = 50 #cm

if glasses:
    directions = directionsG
    dirCap = 2
else:
    directions = directionsNG
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

    # create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initializing components for "instructions"
instructsClock = core.Clock()
instructText = visual.TextStim(
    win=win,
    name='instructText',
    text=
    'Welcome to the experiment.\nA red colored target will appear on the left or the right side of the screen brfore you, followed by a cue. \n\nPress the "left" key when the target appears to the left of the screen, and the "right" key when the target appears to the right. Try to do this as fast as possible. \nPress any key to start the experiment.',
    font='Arial',
    units='height',
    pos=(0, 0),
    height=0.05,
    wrapWidth=None,
    ori=0,
    color='white',
Example #24
0
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "setup"
setupClock = core.Clock()
setupText = visual.TextStim(win=win,
                            name='setupText',
                            text='Use Mouse. Space continue',
                            font='Arial',
                            pos=(0, 0),
                            height=0.05,
                            wrapWidth=None,
                            ori=0,
                            color='white',
                            colorSpace='rgb',
                            opacity=1,
                            languageStyle='LTR',
Example #25
0
def runTrial(trialDict, params):
    # inputs:
    #t_direction ... trial direction ('increase' or 'decrease'
    #coherence ... ranging from 0.5 to 1

    # output:
    # return updated trialDict

    # parse inputs
    direction = trialDict['direction']
    coherence = trialDict['coherence']

    if params['options_playOrientOnEachTrial'] == True:

        #play orient sound
        trialDict['orientOn_s'], trialDict['orientOff_s'] = playOrient(
            dur=params['dur_orient'])

    # clear container for keys
    keys_pressed = []

    # initialize keyboard buffer
    kb = keyboard.Keyboard(device=-1, waitForStart=True)  # start clock
    kb.clock.reset()  # when you want to start RT timer from
    kb.clearEvents()
    kb.start()  # start polling keyboard

    # STIM ON: play a random sound cloud (single time step)
    arr = np.random.randint(params['toneRange_low'],
                            high=params['toneRange_high'],
                            size=params['num_tones'])
    trialDict['stimOn_s'], scratchtime = playSoundCloud(
        arr=arr, dur=params['dur_tonestep'], baseNote=params['baseNote'])

    # start changing pitch stimuli. Stream sound until a response key is pressed or if we time out (set by params['responseTimeLimit_s'])
    while (any(i in keys_pressed for i in params['buttonList_any'])
           == False) & (kb.clock.getTime() <=
                        params['responseTimeLimit_s'][trialDict['block']]):
        arr = changePitch(arr,
                          direction=direction,
                          change_range=params['change_range'],
                          coherence=coherence)
        scratchtime, offTime_s = playSoundCloud(arr=arr,
                                                dur=params['dur_tonestep'],
                                                baseNote=params['baseNote'])
        # check if keys have been pressed
        keys_pressed = kb.getKeys(params['buttonList_any'])

    kb.start()  # stop polling keyboard

    # STIM OFF: stimulus has stopped playing, get most recent stimOff time
    trialDict['stimOff_s'] = offTime_s
    trialDict['wasShown'] = 1

    # figure out whether we timed out
    if len(keys_pressed) == 0:
        # this means we timed out as no response was given
        # response related data remain as "nan" ('buttonPress','choice','buttonPress_s','RT')

        trialDict['correct'] = 0  # this is an error trial
        trialDict['error'] = 1  # this is an error trial

        # present incorrect feedback
        trialDict['fbOn_s'], trialDict['fbOff_s'] = playWrong(
            dur=params['dur_fb'])

    elif len(keys_pressed) > 0:
        # we made a response, lets process the button press

        # process key_press (first key pressed) in relation to trial type
        if trialDict['direction'] == 'increase':
            if (keys_pressed[0] in params['buttonList_inc']):

                # update trialDict
                # note: we use two independent methods to get RT and buttonPress_s. RT should correlate with buttonPress_s - stimOn_s
                trialDict['correct'] = 1
                trialDict['error'] = 0
                trialDict['buttonPress'] = keys_pressed[0].name
                trialDict['choice'] = 'right'
                trialDict[
                    'buttonPress_s'] = trialDict['stimOn_s'] + keys_pressed[
                        0].rt  #keys_pressed[0].tDown - kb.clock.getLastResetTime()
                trialDict['RT'] = keys_pressed[0].rt

                print('Correct! pitch is increasing with coherence = ',
                      trialDict['coherence'], ' RT = ', keys_pressed[0].rt)

                # play feedback
                trialDict['fbOn_s'], trialDict['fbOff_s'] = playCorrect(
                    dur=params['dur_fb'])

            elif (keys_pressed[0] in params['buttonList_dec']):

                # update trialDict
                trialDict['correct'] = 0
                trialDict['error'] = 1
                trialDict['buttonPress'] = keys_pressed[0].name
                trialDict['choice'] = 'left'
                trialDict[
                    'buttonPress_s'] = trialDict['stimOn_s'] + keys_pressed[
                        0].rt  #keys_pressed[0].tDown - kb.clock.getLastResetTime()
                trialDict['RT'] = keys_pressed[0].rt

                print('Incorrect! pitch is increasing with coherence = ',
                      trialDict['coherence'], ' RT = ', keys_pressed[0].rt)

                # play feedback
                trialDict['fbOn_s'], trialDict['fbOff_s'] = playWrong(
                    dur=params['dur_fb'])

        elif trialDict['direction'] == 'decrease':
            if (keys_pressed[0] in params['buttonList_dec']):

                # update trialDict
                trialDict['correct'] = 1
                trialDict['error'] = 1
                trialDict['buttonPress'] = keys_pressed[0].name
                trialDict['choice'] = 'left'
                trialDict[
                    'buttonPress_s'] = trialDict['stimOn_s'] + keys_pressed[
                        0].rt  #keys_pressed[0].tDown - kb.clock.getLastResetTime()
                trialDict['RT'] = keys_pressed[0].rt

                print('Correct! pitch is decreasing with coherence = ',
                      trialDict['coherence'], ' RT = ', keys_pressed[0].rt)

                trialDict['fbOn_s'], trialDict['fbOff_s'] = playCorrect(
                    dur=params['dur_fb'])

            elif (keys_pressed[0] in params['buttonList_inc']):

                # update trialDict
                trialDict['correct'] = 0
                trialDict['error'] = 1
                trialDict['buttonPress'] = keys_pressed[0].name
                trialDict['choice'] = 'right'
                trialDict[
                    'buttonPress_s'] = trialDict['stimOn_s'] + keys_pressed[
                        0].rt  #keys_pressed[0].tDown - kb.clock.getLastResetTime()
                trialDict['RT'] = keys_pressed[0].rt

                print('Incorrect! pitch is decreasing with coherence = ',
                      trialDict['coherence'], ' RT = ', keys_pressed[0].rt)
                trialDict['fbOn_s'], trialDict['fbOff_s'] = playWrong(
                    dur=params['dur_fb'])

    # send a SYNC pulse
    if params['options_sendSYNC'] == True:
        trialDict['TTL1sent_s'] = core.monotonicClock.getTime()

        if params['SYNC_useDigitalOut'] == True:
            # We are sending a digital output
            # Empirically this order seems to lead to a nice positive deflection
            params['SYNC_deviceObj'].getFeedback(u3.BitStateWrite(
                2, 0))  # FI02 to output low
            core.wait(0.1)
            params['SYNC_deviceObj'].getFeedback(u3.BitStateWrite(
                2, 1))  # FI02 to output high

        else:
            # We are sending an analog output
            params['SYNC_deviceObj'].getFeedback(
                u3.DAC0_8(params['SYNC_pulse_val']))
            core.wait(0.1)
            params['SYNC_deviceObj'].getFeedback(
                u3.DAC0_8(params['SYNC_zero_val']))
        """
        # this code is in case you want to send more pulses here
        trialDict['TTL2sent_s'] = core.monotonicClock.getTime() 
        params['SYNC_deviceObj'].getFeedback(u3.DAC0_8(params['SYNC_pulse_val']))
        params['SYNC_deviceObj'].getFeedback(u3.DAC0_8(params['SYNC_zero_val']))
    
        trialDict['TTL3sent_s'] = core.monotonicClock.getTime() 
        params['SYNC_deviceObj'].getFeedback(u3.DAC0_8(params['SYNC_pulse_val']))
        params['SYNC_deviceObj'].getFeedback(u3.DAC0_8(params['SYNC_zero_val']))
        """
        # wait for sync pulses to finish
        core.wait(0.5)

    # return updated trialDict
    return trialDict
def webcamRegistration():

    # Ensure that relative paths start from the same directory as this script
    _thisDir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(_thisDir)

    # Store info about the experiment session
    psychopyVersion = '2020.2.4'
    expName = 'testVideo'  # from the Builder filename that created this script
    expInfo = {'participant': '', 'session': '001'}
    dlg = gui.DlgFromDict(dictionary=expInfo, sort_keys=False, title=expName)
    if dlg.OK == False:
        core.quit()  # user pressed cancel
    expInfo['date'] = data.getDateStr()  # add a simple timestamp
    expInfo['expName'] = expName
    expInfo['psychopyVersion'] = psychopyVersion

    # 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=
        'C:\\Users\\matti\\OneDrive\\Desktop\\Tesi\\testVideo_lastrun.py',
        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
    frameTolerance = 0.001  # how close to onset before 'same' frame

    # Start Code - component code to be run before the window creation

    # Setup the Window
    win = visual.Window(size=(1024, 768),
                        fullscr=True,
                        screen=0,
                        winType='pyglet',
                        allowGUI=False,
                        allowStencil=False,
                        monitor='testMonitor',
                        color=[0, 0, 0],
                        colorSpace='rgb',
                        blendMode='avg',
                        useFBO=True,
                        units='height')
    # store frame rate of monitor if we can measure it
    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

    # create a default keyboard (e.g. to check for escape)
    defaultKeyboard = keyboard.Keyboard()

    # Initialize components for Routine "welcome"
    welcomeClock = core.Clock()
    WelcomeText = visual.TextStim(
        win=win,
        name='WelcomeText',
        text=
        'This is a test to record your webcam.\n\nPress space when ready!\n',
        font='Arial',
        pos=(0, 0),
        height=0.1,
        wrapWidth=None,
        ori=0,
        color='white',
        colorSpace='rgb',
        opacity=1,
        languageStyle='LTR',
        depth=0.0)
    key_resp = keyboard.Keyboard()

    # Initialize components for Routine "WebcamRegistration"
    WebcamRegistrationClock = core.Clock()
    movie = visual.MovieStim3(
        win=win,
        name='movie',
        noAudio=False,
        filename='C:\\Users\\matti\\OneDrive\\Desktop\\Tesi\\video Test.mp4',
        ori=0,
        pos=(0, 0),
        opacity=1,
        loop=False,
        depth=0.0,
    )
    endVideo = keyboard.Keyboard()

    # Create some handy timers
    globalClock = core.Clock()  # to track the time since experiment started
    routineTimer = core.CountdownTimer(
    )  # to track time remaining of each (non-slip) routine

    # ------Prepare to start Routine "welcome"-------
    continueRoutine = True
    # update component parameters for each repeat
    key_resp.keys = []
    key_resp.rt = []
    _key_resp_allKeys = []
    # keep track of which components have finished
    welcomeComponents = [WelcomeText, key_resp]
    for thisComponent in welcomeComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    welcomeClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "welcome"-------
    while continueRoutine:
        # get current time
        t = welcomeClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=welcomeClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *WelcomeText* updates
        if WelcomeText.status == NOT_STARTED and tThisFlip >= 1 - frameTolerance:
            # keep track of start time/frame for later
            WelcomeText.frameNStart = frameN  # exact frame index
            WelcomeText.tStart = t  # local t and not account for scr refresh
            WelcomeText.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(WelcomeText,
                           'tStartRefresh')  # time at next scr refresh
            WelcomeText.setAutoDraw(True)

        # *key_resp* updates
        waitOnFlip = False
        if key_resp.status == NOT_STARTED and tThisFlip >= 2 - frameTolerance:
            # keep track of start time/frame for later
            key_resp.frameNStart = frameN  # exact frame index
            key_resp.tStart = t  # local t and not account for scr refresh
            key_resp.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(key_resp,
                           'tStartRefresh')  # time at next scr refresh
            key_resp.status = STARTED
            # keyboard checking is just starting
            waitOnFlip = True
            win.callOnFlip(key_resp.clock.reset)  # t=0 on next screen flip
            win.callOnFlip(
                key_resp.clearEvents,
                eventType='keyboard')  # clear events on next screen flip
        if key_resp.status == STARTED and not waitOnFlip:
            theseKeys = key_resp.getKeys(keyList=['space'], waitRelease=False)
            _key_resp_allKeys.extend(theseKeys)
            if len(_key_resp_allKeys):
                key_resp.keys = _key_resp_allKeys[
                    -1].name  # just the last key pressed
                key_resp.rt = _key_resp_allKeys[-1].rt
                # a response ends the routine
                continueRoutine = False

        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()

        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in welcomeComponents:
            if hasattr(thisComponent,
                       "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

    # -------Ending Routine "welcome"-------
    for thisComponent in welcomeComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    thisExp.addData('WelcomeText.started', WelcomeText.tStartRefresh)
    thisExp.addData('WelcomeText.stopped', WelcomeText.tStopRefresh)
    # check responses
    if key_resp.keys in ['', [], None]:  # No response was made
        key_resp.keys = None
    thisExp.addData('key_resp.keys', key_resp.keys)
    if key_resp.keys != None:  # we had a response
        thisExp.addData('key_resp.rt', key_resp.rt)
    thisExp.addData('key_resp.started', key_resp.tStartRefresh)
    thisExp.addData('key_resp.stopped', key_resp.tStopRefresh)
    thisExp.nextEntry()
    # the Routine "welcome" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

    # ------Prepare to start Routine "WebcamRegistration"-------
    continueRoutine = True
    # update component parameters for each repeat
    endVideo.keys = []
    endVideo.rt = []
    _endVideo_allKeys = []
    # keep track of which components have finished
    WebcamRegistrationComponents = [movie, endVideo]
    for thisComponent in WebcamRegistrationComponents:
        thisComponent.tStart = None
        thisComponent.tStop = None
        thisComponent.tStartRefresh = None
        thisComponent.tStopRefresh = None
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED
    # reset timers
    t = 0
    _timeToFirstFrame = win.getFutureFlipTime(clock="now")
    WebcamRegistrationClock.reset(
        -_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "WebcamRegistration"-------
    while continueRoutine:
        # get current time
        t = WebcamRegistrationClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=WebcamRegistrationClock)
        tThisFlipGlobal = win.getFutureFlipTime(clock=None)
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *movie* updates
        if movie.status == NOT_STARTED and tThisFlip >= 0.0 - frameTolerance:
            # keep track of start time/frame for later
            movie.frameNStart = frameN  # exact frame index
            movie.tStart = t  # local t and not account for scr refresh
            movie.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(movie, 'tStartRefresh')  # time at next scr refresh
            movie.setAutoDraw(True)

        # *endVideo* updates
        waitOnFlip = False
        if endVideo.status == NOT_STARTED and tThisFlip >= 0.0 - frameTolerance:
            # keep track of start time/frame for later
            endVideo.frameNStart = frameN  # exact frame index
            endVideo.tStart = t  # local t and not account for scr refresh
            endVideo.tStartRefresh = tThisFlipGlobal  # on global time
            win.timeOnFlip(endVideo,
                           'tStartRefresh')  # time at next scr refresh
            endVideo.status = STARTED
            # keyboard checking is just starting
            waitOnFlip = True
            win.callOnFlip(endVideo.clock.reset)  # t=0 on next screen flip
            win.callOnFlip(
                endVideo.clearEvents,
                eventType='keyboard')  # clear events on next screen flip
        if endVideo.status == STARTED and not waitOnFlip:
            theseKeys = endVideo.getKeys(keyList=['q'], waitRelease=False)
            _endVideo_allKeys.extend(theseKeys)
            if len(_endVideo_allKeys):
                endVideo.keys = _endVideo_allKeys[
                    -1].name  # just the last key pressed
                endVideo.rt = _endVideo_allKeys[-1].rt
                # a response ends the routine
                continueRoutine = False

        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            core.quit()

        # check if all components have finished
        if not continueRoutine:  # a component has requested a forced-end of Routine
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in WebcamRegistrationComponents:
            if hasattr(thisComponent,
                       "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

        #####################VIDEO RECORDING#######################################################################################################

        cap = cv2.VideoCapture(0)

        # Define the codec and create VideoWriter object
        fourcc = cv2.VideoWriter_fourcc(*'DIVX')
        out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

        while (cap.isOpened()):
            ret, frame = cap.read()
            if ret == True:
                #  frame = cv2.flip(frame,0)

                # write the flipped frame
                out.write(frame)

                cv2.imshow('frame', frame)
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
            else:
                break

        # Release everything if job is finished
        cap.release()
        out.release()
        cv2.destroyAllWindows()

    # -------Ending Routine "WebcamRegistration"-------
    for thisComponent in WebcamRegistrationComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    movie.stop()
    # check responses
    if endVideo.keys in ['', [], None]:  # No response was made
        endVideo.keys = None
    thisExp.addData('endVideo.keys', endVideo.keys)
    if endVideo.keys != None:  # we had a response
        thisExp.addData('endVideo.rt', endVideo.rt)
    thisExp.addData('endVideo.started', endVideo.tStartRefresh)
    thisExp.addData('endVideo.stopped', endVideo.tStopRefresh)
    thisExp.nextEntry()
    # the Routine "WebcamRegistration" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

    # Flip one final time so any remaining win.callOnFlip()
    # and win.timeOnFlip() tasks get executed before quitting
    win.flip()

    # these shouldn't be strictly necessary (should auto-save)
    thisExp.saveAsWideText(filename + '.csv', delim='auto')
    thisExp.saveAsPickle(filename)
    logging.flush()
    # make sure everything is closed down
    thisExp.abort()  # or data files will save again on exit
    win.close()
    core.quit()
Example #27
0
# Setup the Window
win = visual.Window(
    size=(1024, 768), fullscr=True, screen=0, 
    winType='pyglet', allowGUI=False, allowStencil=False,
    monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
    blendMode='avg', useFBO=True, 
    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "Welcome"
WelcomeClock = core.Clock()
welcome_text = visual.TextStim(win=win, name='welcome_text',
    text='Welcome!\n',
    font='Arial',
    pos=(0, 0), height=0.1, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=0.0);
welcome_resp = keyboard.Keyboard()

# Initialize components for Routine "Wait"
WaitClock = core.Clock()
wait_text = visual.TextStim(win=win, name='wait_text',
                    allowStencil=False,
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "Instructions"
InstructionsClock = core.Clock()
Instruct = visual.TextStim(
    win=win,
    name='Instruct',
    text=
    'You will hear a sentence and will be asked to respond to the last word in the sentence. \n\n\nPRESS ANY KEY TO CONTINUE',
    font='Arial',
    pos=(0, 0),
    height=0.05,
    wrapWidth=None,
    ori=0,
    color='white',
    colorSpace='rgb',
Example #29
0
from sys import exit
from random import shuffle
globalKeys.add(key="q", modifiers=["ctrl"], func=quit)

bg_color = 'white'  # decide background color: white or black
reps = 50  # how many repetitions per condition

# stimulus color always opposite of background color
if bg_color == 'white':
    stim_color = 'black'
elif bg_color == 'black':
    stim_color = 'white'
else:
    exit('wrong bg_color')

kb = keyboard.Keyboard()
my_win = Window(fullscr=True, size=(1000, 600), units='pix', color='white')

# define the "stimulus" rectangle whose color is going to be changing
therect = Rect(my_win,
               width=500,
               height=500,
               lineColor='lightblue',
               fillColor='red')
# define a small information box for continually updated info about the ongoing trials
info = TextStim(my_win,
                text='Info...',
                height=30,
                pos=(-400, 300),
                color='green')
info.autoDraw = True
Example #30
0
# Setup the Window
win = visual.Window(
    size=[1280, 800], fullscr=False, screen=0, 
    winType='pyglet', allowGUI=True, allowStencil=False,
    monitor='testMonitor', color=[0.929,0.969,0.969], colorSpace='rgb',
    blendMode='avg', useFBO=True, 
    units='height')
# store frame rate of monitor if we can measure it
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

# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard()

# Initialize components for Routine "instrucoes"
instrucoesClock = core.Clock()
text = visual.TextStim(win=win, name='text',
    text='default text',
    font='Arial',
    pos=(0, 0.2), height=0.04, wrapWidth=None, ori=0, 
    color='black', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=0.0);
passagem_instrucoes = visual.TextStim(win=win, name='passagem_instrucoes',
    text='Aperte ESPAƇO para continuar',
    font='Arial',
    pos=(0, -0.3), height=0.03, wrapWidth=None, ori=0, 
    color='black', colorSpace='rgb', opacity=1,