Esempio n. 1
0
            New = Pathway + Product
            Newer = New + "/regular/"

            StimProduct = Newer + Product + ".png"
            product = visual.ImageStim(win_exp, image=StimProduct)

            StimPrijs = Newer + Prijs + ".png"
            prijs = visual.ImageStim(win_exp, image=StimPrijs)

            rectangle = visual.Rect(win_exp,
                                    width=.9,
                                    height=1.1,
                                    pos=(0, 0),
                                    fillColor='White')

            timer = core.CountdownTimer(.5)
            while timer.getTime() > 0:
                rectangle.draw()
                Fixationcross.draw()
                win_exp.flip()

            timer = core.CountdownTimer(2.5)
            while timer.getTime() > 0:
                rectangle.draw()
                product.draw()
                win_exp.flip()

            event.clearEvents()

            rectangle.draw()
            prijs.draw()
Esempio n. 2
0
def presTrialVisAudPas(i):

    #transfer info for this trial from design mat
    SclFeedback = design_mat[i, 2]
    SclMaxForce = design_mat[i, 0]
    DurJitter = design_mat[i, 3]

    #present trial intrsuctions
    out_marker.push_sample(['epoch_va_start'])  # send scaling factor
    presTextPsychoPy("Visuell & auditiv")
    core.wait(dur_hint)

    # start baseline
    out_marker.push_sample(['baseline'])
    presTextPsychoPy(" ")
    core.wait(dur_bl)

    # reset trial timer
    timer.reset()
    countdownTimer = core.CountdownTimer(dur_trial)

    # draw fixation cross
    fixation.draw()
    win.flip()
    out_marker.push_sample(['fix_cross'])  # output to lsl

    core.wait(DurJitter)

    tar_force = max_force * SclMaxForce

    # reset input buffer from serial port
    SerialArduino.reset_input_buffer()
    c = 0

    # send scaling factor to lsl
    out_marker.push_sample([
        'trial_start_sfb_{}_sfc_{}'.format(SclFeedback, SclMaxForce)
    ])  # send scaling factor

    sent2PD(s_pitch, 0)  # inital tone for PD
    sent2PD(s_vol, 1)

    # update autodraw
    bar_target.autoDraw = True
    bar_force.autoDraw = True

    # init for LSL data
    start_time = local_clock()
    sent_samples = 0
    current_force = 0

    while countdownTimer.getTime(
    ) + DurJitter > 0:  # add jitter to trial duration

        elapsed_time = local_clock() - start_time
        required_samples = int(
            80 * elapsed_time) - sent_samples  # possible sampling rate of 80Hz

        if required_samples > 0:

            # add from buffer
            current_force = TrialBuff[i][c]
            c += 1

            # get a time stamp in seconds and add hardware time difference 5ms
            stamp = local_clock() - 0.005
            # now send it and wait for a bit
            lc_out.push_chunk([current_force], stamp)
            sent_samples += required_samples

            tmp_crs_pos = (
                (current_force - tar_force) / tar_force
            ) * SclFeedback  # offset inital bar placement, according to Archer ea., 2017
            bar_force.pos = (tmp_crs_pos, 0)
            sent2PD(s_pitch, tmp_crs_pos)

            win.flip()

            # add to buffer for passive condition
            ArdBuff.append(current_force)
            TsBuff.append(stamp)

    # stop autodraw
    bar_target.autoDraw = False
    bar_force.autoDraw = False

    out_marker.push_sample(['end_trial'])  # send 1 for start of fixation cross
    # Turn of DSP in PD
    sent2PD(s_vol, 0)
    def calibrateET(PixW, PixH, NoCP):
        # width and height of window
        WinSize = [PixW, PixH]
        # calibration point size equals 8 pixels
        cpSize = 8
        sd = 5
        # Specify number of Calibration Stimulus Points
        vpx.VPX_SendCommand('calibration_points ' + str(NoCP))
        # calibration of the currently selected point is immediately performed
        vpx.VPX_SendCommand('calibration_snapMode On')
        vpx.VPX_SendCommand('calibration_autoIncrement On')
        vpx.VPX_SendCommand('calibration_PresentationOrder Random')
        # if we would like to restrict the calibration points to a rectangle:
        # coordinates of bounding rectangle, order: Left, Top, Right, Bottom.
        vpx.VPX_SendCommand('calibrationRealRect 0.2 0.3 0.8 0.7')
        # define calibration point
        cpd = visual.Rect(win=myWin,
                          width=cpSize,
                          height=cpSize,
                          units='pix',
                          autoLog=False)
        # green calibration point box
        cpb = visual.Rect(win=myWin,
                          width=cpSize,
                          height=cpSize,
                          units='pix',
                          autoLog=False)
        # white
        cpd.setFillColor([255, 255, 255], u'rgb255')
        # green
        cpb.setFillColor([0, 255, 0], u'rgb255')
        # define calibration clock, will count down
        caliClock = core.CountdownTimer()
        # reset calibration clock to zero
        caliClock.reset()
        # set calibration clock to 1, will count down from 1
        caliClock.add(1.0)
        while caliClock.getTime() > 0:
            pass
        # go trough calibration points
        for p in range(1, NoCP + 1):
            # get the coordinates for the first calibration point
            # this line lets ViewPoint return a cp value for every p value
            vpx.VPX_GetCalibrationStimulusPoint(p, byref(cp))
            # the returned value will be in ViewPoint coordinates
            # (0,0 for top left and 1,1 for bottom right)
            # therefore, the values are transformed to python (0,0 is centre)
            # -(1-x)  # calculate position of cp (x, y)
            cpPos = (cp.x * WinSize[0] - (WinSize[0] / 2),
                     ((1 - cp.y) * WinSize[1]) - (WinSize[1] / 2))
            cpd.setPos(cpPos, log=False)
            cpb.setPos(cpPos, log=False)

            caliClock.reset()
            # draw calibration point and narrowing box
            for j in range(20, 0, -1):  # go from 20 to 0 in -1 steps
                caliClock.add(0.05)
                # decrease size of cp box with every iteration
                cpb.size = (j / sd * cpSize)
                cpb.draw()
                cpd.draw()
                myWin.flip()
                while caliClock.getTime() > 0.0:
                    pass
            # capture current eye position for current calibration point
            vpx.VPX_SendCommand('calibration_snap ' + str(p))

            for j in range(2, 21):  # go from 2 to 20
                caliClock.add(0.05)
                cpb.size = (j / sd * cpSize)
                cpb.draw()
                cpd.draw()
                myWin.flip()
                while caliClock.getTime() > 0.0:
                    pass

            # handle key presses each frame
            for key in event.getKeys():
                if key in ['escape', 'q']:
                    vpx.VPX_SendCommand('dataFile_Close')
                    myWin.close()
                    core.quit()
            caliClock.add(0.2)
            while caliClock.getTime() > 0.0:
                pass

        # clear the screen
        myWin.flip()
Esempio n. 4
0
    radius = 0.9, fillColor = [1, 1, 1],
    lineColor=[1, 1, -1], edges = 128)

beep = sound.Sound(
    value = 'A', secs = 0.2,
    volume = 0.5)

def audGen(): # Generate both Beep noises - one for planning and the other for movement
    beep.play()
    core.wait(1)
    beep.stop()

flicker_frequency = 1.5
current_frame = 0
trialClock=core.Clock()
timer = core.CountdownTimer(15)

while timer.getTime()>0:

    t=trialClock.getTime()
    # When to draw stimuli
    if current_frame % (2*flicker_frequency) < flicker_frequency:
        dotFix.draw()
    window.flip()
    current_frame += 1  # increment by 1
    if (t+3)%5 < 0.19:
        print("Flicker Start")
        print(t)
        solid.draw()
        window.flip()
        core.wait(3)
Esempio n. 5
0
goodbyeText = visual.TextStim(win=win, name='goodbyeText',
    text=goodbyeTextT,
    font='Arial',
    pos=(goodbyeTextX, goodbyeTextY), height=goodbyeTextH, wrapWidth=None, ori=0, 
    color='black', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=0.0);


# ---------- some timers ----------


instructClock = core.Clock()
TrialClock = core.Clock()
globalClock = core.Clock()
sliderTimer = core.CountdownTimer(timeConfidence)





#---------------------------------------------------------------------------#
#-----------------------------------INTRO-----------------------------------#
#---------------------------------------------------------------------------#


# ------Prepare to start Routine "intro"-------
t = 0
frameN = -1

# flow control variable
Esempio n. 6
0
    def runPsychopy(self):
        # make the marker stream. Must do before the window setup to be able to start Lab Recorder
        self.__marker_outlet = self.__createMarkerStream()

        # Get experiement details and filename
        filename, thisExp, expInfo = self.__getDatafilenameAndSetupWindow()

        # 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

        ### ESC flag ###
        self.__endExpNow = False  # flag for 'escape' or other condition => quit the exp

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

        experiment_components = []
        experiment_components.append(
            self.__getMemeStim(meme_filenames[self.__current_meme]))
        random_start_meme_list_2 = rd.randint(0, len(meme_filenames2) - 1)
        experiment_components.append(
            self.__getMemeStim2(meme_filenames2[random_start_meme_list_2]))
        experiment_components.append(self.__getPointsStim())
        self.__startRoutine(experiment_components)

        # Flag the start of the Psychopy experiment
        self.__marker_outlet.push_sample([PSYCHO_PY_MARKERS["psychopyStart"]])

        # Show name of experiment and begin calibration
        self.__showTimedText(introductionText, 1)

        self.__showTextWithSpaceExit(calibrationText)
        self.__marker_outlet.push_sample(
            [PSYCHO_PY_MARKERS["calibrationStart"]])
        self.__marker_outlet.push_sample([PSYCHO_PY_MARKERS["blinkStart"]])
        self.__showTextWithSpaceExit(blinkText, add_instr=False)
        self.__marker_outlet.push_sample([PSYCHO_PY_MARKERS["blinkStop"]])
        self.__marker_outlet.push_sample([PSYCHO_PY_MARKERS["openEyeStart"]])
        self.__showTextWithSpaceExit(openEyeText, add_instr=False)
        self.__marker_outlet.push_sample([PSYCHO_PY_MARKERS["openEyeStop"]])
        self.__marker_outlet.push_sample([PSYCHO_PY_MARKERS["closeEyeStart"]])
        self.__showTextWithSpaceExit(closeEyeText, add_instr=False)
        self.__marker_outlet.push_sample([PSYCHO_PY_MARKERS["closeEyeStop"]])
        self.__marker_outlet.push_sample([PSYCHO_PY_MARKERS["relaxStart"]])
        self.__showTextWithSpaceExit(relaxText, add_instr=False)
        self.__marker_outlet.push_sample([PSYCHO_PY_MARKERS["relaxStop"]])
        self.__showTextWithSpaceExit(
            "Enjoy These Memes\n\npress space to advance through",
            add_instr=False)
        for i in range(3):
            self.__setDrawOn([self.__meme_stim2])
            self.__showTextWithSpaceExit("", add_instr=False)
            self.__endRoutine([self.__meme_stim2])
            random_start_meme_list_2 = (random_start_meme_list_2 +
                                        1) % len(meme_filenames)
            self.__meme_stim2.setImage(
                meme_filenames2[random_start_meme_list_2])

        if (CALIBRATE_EYE):
            self.__showTextWithSpaceExit(calibrationText)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(LEFT_X_COORD, 0),
                                         add_instr=False,
                                         height=0.02)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(RIGHT_X_COORD, 0),
                                         add_instr=False,
                                         height=0.02)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(0, 0),
                                         add_instr=False,
                                         height=0.02)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(0, TOP_Y_COORD),
                                         add_instr=False,
                                         height=0.02)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(0, BOTTOM_Y_COORD),
                                         add_instr=False,
                                         height=0.02)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(0, 0),
                                         add_instr=False,
                                         height=0.02)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(RIGHT_X_COORD, TOP_Y_COORD),
                                         add_instr=False,
                                         height=0.02)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(RIGHT_X_COORD,
                                                   BOTTOM_Y_COORD),
                                         add_instr=False,
                                         height=0.02)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(0, 0),
                                         add_instr=False,
                                         height=0.02)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(LEFT_X_COORD, TOP_Y_COORD),
                                         add_instr=False,
                                         height=0.02)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(LEFT_X_COORD,
                                                   BOTTOM_Y_COORD),
                                         add_instr=False,
                                         height=0.02)
            self.__showTextWithSpaceExit(lookHereText,
                                         location=(0, 0),
                                         add_instr=False,
                                         height=0.02)
            ## CAUTION: data analysis uses the -3rd "(0, 0)" to calibrate for center looking eyes.

        self.__marker_outlet.push_sample(
            [PSYCHO_PY_MARKERS["calibrationStop"]])
        if (SHOW_INTRO):
            self.__marker_outlet.push_sample(
                [PSYCHO_PY_MARKERS["instructionStart"]])
            self.__showTextWithSpaceExit(instructionsText1)
            self.__showTextWithSpaceExit(instructionsText2)
            self.__showTextWithSpaceExit(instructionsText3)
            self.__marker_outlet.push_sample(
                [PSYCHO_PY_MARKERS["instructionStop"]])

        # Create a text supplier
        textSupply = ts.TextSupplier(articles_path)

        self.__setDrawOn([self.__points_stim])
        while (len(textSupply.files_read) <
               NUM_TO_READ) and (not textSupply.getAnotherArticle()):
            num_read = len(textSupply.files_read)
            to_meme = TO_MEME_OR_NOT_TO_MEME[(num_read - 1) %
                                             len(TO_MEME_OR_NOT_TO_MEME)]

            self.__marker_outlet.push_sample([PSYCHO_PY_MARKERS["newArticle"]])
            self.__marker_outlet.push_sample([textSupply.getArticlePath()])
            # Get the article targets
            targets = textSupply.getTargets()
            targetsString = "Identify any words with these letters by pressing 'space'\nPress 'm' to display the letters later:"
            for target in targets:
                targetsString = targetsString + "\n\n" + target

            self.__marker_outlet.push_sample(
                [PSYCHO_PY_MARKERS["memorizationStart"]])
            self.__showTextWithSpaceExit(targetsString)
            self.__marker_outlet.push_sample(
                [PSYCHO_PY_MARKERS["memorizationStop"]])

            targetsString = ""
            for target in targets:
                if (targetsString == ""):
                    targetsString = target
                else:
                    targetsString = targetsString + ", " + target
            self.__letters_stim = self.__getLettersStim(targetsString)
            self.__startRoutine([self.__letters_stim])

            # Reset the timers
            self.__routineTimer.reset()
            self.__kb.clock.reset()
            time_shown = 0
            self.__meme_being_shown = False
            self.__meme_should_be_shown = False
            self.__marker_outlet.push_sample(
                [PSYCHO_PY_MARKERS["responseStart"]])
            secs_to_show = NUM_SECONDS_SHOW_MEME

            while textSupply.hasNext():
                word = textSupply.getNext()

                # If there are supposed to be memes for this article...
                if to_meme != 0:
                    self.__meme_should_be_shown = True
                    time_shown += 1
                    # If shown for long enough, change meme
                    if time_shown > secs_to_show:
                        self.__current_meme = (self.__current_meme +
                                               1) % len(meme_filenames)
                        self.__meme_stim.setImage(
                            meme_filenames[self.__current_meme])
                        self.__marker_outlet.push_sample(
                            [PSYCHO_PY_MARKERS["newMeme"]])
                        self.__marker_outlet.push_sample(
                            [meme_filenames[self.__current_meme]])

                        time_shown = 0

                else:
                    self.__meme_should_be_shown = False

                num_secs = int(
                    (RAND_SECS_STARTBOUND - self.__performance) * 10
                ) / 10  #rd.uniform(RAND_SECS_LOWERBOUND, RAND_SECS_UPPERBOUND)
                num_secs = RAND_SECS_LOWERBOUND if num_secs < RAND_SECS_LOWERBOUND else num_secs
                self.__showWordWithSpaceExitPoints(targetWord=word,
                                                   seconds=num_secs,
                                                   textSupply=textSupply)

            # Meme was previously shown
            if self.__meme_should_be_shown:
                self.__marker_outlet.push_sample(
                    [PSYCHO_PY_MARKERS["memeHidden"]])
                self.__endRoutine([self.__meme_stim])
                self.__meme_being_shown = False
                self.__meme_should_be_shown = False
            self.__marker_outlet.push_sample(
                [PSYCHO_PY_MARKERS["responseStop"]])
            self.__endRoutine([self.__meme_stim])

        self.__endRoutine(experiment_components)

        # Flag the end of the Psychopy experiment
        self.__marker_outlet.push_sample([PSYCHO_PY_MARKERS["psychopyStop"]])

        # Show leaderboard
        leaderboard = lb.Leaderboard(3)
        leaderboard.update(self.__points, expInfo['participant'])
        highest_scores_text = leaderboard.getHighscoresText()
        self.__showTextWithSpaceExit(
            "You have finished this part of the experiment.\nPlease notify your experimenter.\n\nPoints: "
            + str(self.__points) + "\n\n" + highest_scores_text)

        logging.flush()
        # make sure everything is closed down
        thisExp.abort()  # or data files will save again on exit
        self.__win.close()
Esempio n. 7
0
def Practice(expInfo, thisPrac, stim_dir, filenamePrac):

    logging.console.setLevel(
        logging.WARNING)  # this outputs to the screen, not a file

    endExpNow = False  # flag for 'escape' or other condition => quit the exp

    # Setup the Window
    win = visual.Window(size=(1024, 768),
                        fullscr=True,
                        screen=0,
                        allowGUI=False,
                        allowStencil=False,
                        monitor='testMonitor',
                        color='black',
                        colorSpace='rgb',
                        blendMode='avg',
                        useFBO=False,
                        units='pix')

    # Initialize components for Routine "trial"
    trialClock = core.Clock()
    fixation = visual.TextStim(win=win,
                               name='fixation',
                               text='+',
                               font='Arial',
                               pos=(0, 0),
                               height=50,
                               wrapWidth=None,
                               ori=0,
                               color='white',
                               colorSpace='rgb',
                               opacity=1,
                               depth=0.0)
    goal_txt = visual.TextStim(win=win,
                               name='goal_txt',
                               text='Valuable token:',
                               font='Arial',
                               pos=(0, 180),
                               height=40,
                               wrapWidth=None,
                               ori=0,
                               color='white',
                               colorSpace='rgb',
                               opacity=1,
                               depth=-1.0)
    goal_cir = visual.ImageStim(win=win,
                                name='goal_cir',
                                image='sin',
                                mask=None,
                                ori=0,
                                pos=(0, 0),
                                size=[120, 120],
                                color=[1, 1, 1],
                                colorSpace='rgb',
                                opacity=1,
                                flipHoriz=False,
                                flipVert=False,
                                texRes=128,
                                interpolate=True,
                                depth=-2.0)
    sm1 = visual.ImageStim(win=win,
                           name='sm1',
                           image='sin',
                           mask=None,
                           ori=0,
                           pos=(-250, 0),
                           size=[161, 334],
                           color=[1, 1, 1],
                           colorSpace='rgb',
                           opacity=1,
                           flipHoriz=False,
                           flipVert=False,
                           texRes=128,
                           interpolate=True,
                           depth=-5.0)
    sm2 = visual.ImageStim(win=win,
                           name='sm2',
                           image='sin',
                           mask=None,
                           ori=0,
                           pos=(0, 0),
                           size=[161, 334],
                           color=[1, 1, 1],
                           colorSpace='rgb',
                           opacity=1,
                           flipHoriz=False,
                           flipVert=False,
                           texRes=128,
                           interpolate=True,
                           depth=-5.0)
    sm3 = visual.ImageStim(win=win,
                           name='sm3',
                           image='sin',
                           mask=None,
                           ori=0,
                           pos=(250, 0),
                           size=[161, 334],
                           color=[1, 1, 1],
                           colorSpace='rgb',
                           opacity=1,
                           flipHoriz=False,
                           flipVert=False,
                           texRes=128,
                           interpolate=True,
                           depth=-5.0)
    choose = visual.TextStim(win=win,
                             name='choose',
                             text='CHOOSE',
                             font='Arial',
                             pos=(0, -300),
                             height=50,
                             wrapWidth=None,
                             ori=0,
                             color='white',
                             colorSpace='rgb',
                             opacity=1,
                             depth=0.0)

    # Initialize components for Routine "feedback"
    feedbackClock = core.Clock()
    tokenShown = ''
    tsFile = ''
    outc = ''
    sm1_ch = visual.ImageStim(win=win,
                              name='sm1_ch',
                              image='sin',
                              mask=None,
                              ori=0,
                              pos=(-250, 0),
                              size=[161, 334],
                              color=[1, 1, 1],
                              colorSpace='rgb',
                              opacity=1,
                              flipHoriz=False,
                              flipVert=False,
                              texRes=128,
                              interpolate=True,
                              depth=-3.0)
    sm2_ch = visual.ImageStim(win=win,
                              name='sm2_ch',
                              image='sin',
                              mask=None,
                              ori=0,
                              pos=(0, 0),
                              size=[161, 334],
                              color=[1, 1, 1],
                              colorSpace='rgb',
                              opacity=1,
                              flipHoriz=False,
                              flipVert=False,
                              texRes=128,
                              interpolate=True,
                              depth=-3.0)
    sm3_ch = visual.ImageStim(win=win,
                              name='sm3_ch',
                              image='sin',
                              mask=None,
                              ori=0,
                              pos=(250, 0),
                              size=[161, 334],
                              color=[1, 1, 1],
                              colorSpace='rgb',
                              opacity=1,
                              flipHoriz=False,
                              flipVert=False,
                              texRes=128,
                              interpolate=True,
                              depth=-3.0)
    token = visual.ImageStim(win=win,
                             name='token',
                             image='sin',
                             mask=None,
                             ori=0,
                             pos=(0, 0),
                             size=[120, 120],
                             color=[1, 1, 1],
                             colorSpace='rgb',
                             opacity=1,
                             flipHoriz=False,
                             flipVert=False,
                             texRes=128,
                             interpolate=True,
                             depth=-1.0)
    reward = visual.TextStim(win=win,
                             name='reward',
                             text='default text',
                             font=u'Arial',
                             pos=(0, 0),
                             height=60,
                             wrapWidth=None,
                             ori=0,
                             color=u'white',
                             colorSpace='rgb',
                             opacity=1,
                             depth=-2.0)

    # Initialize components for Routine "thanks"
    thanksClock = core.Clock()
    thanksMsg = visual.TextStim(win=win,
                                name='thanksMsg',
                                text='default text',
                                font='Arial',
                                pos=[0, 0],
                                height=40,
                                wrapWidth=None,
                                ori=0,
                                color=u'white',
                                colorSpace='rgb',
                                opacity=1,
                                depth=0.0)

    # 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

    #choose trial file depending on participant number
    #p_nb = int(expInfo['participant'])
    #f_nb = (p_nb % 6) + 1
    #fname = 'trial_lists/practice_%s.xlsx' % (str(f_nb)) #change practice file based on subject number
    fname = 'trial_lists/practice_example.xlsx'  #same practice for everyone
    #create variable to calculate earnings and proportion correct
    earnings = 0
    nb_corr = 0

    nb_tr = 27  #can be changed if necessary
    tr = 1  #keep track of trial number

    # set up handler to look after randomisation of conditions etc
    trials = data.TrialHandler(nReps=1,
                               method='sequential',
                               extraInfo=expInfo,
                               originPath=-1,
                               trialList=data.importConditions(fname),
                               seed=None,
                               name='trials')
    thisPrac.addLoop(trials)  # add the loop to the experiment
    thisTrial = trials.trialList[
        0]  # so we can initialise stimuli with some values
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)

    for thisTrial in trials:
        # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
        if thisTrial != None:
            for paramName in thisTrial.keys():
                exec(paramName + '= thisTrial.' + paramName)

        # ------Prepare to start Routine "trial"-------
        t = 0
        trialClock.reset()  # clock
        frameN = -1
        continueRoutine = True
        # update component parameters for each repeat
        goal_cir.setImage(stim_dir + os.sep + tokenFile)
        #determine entropy level
        if buCond == 1:  #low BU
            bu = 'lbu'
        elif buCond == 2:  #high BU
            bu = 'hbu'
        #determine horizontal order
        if horizOrd == 1:  #G-R-B
            lc = 'G'
            mc = 'R'
            rc = 'B'
        elif horizOrd == 2:  #R-B-G
            lc = 'R'
            mc = 'B'
            rc = 'G'
        elif horizOrd == 3:  #B-G-R
            lc = 'B'
            mc = 'G'
            rc = 'R'
        if unavailAct == 1:
            sm1n = '%s%i_%s_ua.png' % (lc, vertOrd, bu)
            sm2n = '%s%i_%s_a.png' % (mc, vertOrd, bu)
            sm3n = '%s%i_%s_a.png' % (rc, vertOrd, bu)
        elif unavailAct == 2:
            sm1n = '%s%i_%s_a.png' % (lc, vertOrd, bu)
            sm2n = '%s%i_%s_ua.png' % (mc, vertOrd, bu)
            sm3n = '%s%i_%s_a.png' % (rc, vertOrd, bu)
        elif unavailAct == 3:
            sm1n = '%s%i_%s_a.png' % (lc, vertOrd, bu)
            sm2n = '%s%i_%s_a.png' % (mc, vertOrd, bu)
            sm3n = '%s%i_%s_ua.png' % (rc, vertOrd, bu)
        sm1.setImage(stim_dir + os.sep + sm1n)
        sm2.setImage(stim_dir + os.sep + sm2n)
        sm3.setImage(stim_dir + os.sep + sm3n)
        key_choice = event.BuilderKeyResponse()
        # keep track of which components have finished
        trialComponents = [
            fixation, goal_txt, goal_cir, sm1, sm2, sm3, choose, key_choice
        ]
        for thisComponent in trialComponents:
            if hasattr(thisComponent, 'status'):
                thisComponent.status = NOT_STARTED

        # -------Start Routine "trial"-------
        while continueRoutine:
            # 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

            # *fixation* updates
            if t >= 0.0 and fixation.status == NOT_STARTED:
                # keep track of start time/frame for later
                fixation.tStart = t
                fixation.frameNStart = frameN  # exact frame index
                fixation.setAutoDraw(True)
            frameRemains = 0.0 + 1.0 - win.monitorFramePeriod * 0.75  # most of one frame period left
            if fixation.status == STARTED and t >= frameRemains:
                fixation.setAutoDraw(False)

            # *goal_txt* updates
            if t >= 1 and goal_txt.status == NOT_STARTED:
                # keep track of start time/frame for later
                goal_txt.tStart = t
                goal_txt.frameNStart = frameN  # exact frame index
                goal_txt.setAutoDraw(True)
            frameRemains = 1 + 2 - win.monitorFramePeriod * 0.75  # most of one frame period left
            if goal_txt.status == STARTED and t >= frameRemains:
                goal_txt.setAutoDraw(False)

            # *goal_cir* updates
            if t >= 1 and goal_cir.status == NOT_STARTED:
                # keep track of start time/frame for later
                goal_cir.tStart = t
                goal_cir.frameNStart = frameN  # exact frame index
                goal_cir.setAutoDraw(True)
            frameRemains = 1 + 2 - win.monitorFramePeriod * 0.75  # most of one frame period left
            if goal_cir.status == STARTED and t >= frameRemains:
                goal_cir.setAutoDraw(False)

            # *sm_ch* updates
            if t >= 3 and sm1.status == NOT_STARTED:
                # keep track of start time/frame for later
                sm1.tStart = t
                sm1.frameNStart = frameN  # exact frame index
                sm1.setAutoDraw(True)
                sm2.setAutoDraw(True)
                sm3.setAutoDraw(True)

            # *key_choice* updates
            if t >= 5 and key_choice.status == NOT_STARTED:
                # keep track of start time/frame for later
                key_choice.tStart = t
                key_choice.frameNStart = frameN  # exact frame index
                key_choice.status = STARTED
                # keyboard checking is just starting
                win.callOnFlip(
                    key_choice.clock.reset)  # t=0 on next screen flip
                event.clearEvents(eventType='keyboard')
                choose.tgStart = t

            if key_choice.status == STARTED:
                choose.setAutoDraw(True)
                theseKeys = event.getKeys(keyList=[availKey1, availKey2])

                # check for quit:
                if "escape" in theseKeys:
                    endExpNow = True
                if len(theseKeys) > 0:  # at least one key was pressed
                    key_choice.keys = theseKeys[
                        -1]  # just the last key pressed
                    key_choice.rt = key_choice.clock.getTime()
                    if key_choice.keys == 'left':
                        choice = 1
                    elif key_choice.keys == 'down':
                        choice = 2
                    elif key_choice.keys == 'right':
                        choice = 3
                    # was this 'correct'?
                    if choice == corrAct:
                        key_choice.corr = 1
                    else:
                        key_choice.corr = 0
                    # a response ends the routine
                    continueRoutine = False

            # 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

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

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

        # -------Ending Routine "trial"-------
        for thisComponent in trialComponents:
            if hasattr(thisComponent, "setAutoDraw"):
                thisComponent.setAutoDraw(False)
        # check responses
        if key_choice.keys in ['', [], None]:  # No response was made
            key_choice.keys = None
            key_choice.corr = 0

        # store data for trials (TrialHandler)
        trials.addData('choice', choice)
        trials.addData('isCorr', key_choice.corr)
        if key_choice.keys != None:  # we had a response
            trials.addData('choiceRT', key_choice.rt)
        # the Routine "trial" was not non-slip safe, so reset the non-slip timer
        routineTimer.reset()

        # ------Prepare to start Routine "feedback"-------
        t = 0
        feedbackClock.reset()  # clock
        frameN = -1
        continueRoutine = True
        routineTimer.add(4.500000)
        # update component parameters for each repeat
        if key_choice.keys == 'left':
            sm1chn = '%s%i_%s_p.png' % (lc, vertOrd, bu)
            sm2chn = sm2n
            sm3chn = sm3n
        elif key_choice.keys == 'down':
            sm1chn = sm1n
            sm2chn = '%s%i_%s_p.png' % (mc, vertOrd, bu)
            sm3chn = sm3n
        elif key_choice.keys == 'right':
            sm1chn = sm1n
            sm2chn = sm2n
            sm3chn = '%s%i_%s_p.png' % (rc, vertOrd, bu)
        sm1_ch.setImage(stim_dir + os.sep + sm1chn)
        sm2_ch.setImage(stim_dir + os.sep + sm2chn)
        sm3_ch.setImage(stim_dir + os.sep + sm3chn)

        n = random()
        ch = key_choice.keys
        if (ch == 'left' and lc == 'G') or (ch == 'down' and mc == 'G') or (
                ch == 'right' and rc == 'G'):  #green sm chosen
            if (bu == 'lbu' and n <= 0.75) or (bu == 'hbu' and n <= 0.5):
                tokenShown = 'green'
                tsFile = 'green.png'
            elif (bu == 'lbu' and n > 0.75
                  and n <= 0.95) or (bu == 'hbu' and n > 0.5 and n <= 0.8):
                tokenShown = 'red'
                tsFile = 'red.png'
            elif (bu == 'lbu' and n > 0.95) or (bu == 'hbu' and n > 0.8):
                tokenShown = 'blue'
                tsFile = 'blue.png'
            if bu == 'lbu':
                P_green = 0.75
                P_red = 0.2
                P_blue = 0.05
            elif bu == 'hbu':
                P_green = 0.5
                P_red = 0.3
                P_blue = 0.2
        elif (ch == 'left' and lc == 'R') or (ch == 'down' and mc == 'R') or (
                ch == 'right' and rc == 'R'):  #red sm chosen
            if (bu == 'lbu' and n <= 0.75) or (bu == 'hbu' and n <= 0.5):
                tokenShown = 'red'
                tsFile = 'red.png'
            elif (bu == 'lbu' and n > 0.75
                  and n <= 0.95) or (bu == 'hbu' and n > 0.5 and n <= 0.8):
                tokenShown = 'blue'
                tsFile = 'blue.png'
            elif (bu == 'lbu' and n > 0.95) or (bu == 'hbu' and n > 0.8):
                tokenShown = 'green'
                tsFile = 'green.png'
            if bu == 'lbu':
                P_red = 0.75
                P_blue = 0.2
                P_green = 0.05
            elif bu == 'hbu':
                P_red = 0.5
                P_blue = 0.3
                P_green = 0.2
        elif (ch == 'left' and lc == 'B') or (ch == 'down' and mc == 'B') or (
                ch == 'right' and rc == 'B'):  #blue sm chosen:
            if (bu == 'lbu' and n <= 0.75) or (bu == 'hbu' and n <= 0.5):
                tokenShown = 'blue'
                tsFile = 'blue.png'
            elif (bu == 'lbu' and n > 0.75
                  and n <= 0.95) or (bu == 'hbu' and n > 0.5 and n <= 0.8):
                tokenShown = 'green'
                tsFile = 'green.png'
            elif (bu == 'lbu' and n > 0.95) or (bu == 'hbu' and n > 0.8):
                tokenShown = 'red'
                tsFile = 'red.png'
            if bu == 'lbu':
                P_blue = 0.75
                P_green = 0.2
                P_red = 0.05
            elif bu == 'hbu':
                P_blue = 0.5
                P_green = 0.3
                P_red = 0.2

        if tokenShown == goalToken:
            outc = '+10c'
            ov = 10
            isgoal = 1
        else:
            outc = '0c'
            ov = 0
            isgoal = 0
        if goalToken == 'green':
            P_goal = P_green
        elif goalToken == 'red':
            P_goal = P_red
        elif goalToken == 'blue':
            P_goal = P_blue

        token.setImage(stim_dir + os.sep + tsFile)
        reward.setText(outc)
        # keep track of which components have finished
        feedbackComponents = [sm1_ch, sm2_ch, sm3_ch, token, reward]
        for thisComponent in feedbackComponents:
            if hasattr(thisComponent, 'status'):
                thisComponent.status = NOT_STARTED

        # -------Start Routine "feedback"-------
        while continueRoutine and routineTimer.getTime() > 0:
            # get current time
            t = feedbackClock.getTime()
            frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
            # update/draw components on each frame

            # *ch_fb* updates
            if t >= 0.0 and sm1_ch.status == NOT_STARTED:
                # keep track of start time/frame for later
                sm1_ch.tStart = t
                sm1_ch.frameNStart = frameN  # exact frame index
                sm1_ch.setAutoDraw(True)
                sm2_ch.setAutoDraw(True)
                sm3_ch.setAutoDraw(True)
            frameRemains = 0.0 + 0.5 - win.monitorFramePeriod * 0.75  # most of one frame period left
            if sm1_ch.status == STARTED and t >= frameRemains:
                sm1_ch.setAutoDraw(False)
                sm2_ch.setAutoDraw(False)
                sm3_ch.setAutoDraw(False)

            # *token* updates
            if t >= 0.5 and token.status == NOT_STARTED:
                # keep track of start time/frame for later
                token.tStart = t
                token.frameNStart = frameN  # exact frame index
                token.setAutoDraw(True)
            frameRemains = 0.5 + 2 - win.monitorFramePeriod * 0.75  # most of one frame period left
            if token.status == STARTED and t >= frameRemains:
                token.setAutoDraw(False)

            # *reward* updates
            if t >= 2.5 and reward.status == NOT_STARTED:
                # keep track of start time/frame for later
                reward.tStart = t
                reward.frameNStart = frameN  # exact frame index
                reward.setAutoDraw(True)
            frameRemains = 2.5 + 2 - win.monitorFramePeriod * 0.75  # most of one frame period left
            if reward.status == STARTED and t >= frameRemains:
                reward.setAutoDraw(False)

            # 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 feedbackComponents:
                if hasattr(thisComponent,
                           "status") and thisComponent.status != FINISHED:
                    continueRoutine = True
                    break  # at least one component has not yet finished

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

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

        # -------Ending Routine "feedback"-------
        for thisComponent in feedbackComponents:
            if hasattr(thisComponent, "setAutoDraw"):
                thisComponent.setAutoDraw(False)

        trials.addData('pGreen', P_green)
        trials.addData('pRed', P_red)
        trials.addData('pBlue', P_blue)
        trials.addData('pGoal', P_goal)
        trials.addData('randn', n)
        trials.addData('tokenShown', tokenShown)
        trials.addData('tsFile', tsFile)
        trials.addData('isGoal', isgoal)
        trials.addData('outcome', ov)
        earnings = earnings + ov
        nb_corr = nb_corr + key_choice.corr

        thisPrac.nextEntry()
        tr = tr + 1

    # get names of stimulus parameters
    if trials.trialList in ([], [None], None):
        params = []
    else:
        params = trials.trialList[0].keys()
    # save data for this loop
    trials.saveAsExcel(filenamePrac + '_final.xlsx',
                       sheetName='trials',
                       stimOut=params,
                       dataOut=['all_raw'])

    prop_corr = nb_corr * 100 / nb_tr
    print 'Total earnings practice = $%.2f' % (
        earnings / 100)  #print earnings in output window
    print 'Percent correct = %.2f' % (prop_corr)

    # ------Prepare to start Routine "thanks"-------
    t = 0
    thanksClock.reset()  # clock
    frameN = -1
    continueRoutine = True
    routineTimer.add(5.000000)
    # show cumulated earning
    thanksText = 'End of the practice session\n\nTotal earnings = $%.2f \n\nPercent correct = %.2f' % (
        earnings / 100.0, prop_corr)
    thanksMsg.setText(thanksText)
    # keep track of which components have finished
    thanksComponents = [thanksMsg]
    for thisComponent in thanksComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    # -------Start Routine "thanks"-------
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = thanksClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)

        # *thanksMsg* updates
        if t >= 0.0 and thanksMsg.status == NOT_STARTED:
            # keep track of start time/frame for later
            thanksMsg.tStart = t
            thanksMsg.frameNStart = frameN  # exact frame index
            thanksMsg.setAutoDraw(True)
        frameRemains = 0.0 + 5 - win.monitorFramePeriod * 0.75  # most of one frame period left
        if thanksMsg.status == STARTED and t >= frameRemains:
            thanksMsg.setAutoDraw(False)

        # 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 thanksComponents:
            if hasattr(thisComponent,
                       "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

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

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

    # -------Ending Routine "thanks"-------
    for thisComponent in thanksComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)

    #-------------SAVE DATA IN VARIOUS FILES-------------------
    # these shouldn't be strictly necessary (should auto-save)
    thisPrac.saveAsWideText(filenamePrac + '_backup.csv')
    thisPrac.saveAsPickle(filenamePrac + '_data')

    wb = open_workbook(filenamePrac + '_final.xlsx')
    s = wb.sheet_by_index(0)
    d = {}
    for col in range(s.ncols):
        key_name = s.cell(0, col).value
        key_vals = s.col_values(col, start_rowx=1, end_rowx=nb_tr + 1)
        d[key_name] = key_vals
    wb_fin = xlsxwriter.Workbook(filenamePrac + '_final_ord.xlsx',
                                 {'strings_to_numbers': True})
    ws_fin = wb_fin.add_worksheet()
    ws_fin.write(0, 0, "index")
    ws_fin.write_column(1, 0, tuple([int(num) for num in d['order']]))
    ws_fin.write(0, 1, "trialNb")
    ws_fin.write_column(1, 1, tuple([int(num) for num in d['trialNb']]))
    ws_fin.write(0, 2, "goalToken")
    ws_fin.write_column(1, 2, tuple([str(num) for num in d['goalToken']]))
    ws_fin.write(0, 3, "unavAct")
    ws_fin.write_column(1, 3, tuple([int(num) for num in d['unavailAct']]))
    ws_fin.write(0, 4, "corrAct")
    ws_fin.write_column(1, 4, tuple([int(num) for num in d['corrAct']]))
    ws_fin.write(0, 5, "bestAct")
    ws_fin.write_column(1, 5, tuple([int(num) for num in d['bestAct']]))
    ws_fin.write(0, 6, "choice")
    ws_fin.write_column(1, 6, tuple([int(num) for num in d['choice_raw']]))
    ws_fin.write(0, 7, "isCorr")
    ws_fin.write_column(1, 7, tuple([int(num) for num in d['isCorr_raw']]))
    ws_fin.write(0, 8, "choiceRT")
    ws_fin.write_column(1, 8, tuple([float(num) for num in d['choiceRT_raw']]))
    ws_fin.write(0, 9, "pGreen")
    ws_fin.write_column(1, 9,
                        tuple([round(num, 2) for num in d['pGreen_raw']]))
    ws_fin.write(0, 10, "pRed")
    ws_fin.write_column(1, 10, tuple([round(num, 2) for num in d['pRed_raw']]))
    ws_fin.write(0, 11, "pBlue")
    ws_fin.write_column(1, 11,
                        tuple([round(num, 2) for num in d['pBlue_raw']]))
    ws_fin.write(0, 12, "pGoal")
    ws_fin.write_column(1, 12,
                        tuple([round(num, 2) for num in d['pGoal_raw']]))
    ws_fin.write(0, 13, "randn")
    ws_fin.write_column(1, 13, tuple([float(num) for num in d['randn_raw']]))
    ws_fin.write(0, 14, "isGoal")
    ws_fin.write_column(1, 14, tuple([int(num) for num in d['isGoal_raw']]))
    ws_fin.write(0, 15, "tokenShown")
    ws_fin.write_column(1, 15,
                        tuple([str(num) for num in d['tokenShown_raw']]))
    ws_fin.write(0, 16, "outcome")
    ws_fin.write_column(1, 16, tuple([int(num) for num in d['outcome_raw']]))
    wb_fin.close()

    logging.flush()
    # make sure everything is closed down
    thisPrac.abort()  # or data files will save again on exit
Esempio n. 8
0
def break_time(trial_no):
    # Create stimuli and actions in break trials
    may_break_text = \
        "\
You have completed {} trials, you may take a 1-minute break, \n\n\
If you don't need to, \n\
Press 'Spacebar' to Skip. \n\
" .format(trial_no + 1)
    must_break_text = \
        "\
You have completed {} trials, Take a 2-minute break.\
" .format(trial_no + 1)
    end_break_text = \
        "\
Break Ended, \nPress 'f' or 'j' to Continue the experiment.\
"

    break_text = visual.TextStim(win=win,
                                 text=' ',
                                 font='Times New Roman',
                                 pos=(0, -8),
                                 color='black',
                                 units='deg',
                                 height=0.9,
                                 wrapWidth=20)
    break_timer = visual.TextStim(win=win,
                                  text=' ',
                                  font='Source Code Pro',
                                  pos=(0, 0),
                                  color='black',
                                  units='deg',
                                  height=4,
                                  wrapWidth=20)

    if trial_no == breaktrial[1]:  # Must break
        break_text.setText(must_break_text)
        break_text.draw()
        win.flip()
        timer = core.CountdownTimer(long_break_time)
        while timer.getTime() > 0:
            break_timer.setText(round(timer.getTime(), 1))
            break_text.draw()
            break_timer.draw()
            win.flip()
            if event.getKeys(['end']):
                win.close()
                sys.exit()

    else:  # Self-Terminated Break
        break_text.setText(may_break_text)
        break_text.draw()
        win.flip()
        timer = core.CountdownTimer(short_break_time)
        while timer.getTime() > 0:
            break_timer.setText(round(timer.getTime(), 1))
            break_text.draw()
            break_timer.draw()
            win.flip()
            if event.getKeys(['space']):
                break
            elif event.getKeys(['end']):
                win.close()
                sys.exit()

    break_text.setText(end_break_text)
    break_timer.setText(round(timer.getTime(), 1))
    break_text.draw()
    break_timer.draw()
    win.flip()
    breakresp = event.waitKeys(maxWait=1000,
                               keyList=['end', 'f', 'j'],
                               clearEvents=True)
    if 'f' in breakresp or 'j' in breakresp:
        pass
    elif 'end' in breakresp:
        win.close()
        sys.exit()
Esempio n. 9
0
                           name='text',
                           text=u'text',
                           font=u'Times New Roman',
                           pos=[0, 100],
                           height=NBack_Prac1_TextSize,
                           wrapWidth=None,
                           color=u'white',
                           colorSpace=u'rgb',
                           opacity=1,
                           depth=0.0)

resp = event.BuilderKeyResponse()  # create an object of type KeyResponse

# Set up the clocks
TrialClock = core.Clock()
CountDownClock = core.CountdownTimer()
LetterOnCountDownClock = core.CountdownTimer()
ElapsedTimeClock = core.Clock()

# Need instructions and wait
textInstr1.setAutoDraw(True)
# Put the probe dot on the screen
win.flip()
# Start the probe timer

WaitingFlag = True
while WaitingFlag is True:
    theseKeys = event.getKeys(keyList=['escape', 'return'])
    if 'escape' in theseKeys:
        core.quit()
    elif 'return' in theseKeys:
Esempio n. 10
0
def runTrials():
 
 '''
 This script assumes there are is a folder called 'images' with all images and a folder 'shuffled' 
 but having the same file names 
 
 Script must be run from th folder where the script is located!
 '''
 
 trial_duration=4 #how long is one trial in sec
 reps=54 #how often each condition'shuffle pair is shown. It's always the same order.
  
 ##############################################
 ##############################################

 conditions=[]  
 for i in [2,4,6]:#this is frame_rates in Hz
  for j in [False,True]:
   conditions.append([i,j])
 nReps=len(conditions)*reps #how many trials like this; must be multiple of 6 as each of the 3 frame rates is followed by a shuffled version


# Ensure that relative paths start from the same directory as this script
 #_thisDir = os.path.dirname(os.path.abspath(__file__))
 _thisDir = 'C:/Users/Sackler6/Documents/Nick/'
 os.chdir(_thisDir)

 # Store info about the experiment session
 psychopyVersion = '3.1.0'
 expName = 'oneImage'  # from the Builder filename that created this script
 expInfo = {'participant': '', 'session': '06'}
 dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=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='untitled.py',
     savePickle=True, saveWideText=True,
     dataFileName=filename)

 endExpNow = False  # flag for 'escape' or other condition => quit the exp


#Welcome Message
 instr='''
In this experiment we are interested in the speed at which you can process visual information.\n
We will present you with a stream of either real or scambled images.\n
Your task is to maintain fixation on a red  square, while paying attention to the periphery of your vision. \n
During the stream of images we will present a red square in a random corner of one of the images\n
At the end of each trial you will be asked which corner the image was presented in.\n

*** Please place your chin on the chinrest, relax till the count of 5 the press any key***\n

***The experiment will begin as soon as you press any key***\n
'''

#Create the main Window 
 win = visual.Window([1000,1000],monitor="testMonitor",  units="height", fullscr=FullScreen_opt)

#Print the instruction message

 instructions = visual.TextStim(win, 
                                text=instr,
                                units='pix', 
                                color='white',
                                font='Arial', 
                                height=22, 
                                pos=(0,0))
 instructions.autoDraw = True  # Automatically draw every frame
 win.flip()
 event.waitKeys() #wait for any key to be pressed to continue the experiment
 instructions.autoDraw = False  # Turn off instructions
 win.flip()
 core.wait(1.0)

 ##############################################
 ##############################################

  
 #create a constant little square box as a fixation point
 fixation = visual.GratingStim(win=win, size=0.01, pos=[0,0], sf=0, color='red')

 #create rating for square location: it must be in one corner
 rating = visual.RatingScale(win=win, name='rating', marker='triangle', size=1.5, pos=[0.0, -0.4], low=1,textSize=0.4, high=4,tickMarks=range(1,5), labels=['Top left','Top right','Bottom right','Bottom left'], scale='In which corner was the red square?')

 # 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 

 # set up handler to look after randomisation of conditions etc
 trials_3 = data.TrialHandler(nReps=nReps, method='random', 
     extraInfo=expInfo, originPath=-1,
     trialList=[None],
     seed=None, name='trials_3')
 thisExp.addLoop(trials_3)  # add the loop to the experiment
 thisTrial_3 = trials_3.trialList[0]  # so we can initialise stimuli with some values
 # abbreviate parameter names if possible (e.g. rgb = thisTrial_3.rgb)
 if thisTrial_3 != None:
     for paramName in thisTrial_3:
         exec('{} = thisTrial_3[paramName]'.format(paramName))

 t_rial=0

 for thisTrial_3 in trials_3:
   
     frame_rate,shuffle_trial=conditions[t_rial%6]

     n_images=trial_duration*frame_rate
     duration_of_each_image=float(frame_rate)**-1 
  
     currentLoop = trials_3
     # abbreviate parameter names if possible (e.g. rgb = thisTrial_3.rgb)
     if thisTrial_3 != None:
         for paramName in thisTrial_3:
             exec('{} = thisTrial_3[paramName]'.format(paramName))

     # ------Prepare to start Routine "trial"-------

     #Red square to be detected: pick random frame, random corner  

     locs=[[-0.2,0.2],[0.2,0.2],[0.2,-0.2],[-0.2,-0.2]]
     chosen_index_for_location=choice(range(4),1)[0]
     chosen_loc=locs[chosen_index_for_location]
     chosen_image=choice(range(n_images),1)
     
     red_square = visual.GratingStim(win=win, size=0.01, pos=chosen_loc, sf=0, color='red')


     path_to_images='C:/Users/Sackler6/Documents/Nick/images/' 
     path_to_shuffled_images='/'.join(path_to_images.split('/')[:-2])+'/shuffled/'


     if shuffle_trial: #load image paths used for previous block

      path_to_exp_data=os.path.dirname(filename)

      img_paths=np.load(path_to_exp_data+'/images.npy')     

      im_50=[]

      for img_path in img_paths: #save corresponding shuffled image paths
 
       im_50.append(path_to_shuffled_images+'/%s' %((img_path.split('/'))[-1]))

     else:

      #we want to show random images in sequence, always other images; this is achieved by sampling from that massive mini-imagenet, a folder with many low-res images
      
      f=os.listdir(path_to_images)
      f_50=sample(f,n_images)

      im_50=[path_to_images+'/'+i for i in f_50]

     images=[]
     image_names=[]
     image_paths=[]

     # Initialize components for Routine "trial"
     trialClock = core.Clock()

     for i in range(n_images):

         img=im_50[i]
         image_paths.append(img)
         images.append(visual.ImageStim(
         win=win,
         name='image'+str(i), 
         image=img, mask=None,
         ori=0, pos=(0, 0), size=(0.5, 0.5),
         color=[1,1,1], colorSpace='rgb', opacity=1,
         flipHoriz=False, flipVert=False,
         texRes=128, interpolate=True, depth=1.0))
         win.flip()
         image_names.append('image'+str(i))

     np.save('C:/Users/Sackler6/Documents/Nick/data/images.npy',image_paths)
 
     t_rial+=1

     t = 0
     trialClock.reset()  # clock
     frameN = -1

     continueRoutine = True
     #routineTimer.add(n_images*duration_of_each_image)
     # update component parameters for each repeat
     # keep track of which components have finished
     trialComponents = [x for x in images]
     trialComponents.append(rating)
     for thisComponent in trialComponents:
         thisComponent.tStart = None
         thisComponent.tStop = None
         thisComponent.tStartRefresh = None
         thisComponent.tStopRefresh = None
         if hasattr(thisComponent, 'status'):
             thisComponent.status = NOT_STARTED

     rating.reset()
     

      ######################################################################################################
      ######################################################################################################
      #Send a an EEG marker here based on framerate i.e. 2,4,6
     if shuffle_trial:
                        
       triggerCode=frame_rate + 10
     else:
       triggerCode=frame_rate
       
     sendParallelTrigger(pport_address,triggerCode) 

     
     # -------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
         fixation.setAutoDraw(True) 
         fixation.setDepth(0.0)

         k=0 #image counter
         k_max=len(images)


         for image in images:
          # *image* updates
          images_start=t
          
           
          
          
          
          if t >= duration_of_each_image*k and image.status == NOT_STARTED:
              # keep track of start time/frame for later
                      
              image.tStart = t  # not accounting for scr refresh
 


              image.frameNStart = frameN  # exact frame index
              win.timeOnFlip(image, 'tStartRefresh')  # time at next scr refresh
              image.setAutoDraw(True)
          
              if k==chosen_image:
               red_square.setAutoDraw(True) 
               red_square.setDepth(0.0)          
              
          frameRemains = duration_of_each_image*k + duration_of_each_image - win.monitorFramePeriod * 0.75  # most of one frame period left
          if image.status == STARTED and t >= frameRemains:
                    
              # keep track of stop time/frame for later
              image.tStop = t  # not accounting for scr refresh
              image.frameNStop = frameN  # exact frame index
              win.timeOnFlip(image, 'tStopRefresh')  # time at next scr refresh
              image.setAutoDraw(False)

              if k==chosen_image:
               red_square.setAutoDraw(False)            

          k+=1     
       
         if t>trial_duration and rating.status == NOT_STARTED:
             # keep track of start time/frame for later
             rating.tStart = t  # not accounting for scr refresh

             
            ######################################################################################################
            ######################################################################################################
            #Send a an EEG marker here based on framerate + 100
             if shuffle_trial:
              triggerCode=frame_rate+10 +100
             else:
              triggerCode=frame_rate +100

             sendParallelTrigger(pport_address,triggerCode)

             rating.frameNStart = frameN  # exact frame index
             win.timeOnFlip(rating, 'tStartRefresh')  # time at next scr refresh
             rating.setAutoDraw(True)
             continueRoutine &= rating.noResponse

         # check for quit (typically the Esc key)
         if endExpNow or keyboard.Keyboard().getKeys(keyList=["escape"]):
             core.quit()
             visual.Window.close()
         
         # 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()

         if len(event.getKeys())>0:
             break


     # -------Ending Routine "trial"-------
     for thisComponent in trialComponents:
         if hasattr(thisComponent, "setAutoDraw"):
             thisComponent.setAutoDraw(False)

     trials_3.addData('square_correct',(rating.getRating()-1)==chosen_index_for_location)
     trials_3.addData('frame_rate',frame_rate)
     trials_3.addData('shuffle_trial',shuffle_trial)
     trials_3.addData('trial_duration',trial_duration)
     trials_3.addData('images_start',images_start)
     trials_3.addData('images_start_CPU',str(datetime.now()))                
     trials_3.addData('rating.tStart',rating.tStart)
     trials_3.addData('rating.tStart_CPU',str(datetime.now()))
     thisExp.nextEntry() 

 os.remove('C:/Users/Sackler6/Documents/Nick/data/images.npy')
 # Flip one final time so any remaining win.callOnFlip() 
 # and win.timeOnFlip() tasks get executed before quitting
 win.flip()
 thisExp.saveAsWideText(filename+'.csv')
# logging.flush()

 # make sure everything is closed down
 thisExp.abort()  # or data files will save again on exit
 win.close()
 core.quit()
Esempio n. 11
0
    def runPsychopy(self):
        # make the marker stream. Must do before the window setup to be able to start Lab Recorder
        self.__marker_outlet = self.__createMarkerStream()

        # Get experiement details and filename
        filename, thisExp, expInfo = self.__getDatafilenameAndSetupWindow()

        # 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

        ### ESC flag ###
        self.__endExpNow = False  # flag for 'escape' or other condition => quit the exp

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

        # Flag the start of the Psychopy experiment
        self.__marker_outlet.push_sample([RECORDING_START_MARKER])
        self.__showTextWithSpaceExit(instructions_text)
        self.__marker_outlet.push_sample([CALIBRATION_START_MARKER])
        self.__marker_outlet.push_sample([BLINK_START_MARKER])
        self.__showTextWithSpaceExit(blink_text)
        self.__marker_outlet.push_sample([BLINK_END_MARKER])
        self.__marker_outlet.push_sample([CLOSE_EYE_START_MARKER])
        self.__showTextWithSpaceExit(close_eye_text)
        self.__marker_outlet.push_sample([CLOSE_EYE_END_MARKER])

        self.__marker_outlet.push_sample([CALIBRATION_END_MARKER])

        for i in range(NUM_IMAGES_TO_SHOW):
            if i % 140 == 0:
                print("shuffling!")
                rd.shuffle(faces_filenames)
                rd.shuffle(landscape_filenames)

            # Reset the timers
            self.__routineTimer.reset()
            self.__kb.clock.reset()
            time_shown = 0
            self.__marker_outlet.push_sample([CROSS_START_MARKER])
            self.__showTimedText(
                "+",
                rd.randrange((NUM_SECONDS_TO_SHOW_CROSS) * 10,
                             (NUM_SECONDS_TO_SHOW_CROSS + 0.2) * 10) / 10)
            self.__marker_outlet.push_sample([CROSS_END_MARKER])

            self.__marker_outlet.push_sample([NEW_IMAGE_START_MARKER])
            self.__marker_outlet.push_sample(
                [FACE_IMAGE_MARKER] if self.__current_type ==
                FACE else [LANDSCAPE_IMAGE_MARKER])

            self.__getNextImage()
            self.__startRoutine([self.__image_stim])
            self.__marker_outlet.push_sample([self.__image_filename])
            print(self.__image_filename)

            self.__setDrawOn([self.__image_stim])
            self.__showTimedText(
                "",
                rd.randrange((NUM_SECONDS_TO_SHOW_IMAGE) * 10,
                             (NUM_SECONDS_TO_SHOW_IMAGE + 0.2) * 10) / 10)
            self.__endRoutine([self.__image_stim])

            self.__marker_outlet.push_sample([NEW_IMAGE_END_MARKER])

        # Flag the end of the Psychopy experiment

        self.__marker_outlet.push_sample([RECORDING_END_MARKER])

        logging.flush()
        # make sure everything is closed down
        thisExp.abort()  # or data files will save again on exit
        self.__win.close()
Esempio n. 12
0
monitor_to_use = 1
square_left_number_frames = 3    # 3 frames ON and 3 frames OFF to make 10 Hz
square_right_number_frames = 5   # 5 frames ON and 5 frames OFF to make 6 Hz
square_up_number_frames = 4      # 4 frames ON and 4 frames OFF to make 7.5 Hz
square_down_number_frames = 4    # 4 frames ON BUT 3 frames OFF to make 8.57 Hz

# Create LSL inlet and send the first event "Waiting..." during the pause everything is being set up
info = StreamInfo('MyMarkerStream', 'Markers', 1, 0, 'string', 'Experiment01')
outlet = StreamOutlet(info)
outlet.push_sample(['Waiting...'])
time.sleep(1)

# Create an artificial pause to give time to prepare LSL recording externally
clock_object = core.Clock()
recording_pause = 10
countdown_time = core.CountdownTimer(recording_pause)
while countdown_time.getTime() > 0:
    elapsed_time = clock_object.getTime()
clock_object.reset()
elapsed_time = 0
# ----------------------------------------------------------------------------------------------------------------------


# ----------------------------------------------------------------------------------------------------------------------
# ---- Create a full-screen window with invisible mouse, collect real monitor refresh rate ----
window_handle = visual.Window([1920, 1080], fullscr=True, winType='pyglet', monitor='testMonitor', units='deg',
                              screen=monitor_to_use, color=[-1, -1, -1], colorSpace='rgb')

# Enable frame monitoring and logging (to detect drop frames)
monitor_frame_rate = int(window_handle.getActualFrameRate())
window_handle.setMouseVisible(False)
Esempio n. 13
0
uText.setAutoDraw(False)
iText.setAutoDraw(False)
# ==============================================================================================
# Trial Objects: Creation of Trail Objects and sounds
# ==============================================================================================
TrialClock = core.Clock()
pyGamSound = SoundPygame(value='A')
# ==============================================================================================
# Exit Objects: Creation of Exit Objects
# ==============================================================================================
ExitClock = core.Clock()
# ==============================================================================================
# Timers: 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 Instructions: Set up Instructions
# ==============================================================================================
instructionsIndex = 0
continueRoutine = not cfg.getVal("skip_instructions")
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
InstructionsClock.reset(
    -_timeToFirstFrame)  # t0 is time of first possible flip
frameN = -1
# config ui elements
header.setText(cfg.getVal("instructions_header"))
header.setColor(guid.c("general_text"))
body.setColor(guid.c("general_text"))
Esempio n. 14
0
    mask=None,
    pos=(0.0,0.0),
    size=(1.5,1.5))
    
ThankYouScreen = visual.TextStim(win=win, ori=0, name='text',
    text=u'Merci',    font=u'Arial',
    pos=[0, 0], height=ExpParameters['TextSize'], wrapWidth=None,
    color=u'white', colorSpace=u'rgb', opacity=1,
    depth=0.0)


resp = event.BuilderKeyResponse()  # create an object of type KeyResponse

# Set up the clocks
TrialClock = core.Clock()
CountDownClock = core.CountdownTimer()
ElapsedTimeClock = core.Clock()


# PRESENT THE SCREEN TO WAIT FOR THE MRI TRIGGER
vol = launchScan(win, MR_settings,  mode='Scan')

# Cross hair
ElapsedTimeClock.reset()
CountDownClock.reset()
CountDownClock.add(ExpParameters['IntroOffDuration'])
CrossHair.draw()
win.flip()
while CountDownClock.getTime() > 0:
    theseKeys = event.getKeys()
    if "escape" in theseKeys:
Esempio n. 15
0
def runExp(participantId):
    # Ensure that relative paths start from the same directory as this scripta
    _thisDir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(_thisDir)

    # Store info about the experiment session
    psychopyVersion = '2020.2.4'
    expName = 'ExpGiulia'  # from the Builder filename that created this script
    expInfo = {'participant': participantId, '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_%s' % (expInfo['participant'],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=os.getcwd(),
                                     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 "trial"
    trialClock = core.Clock()
    welcomeText = visual.TextStim(win=win, name='welcomeText',
                                  text='Welcome to this experiment.\n\nPress the spacebar when you are ready and the video will start!',
                                  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 "Video"
    VideoClock = core.Clock()
    video = visual.MovieStim3(
        win=win, name='video',
        noAudio=False,
        #filename='C:\\Users\\matti\\OneDrive\\Desktop\\Tesi\\VideoEsperimenti\\filmato_Giulia.mp4',
        filename='videos\\filmato_Giulia.mp4',
        ori=0, pos=(0, 0), opacity=1,
        loop=False,
        depth=0.0,
    )

    # 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 "trial"-------
    continueRoutine = True
    # update component parameters for each repeat
    key_resp.keys = []
    key_resp.rt = []
    _key_resp_allKeys = []
    # keep track of which components have finished
    trialComponents = [welcomeText, key_resp]
    for thisComponent in trialComponents:
        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")
    trialClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

    # -------Run Routine "trial"-------
    while continueRoutine:
        # get current time
        t = trialClock.getTime()
        tThisFlip = win.getFutureFlipTime(clock=trialClock)
        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 >= 0.0 - 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 >= 0.0 - 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"]):
            win.close()
            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()

    # -------Ending Routine "trial"-------
    for thisComponent in trialComponents:
        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 "trial" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

    # ------Prepare to start Routine "Video"-------
    continueRoutine = True
    # update component parameters for each repeat
    # keep track of which components have finished
    VideoComponents = [video]
    for thisComponent in VideoComponents:
        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")
    VideoClock.reset(-_timeToFirstFrame)  # t0 is time of first possible flip
    frameN = -1

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

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

        # check for quit (typically the Esc key)
        if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]):
            win.close()
            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 VideoComponents:
            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 "Video"-------
    for thisComponent in VideoComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    video.stop()
    # the Routine "Video" 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()
    logging.flush()

    for thisThread in threading.enumerate():
        if hasattr(thisThread, 'stop') and hasattr(thisThread, 'running'):
            # this is one of our event threads - kill it and wait for success
            thisThread.stop()
            while thisThread.running == 0:
                pass  # wait until it has properly finished polling

    sys.exit(1)  # quits the python session entirely
Esempio n. 16
0
        cont = 0
    elif allKeys == [next]:
        gallery_inside = 0

instructions = 1
while instructions and cont:
    instr_text.draw()
    win.flip()
    allKeys = event.getKeys()
    if allKeys == ['escape']:
        cont = 0
    elif allKeys == [next]:
        instructions = 0

# 5. Practice
fixationTimer = core.CountdownTimer()
feedbackTimer = core.CountdownTimer()
imageTimer = core.CountdownTimer()
practiceTimer = core.CountdownTimer()
while practice and cont:
    instr_text.setText('Figyeljen, kezdődik a gyakorlás.')
    trials = len(practice_table.index)
    practiceTimer.reset(2.0)
    while cont and practiceTimer.getTime() > 0:
        instr_text.draw()
        win.flip()
        thisKey = keyboard.Keyboard().getKeys()
        if thisKey == ['escape']:
            cont = 0
        elif thisKey == [pause_button]:
            cont = insert_pause()
Esempio n. 17
0
    # start block
    for trial, condition in enumerate(conditions):
        logging.info('Starting trial #%s with %s stimuli', trial + 1,
                     condition[0])

        triggerId = trigger.sendTriggerId()
        datalog["triggerID"] = triggerId

        ###############
        # Wait a little

        screen.show_blank()

        # start delay
        delayTimer = core.CountdownTimer(CONF["pause"]["duration"])
        logging.info("starting delay of %s", delayTimer)

        extraKeys = []
        while delayTimer.getTime() > 0:
            #  Record any extra key presses during wait
            key = kb.getKeys()
            if key:
                quitExperimentIf(key[0].name == 'q')
                extraKeys.append(mainClock.getTime())
                trigger.send("BadResponse")

            core.wait(0.1)

        #######################
        # Stimulus presentation
Esempio n. 18
0
def testEvent(image, lure, tafc_time=4, reloc_time=6):
    # get location response
    object_im.setImage('images/' + image)
    lure_im.setImage('images/' + lure)

    # set the image locations
    tafc_xsep = 75

    target_left = random.choice([0, 1])
    if target_left == 1:
        object_im.setPos([-tafc_xsep, 0])
        lure_im.setPos([tafc_xsep, 0])
    else:
        object_im.setPos([tafc_xsep, 0])
        lure_im.setPos([-tafc_xsep, 0])

    # two-alternative forced choice (tafc)
    moveMouse(WINSIZE[0] / 2, WINSIZE[1] / 2)
    RT.reset()
    myMouse.clickReset()
    prompt.setText("TEST")
    tafc_choiceMade = False
    timer = core.CountdownTimer(tafc_time)
    win.setMouseVisible(True)
    while not tafc_choiceMade and timer.getTime() > 0:
        mouse1 = 0
        while mouse1 < 1 and timer.getTime() > 0:
            for key in event.getKeys():
                if key in [QUITKEY]:
                    core.quit()
            study_area.draw()
            prompt.draw()
            object_im.draw()
            lure_im.draw()
            win.flip()
            mouse_pos = myMouse.getPos()
            mouse1, mouse2, mouse3 = myMouse.getPressed()
            # wait for button to be released
            while myMouse.getPressed()[0] and timer.getTime() > 0:
                pass
        # was a valid response given?
        if abs(-tafc_xsep -
               mouse_pos[0]) < 50 and mouse_pos[1] < 50 and mouse1 > 0:
            resp_left = 1
            tafc_choiceMade = True
        elif abs(tafc_xsep -
                 mouse_pos[0]) < 50 and mouse_pos[1] < 50 and mouse1 > 0:
            resp_left = 0
            tafc_choiceMade = True
        else:  # valid choice wasnt made
            tafc_choiceMade = False
            mouse1 = 0
        if tafc_choiceMade == True:
            win.setMouseVisible(False)
            moveMouse(WINSIZE[0] / 2, WINSIZE[1] / 2)
            tafc_rt = RT.getTime()
            while timer.getTime() > 0:
                study_area.draw()
                win.flip()
    if not tafc_choiceMade:
        # if the time ran out
        tafc_rt = 'NA'
        resp_left = "NA"

    win.setMouseVisible(False)
    moveMouse(WINSIZE[0] / 2, WINSIZE[1] / 2)

    # if a choice was made set the chosen image
    if resp_left != "NA":
        if target_left != resp_left:  # they chose the lure...
            object_im.setImage('images/' + lure)

    if resp_left == "NA":  # if they didnt make a choice we have to remind them to respond faster
        prompt.setText("PLEASE RESPOND FASTER")
        prompt.setColor([1, -1, -1])
        prompt.draw()
        win.flip()
        core.wait(reloc_time)
        prompt.setColor(BACKGROUND)
        # add NAs to this part of the data
        reloc_rt = "NA"
        mouse_pos = ["NA", "NA"]
    else:
        # if they did make a response run the relocation part
        RT.reset()
        myMouse.clickReset()
        moveMouse(WINSIZE[0] / 2, WINSIZE[1] / 2)

        prompt.setText("TEST")
        choiceMade = False
        timer = core.CountdownTimer(reloc_time)
        while not choiceMade and timer.getTime() > 0:
            mouse1 = 0
            while mouse1 < 1 and timer.getTime() > 0:
                for key in event.getKeys():
                    if key in [QUITKEY]:
                        core.quit()

                mouse_pos = myMouse.getPos()
                object_im.setPos(mouse_pos)

                study_area.draw()
                fixation.draw()
                prompt.draw()
                # dont draw object if outside the valid area
                if numpy.sqrt((mouse_pos[0])**2 + (mouse_pos[1])**2) > 500:
                    pass
                else:
                    object_im.draw()
                win.flip()

                mouse1, mouse2, mouse3 = myMouse.getPressed()

                # wait for button to be released
                while myMouse.getPressed()[0] and timer.getTime() > 0:
                    pass
            # dont accept clicks outside the valid area
            if numpy.sqrt((mouse_pos[0])**2 + (mouse_pos[1])**2) > 500:
                choiceMade = False
                mouse1 = 0
            else:
                choiceMade = True
                reloc_rt = RT.getTime()
                while timer.getTime() > 0:
                    study_area.draw()
                    fixation.draw()
                    object_im.draw()
                    win.flip()
        if choiceMade == False:
            # if the time ran out
            reloc_rt = 'NA'

    return (mouse_pos, reloc_rt, target_left, resp_left, tafc_rt)
 def clock(self):
     # crate timers
     self.globalClock = core.Clock()
     self.routineTimer = core.CountdownTimer()
Esempio n. 20
0
    win=mywin,
    mask='circle',
    tex='saw',
    size=20,
    rgb=[1, 1, 1],
    pos=[0, 0],
    angularCycles=4,
    angularRes=3600,
    contrast=-1.0
)  #angularCycles are the number of black/white bars presented by the stimulus. Adult optimal is 12 angular cycles, larvae optimal is 16 angular cycles (See Table 1).
fixation = visual.GratingStim(win=mywin,
                              size=999,
                              pos=[0, 0],
                              sf=0,
                              rgb=[0.5, 0.5, 0.5])
timer = core.CountdownTimer(TIME)
#draw the stimuli and update the window. The phase is always advanced by 0.05 of a cycle.
while True:  #this creates a never-ending loop
    while timer.getTime() > 0:
        grating.setAngularPhase(SPEED, '-')
        grating.draw()
        mywin.flip()
        if len(event.getKeys()) > 0: sys.exit(0)
        event.clearEvents()
    timer.reset(TIME)
    while timer.getTime() > 0:
        fixation.draw()
        mywin.flip()
        if len(event.getKeys()) > 0: sys.exit(0)
        event.clearEvents()
    timer.reset(TIME)
Esempio n. 21
0
    middle_right = visual.Rect(win=win, units ="pix", width=70, height=370, fillColor=[0, 0, 0], lineColor=[0, 0, 0], pos=[230, 60])
    ring_right = visual.Rect(win=win, units ="pix", width=70, height=330, fillColor=[0, 0, 0], lineColor=[0, 0, 0], pos=[305, 40])
    pinky_right = visual.Rect(win=win, units ="pix", width=70, height=240, fillColor=[0, 0, 0], lineColor=[0, 0, 0], pos=[380, -5])

    thumb_left = visual.Rect(win=win, units ="pix", width=70, height=200, fillColor=[0, 0, 0], lineColor=[0, 0, 0], pos=[-80, -25])
    index_left = visual.Rect(win=win, units ="pix", width=70, height=330, fillColor=[0, 0, 0], lineColor=[0, 0, 0], pos=[-155, 40])
    middle_left = visual.Rect(win=win, units ="pix", width=70, height=370, fillColor=[0, 0, 0], lineColor=[0, 0, 0], pos=[-230, 60])
    ring_left = visual.Rect(win=win, units ="pix", width=70, height=330, fillColor=[0, 0, 0], lineColor=[0, 0, 0], pos=[-305, 40])
    pinky_left = visual.Rect(win=win, units ="pix", width=70, height=240, fillColor=[0, 0, 0], lineColor=[0, 0, 0], pos=[-380, -5])

    stimuli_cases = {'1': lambda : thumb_left, '2': lambda: index_left, '3': lambda: middle_left, '4': lambda: ring_left, '5': lambda: pinky_left, '6': lambda: thumb_right, '7': lambda: index_right, '8': lambda: middle_right, '9': lambda: ring_right, '10': lambda: pinky_right, 'REST': lambda: 'rest', 'FEET': lambda: 'feet', 'FACE': lambda: 'face'}
 
    # Start the timer
    trialClock = core.Clock()
    globalClock = core.Clock()
    routineTimer = core.CountdownTimer()
    logging.setDefaultClock(globalClock)
    
    # INIT
    fixation.setAutoDraw(True)
    win.flip()
    keys = event.waitKeys(keyList=ACCEPTED_KEYS)
    globalClock.reset()
    routineTimer.reset()
    routineTimer.add(BEGIN_TRIAL_DELAY)
    if ('escape' in keys):
        core.quit()
    while routineTimer.getTime()>0:
        continue
    for thisTrial in trials:
        finger = stimuli_cases[list(thisTrial.values())[0]]()
 def set_timer_duration(self, time_duration):
     self.has_timer = True
     self.routine_timer = core.CountdownTimer()
     self.routine_timer.add(time_duration)
    if thisResp == 1:
        CorrectResp = 1
    CorrectRT = 0
    if thisResp == 1:
        CorrectRT = RT

    dataFile.write('%i,%.2f,%s,%i,%0.3f,%0.4f,%0.4f\n' %
                   (TrialCount, NoiseOpacity, k[-1], CorrectResp,
                    globalClock.getTime(), RT, CorrectRT))

    CurrentTrial += 1
    # Check for an overall elapsed time and a total trial count
    # If either of these are exceeded, then end the experiment
    if len(staircase.data) > MaxTrials:
        # Thank you
        countDown = core.CountdownTimer()
        textThankyou.setAutoDraw(True)
        countDown.add(3)
        win.flip()
        while countDown.getTime() > 0:
            pass
        win.flip()

        win.close()
        EndFlag = 'MaxTrialsExceeded'
        dataFile.write('%s\n' % (EndFlag))
        Capacity = 1 - numpy.mean(staircase.reversalIntensities)
        dataFile1.write('%0.4f' % (Capacity))
        print
        print "Ending because the maximum number of trials was reached."
        print
Esempio n. 24
0
    def start_experiment(self):
        global currentrewardlocation
        global angle_desired

        """ Display a reward location and start timer"""
        while self._currenttrial < self.numtrials:
            
        
            print ('Trial %d beginning...' % self._currenttrial)
            
            
            currentreward = np.random.choice(len(self.rewardlocation), 1)
            currentrewardlocation = self.rewardlocation.iloc[currentreward]
            
            small_rotation=atan(abs(currentrewardlocation['y1']-currentrewardlocation['y2']) / abs(currentrewardlocation['x1']-currentrewardlocation['x2']))
            #print (currentrewardlocation['y1'],currentrewardlocation['y2'],currentrewardlocation['x1'],currentrewardlocation['x2'])
            #print (small_rotation)
            if (int(currentrewardlocation['y1']-currentrewardlocation['y2'])<=0) & (int(currentrewardlocation['x1']-currentrewardlocation['x2'])<=0):
                
                angle_desired=2*pi-small_rotation
                
            elif (int(currentrewardlocation['y1']-currentrewardlocation['y2'])>=0) & (int(currentrewardlocation['x1']-currentrewardlocation['x2'])>=0):
                angle_desired=pi-small_rotation
            
            elif (int(currentrewardlocation['y1']-currentrewardlocation['y2'])<=0) & (int(currentrewardlocation['x1']-currentrewardlocation['x2'])>=0):
                
                angle_desired=pi+small_rotation
                
            else:
                angle_desired=small_rotation
                
           
                    
            # Start trial - show reward
            print ('Go to reward location (%d, %d)' % (currentrewardlocation['x1'], currentrewardlocation['y1']))
            
           
            self.plotrewardlocation(currentrewardlocation)

            # Set up plot for realtime plotting
            cv2.namedWindow('Trial %d Reward' % self._currenttrial, cv2.WINDOW_NORMAL)
            cv2.resizeWindow('Trial %d Reward' % self._currenttrial, 800, 800)

            
            # Start timer for reward timeout
            
            timer = core.CountdownTimer(self.rewardtimeout)
            abstime = core.MonotonicClock()
            
            
            found=0
            check_duration=0
        
            elapsedtime = abstime.getTime()
            os.system('play -n synth %s sin %s' % (0.5, frequency))
            self.realtime_elapsedtime(rewardloc=currentrewardlocation,
                                          elapsedtime=elapsedtime, robotloc=(int(loc_x_rotate),int(loc_y_rotate)),foundOrNot=found)
            while (timer.getTime() > 0) & (found==0):
               
               #subcribe to robot location,joy and laser scan data
                rospy.Subscriber("/amcl_pose", PoseWithCovarianceStamped, get_xy_loc)
                #rospy.Subscriber("joy", Joy, processjoy)
                #rospy.Subscriber("/base_scan", LaserScan, LaserData)

                # Print elapsed time on map and console
                elapsedtime = abstime.getTime()
                self.realtime_elapsedtime(rewardloc=currentrewardlocation,
                                          elapsedtime=elapsedtime, robotloc=(int(loc_x_rotate),int(loc_y_rotate)),foundOrNot=found)
                
                
                #print "\033[K Elapsed Time : ", elapsedtime, "\r",
                sys.stdout.flush()
                
                #if(abs(int(loc_x_rotate) - int(currentrewardlocation['x1']))<30) & (abs(int(loc_y_rotate) - int(currentrewardlocation['y1']))<30):
                #if ((abs(int(loc_x) - int(currentrewardlocation['x']))<40) & (abs(int(loc_y) - int(currentrewardlocation['y']))<40) & (abs(orien_z-self.orientation)<0.333)):
                    #print (abs(int(loc_x) - int(currentrewardlocation['x'])))
                if (abs(int(loc_x_rotate) - int(currentrewardlocation['x1']))<self.position_tolerance) & (abs(int(loc_y_rotate) - int(currentrewardlocation['y1']))<self.position_tolerance) & (abs(angle_desired-angle_current)<self.angle_tolerance) :   
                    check_duration = check_duration + 1
                    #print ('duration %d' %check_duration)
            
                    if (check_duration==self.stay_duration):
                        found=1
                        self.realtime_elapsedtime(rewardloc=currentrewardlocation,
                                          elapsedtime=elapsedtime, robotloc=(int(loc_x_rotate),int(loc_y_rotate)),foundOrNot=found)
                        
                        for x in range(0, 6):
                            
                            os.system('play -n synth %s sin %s' % (0.2, frequency))

                            time.sleep(.2)
                        print('\n Trial Ended; Target %s Found' % self._currenttrial)
                        break
                
                else:
                    check_duration=0
                  


            if(found==0):
                print('\n Trial Ended; Time Out')
                self.realtime_elapsedtime(rewardloc=currentrewardlocation,
                                          elapsedtime=elapsedtime, robotloc=(int(loc_x_rotate),int(loc_y_rotate)),foundOrNot=2)
                for x in range(0, 12): 
                    os.system('play -n synth %s sin %s' % (0.15, (frequency-x*100)))
                    
            cv2.destroyAllWindows()
            self.updatetrial()  # Trial ended - start of next trial
Esempio n. 25
0
text_1 = visual.TextStim(win,
                         text=u'',
                         height=48,
                         font='Hei',
                         pos=(0.0, 0.0),
                         color='white')
text_1.text = u'欢迎参加心理学实验!'

# 呈现指导语刺激
text_1.draw()
win.flip()
core.wait(0)
k_1 = event.waitKeys()

# 倒计时时钟
dtimer = core.CountdownTimer(4)
while dtimer.getTime() > 0:
    text_1.text = str(int(dtimer.getTime()))
    text_1.draw()
    win.flip()

# 随机刺激材料
pic_list = []
pic_ims = glob.glob("/Users/zapp/Downloads/daily-download.ZAPP.com/exp/*.jpg")
for image in pic_ims:
    pic_list.append(image)
random.shuffle(pic_list)

Word_list = [
    '幽雅', '无私', '正义', '端庄', '富丽', '苦闷', '郁闷', '自卑', '偏见', '新颖', '天使', '虚伪',
    '乞丐', '疾病', '宽厚', '高贵', '焦躁', '疲倦', '细菌', '雅致', '坦诚', '压力', '精品', '懒惰'
def digitSpanTask(experimentStructure, stimuliStructure, globalClock, filename, myGoal, backward, dspanCond):
    """ This function implements a digit-span task
    
        Input:
            experimentStructure: all general experimental properties 
            stimuliStructure: all general stimulus properties
            globalClock: clock to control timing during fMRI
            filename: not used anymore
            myGoal: indicates how many digits have to be remembered in current trial
            backward: indicates if forward or backward condition is used
            dspanCond: condition string for data logging
        
        Return:
            routineTimer:  timer to control presentation times
            globalClock: clock to control timing during fMRI
            fixCrossTiming: actual presentation time of fixation cross during digit span phase
            corrRep: indicats if correct responses have been given
    
    """
    
    # Create some shortnames
    expInfo         = experimentStructure['expInfo']
    thisExp         = experimentStructure['thisExp']
    win             = experimentStructure['win']
    NOT_STARTED     = experimentStructure['NOT_STARTED']
    STARTED         = experimentStructure['STARTED']
    FINISHED        = experimentStructure['FINISHED']
    endExpNow       = experimentStructure['endExpNow']
    event           = experimentStructure['event']
    win             = experimentStructure['win']
    fixationCross   = stimuliStructure['fixationCross']
    fixCrossTiming  = stimuliStructure['fixCrossTiming']
    jitter          = stimuliStructure['jitter']
    stimulusTiming  = stimuliStructure['stimulusTiming']
    feedbackClock   = stimuliStructure['feedbackClock']
    
    _thisDir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(_thisDir)

    myD     = 0
    corrRep = []
    while True: 
        blockIndex = 'blockFiles/digit-span/digit-span.xlsx'
        routineTimer    = core.CountdownTimer()
        (feedbackClock, feedbackText)  = initializeFeedback(win, expInfo)
        text = feedbackText
        
        # Set up handler to look after randomisation of conditions etc
        N_Back = data.TrialHandler(nReps = 1, method = 'random', 
            extraInfo = None, originPath = -1,
            trialList = data.importConditions(blockIndex),
            seed = None, autoLog = False) 
            
        thisTrial = N_Back.trialList[0]  # so we can initialise stimuli with some values
        if thisTrial != None:
                for paramName in thisTrial.keys():
                    exec(paramName + '= thisTrial.' + paramName)

        myCount         = 0
        presentedDigits = []
        while True: 
         
            thisTrial = N_Back.next()
            
            # Abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
            if thisTrial != None:
                for paramName in thisTrial.keys():
                    exec(paramName + '= thisTrial.' + paramName)
         
            presentedDigits.append(thisTrial.stim)
            
            (N_Back, decision1, thisExp, thisTrial, miss) = runDigitSpan(experimentStructure, stimuliStructure, globalClock, filename, routineTimer, text, stim, N_Back,thisExp, thisTrial)

            myCount = myCount + 1
            if (myCount) == myGoal:
                break
            
        endExpNow = False  # flag for 'escape' or other condition => quit the exp

        # Initialize components for Routine "trial"
        trialClock = core.Clock()
        if backward == False:
            Question = visual.TextStim(win=win, name='Question',
                text='Welche Zahlen wurden angezeigt (vorwärts)?',
                font='Arial',
                pos=[0, 0.6], height=0.1, wrapWidth=1.5, ori=0, 
                color='white', colorSpace='rgb', opacity=1,
                depth=0.0, units = 'norm');
        elif backward == True:
            Question = visual.TextStim(win=win, name='Question',
                text='Welche Zahlen wurden angezeigt (rückwärts)?',
                font='Arial',
                pos=[0, 0.6], height=0.1, wrapWidth=1.5, ori=0, 
                color='white', colorSpace='rgb', opacity=1,
                depth=0.0, units = 'norm');
            
        AnswerDisplay = visual.TextStim(win=win, name='AnswerDisplay',
            text='default text',
            font='Arial',
            pos=[0, 0], height=0.1, wrapWidth=None, ori=0, 
            color=[-1.000,-1.000,-1.000], colorSpace='rgb', opacity=1,
            depth=-3.0, units = 'norm');

        # 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 

        # Set up handler to look after randomisation of conditions etc
        trials = data.TrialHandler(nReps=1, method='random', 
            extraInfo=expInfo, originPath=-1,
            trialList=[None],
            seed=None, name='trials')
        thisExp.addLoop(trials)  # add the loop to the experiment
        thisTrial = trials.trialList[0]  # so we can initialise stimuli with some values
        
        # Abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
        if thisTrial != None:
            for paramName in thisTrial.keys():
                exec(paramName + '= thisTrial.' + paramName)

        for thisTrial in trials:
            currentLoop = trials
            
            # Abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
            if thisTrial != None:
                for paramName in thisTrial.keys():
                    exec(paramName + '= thisTrial.' + paramName)
            
            # ------Prepare to start Routine "trial"-------
            t = 0
            trialClock.reset()  # clock
            frameN = -1
            continueRoutine = True
            # Update component parameters for each repeat
            AnswerFinished = event.BuilderKeyResponse()
            RecordAnswer = event.BuilderKeyResponse()
            AnswerDisplay.setText(RecordAnswer.keys)
            
            # Keep track of which components have finished
            trialComponents = [Question, AnswerFinished, RecordAnswer, AnswerDisplay]
            for thisComponent in trialComponents:
                if hasattr(thisComponent, 'status'):
                    thisComponent.status = NOT_STARTED
            
            # -------Start Routine "trial"-------
            while continueRoutine:
                # 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
                
                # *Question* updates
                if t >= 0.0 and Question.status == NOT_STARTED:
                    # Keep track of start time/frame for later
                    Question.tStart = t
                    Question.frameNStart = frameN  # exact frame index
                    Question.setAutoDraw(True)
                
                # *AnswerFinished* updates
                if t >= 0.0 and AnswerFinished.status == NOT_STARTED:
                    # Keep track of start time/frame for later
                    AnswerFinished.tStart = t
                    AnswerFinished.frameNStart = frameN  # exact frame index
                    AnswerFinished.status = STARTED
                    # Keyboard checking is just starting
                    win.callOnFlip(AnswerFinished.clock.reset)  # t=0 on next screen flip
                    event.clearEvents(eventType='keyboard')
                if AnswerFinished.status == STARTED:
                    theseKeys = event.getKeys(keyList=['return'])
                    
                    # check for quit:
                    if "escape" in theseKeys:
                        endExpNow = True
                    if len(theseKeys) > 0:  # at least one key was pressed
                        AnswerFinished.keys = theseKeys[-1]  # just the last key pressed
                        AnswerFinished.rt = AnswerFinished.clock.getTime()
                        # a response ends the routine
                        continueRoutine = False
                
                # *RecordAnswer* updates
                if t >= 0.0 and RecordAnswer.status == NOT_STARTED:
                    # Keep track of start time/frame for later
                    RecordAnswer.tStart = t
                    RecordAnswer.frameNStart = frameN  # exact frame index
                    RecordAnswer.status = STARTED
                    # Keyboard checking is just starting
                    win.callOnFlip(RecordAnswer.clock.reset)  # t=0 on next screen flip
                    event.clearEvents(eventType='keyboard')
                if RecordAnswer.status == STARTED:
                    theseKeys = event.getKeys(keyList=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
                    
                    # check for quit:
                    if "escape" in theseKeys:
                        endExpNow = True
                    if len(theseKeys) > 0:  # at least one key was pressed
                        RecordAnswer.keys.extend(theseKeys)  # storing all keys
                        RecordAnswer.rt.append(RecordAnswer.clock.getTime())
                
                # *AnswerDisplay* updates
                if t >= 0.0 and AnswerDisplay.status == NOT_STARTED:
                    # keep track of start time/frame for later
                    AnswerDisplay.tStart = t
                    AnswerDisplay.frameNStart = frameN  # exact frame index
                    AnswerDisplay.setAutoDraw(True)
                displaystring=" ".join(RecordAnswer.keys) #convert list of pressed keys to string
                displaystring=displaystring.replace(' ','') #remove intermediate spaces
                
                # Do some text cleanup...replacing key names with puntuation and effectively disabling keys like 'back','shift', etc.
                displaystring=displaystring.replace('space',' ') 
                displaystring=displaystring.replace('comma',',')
                displaystring=displaystring.replace('lshift','')
                displaystring=displaystring.replace('rshift','')
                displaystring=displaystring.replace('period','.')
                displaystring=displaystring.replace('back','')
                
                # Set text of AnswerDisplay to modified string
                AnswerDisplay.setText(displaystring)
                
                # 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
                
                # Check for quit (the Esc key)
                if endExpNow or event.getKeys(keyList=["escape"]):
                    core.quit()
                
                # Check for delete
                if endExpNow or event.getKeys(keyList=["backspace"]):
                    if len(RecordAnswer.keys) > 0:
                        RecordAnswer.keys.pop(-1)
                    
                # Refresh the screen
                if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
                    win.flip()
            
            # -------Ending Routine "trial"-------
            for thisComponent in trialComponents:
                if hasattr(thisComponent, "setAutoDraw"):
                    thisComponent.setAutoDraw(False)
            
            # Check response
            if len(presentedDigits) == len(RecordAnswer.keys):
                new_list = []
                for i in range (0,len(presentedDigits)):
                    if backward == False:
                        if str(presentedDigits[i]) == RecordAnswer.keys[i]:
                            new_list.append(1)
                    elif backward == True:
                        
                        if str(presentedDigits[-i-1]) == RecordAnswer.keys[i]:
                            new_list.append(1)
                        
                if sum(new_list) == len(presentedDigits):
                    corrRep.append(1)
                    
            # Check responses
            if AnswerFinished.keys in ['', [], None]:  # No response was made
                AnswerFinished.keys=None
            trials.addData('AnswerFinished.keys',AnswerFinished.keys)
            if AnswerFinished.keys != None:  # we had a response
                trials.addData('AnswerFinished.rt', AnswerFinished.rt)
            
            # Check responses
            if RecordAnswer.keys in ['', [], None]:  # No response was made
                RecordAnswer.keys=None
            trials.addData('RecordAnswer.keys',RecordAnswer.keys)
            if RecordAnswer.keys != None:  # we had a response
                trials.addData('RecordAnswer.rt', RecordAnswer.rt)
            trials.addData('RecordAnswer.keys',displaystring)
            trials.addData('corrRep', corrRep)
            trials.addData('dspanCond', dspanCond)
            trials.addData('dspan', myGoal-1)
            trials.addData('stim', presentedDigits)

            # The Routine "trial" was not non-slip safe, so reset the non-slip timer
            routineTimer.reset()
            
            # Start next trial
            thisExp.nextEntry()
        
        # Update digit span estimate
        myD = myD + 1
        if (myD) == 2:
            break
    
    return(routineTimer, globalClock, fixCrossTiming, corrRep)
Esempio n. 27
0
def presTrialAudSchweb(i):

    #transfer info for this trial from design mat
    SclFeedback = design_mat[i, 2]
    SclMaxForce = design_mat[i, 0]
    DurJitter = design_mat[i, 3]

    #present trial intrsuctions
    out_marker.push_sample(['epoch_ao_start'])  # send scaling factor
    presTextPsychoPy("Nur auditiv")
    core.wait(dur_hint)

    # start baseline
    out_marker.push_sample(['baseline'])
    presTextPsychoPy(" ")
    core.wait(dur_bl)

    # reset trial timer
    timer.reset()
    countdownTimer = core.CountdownTimer(dur_trial)

    # draw fixation cross
    fixation.draw()
    win.flip()
    out_marker.push_sample(['fix_cross'])  # output to lsl
    core.wait(DurJitter)

    tar_force = max_force * SclMaxForce

    # reset input buffer from serial port
    SerialArduino.reset_input_buffer()
    ArdBuff = []

    # send scaling factor to lsl
    out_marker.push_sample([
        'trial_start_sfb_{}_sfc_{}'.format(SclFeedback, SclMaxForce)
    ])  # send scaling factor
    sent2PD(schweb_vol, 1)
    sent2PD(schweb_pitch, 0)  # inital tone for PD

    # update autodraw
    bar_target.autoDraw = True

    # init for LSL data
    start_time = local_clock()
    sent_samples = 0
    current_force = 0

    c_flush = 0
    while countdownTimer.getTime(
    ) + DurJitter > 0:  # add jitter to trial duration

        elapsed_time = local_clock() - start_time
        required_samples = int(
            80 * elapsed_time) - sent_samples  # possible sampling rate of 80Hz

        if required_samples > 0:

            tmp = SerialArduino.readline().rstrip()  # read from serial port

            if not tmp:  # continue to next iteration if buffer is empty
                tmp = current_force
            else:
                try:
                    current_force = float(tmp)
                except ValueError:
                    current_force = current_force

            if c_flush % clr_buf == 0:  # flush buffer every 10 runs for no overhead
                SerialArduino.reset_input_buffer()

            # get a time stamp in seconds and add hardware time difference 5ms
            stamp = local_clock() - 0.005
            # now send it and wait for a bit
            lc_out.push_chunk([current_force])
            sent_samples += required_samples

            tmp_x_pos = (
                (current_force - tar_force) / tar_force
            ) * SclFeedback  # offset inital bar placement, according to Archer ea., 2017
            sent2PD(schweb_pitch, tmp_x_pos)

            # update drawing of bars to automatic
            win.flip()

            # add to buffer for passive condition
            ArdBuff.append(current_force)
            TsBuff.append(stamp)

            c_flush += 1

    # stop autodraw
    bar_target.autoDraw = False

    out_marker.push_sample(['end_trial'])  # send 1 for start of fixation cross
    # Turn of DSP in PD
    sent2PD(schweb_vol, 0)

    TrialBuff[i] = ArdBuff
Esempio n. 28
0
def run4_func(expInfo):
    # main function
    # Ensure that relative paths start from the same directory as this script
    _thisDir = os.path.dirname(os.path.abspath(__file__)).decode(
        sys.getfilesystemencoding())
    os.chdir(_thisDir)

    # Store info about the experiment session
    expName = u'tnac_exp'  # from the Builder filename that created this script
    expInfo['expName'] = expName

    # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
    filename = _thisDir + os.sep + u'data/%s_%s_%s' % (
        expInfo['participant'], expName, expInfo['date'])

    trg_dict = {
        "music": 1,
        "voice": 2,
        "song": 3,
        "sound_off": 100,
        "pause_block": 200,
        "stop_run": 300,
        "start_run": 400,
        "start_block": 500,
    }

    #define path to csvs
    run_var = _thisDir + '/run4.csv'
    # An ExperimentHandler isn't essential but helps with data saving
    thisExp = data.ExperimentHandler(name=expName,
                                     version='',
                                     extraInfo=expInfo,
                                     runtimeInfo=None,
                                     originPath=None,
                                     savePickle=True,
                                     saveWideText=True,
                                     dataFileName=filename)
    # save a log file for detail verbose info
    logFile = logging.LogFile(filename + '.log', level=logging.EXP)
    logging.console.setLevel(
        logging.WARNING)  # this outputs to the screen, not a file

    endExpNow = False  # flag for 'escape' or other condition => quit the exp

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

    # Setup the Window
    ## TODO: set window to fullscreen
    win = visual.Window(size=[1366, 768],
                        fullscr=True,
                        screen=0,
                        allowGUI=True,
                        allowStencil=False,
                        monitor='testMonitor',
                        color=[0, 0, 0],
                        colorSpace='rgb',
                        blendMode='avg',
                        useFBO=True)
    # 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

    # Initialize components for Routine "trial"
    trialClock = core.Clock()
    stim_1 = sound.Sound('A', secs=-1)
    stim_1.setVolume(1)
    fix_1 = visual.TextStim(win=win,
                            name='fix_1',
                            text='+',
                            font='Arial',
                            pos=(0, 0),
                            height=0.1,
                            wrapWidth=None,
                            ori=0,
                            color='white',
                            colorSpace='rgb',
                            opacity=1,
                            depth=-1.0)

    # Initialize components for Routine "run_start"
    run_startClock = core.Clock()
    run_start_msg_screen = visual.TextStim(win=win,
                                           name='run_start_msg_screen',
                                           text=u'Kurze Pause.',
                                           font='Arial',
                                           units='norm',
                                           pos=[0, 0],
                                           height=0.12,
                                           wrapWidth=2,
                                           ori=0,
                                           color='white',
                                           colorSpace='rgb',
                                           opacity=1,
                                           depth=0.0)

    # Initialize components for Routine "run_trigger_sync"
    StartClock = core.Clock()
    run_trigger_syncClock = core.Clock()
    run_start_msg = visual.TextStim(win=win,
                                    name='run_start_msg',
                                    text='Durchgang beginnt!',
                                    font='Arial',
                                    units='norm',
                                    pos=[0, 0],
                                    height=0.15,
                                    wrapWidth=2,
                                    ori=0,
                                    color='white',
                                    colorSpace='rgb',
                                    opacity=1,
                                    depth=-1.0)
    movie = visual.MovieStim3(
        win=win,
        name='movie',
        units='pix',
        noAudio=True,
        # rename path
        filename='C:\Paradigmen\AG_Brain\Peer\TNAC\movies\mov4.mkv',
        ori=0,
        pos=(0, 0),
        opacity=1,
        depth=0.0,
    )

    # 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

    block_delay = [4, 5, 6] * 12
    random.shuffle(block_delay)
    #print(block_delay)
    # ------Prepare to start Routine "run_start"-------
    t = 0
    run_startClock.reset()  # clock
    frameN = -1
    continueRoutine = True
    # update component parameters for each repeat
    run_start_trigger_key = event.BuilderKeyResponse()
    # keep track of which components have finished
    run_startComponents = [run_start_msg_screen, run_start_trigger_key]
    for thisComponent in run_startComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    # -------Start Routine "run_start"-------
    while continueRoutine:
        # get current time
        t = run_startClock.getTime()
        thisExp.addData('start_run', globalClock.getTime())
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *run_start_msg_screen* updates
        if t >= 0.0 and run_start_msg_screen.status == NOT_STARTED:
            # keep track of start time/frame for later
            run_start_msg_screen.tStart = t
            run_start_msg_screen.frameNStart = frameN  # exact frame index
            run_start_msg_screen.setAutoDraw(True)

        # *run_start_trigger_key* updates
        if t >= 0.0 and run_start_trigger_key.status == NOT_STARTED:
            # keep track of start time/frame for later
            run_start_trigger_key.tStart = t
            run_start_trigger_key.frameNStart = frameN  # exact frame index
            run_start_trigger_key.status = STARTED
            # keyboard checking is just starting
            event.clearEvents(eventType='keyboard')
        if run_start_trigger_key.status == STARTED:
            theseKeys = event.getKeys(keyList=['s'])

            # check for quit:
            if "escape" in theseKeys:
                endExpNow = True
            if len(theseKeys) > 0:  # at least one key was pressed
                # a response ends the routine
                continueRoutine = False

        # 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 run_startComponents:
            if hasattr(thisComponent,
                       "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

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

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

    # -------Ending Routine "run_start"-------
    for thisComponent in run_startComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # the Routine "run_start" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

    # ------Prepare to start Routine "run_trigger_sync"-------
    t = 0
    run_trigger_syncClock.reset()  # clock
    frameN = -1
    continueRoutine = True
    # update component parameters for each repeat
    run_trigger_sync_ = event.BuilderKeyResponse()

    # keep track of which components have finished
    run_trigger_syncComponents = [run_trigger_sync_, run_start_msg]
    for thisComponent in run_trigger_syncComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    # -------Start Routine "run_trigger_sync"-------
    while continueRoutine:
        # get current time
        print('waiting for scanner trigger....')
        t = run_trigger_syncClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *run_trigger_sync_* updates
        if t >= 0.0 and run_trigger_sync_.status == NOT_STARTED:
            # keep track of start time/frame for later
            run_trigger_sync_.tStart = t
            run_trigger_sync_.frameNStart = frameN  # exact frame index
            run_trigger_sync_.status = STARTED
            # keyboard checking is just starting
            win.callOnFlip(
                run_trigger_sync_.clock.reset)  # t=0 on next screen flip
            event.clearEvents(eventType='keyboard')
        if run_trigger_sync_.status == STARTED:
            theseKeys = event.getKeys(keyList=['t'])

            # check for quit:
            if "escape" in theseKeys:
                endExpNow = True
            if len(theseKeys) > 0:  # at least one key was pressed
                run_trigger_sync_.keys = theseKeys[
                    -1]  # just the last key pressed
                run_trigger_sync_.rt = run_trigger_sync_.clock.getTime()
                # a response ends the routine
                continueRoutine = False

        # *run_start_msg* updates
        if t >= 0.0 and run_start_msg.status == NOT_STARTED:
            # keep track of start time/frame for later
            run_start_msg.tStart = t
            run_start_msg.frameNStart = frameN  # exact frame index
            run_start_msg.setAutoDraw(True)
        frameRemains = 0.0 + 5 - win.monitorFramePeriod * 0.75  # most of one frame period left
        if run_start_msg.status == STARTED and t >= frameRemains:
            run_start_msg.setAutoDraw(False)

        # 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 run_trigger_syncComponents:
            if hasattr(thisComponent,
                       "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

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

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

    # -------Ending Routine "run_trigger_sync"-------
    for thisComponent in run_trigger_syncComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    # check responses
    if run_trigger_sync_.keys in ['', [], None]:  # No response was made
        run_trigger_sync_.keys = None
    thisExp.addData('run_trigger_sync_.keys', run_trigger_sync_.keys)
    if run_trigger_sync_.keys != None:  # we had a response
        thisExp.addData('run_trigger_sync_.rt', run_trigger_sync_.rt)
    run_start_timestamp = StartClock.getTime()

    send_trigger(400)
    # the Routine "run_trigger_sync" was not non-slip safe, so reset the non-slip timer
    routineTimer.reset()

    start_delay = False
    delay_counter = 0
    #print(block_delay)
    #print(delay_counter)
    # start movie for whole run (loop over trials)
    mov = 'movies/mov4.mkv'
    #print(mov)
    movie.setMovie(mov)
    if t >= 0.0 and movie.status == NOT_STARTED:
        # keep track of start time/frame for later
        movie.tStart = t
        movie.frameNStart = frameN  # exact frame index
        movie.setAutoDraw(True)
        frameRemains = 0.0 + 2 - win.monitorFramePeriod * 0.75  # most of one frame period left

        # set up handler to look after randomisation of conditions etc
        trials = data.TrialHandler(nReps=1,
                                   method='sequential',
                                   extraInfo=expInfo,
                                   originPath=-1,
                                   trialList=data.importConditions(run_var),
                                   seed=None,
                                   name='trials')
        thisExp.addLoop(trials)  # add the loop to the experiment
        thisTrial = trials.trialList[
            0]  # so we can initialise stimuli with some values
        # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
        if thisTrial != None:
            for paramName in thisTrial.keys():
                exec(paramName + '= thisTrial.' + paramName)
        stimuli_played = 0

        for thisTrial in trials:
            currentLoop = trials
            # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
            if thisTrial != None:
                for paramName in thisTrial.keys():
                    exec(paramName + '= thisTrial.' + paramName)

            # ------Prepare to start Routine "trial"-------
            t = 0
            trialClock.reset()  # clock
            frameN = -1
            continueRoutine = True

            routineTimer.add(2.000000)
            # update component parameters for each repeat
            stim_1.setSound(stimuli, secs=2)
            #read stimuli into dict and set port value
            abc = stimuli.split('/')[0]
            trg = trg_dict.get(abc, 100)
            # keep track of which components have finished
            trialComponents = [stim_1, fix_1]
            for thisComponent in trialComponents:
                if hasattr(thisComponent, 'status'):
                    thisComponent.status = NOT_STARTED

            # -------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 stim_1
                if t >= 0.0 and stim_1.status == NOT_STARTED:
                    # keep track of start time/frame for later
                    stim_1.tStart = t
                    stim_1.frameNStart = frameN  # exact frame index

                    ## TODO reinstate: send_trigger(abc)
                    #print(abc)
                    stim_1.play(
                    )  # start the sound (it finishes automatically)
                    send_trigger(trg)  # send block specific trigger
                    # get time for stimuls start
                    thisExp.addData('stimulus_start_global',
                                    globalClock.getTime())
                    thisExp.addData('stimulus_start_routineTimer',
                                    routineTimer.getTime())
                    thisExp.addData('stimulus_start_', frameN)
                    #print(stim_1)
                    stimuli_played += 1
                    if stimuli_played % 5 == 0:
                        start_delay = True
                    #print('stimuli_nr:'+str(stimuli_played))

                frameRemains = 0.0 + 1.5 - win.monitorFramePeriod * 0.75  # most of one frame period left
                #frameRemainsdelay = 0.0 + 1.5- win.monitorFramePeriod * 0.75  # most of one frame period left
                if stim_1.status == STARTED and t >= frameRemains:
                    stim_1.stop()  # stop the sound (if longer than duration)
                    send_trigger(100)  # send sound off trigger
                    # get info on stim end
                thisExp.addData('stimulus_end_global', globalClock.getTime())
                thisExp.addData('stimulus_end_routineTimer',
                                routineTimer.getTime())

                # add delay intervall after 5 stimuli
                if stimuli_played % 5 == 0 and start_delay and delay_counter != 35:
                    send_trigger(200)
                    delay = block_delay[delay_counter]
                    routineTimer.add(block_delay[delay_counter])
                    #frameRemainsdelay = 0.0 + 1.5 + delay - win.monitorFramePeriod * 0.75  # most of one frame period left
                    #print('delay='+str(delay_counter))
                    delay_counter += 1
                    thisExp.addData('delay_counter',
                                    block_delay[delay_counter])
                    thisExp.addData('block_end_global', globalClock.getTime())
                    start_delay = False

                if stim_1.status == STARTED and t >= frameRemains:
                    stim_1.stop()  # stop the sound (if longer than duration)
                    send_trigger(100)  # send sound off trigger
                    # get info on stim end
                thisExp.addData('stimulus_end_global', globalClock.getTime())
                thisExp.addData('stimulus_end_routineTimer',
                                routineTimer.getTime())

                # 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

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

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

            stim_1.stop()  # ensure sound has stopped at end of routine
            thisExp.nextEntry()

            # completed 1 repeats of 'trials'

        thisExp.nextEntry()

        # completed 1 repeats of 'block'

    if stimuli_played == 180:
        movie.setAutoDraw(False)
        send_trigger(300)  # END RUN
        thisExp.saveAsWideText(filename + 'run4' + '.csv')
        thisExp.saveAsPickle(filename + 'run4')
        logging.flush()
        # make sure everything is closed down
        thisExp.abort()  # or data files will save again on exit
        win.close()
very_ = visual.TextStim(win=win,
                        name='very_',
                        text='Positive',
                        font='Arial',
                        pos=(0.45, -0.4),
                        height=0.07,
                        wrapWidth=None,
                        ori=0,
                        color='white',
                        colorSpace='rgb',
                        opacity=1,
                        depth=-5.0)

# 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

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(
    nReps=1,
    method='sequential',
    extraInfo=expInfo,
    originPath=-1,
    trialList=data.importConditions('SharedRewardPost.csv'),
    seed=None,
    name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
thisTrial = trials.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
Esempio n. 30
0
                           mask=None,
                           ori=0,
                           pos=[0, 0],
                           size=[1.2, 1.2],
                           color=[1, 1, 1],
                           colorSpace='rgb',
                           opacity=1,
                           flipHoriz=False,
                           flipVert=False,
                           texRes=128,
                           interpolate=True,
                           depth=0.0)

# 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 "Image"-------
t = 0
ImageClock.reset()  # clock
frameN = -1

# update component parameters for each repeat
key_resp_10 = event.BuilderKeyResponse(
)  # create an object of type KeyResponse
key_resp_10.status = NOT_STARTED
# keep track of which components have finished
ImageComponents = []
ImageComponents.append(image)
ImageComponents.append(key_resp_10)
for thisComponent in ImageComponents:
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED