예제 #1
0
    #print(interframeIntervals)
    frameTimeTolerance = .3  #proportion longer than refreshRate that will not count as a miss
    longFrameLimit = np.round(1000 / refreshRate * (1.0 + frameTimeTolerance),
                              2)
    idxsInterframeLong = np.where(interframeIntervals > longFrameLimit)[
        0]  #frames that exceeded 150% of expected duration
    numCasesInterframeLong = len(idxsInterframeLong)
    if numCasesInterframeLong > 0:
        print(numCasesInterframeLong, 'frames of', trialFrames,
              'were longer than',
              str(1000 / refreshRate * (1.0 + frameTimeTolerance)))
    return numCasesInterframeLong


##Set up stimuli
stimulus = visual.Circle(myWin, radius=.2, fillColor=(1, 1, 1))
nDots = 24

radius = 4
center = (0, 0)
sameEachTime = True
#(nDots, radius, center, stimulusObject, sameEachTime = True)
stimuli = drawStimuli(nDots, radius, center, stimulus, sameEachTime)
#print(stimuli)
#print('length of stimuli object', len(stimuli))

######Create visual objects, noise masks, response prompts etc. ###########
######Draw your stimuli here if they don't change across trials, but other parameters do (like timing or distance)
######If you want to automate your stimuli. Do it in a function below and save clutter.
######For instance, maybe you want random pairs of letters. Write a function!
###########################################################################
예제 #2
0
    def _createStim(self):
        """
            outer_diameter: 35
            outer_stroke_width: 5
            outer_fill_color: [255,255,255]
            outer_line_color: [255,255,255]
            inner_diameter: 5
            inner_stroke_width: 0
            inner_color: [0,0,0]
            inner_fill_color: [0,0,0]
            inner_line_color: [0,0,0]        
            calibration_prefs=self._eyetrackerinterface.getConfiguration()['calibration']['target_attributes']
        """
        coord_type = self._eyetrackerinterface._display_device.getCoordinateType(
        )
        calibration_prefs = self._eyetrackerinterface.getConfiguration(
        )['calibration']['target_attributes']
        self.calibrationPointOUTER = visual.Circle(
            self.window,
            pos=(0, 0),
            lineWidth=calibration_prefs['outer_stroke_width'],
            radius=calibration_prefs['outer_diameter'] / 2.0,
            name='CP_OUTER',
            fillColor=calibration_prefs['outer_fill_color'],
            lineColor=calibration_prefs['outer_line_color'],
            fillColorSpace='rgb255',
            lineColorSpace='rgb255',
            opacity=1.0,
            interpolate=False,
            edges=64,
            units=coord_type)

        self.calibrationPointINNER = visual.Circle(
            self.window,
            pos=(0, 0),
            lineWidth=calibration_prefs['inner_stroke_width'],
            radius=calibration_prefs['inner_diameter'] / 2.0,
            name='CP_INNER',
            fillColor=calibration_prefs['inner_fill_color'],
            lineColor=calibration_prefs['inner_line_color'],
            fillColorSpace='rgb255',
            lineColorSpace='rgb255',
            opacity=1.0,
            interpolate=False,
            edges=64,
            units=coord_type)

        instuction_text = "Press SPACE to Start Calibration; ESCAPE to Exit."
        self.textLineStim = visual.TextStim(self.window,
                                            text=instuction_text,
                                            pos=self.TEXT_POS,
                                            height=self.TEXT_HEIGHT,
                                            color=self.TEXT_COLOR,
                                            colorSpace='rgb255',
                                            alignHoriz='center',
                                            alignVert='center',
                                            units='pix',
                                            wrapWidth=self.width * 0.9)

        # create Tobii eye position feedback graphics
        #
        sw, sh = self.screenSize
        self.hbox_bar_length = hbox_bar_length = sw / 4
        hbox_bar_height = 6
        marker_diameter = 7
        self.marker_heights = (-sh / 2.0 * .7, -sh / 2.0 * .75, -sh / 2.0 * .8,
                               -sh / 2.0 * .7, -sh / 2.0 * .75, -sh / 2.0 * .8)

        bar_vertices = [-hbox_bar_length / 2, -hbox_bar_height / 2
                        ], [hbox_bar_length / 2, -hbox_bar_height / 2
                            ], [hbox_bar_length / 2, hbox_bar_height / 2
                                ], [-hbox_bar_length / 2, hbox_bar_height / 2]

        self.feedback_resources = psychopy.iohub.OrderedDict()

        self.feedback_resources['hbox_bar_x'] = visual.ShapeStim(
            win=self.window,
            lineColor='White',
            fillColor='Firebrick',
            vertices=bar_vertices,
            pos=(0, self.marker_heights[0]))
        self.feedback_resources['hbox_bar_y'] = visual.ShapeStim(
            win=self.window,
            lineColor='White',
            fillColor='DarkSlateGray',
            vertices=bar_vertices,
            pos=(0, self.marker_heights[1]))
        self.feedback_resources['hbox_bar_z'] = visual.ShapeStim(
            win=self.window,
            lineColor='White',
            fillColor='GoldenRod',
            vertices=bar_vertices,
            pos=(0, self.marker_heights[2]))

        marker_vertices = [-marker_diameter,
                           0], [0,
                                marker_diameter], [marker_diameter,
                                                   0], [0, -marker_diameter]
        self.feedback_resources['left_hbox_marker_x'] = visual.ShapeStim(
            win=self.window,
            lineColor='White',
            fillColor='Black',
            vertices=marker_vertices,
            pos=(0, self.marker_heights[0]))
        self.feedback_resources['left_hbox_marker_y'] = visual.ShapeStim(
            win=self.window,
            lineColor='White',
            fillColor='Black',
            vertices=marker_vertices,
            pos=(0, self.marker_heights[1]))
        self.feedback_resources['left_hbox_marker_z'] = visual.ShapeStim(
            win=self.window,
            lineColor='White',
            fillColor='Black',
            vertices=marker_vertices,
            pos=(0, self.marker_heights[2]))
        self.feedback_resources['right_hbox_marker_x'] = visual.ShapeStim(
            win=self.window,
            lineColor='White',
            fillColor='DimGray',
            vertices=marker_vertices,
            pos=(0, self.marker_heights[0]))
        self.feedback_resources['right_hbox_marker_y'] = visual.ShapeStim(
            win=self.window,
            lineColor='White',
            fillColor='DimGray',
            vertices=marker_vertices,
            pos=(0, self.marker_heights[1]))
        self.feedback_resources['right_hbox_marker_z'] = visual.ShapeStim(
            win=self.window,
            lineColor='White',
            fillColor='DimGray',
            vertices=marker_vertices,
            pos=(0, self.marker_heights[2]))
예제 #3
0
    font='Arial',
    pos=[0,0], height=100, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1,
    depth=-1.0);

trialFinishedClock = core.Clock()
trial_finished = visual.TextStim(win=win, name='trial_finished',
    text='Thanks for your participation.\nPress any key to finish the trial.',
    font='Arial',
    pos=(0, 0), height=30, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1,
    depth=-1.0);
    
scaling_val = 35

circle_inner_feedback1 = visual.Circle(win2, edges=96, radius=baseline_inner * scaling_val, lineWidth=1, lineColor=(-0.3 , -0.3, -0.3), fillColor=(-0.3 , -0.3, -0.3), interpolate=True)
circle_outer_feedback1 = visual.Circle(win2, edges=96, radius=baseline_outer * scaling_val, lineWidth=1, lineColor=(0 , 0, 0), fillColor=(0 , 0, 0), interpolate=True)
circle_pupil_size_live1 = visual.Circle(win2, edges=96, radius=0, lineWidth=4, lineColor=(0,-1,-1), interpolate=True)

circle_inner_feedback= visual.Circle(win, edges=96, radius=baseline_inner * scaling_val, lineWidth=1, lineColor=(-0.3 , -0.3, -0.3), fillColor=(-0.3 , -0.3, -0.3), interpolate=True)
circle_outer_feedback = visual.Circle(win, edges=96, radius=baseline_outer * scaling_val, lineWidth=1, lineColor=(0 , 0, 0), fillColor=(0 , 0, 0), interpolate=True)
circle_pupil_size_live = visual.Circle(win, edges=96, radius=0, lineWidth=4, lineColor=(0,-1,-1), interpolate=True)


print("Testing")


loop_counter = 0
# stim trial counter
stim_counter = visual.TextStim(
    win=win,
logging.info(runInfo)
logging.info('gammaGrid='+str(mon.getGammaGrid()))
logging.info('linearizeMethod='+str(mon.getLinearizeMethod()))

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


######Create visual objects, noise masks, response prompts etc. ###########
######Draw your stimuli here if they don't change across trials, but other parameters do (like timing or distance)
######If you want to automate your stimuli. Do it in a function below and save clutter.
######For instance, maybe you want random pairs of letters. Write a function!
###########################################################################

fixSize = .1

fixation= visual.Circle(myWin, radius = fixSize , fillColor = (1,1,1), units='deg')
# fixationBlank= visual.PatchStim(myWin, tex= -1*fixatnNoiseTexture, size=(fixSizePix,fixSizePix), units='pix', mask='circle', interpolate=False, autoLog=False) #reverse contrast
# fixationPoint= visual.PatchStim(myWin,tex='none',colorSpace='rgb',color=(1,1,1),size=10,units='pix',autoLog=autoLogging)

# numChecksAcross = 128
# nearestPowerOfTwo = round( sqrt(numChecksAcross) )**2 #Because textures (created on next line) must be a power of 2
# whiteNoiseTexture = np.round( np.random.rand(nearestPowerOfTwo,nearestPowerOfTwo) ,0 )   *2.0-1 #Can counterphase flicker  noise texture to create salient flicker if you break fixation
# noiseMask= visual.PatchStim(myWin, tex=whiteNoiseTexture, size=(widthPix,heightPix), units='pix', interpolate=False, autoLog=autoLogging)
# whiteNoiseTexture2 = np.round( np.random.rand(nearestPowerOfTwo,nearestPowerOfTwo) ,0 )   *2.0-1 #Can counterphase flicker  noise texture to create salient flicker if you break fixation
# noiseMask2= visual.PatchStim(myWin, tex=whiteNoiseTexture2, size=(widthPix,heightPix), units='pix', interpolate=False, autoLog=autoLogging)
# whiteNoiseTexture3 = np.round( np.random.rand(nearestPowerOfTwo,nearestPowerOfTwo) ,0 )   *2.0-1 #Can counterphase flicker  noise texture to create salient flicker if you break fixation
# noiseMask3= visual.PatchStim(myWin, tex=whiteNoiseTexture3, size=(widthPix,heightPix), units='pix', interpolate=False, autoLog=autoLogging)
# whiteNoiseTexture4 = np.round( np.random.rand(nearestPowerOfTwo,nearestPowerOfTwo) ,0 )   *2.0-1
# noiseMask4= visual.PatchStim(myWin, tex=whiteNoiseTexture4, size=(widthPix,heightPix), units='pix', interpolate=False, autoLog=autoLogging)
# whiteNoiseTexture5 = np.round( np.random.rand(nearestPowerOfTwo,nearestPowerOfTwo) ,0 )   *2.0-1
# noiseMask5= visual.PatchStim(myWin, tex=whiteNoiseTexture5, size=(widthPix,heightPix), units='pix', interpolate=False, autoLog=autoLogging)
예제 #5
0
#!/usr/bin/env python2
from psychopy import visual, core, event

#create a window to draw in
myWin = visual.Window((800.0, 800.0),
                      allowGUI=False,
                      winType='pyglet',
                      monitor='testMonitor',
                      units='deg',
                      screen=0)
myWin.setRecordFrameIntervals()
#choose some fonts. If a list is provided, the first font found will be used.
fancy = ['Monotype Corsiva', 'Palace Script MT', 'Edwardian Script ITC']

#INITIALISE SOME STIMULI
circle = visual.Circle(myWin, radius=2, edges=32)
circle.pos = (0, 0)
circle.draw()

square = visual.Rect(myWin, width=1, height=1)
square.pos = (4, 4)
square.draw()

TVertiLine = visual.Line(myWin, start=(-3, -3), end=(-3, 1))
TVertiLine.draw()

myWin.flip()
#pause, so you get a chance to see it!
core.wait(5.0)
예제 #6
0
def show_eyes(controller):
    running = True
    # start tracking
    controller.tobii_cont.startTracking()

    # set up figures to draw
    left_eye = visual.Circle(controller.experWin, radius=0.025, units='norm')
    right_eye = visual.Circle(controller.experWin, radius=0.025, units='norm')
    left_eye_test = visual.Circle(controller.testWin,
                                  radius=0.025,
                                  units='norm')
    right_eye_test = visual.Circle(controller.testWin,
                                   radius=0.025,
                                   units='norm')
    left_text = visual.TextStim(controller.experWin,
                                height=0.1,
                                pos=(-0.6, -0.8),
                                units='norm')
    right_text = visual.TextStim(controller.experWin,
                                 height=0.1,
                                 pos=(0.6, -0.8),
                                 units='norm')
    press_text = visual.TextStim(controller.experWin,
                                 height=0.1,
                                 pos=(0, -0.3),
                                 text='Press any button to quit',
                                 units='norm')

    # run while key is not pressed
    while running:
        pressed = event.getKeys()
        if len(pressed) > 0:
            running = False  # stops running if a key is pressed

        # get pupil and validity information from Tobii
        curr_pupil = controller.tobii_cont.getCurrentPupilsandValidity()
        if curr_pupil == (None, None, None, None):
            continue
        left_pupil, left_validity, right_pupil, right_validity = curr_pupil

        # get gaze direction information from Tobii
        curr_gaze = controller.tobii_cont.getCurrentGazePosition()
        if curr_gaze == (None, None, None, None):
            continue
        left_x, left_y, right_x, right_y = curr_gaze

        # set colors based on validities
        if left_validity == 0:
            left_eye.lineColor = [-1, 1, -1]
            left_eye_test.lineColor = [-1, 1, -1]
        elif left_validity == 1:
            left_eye.lineColor = [-0.5, 0.5, -1]
            left_eye_test.lineColor = [-0.5, 0.5, -1]
        elif left_validity == 2:
            left_eye.lineColor = [0, 0, -1]
            left_eye_test.lineColor = [0, 0, -1]
        elif left_validity == 3:
            left_eye.lineColor = [0.5, -0.5, -1]
            left_eye_test.lineColor = [0.5, -0.5, -1]
        else:
            left_eye.lineColor = [1, -1, -1]
            left_eye_test.lineColor = [1, -1, -1]

        if right_validity == 0:
            right_eye.lineColor = [-1, 1, -1]
            right_eye_test.lineColor = [-1, 1, -1]
        elif right_validity == 1:
            right_eye.lineColor = [-0.5, 0.5, -1]
            right_eye_test.lineColor = [-0.5, 0.5, -1]
        elif right_validity == 2:
            right_eye.lineColor = [0, 0, -1]
            right_eye_test.lineColor = [0, 0, -1]
        elif right_validity == 3:
            right_eye.lineColor = [0.5, -0.5, -1]
            right_eye_test.lineColor = [0.5, -0.5, -1]
        else:
            right_eye.lineColor = [1, -1, -1]
            right_eye_test.lineColor = [1, -1, -1]

        # draw appropriate figures to visualize gaze on experimenter's screen
        if left_validity < 4:
            left_eye.pos = (left_x, left_y)
            left_eye_test.pos = (left_x, left_y)
            left_text.setText('Left Pupil Diameter: ' + str(left_pupil))
            left_eye.draw()
            left_eye_test.draw()
            left_text.draw()

        if right_validity < 4:
            right_eye.pos = (right_x, right_y)
            right_eye_test.pos = (right_x, right_y)
            right_text.setText('Right Pupil Diameter: ' + str(right_pupil))
            right_eye.draw()
            right_eye_test.draw()
            right_text.draw()

        # draw instruction
        press_text.draw()

        # update experimenter's and participant's screens
        controller.experWin.flip()
        controller.testWin.flip()
    # stop tracking
    controller.tobii_cont.stopTracking()
예제 #7
0
    def __init__(self,
                 params=None,
                 win=None,
                 exp_info=None,
                 txt_ins=None,
                 stimulus_list=None):
        self.win = win
        self.params = params
        self.exp_info = exp_info
        self.txt_ins = txt_ins
        self.stimulus_list = stimulus_list

        if self.params["EEG"]:
            self.pport = PortParallel()
        else:
            self.pport = False

        #Get a list of stimuli for the practice trial
        #The list contain all the stimuli in the practice folder as win.image
        self.practice_stim_list = get_practice_stim(params["Practice_path"],
                                                    self.win)

        self.stimulus_time = float(params[u"SJ_stim_time"])
        self.primer_time = float(params[u"Primer_time"])
        self.between_stim_time = float(params[u"SJ_between_stim_time"])

        # Create the mouse, primer and similarity bar component
        self.primer = visual.Circle(win=self.win,
                                    radius=45,
                                    units="pix",
                                    fillColor=[-1, -1, -1],
                                    lineColor=[-1, -1, -1])
        self.horizontal_line = visual.Line(win=self.win,
                                           units="pix",
                                           lineColor=[+1, +1, +1],
                                           lineWidth=10,
                                           start=(-50, 0),
                                           end=(+50, 0))
        self.vertical_line = visual.Line(win=self.win,
                                         units="pix",
                                         lineColor=[+1, +1, +1],
                                         lineWidth=10,
                                         start=(0, -50),
                                         end=(0, +50))
        self.center = visual.Circle(win=self.win,
                                    radius=5,
                                    units="pix",
                                    fillColor=[-1, -1, -1],
                                    lineColor=[-1, -1, -1])
        self.similarity_bar = visual.Line(win=self.win,
                                          units="pix",
                                          lineColor=[-1, -1, -1],
                                          lineWidth=100,
                                          start=(-500, 0),
                                          end=(+500, 0))
        self.cursor = visual.Line(win=self.win,
                                  lineColor=[+1, +1, +1],
                                  lineWidth=10,
                                  start=(0, -0.1),
                                  end=(0, +0.1))
        self.txt_diff = visual.TextStim(win=self.win,
                                        text=self.txt_ins["Different"],
                                        pos=(-0.7, -0.2),
                                        color="Black")
        self.txt_sim = visual.TextStim(win=self.win,
                                       text=self.txt_ins["Similar"],
                                       pos=(+0.7, -0.2),
                                       color="Black")
        self.mouse = event.Mouse(visible=False, newPos=None, win=None)

        #Adapt the trial list if stimuli orientation is changing
        if self.params["Orientation"] == "True":
            if exp_info['Exp'] == "Fish":
                self.sj_trials_list = get_list_sj_trial_with_orientation(
                    stimulus_list, self.win, params)
        else:
            pass

        #Create data handler
        file_name = exp_info['Exp'] + "_Version" + exp_info[
            'Version'] + "_" + exp_info["Name"] + "_SJ"
        self.sj_data = data.ExperimentHandler(
            name='SJ',
            version=exp_info['Version'],
            extraInfo=exp_info,
            runtimeInfo=None,
            savePickle=False,
            saveWideText=True,
            dataFileName=params["SJ_saving_path"] + file_name,
            autoLog=True)
예제 #8
0
    color=[-1, -1, -1],
    units='deg',
    fullscr=True,
    allowGUI=False
)  # Initiate psychopy Window as the object "win", using the myMon object from last line. Use degree as units!

# Stuff
clock = core.Clock()
writer = ppc.csvWriter(str(V['subject']), saveFolder=SAVE_FOLDER)

# create base stimli

square1 = visual.Rect(win, width=2.85, height=2.45, pos=[-5, 0])
#square2=visual.Rect(win, width=2, height=2, pos=([0, 0]))
square3 = visual.Rect(win, width=2.85, height=2.45, pos=[5, 0])
fixation = visual.Circle(win, pos=([0, .05]),
                         radius=.2)  # check sizes, should be 1x1 degrees

# Responses and keys
KEYS_QUIT = ['q']  # Keys that quits the experiment
RESPONSES = {'left': 'lctrl', 'right': 'rctrl'}

# Create instruction stimuli

breaktxt1 = 'You are now on a break. Please rest your eyes for a few seconds. When you are ready, please push a response key to continue.'
breaktxt2 = 'Ready?'
breaktxt3 = 'The practice is over, and you are now about to start the main experiment.\n\n\n\nPlease remember to be as quick and accurate as you can with your responses. When you are ready to begin, push a button to continue.'
breaktxt4 = 'You have now finished the task.\n\n\n\nPlease sit and wait for the experimenter.'
breakInstr = visual.TextStim(win,
                             text=breaktxt1,
                             pos=([0, 0]),
                             height=1,
예제 #9
0
from psychopy import visual, event

win0 = visual.Window(size=(800, 800),
                     fullscr=False,
                     units="pix",
                     color=[1, 1, 1],
                     monitor="testMonitor")

circle = visual.Circle(
    win=win0,
    radius=1,
    fillColor=[-1, -1, -1],
    lineColor=[-1, -1, -1],
    units="pix",
    # edges=128
)

f = 1
while (f <= 200):
    circle.radius = f
    f += 1
    circle.draw()
    win0.flip()

event.waitKeys()
win0.close()
예제 #10
0
    def run(self, file_name, settings_file):
        with codecs.open(file_name, 'r', encoding='utf-8') as output_file:
            output_lines = output_file.readlines()

        experiment = asrt.Experiment('')
        experiment.settings = asrt.ExperimentSettings(settings_file, "")
        experiment.all_settings_def()

        experiment.monitor_settings()
        experiment.dict_pos = {1: (float(experiment.settings.asrt_distance) * (-0.5), float(experiment.settings.asrt_distance) * (-0.5)),
                               2: (float(experiment.settings.asrt_distance) * 0.5, float(experiment.settings.asrt_distance) * (-0.5)),
                               3: (float(experiment.settings.asrt_distance) * (-0.5), float(experiment.settings.asrt_distance) * 0.5),
                               4: (float(experiment.settings.asrt_distance) * 0.5, float(experiment.settings.asrt_distance) * 0.5)}
        experiment.colors = {'wincolor': 'White', 'linecolor': 'black',
                             'stimp': experiment.settings.asrt_pcolor, 'stimr': experiment.settings.asrt_rcolor}

        with visual.Window(size=experiment.mymonitor.getSizePix(), color=experiment.colors['wincolor'], fullscr=False, monitor=experiment.mymonitor, units="cm") as experiment.mywindow:

            stimP = visual.Circle(win=experiment.mywindow, radius=experiment.settings.asrt_size, units="cm",
                                  fillColor=experiment.colors['stimp'], lineColor=experiment.colors['linecolor'], pos=experiment.dict_pos[1])
            stimR = visual.Circle(win=experiment.mywindow, radius=experiment.settings.asrt_size, units="cm",
                                  fillColor=experiment.colors['stimr'], lineColor=experiment.colors['linecolor'], pos=experiment.dict_pos[1])
            stimbg = visual.Circle(win=experiment.mywindow, radius=experiment.settings.asrt_size, units="cm",
                                   fillColor=None, lineColor=experiment.colors['linecolor'])
            eye_pos = visual.Circle(win=experiment.mywindow, radius=experiment.settings.asrt_size / 2.0, units="cm",
                                    fillColor='Red', lineColor='Red')
            AOI_rect = visual.Rect(win=experiment.mywindow, width=experiment.settings.AOI_size, height=experiment.settings.AOI_size, units="cm",
                                   fillColor=None, lineColor='Red', lineWidth=2.0)

            last_trial = -1
            last_trial_phase = 'before_stimulus'
            sampling_counter = 0
            block_displayed = False
            for line in output_lines[1:]:

                trial_pos = output_lines[0].split('\t').index("trial")
                pattern_random_pos = output_lines[0].split('\t').index("trial_type_pr")
                asrt_type_pos = output_lines[0].split('\t').index("asrt_type")
                stimulus_pos = output_lines[0].split('\t').index("stimulus")
                block_pos = output_lines[0].split('\t').index("block")
                RSI_pos = output_lines[0].split('\t').index("RSI_time")
                trial_phase_pos = output_lines[0].split('\t').index("trial_phase")

                current_trial = line.split('\t')[trial_pos]
                current_pattern_random = line.split('\t')[pattern_random_pos]
                asrt_type = line.split('\t')[asrt_type_pos]
                current_stimulus = int(line.split('\t')[stimulus_pos])
                trial_phase = line.split('\t')[trial_phase_pos]
                block_number = line.split('\t')[block_pos]
                RSI_time = line.split('\t')[RSI_pos]

                if current_trial == '1' and trial_phase == 'before_stimulus':
                    if not block_displayed:
                        text_stim = visual.TextStim(experiment.mywindow, text=block_number + ". blokk kezdete...",
                                                    units='cm', height=1.0, wrapWidth=20, color='black')
                        text_stim.draw()
                        experiment.mywindow.flip()
                        core.wait(1.5)
                        block_displayed = True
                    last_trial = current_trial
                    continue

                block_displayed = False
                if sampling_counter > 4:
                    sampling_counter = 0
                    left_gaze_XY = (float(line.split('\t')[23].replace(',', '.')), float(line.split('\t')[24].replace(',', '.')))
                    left_gaze_valid = bool(line.split('\t')[32])
                    right_gaze_XY = (float(line.split('\t')[25].replace(',', '.')), float(line.split('\t')[26].replace(',', '.')))
                    right_gaze_valid = bool(line.split('\t')[33])
                    x_coord = None
                    y_coord = None
                    if left_gaze_valid and right_gaze_valid:
                        x_coord = (left_gaze_XY[0] + right_gaze_XY[0]) / 2
                        y_coord = (left_gaze_XY[1] + right_gaze_XY[1]) / 2
                    elif left_gaze_valid:
                        x_coord = left_gaze_XY[0]
                        y_coord = left_gaze_XY[1]
                    elif right_gaze_valid:
                        x_coord = right_gaze_XY[0]
                        y_coord = right_gaze_XY[1]

                    eye_pos.setPos(experiment.ADCS_to_PCMCS((x_coord, y_coord)))
                    eye_pos.draw()
                    eye_pos_drawn = True

                if current_trial != last_trial or last_trial_phase != trial_phase or eye_pos_drawn:
                    experiment.stim_bg(stimbg)
                    experiment.stim_bg(AOI_rect)

                    if trial_phase != 'before_stimulus':
                        if current_pattern_random == 'pattern':
                            if asrt_type == 'explicit':
                                stimP.fillColor = experiment.colors['stimp']
                            else:
                                stimP.fillColor = experiment.colors['stimr']
                            stimP.setPos(experiment.dict_pos[current_stimulus])
                        else:
                            stimR.setPos(experiment.dict_pos[current_stimulus])
                        if current_pattern_random == 'pattern':
                            stimP.draw()
                        else:
                            stimR.draw()
                    text_stim = visual.TextStim(experiment.mywindow, text=current_trial + ". trial",
                                                units='cm', height=0.8, wrapWidth=20, color='black', pos=(0.0, 12.0))
                    text_stim.draw()
                    experiment.mywindow.flip()

                core.wait(0.008)
                last_trial = current_trial
                last_trial_phase = trial_phase
                sampling_counter += 1
                eye_pos_drawn = False
예제 #11
0
numInList[1] = len(Blist)
numInList[2] = len(Clist)
#generate my random sequence --need 36 of each list
Asequence = numpy.random.randint(0, high=numInList[0], size=36)
Bsequence = numpy.random.randint(0, high=numInList[1], size=36)
Csequence = numpy.random.randint(0, high=numInList[2], size=36)

numpy.savetxt('designMatrix.txt', designMatrix, fmt='%.3i')

#make a fixation cross which will rotate 45 deg on occasion
#this will be a problem. Need a square that embiggens
fix0 = visual.Circle(winSub,
                     radius=IR / 2.0,
                     edges=32,
                     lineColor=gray,
                     lineColorSpace='rgb',
                     pos=[8, 0],
                     fillColor=gray,
                     fillColorSpace='rgb',
                     autoLog=False)
fix1 = visual.ShapeStim(winSub,
                        pos=[8.0, 0.0],
                        vertices=((0.0, -0.2), (0.0, 0.2)),
                        lineWidth=3.0,
                        lineColor=black,
                        lineColorSpace='rgb',
                        fillColor=black,
                        fillColorSpace='rgb',
                        autoLog=False)

fix2 = visual.ShapeStim(winSub,
예제 #12
0
    def sart_trial(self, win):
        omitNum = self.omitNum
        fb = True
        clock = core.Clock()
        random.shuffle(self.fontSizes)
        random.shuffle(self.numbers)
        fontSize = self.fontSizes[0]
        number = self.numbers[0]

        mouse = event.Mouse(visible=0)
        xStim = visual.TextStim(win,
                                text="X",
                                height=3.35,
                                color="white",
                                pos=(0, 0))
        circleStim = visual.Circle(win,
                                   radius=1.50,
                                   lineWidth=8,
                                   lineColor="white",
                                   pos=(0, -.2))
        numStim = visual.TextStim(win, font="Arial", color="white", pos=(0, 0))
        correctStim = visual.TextStim(win,
                                      text="CORRECT",
                                      color="green",
                                      font="Arial",
                                      pos=(0, 0))
        incorrectStim = visual.TextStim(win,
                                        text="INCORRECT",
                                        color="red",
                                        font="Arial",
                                        pos=(0, 0))
        mouse.setVisible(0)
        respRt = "NA"
        numStim.setHeight(fontSize)
        numStim.setText(number)
        numStim.draw()
        event.clearEvents()
        clock.reset()
        stimStartTime = time.clock()
        win.flip()
        xStim.draw()
        circleStim.draw()
        waitTime = .25 - (time.clock() - stimStartTime)
        core.wait(waitTime, hogCPUperiod=waitTime)
        maskStartTime = time.clock()
        win.flip()
        waitTime = .90 - (time.clock() - maskStartTime)
        core.wait(waitTime, hogCPUperiod=waitTime)
        win.flip()
        allKeys = event.getKeys(timeStamped=clock)
        respAcc = 0
        if len(allKeys) != 0:
            respRt = allKeys[0][1]
        if len(allKeys) == 0:
            if omitNum == number:
                respAcc = 1
            else:
                respAcc = 0
        else:
            if omitNum == number:
                respAcc = 0
            else:
                respAcc = 1

        self.correctResponses += [respAcc]
        #print "correctResponses = ", self.correctResponses

        if fb == True:
            if respAcc == 0:
                incorrectStim.draw()
            else:
                correctStim.draw()
        stimStartTime = time.clock()
        win.flip()
        waitTime = .90 - (time.clock() - stimStartTime)
        core.wait(waitTime, hogCPUperiod=waitTime)
        win.flip()
        endTime = time.clock()
        foo = 0

        if respRt == "NA":
            if respAcc == 1:
                reactionTime = np.mean(self.states)
            else:
                #incorrect response -> did not answer when they should have
                #penalize by treating this as very high RT of 2 seconds
                reactionTime = 2
        else:  #subject answered
            if respAcc == 0:  #incorrectly
                reactionTime = 2
            else:  #correctly, in which case, reactionTime = respRt
                reactionTime = respRt

        self.states += [reactionTime]

        self.reactionTimes += [reactionTime]

        return [reactionTime]
예제 #13
0
corrLocation=[]             #List of Correct color location

userResponse=[]             #List of user Responses on the Location of the different colored circle


timebetweenframes = .083 #.083 gives about 12 letters/s.Same as JosephChunNakayama.since we're not counting frames,won't be exact  
timebetweenframes = .04
noisecontrast=.7
nletterstoshow=len(letters)

#grating= visual.GratingStim(win=mywin, mask="gauss", units="pix", size=gratingdiam, pos=[xecc[0],yecc[0]], sf=[gratingfreq,0],contrast=gratingcontrast)

rad = circleSize / 2
colorDiff = '#3373FF' #A slightly lighter shade of blue
mainColor = '#3346FF' #Blue
circle = visual.Circle(mywin,radius = rad, edges = 32)
#fixation = visual.GratingStim(win=mywin, size=15, pos=[0,0], sf=0, rgb= 1,contrast=.5)
blankletter=visual.GratingStim(win=mywin, size=30, pos=[0,0],sf=0, rgb=1, contrast=0)
trialClock = core.Clock()
centraltext=visual.TextStim(win=mywin, text='B',pos=[0,0],rgb=1,contrast=lettercontrast,height=letterheight)
#noiseTexture = scipy.random.rand(128,128)*2.0-1 #from demo visual_noise.py
#noisepatch=visual.GratingStim(win=mywin, tex=noiseTexture, mask="gauss", units="pix", size=gratingdiam, pos=[xecc[0],yecc[0]], contrast=noisecontrast)




#write excel file with results

data = [("Trial", "User Response","Correct Location")]

def write_file(filename):
    def __init__(self, tracker, win):
        '''Initialize

        tracker: an EyeLink instance (connection)
        win: the PsychoPy window we use for calibration'''

        pylink.EyeLinkCustomDisplay.__init__(self)

        # background and target color
        self._backgroundColor = win.color
        self._foregroundColor = 'black'

        # window to use for calibration
        self._display = win
        # make the mouse cursor invisible
        self._display.mouseVisible = False

        # display width & height
        self._w, self._h = win.size

        # resolution fix for Mac retina displays
        if 'Darwin' in platform.system():
            sys_cmd = 'system_profiler SPDisplaysDataType | grep Retina'
            is_ret = os.system(sys_cmd)
            if is_ret == 0:
                self._w = int(self._w / 2.0)
                self._h = int(self._h / 2.0)

        # store camera image pixels in an array
        self._imagebuffer = array.array('I')

        # store the color palette for camera image drawing
        self._pal = None

        # initial size of the camera image
        self._size = (384, 320)

        # initial mouse configuration
        self._mouse = event.Mouse(False)
        self.last_mouse_state = -1

        # camera image title
        self._msgHeight = self._size[1] / 16.0
        self._title = visual.TextStim(self._display,
                                      '',
                                      wrapWidth=self._w,
                                      color=self._foregroundColor)

        # calibration target
        self._targetSize = self._w / 64.
        self._tar = visual.Circle(self._display,
                                  size=self._targetSize,
                                  lineColor=self._foregroundColor,
                                  lineWidth=self._targetSize / 2)

        # calibration sounds (beeps)
        self._target_beep = Sound('type.wav', stereo=True)
        self._error_beep = Sound('error.wav', stereo=True)
        self._done_beep = Sound('qbeep.wav', stereo=True)

        # a reference to the tracker connection
        self._tracker = tracker

        # for a clearer view we always enlarge the camera image
        self.imgResize = None
예제 #15
0
#===============================
# Creation of window and stimuli
#===============================

# win = visual.Window(color='white', units='pix', fullscr=True)#True, allowGUI=False)
win = visual.Window([800, 600], units='pix')
mouse = event.Mouse(visible=True)

# Creation of stimuli
start_zone = visual.Rect(win,
                         pos=(-300, 0),
                         width=8,
                         height=8,
                         fillColor='red',
                         opacity=0.5)
cursor = visual.Circle(win, radius=cursorRad, edges=13, units='pix')
target = visual.Circle(win,
                       radius=targetRad,
                       edges=13,
                       units='pix',
                       lineWidth=0,
                       fillColor='Red',
                       pos=(250, 0))
time_up_message = visual.TextStim(
    win, text="Time is up! Try again.", color='red', height=30,
    bold=True)  # text that overlays image after 30 seconds
start_message = visual.TextStim(win,
                                text="Press space to start the experiment.",
                                color='black',
                                height=30)
instr = visual.TextStim(win,
예제 #16
0
                          lineColor=shape_color,
                          lineColorSpace='rgb255',
                          fillColor=shape_color,
                          fillColorSpace='rgb255',
                          opacity=1,
                          interpolate=True,
                          autoDraw=False)

ball = visual.Circle(win=window_1,
                     name='ball',
                     units='pix',
                     edges=100,
                     ori=0,
                     pos=(0, 0),
                     size=initial_size_px,
                     lineWidth=1,
                     lineColor=shape_color,
                     lineColorSpace='rgb255',
                     fillColor=shape_color,
                     fillColorSpace='rgb255',
                     opacity=1,
                     interpolate=True,
                     autoDraw=False)

triangle = visual.Polygon(win=window_1,
                          name='triangle',
                          units='pix',
                          edges=3,
                          ori=0,
                          pos=(0, 0),
                          size=initial_size_px,
예제 #17
0
def startleDisplayProtocol(t1, t2, t3, speed, color):
    # note that here t1, t2, t3 are in frames
    mywin.winHandle.maximize()
    mywin.winHandle.set_fullscreen(True)
    mywin.winHandle.activate()

    radDisc = scalingFactor/2.5
    shape1 = visual.Circle(mywin, radius=radDisc, fillColor=color,pos=(-width_plate / 6.4, (scalingFactor/2.) + height_plate / 8.2))
    shape2 = visual.Circle(mywin, radius=radDisc, fillColor=color,pos=(0, (scalingFactor/2.) + height_plate / 8.2))
    shape3 = visual.Circle(mywin, radius=radDisc, fillColor=color,pos=(width_plate / 6.4, (scalingFactor/2.) +height_plate / 8.2))
    shape4 = visual.Circle(mywin, radius=radDisc, fillColor=color,pos=(-width_plate / 6.4, (scalingFactor/2.) + -height_plate / 8.2))
    shape5 = visual.Circle(mywin, radius=radDisc, fillColor=color,pos=(0, (scalingFactor/2.) + -height_plate / 8.2))
    shape6 = visual.Circle(mywin, radius=radDisc, fillColor=color,pos=(width_plate / 6.4, (scalingFactor/2.) + -height_plate / 8.2))

    shape1b = visual.Circle(mywin, radius=scalingFactor, lineWidth=2., lineColor='black',pos=(-width_plate / 6.4, height_plate / 8.2))
    shape2b = visual.Circle(mywin, radius=scalingFactor, lineWidth=2., lineColor='black',pos=(0, height_plate / 8.2))
    shape3b = visual.Circle(mywin, radius=scalingFactor, lineWidth=2., lineColor='black',pos=(width_plate / 6.4, height_plate / 8.2))
    shape4b = visual.Circle(mywin, radius=scalingFactor, lineWidth=2., lineColor='black',pos=(-width_plate / 6.4, -height_plate / 8.2))
    shape5b = visual.Circle(mywin, radius=scalingFactor, lineWidth=2., lineColor='black',pos=(0, -height_plate / 8.2))
    shape6b = visual.Circle(mywin, radius=scalingFactor, lineWidth=2., lineColor='black',pos=(width_plate / 6.4, -height_plate / 8.2))

    # This is before the start of the experiment. Position the wells, add larvae, top up wells with water
    # and focus the camera! Press 'ESC' to start the experiment
    while True:
        white.draw()
        plate.draw()
        shape1b.draw()
        shape2b.draw()
        shape3b.draw()
        shape4b.draw()
        shape5b.draw()
        shape6b.draw()

        mywin.flip()
        if event.waitKeys(0.5) == ["escape"]:
            break
    event.clearEvents()

    # start the camera here, and start recording
    #startCamera(t1+t2+t3)

    # This is the acclimatization phase
    for frameN in range(t1):
        white.draw()
        plate.draw()

        shape1b.draw()
        shape2b.draw()
        shape3b.draw()
        shape4b.draw()
        shape5b.draw()
        shape6b.draw()

        #mywin.logOnFlip(level=logging.CRITICAL, msg='sent on actual flip')
        mywin.flip()

    initpos = [-width_plate / 6.4, height_plate / 8.2]
    ops='+'

    # This is the startle phase
    for frameN in range(t2):
        white.draw()
        plate.draw()

        shape1.draw()
        shape2.draw()
        shape3.draw()
        shape4.draw()
        shape5.draw()
        shape6.draw()

        if (shape1.pos[0]-radDisc) <= (initpos[0]-scalingFactor/1.4142):
            ops='+'
        elif (shape1.pos[0]+radDisc) >= (initpos[0]+scalingFactor/1.4142):
            ops = '-'
        shape1.setPos([speed,0], operation=ops)
        shape2.setPos([speed, 0], operation=ops)
        shape3.setPos([speed, 0], operation=ops)
        shape4.setPos([speed, 0], operation=ops)
        shape5.setPos([speed, 0], operation=ops)
        shape6.setPos([speed, 0], operation=ops)

        shape1b.draw()
        shape2b.draw()
        shape3b.draw()
        shape4b.draw()
        shape5b.draw()
        shape6b.draw()

        #mywin.logOnFlip(level=logging.CRITICAL, msg='sent on actual flip')
        mywin.flip()

    # This is the recovery phase
    for frameN in range(t3):
        white.draw()
        plate.draw()
        shape1b.draw()
        shape2b.draw()
        shape3b.draw()
        shape4b.draw()
        shape5b.draw()
        shape6b.draw()

        #mywin.logOnFlip(level=logging.CRITICAL, msg='sent on actual flip')
        mywin.flip()

    for frameN in range(300):
        white.draw()
        plate.draw()
        mywin.flip()

    mywin.close()
    core.quit()
예제 #18
0
    def _questionnaire(self, exp_win, ctl_win, questions):
        if questions is None:
            return
        exp_win.setColor([0] * 3, colorSpace='rgb')
        lines = []
        bullets = []
        responses = []
        texts = []
        legends = []
        y_spacing = 80
        win_width = exp_win.size[0]
        scales_block_x = win_width * 0.25
        scales_block_y = len(questions) // 2 * y_spacing
        extent = win_width * 0.2

        # add legends to Likert scale
        legends.append(visual.TextStim(
            exp_win,
            text = 'Disagree',
            units="pix",
            pos=(scales_block_x - extent*0.75, scales_block_y*1.1),
            wrapWidth= win_width * 0.5,
            height= y_spacing / 3,
            anchorHoriz="right",
            alignText="right",
            bold=True
        ))
        legends.append(visual.TextStim(
            exp_win,
            text = 'Agree',
            units="pix",
            pos=(scales_block_x + extent*1.15, scales_block_y*1.1),
            wrapWidth= win_width * 0.5,
            height= y_spacing / 3,
            anchorHoriz="right",
            alignText="right",
            bold=True
        ))


        active_question = 0

        # create all stimuli
        #all_questions_text = ""
        for q_n, (key, question, n_pts) in enumerate(questions):
            default_response = n_pts // 2
            responses.append(default_response)
            x_spacing = extent * 2 / (n_pts - 1)
            #all_questions_text += question + "\n\n"

            y_pos = scales_block_y - q_n * y_spacing

            lines.append(
                visual.Line(
                    exp_win,
                    (scales_block_x - extent, y_pos),
                    (scales_block_x + extent, y_pos),
                    units="pix",
                    lineWidth=6,
                    autoLog=False,
                    lineColor=(0, -1, -1) if q_n == 0 else (-1, -1, -1),
                )
            )
            bullets.append(
                [
                    visual.Circle(
                        exp_win,
                        units="pix",
                        radius=10,
                        pos=(
                            scales_block_x - extent + i * x_spacing,
                            y_pos,
                        ),
                        fillColor= (1, 1, 1) if default_response == i else (-1, -1, -1),
                        lineColor=(-1, -1, -1),
                        lineWidth=10,
                        autoLog=False,
                    )
                    for i in range(n_pts)
                ]
            )
            texts.append(visual.TextStim(
                exp_win,
                text = question,
                units="pix",
                bold = q_n == active_question,
                pos=(0, y_pos),
                wrapWidth= win_width * 0.5,
                height= y_spacing / 3,
                anchorHoriz="right",
                alignText="right"
            ))
            responses[q_n] = default_response



        # questionnaire interaction loop
        n_flips = 0
        while True:
            self._handle_controller_presses(exp_win)
            new_key_pressed = [k[0] for k in self._new_key_pressed]
            if "u" in new_key_pressed and active_question > 0:
                active_question -= 1
            elif "d" in new_key_pressed and active_question < len(questions)-1:
                active_question += 1
            elif "r" in new_key_pressed and responses[active_question] < n_pts - 1:
                responses[active_question] += 1
            elif "l" in new_key_pressed and responses[active_question] > 0:
                responses[active_question] -= 1
            elif "a" in new_key_pressed:
                for (key, question, n_pts), value in zip(questions, responses):
                    self._log_event({
                        "trial_type": "questionnaire-answer",
                        "game": self.game_name,
                        "level": self.state_name,
                        "stim_file": self.movie_path,
                        "question": key,
                        "value": value
                    })
                break
            elif n_flips > 1:
                time.sleep(.01)
                continue

            if n_flips > 0: #avoid double log when first loading questionnaire
                self._log_event({
                    "trial_type": "questionnaire-value-change",
                    "game": self.game_name,
                    "level": self.state_name,
                    "stim_file": self.movie_path,
                    "question": questions[active_question][0],
                    "value": responses[active_question]
                })

            exp_win.logOnFlip(
                level=logging.EXP,
                msg="level ratings %s" % responses)
            for q_n, (txt, line, bullet_q) in enumerate(zip(texts, lines, bullets)):
                #txt.bold = q_n == active_question
                txt._pygletTextObj.set_style('bold', q_n == active_question)
                line.lineColor = (0, -1, -1) if q_n == active_question else (-1, -1, -1)
                for bullet_n, bullet in enumerate(bullet_q):
                    bullet.fillColor = (1, 1, 1) if responses[q_n] == bullet_n else (-1, -1, -1)

            for stim in lines + sum(bullets, []) + texts + legends:
                stim.draw(exp_win)
            yield True
            n_flips += 1
def judge_page():
    global up_station
    global down_station
    global left_station
    global right_station
    global k_list
    # 利用坐标,制作可通行标志三角形的大小和形状
    triang_1_vert = [[0, 0.10], [-0.10, -0.10], [0.10, -0.10]]
    triang_4_vert = [[-0.10, 0.10], [0.10, 0], [-0.10, -0.10]]
    triang_2_vert = [[-0.10, 0.10], [0.10, 0.10], [0, -0.10]]
    triang_3_vert = [[-0.10, 0], [0.10, 0.10], [0.10, -0.10]]
    # 将上面制作好的三角形呈现,不描边,填充白色,透明度0.3,定位
    triang_1 = visual.ShapeStim(win,
                                lineColor=None,
                                fillColor='white',
                                vertices=triang_1_vert,
                                pos=(0, 0.1))
    triang_2 = visual.ShapeStim(win,
                                lineColor=None,
                                fillColor='white',
                                vertices=triang_2_vert,
                                pos=(0, -0.3))
    triang_3 = visual.ShapeStim(win,
                                lineColor=None,
                                fillColor='white',
                                vertices=triang_3_vert,
                                pos=(-0.2, -0.1))
    triang_4 = visual.ShapeStim(win,
                                lineColor=None,
                                fillColor='white',
                                vertices=triang_4_vert,
                                pos=(0.2, -0.1))
    # 表示不能通行的标志圆形,不再需要坐标来确定形状
    cri_1 = visual.Circle(win,
                          radius=0.1,
                          edges=32,
                          lineColor=None,
                          fillColor='white',
                          opacity=0.3,
                          pos=(0, 0.1))
    cri_2 = visual.Circle(win,
                          radius=0.1,
                          edges=32,
                          lineColor=None,
                          fillColor='white',
                          opacity=0.3,
                          pos=(0, -0.3))
    cri_3 = visual.Circle(win,
                          radius=0.1,
                          edges=32,
                          lineColor=None,
                          fillColor='white',
                          opacity=0.3,
                          pos=(-0.2, -0.1))
    cri_4 = visual.Circle(win,
                          radius=0.1,
                          edges=32,
                          lineColor=None,
                          fillColor='white',
                          opacity=0.3,
                          pos=(0.2, -0.1))
    # 生成起点和终点站的中文名称(需要加上“当前站台”和“终点”字样吗?)
    text_53 = visual.TextStim(win,
                              text=u'',
                              height=0.2,
                              pos=(0, 0.4),
                              color='white',
                              bold=True,
                              italic=0)
    text_53.text = station_list_str[station_list.index(station_1)]
    text_54 = visual.TextStim(win,
                              text=u'',
                              height=0.2,
                              pos=(0, -0.6),
                              bold=True,
                              italic=0)
    text_54.text = station_list_str[station_list.index(station_2)]
    text_54.color = judge_function.line_color(station_2)
    text_53.draw()
    text_54.draw()
    # 定义上下左右按键的数学关系
    up_station = (station_1[0], station_1[1] + 1)
    down_station = (station_1[0], station_1[1] - 1)
    left_station = (station_1[0] - 1, station_1[1])
    right_station = (station_1[0] + 1, station_1[1])
    # 生成指示方向的标志,同时限定被试能够进行判断的按键
    k_list = []
    if up_station in station_list and judge_function.if_same_line(
            up_station, station_1) == 1:
        triang_1.draw()
        k_list.append('1')
    else:
        cri_1.draw()

    if down_station in station_list and judge_function.if_same_line(
            down_station, station_1) == 1:
        triang_2.draw()
        k_list.append('2')
    else:
        cri_2.draw()

    if left_station in station_list and judge_function.if_same_line(
            left_station, station_1) == 1:
        triang_3.draw()
        k_list.append('3')
    else:
        cri_3.draw()

    if right_station in station_list and judge_function.if_same_line(
            right_station, station_1) == 1:
        triang_4.draw()
        k_list.append('4')
    else:
        cri_4.draw()
# 呈现当前的赏金信息和积累的奖赏总数
    info_reward()
    text_55 = visual.TextStim(win,
                              text=u'',
                              height=0.15,
                              pos=(0, 0.7),
                              color='white',
                              bold=True,
                              italic=0)
    text_55.text = '最短路线赏金:50'
    text_55.draw()

    win.flip()
예제 #20
0
def createStimulusObjects(win, frameDur):

    # set some colors
    tokenRewardColor = [0, 0, 1]
    tokenHoleColor = [-0.2, -0.2, -0.2]

    # instructions text
    message = visual.TextStim(win=win,
                              ori=0,
                              name='message',
                              text=u'Please press a key to begin.',
                              font=u'Arial',
                              pos=[0, 0],
                              height=0.05,
                              wrapWidth=1.2,
                              color=u'white',
                              colorSpace='rgb',
                              alignHoriz='center')

    # circular token
    token = visual.Circle(win=win,
                          radius=0.1,
                          edges=64,
                          units='height',
                          lineWidth=2,
                          lineColor=[1, 1, 1],
                          fillColor=[0, 0, 0],
                          pos=(0, 0),
                          interpolate=True,
                          name='token')

    # text with token value
    tokenText = visual.TextStim(win=win,
                                ori=0,
                                name='tokenText',
                                text='0',
                                font=u'Arial',
                                units='height',
                                pos=[0, 0],
                                height=0.05,
                                wrapWidth=None,
                                color=[1, 1, 1],
                                colorSpace='rgb',
                                opacity=1,
                                depth=0.0)

    # 'ready' text on the token
    readyText = visual.TextStim(win=win,
                                ori=0,
                                name='readyText',
                                text='Grip!',
                                font=u'Arial',
                                units='height',
                                pos=[0, 0],
                                height=0.03,
                                wrapWidth=None,
                                color=[1, 1, 1],
                                colorSpace='rgb',
                                opacity=1,
                                depth=0.0)

    # text for "SOLD"
    soldText = visual.TextStim(win=win,
                               ori=0,
                               name='soldText',
                               text='SOLD',
                               font=u'Arial',
                               units='height',
                               pos=[0, 0],
                               height=0.15,
                               wrapWidth=None,
                               color=[1, -0.5, -0.5],
                               colorSpace='rgb',
                               opacity=1,
                               depth=0.0)

    # progress bar
    progBarMaxTime = 30  # in s
    progBarMaxLength = 0.5  # in screen height units
    progBarVertPos = -0.2  # will need this when updating the position
    progressBar = visual.Rect(win=win,
                              units='height',
                              pos=(0, progBarVertPos),
                              width=1,
                              height=0.05,
                              fillColor=[1, 1, 1],
                              name='progressBar',
                              autoLog=False)

    # progress bar base
    baseN = progBarVertPos + 0.03
    baseS = progBarVertPos - 0.03
    baseE = -0.25 + 0.015
    baseW = -0.25 - 0.005
    baseVerts = ((baseE, baseN), (baseW, baseN), (baseW, baseS), (baseE, baseS)
                 )  # NE, NW, SW, SE
    progressBarBase = visual.ShapeStim(win=win,
                                       units='height',
                                       vertices=baseVerts,
                                       closeShape=False,
                                       lineColor=[-0.2, -0.2, -0.2],
                                       lineWidth=5,
                                       name='progressBarBase')

    # time left text: TextStim version
    # slow to update; tend to get skipped frames at whole numbers of seconds
    timeLeftText = visual.TextStim(win=win,
                                   ori=0,
                                   text='Time left',
                                   font=u'Arial',
                                   units='height',
                                   pos=[-0.1, -0.3],
                                   height=0.03,
                                   wrapWidth=None,
                                   color=[1, 1, 1],
                                   alignHoriz='left',
                                   autoLog=False,
                                   name='timeLeftText')

    # total earned text: TextStim version
    totalEarnedText = visual.TextStim(win=win,
                                      ori=0,
                                      text='Total earned: $0.00',
                                      font=u'Arial',
                                      units='height',
                                      pos=[-0.1, -0.35],
                                      height=0.03,
                                      wrapWidth=None,
                                      color=[1, 1, 1],
                                      alignHoriz='left',
                                      name='totalEarnedText')

    # grip force meter
    meterDial = visual.Circle(win=win,
                              radius=0.1,
                              units='height',
                              fillColor=[-0.5, -0.5, -0.5],
                              pos=[0, 0],
                              name='meterDial')
    meterMarker = visual.Line(win=win,
                              start=(0, 0.05),
                              end=(0, 0.1),
                              units='height',
                              lineColor=[1, 1, 1],
                              lineWidth=2,
                              name='meterMarker')
    meterNeedle = visual.ShapeStim(win=win,
                                   vertices=((0, 0.09), (0.01, -0.02),
                                             (-0.01, -0.02)),
                                   units='height',
                                   fillColor=[1, 0, 0],
                                   lineColor=[1, 0, 0],
                                   pos=(0, 0),
                                   autoLog=False,
                                   name='meterNeedle')
    meterDial.size *= 1  # resize all meter components
    meterMarker.size *= 1
    meterNeedle.size *= 1

    return {
        'message': message,
        'token': token,
        'tokenText': tokenText,
        'readyText': readyText,
        'soldText': soldText,
        'progressBar': progressBar,
        'progressBarBase': progressBarBase,
        'timeLeftText': timeLeftText,
        'totalEarnedText': totalEarnedText,
        'progBarMaxTime': progBarMaxTime,
        'progBarMaxLength': progBarMaxLength,
        'tokenRewardColor': tokenRewardColor,
        'tokenHoleColor': tokenHoleColor,
        'frameDur': frameDur,
        'meterDial': meterDial,
        'meterMarker': meterMarker,
        'meterNeedle': meterNeedle
    }
예제 #21
0
    'press the spacebar only when you see a sqaure, press any key to continue')


def displayInstructions(text, acceptedKeys=None):
    instruct = visual.TextStim(win, text=text, color='red')
    instruct.draw()
    win.flip()

    key = event.waitKeys(keyList=acceptedKeys)

    win.flip()


# Fixation

fix = visual.Circle(win, size=0.5, fillColor='red', lineColor='red')

# onset times

times = [120, 60, 30, 12, 18]

# Experiment handler
filename = "data/" + info[
    'Participant']  #This is the file name in the data/ directory

RT_Exp = data.ExperimentHandler(
    name='Simple Reaction Time Task',
    version='1.0',  #not needed, just handy
    extraInfo=info,  #the info we created earlier
    dataFileName=filename,  # using our string with data/name_date
)
예제 #22
0
def generateTests(size, padding, instances, ratios, tag, type='all'):
    """ 
    Name captures function.
    PARAMETERS:
        size: int representing desired side length of square images
        padding: int or float representing desired minimum number of pixels 
            between dots or dots and the image edges
        instances: int representing the desired number of unique instances per 
            variable value combination
        ratios: list of floats representing desired area ratios
        tag: str to occur at start of names of all files saved
        type: 'all' (default), 'aa control', 'ma control', or 'control', 
            indicating which type of trials to generate, corresponding to all 
            kinds, only trials in which paired stimuli have the same AA and 
            differing MA, only trials where paired images have the same MA and 
            differing AA, or only trials in which both MA and AA are equated
    """

    # Make a list containing a dictionary representing each pair of images to
    # be generated
    trials = []
    if type in ['all', 'ma control']:
        for AARatio in ratios:
            for trial in range(instances):
                trials.append({
                    'AA Ratio': AARatio,
                    'MA Ratio': 1.0,
                    'instance ID': trial
                })
    if type in ['all', 'aa control']:
        for MARatio in ratios:
            for trial in range(instances):
                trials.append({
                    'AA Ratio': 1.0,
                    'MA Ratio': MARatio,
                    'instance ID': trial
                })
    if type in ['all', 'control']:
        for trial in range(instances):
            trials.append({
                'AA Ratio': 1.0,
                'MA Ratio': 1.0,
                'instance ID': trial
            })

    # Set up materials to be saved upon conclusion of generating
    infoFile = 'Stimuli/' + tag + '_trial_info.txt'
    headers = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\n'.format(
        'TrialNumber', 'InstanceID', 'AARatio', 'MARatio', 'lowerAA',
        'higherAA', 'lowerMA', 'higherMA', 'comparisonNumerosity', 'FileOne',
        'FileTwo')
    with open(infoFile, 'w') as file:
        file.write(headers)
        file.close()
    images = np.empty((len(trials) * 2, size, size, 3))

    for trial in trials:
        # Extract variable values from dictionary
        aaRatio = trial['AA Ratio']
        maRatio = trial['MA Ratio']
        instance = trial['instance ID']
        trialNumber = trials.index(trial)

        # Setting possible diameter range to correspond with stimuli in Yousif
        # & Keil, 2019, which had a diameter range of [20, 100] and size of
        # 400 x 400
        minDiameter = math.floor((20. / 400) * size)
        maxDiameter = math.floor((100. / 400) * size)

        success = False
        while success == False:
            # Generate the intial set of seven dots
            loop = True
            while loop == True:
                loop = False
                dots = []
                aa = 0
                ma = 0
                counter_1 = 0
                while len(dots) < 7:
                    counter_1 += 1
                    # Generate a possible diameter value
                    dotAttempt = math.floor(
                        np.random.uniform(minDiameter, maxDiameter))
                    posBound = (size / 2) - (dotAttempt / 2 + padding)
                    posAttempt = (math.floor(
                        np.random.uniform(-posBound, posBound)),
                                  math.floor(
                                      np.random.uniform(-posBound, posBound)))
                    # Check whether this dot fits the others
                    goodDot = False
                    if len(dots) == 0:
                        goodDot = True
                    else:
                        goodDot = True
                        for dot in dots:
                            centerDistance = math.sqrt(
                                (dot[1][0] - posAttempt[0])**2 +
                                (dot[1][1] - posAttempt[1])**2)
                            if centerDistance < (dot[0] / 2 + dotAttempt / 2 +
                                                 padding):
                                goodDot = False
                    if goodDot:
                        dots.append([dotAttempt, posAttempt])
                        aa += (2 * dotAttempt)
                        ma += math.floor((math.pi * (dotAttempt / 2)**2))
                    if (counter_1 - 7) > 25:
                        loop = True
                        break
            setOne = {'dots': dots, 'aa': aa, 'ma': ma}

            # The second image generated will always have a greater numerosity;
            # here, we vary whether it has more or less area
            targetAA = setOne['aa'] * aaRatio
            targetMA = setOne['ma'] * maRatio

            # Generate the next set of dots
            counter_2 = 0
            while True:
                counter_2 += 1
                dots = []
                aa = 0
                ma = 0
                if counter_2 > 50:
                    break
                counter_3 = 0
                while math.floor(aa) < math.floor(targetAA):
                    counter_3 += 1
                    # If this stimulus could be made to meet the AA target with
                    # the addition of a single dot with a diameter within
                    # the acceptable range, then add this dot
                    if (targetAA - aa) / 2 < maxDiameter:
                        dotAttempt = math.floor((targetAA - aa) / 2)
                    # Otherwise, randomly generate a diameter within the range
                    else:
                        dotAttempt = math.floor(
                            np.random.uniform(minDiameter, maxDiameter))
                    # For some reason, PsychoPy seems to duplicate image size, so that
                    # with size = (64, 64), we get a 128 x 128 image. To resolve this,
                    # the x and y coordinates can only range between -size / 4 and
                    # size / 4, rather than -size / 2 and size / 2 as we'd expect.
                    posBound = (size / 2) - (dotAttempt / 2 + padding)
                    posAttempt = (math.floor(
                        np.random.uniform(-posBound, posBound)),
                                  math.floor(
                                      np.random.uniform(-posBound, posBound)))
                    # Check whether this dot fits the others
                    goodDot = False
                    if len(dots) == 0:
                        goodDot = True
                    else:
                        goodDot = True
                        for dot in dots:
                            centerDistance = math.sqrt(
                                (dot[1][0] - posAttempt[0])**2 +
                                (dot[1][1] - posAttempt[1])**2)
                            if centerDistance < (dot[0] / 2 + dotAttempt / 2 +
                                                 padding):
                                goodDot = False
                    if goodDot:
                        dots.append([dotAttempt, posAttempt])
                        aa += 2 * dotAttempt
                        ma += math.floor(math.pi * (dotAttempt / 2)**2)
                    # If there are 300 attempts that don't yield a dot, start
                    # over. 300 was arbitrarily chosen
                    if counter_3 > 200:
                        break
                # Accept the second set of dots if its MA value differs from the
                # target by no more than 1%, as in Yousif & Keil, 2019
                if aa == targetAA and abs((ma / targetMA) - 1) <= 0.005:
                    success = True
                    break

        setTwo = {
            'dots': dots,
            'aa': aa,
            'ma': ma,
        }

        print("Trial " + str(trialNumber) + " complete")

        # Render and save images
        fileOne = 'Stimuli/' + tag + '_' + str(trialNumber) + '_1.png'
        fileTwo = 'Stimuli/' + tag + '_' + str(trialNumber) + '_2.png'

        mas = []
        for image in [setOne, setTwo]:
            #  For some reason, the 'size' argument specifies the length of
            # half of each coordinate axis, so that size / 2 is required to
            # obtain a side length totaling size.
            win = visual.Window(size=(size / 2, size / 2),
                                units='pix',
                                fullscr=False,
                                screen=0,
                                monitor='testMonitor',
                                color='#ffffff',
                                colorSpace='rgb')
            win.flip()
            for dot in image['dots']:
                circle = visual.Circle(win,
                                       units='pix',
                                       radius=dot[0] / 4,
                                       pos=(dot[1][0] / 2, dot[1][1] / 2),
                                       fillColor='#000000',
                                       lineWidth=0.0)
                circle.draw()
            win.getMovieFrame(buffer='back')
            if image == setOne:
                imageName = fileOne
                imageIndex = 2 * trialNumber
            else:
                imageName = fileTwo
                imageIndex = 2 * trialNumber + 1
            win.saveMovieFrames(imageName)
            win.clearBuffer()
            win.close()
            # Convert image to array
            image = Image.open(imageName)
            # Normalize image
            imageAsArray = np.array(image) / 255.0
            # Add images to dataset array
            images[imageIndex] = imageAsArray
            # Calculate true MA from image
            reduced = imageAsArray.dot([1, 1, 1])
            new_shape = reduced.shape[0] * reduced.shape[1]
            flattened = np.reshape(reduced, new_shape) / 3
            ma = (imageAsArray.shape[0] * imageAsArray.shape[1]) - np.sum(
                flattened, axis=-1)
            mas.append(ma)

        # Push trial info to list
        """ FORMAT OF TRIALINFO LIST:
        trialInfo = [['TrialNumber', 'InstanceID', 'AARatio', 'MARatio', 'lowerAA',
                'higherAA', 'lowerMA', 'higherMA', 'comparisonNumerosity', 
                'FileOne', 'FileTwo']]
        """
        info = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}\n'.format(
            trialNumber, instance, aaRatio, maRatio,
            min(setOne['aa'], setTwo['aa']), max(setOne['aa'], setTwo['aa']),
            min(mas), max(mas), len(setTwo['dots']), fileOne, fileTwo)
        with open(infoFile, 'a') as file:
            file.write(info)
            file.close()

    imageDict = {'images': images}
    filename = 'test_data_' + tag + '.txt'
    with open(filename, 'wb') as file:
        pkl.dump(imageDict, file)

    # Close PsychoPy
    win.close()
    core.quit()
# Create task window
sx = 1000
sy = 800
win = visual.Window(size=(sx, sy), units="pix")

# Create Visual Stimuli
# fixation cross
cross = visual.TextStim(win, text="+", height=40)

#Coin Stimuli
#heads coins
leftPos = (-sx * .25, 0)
heads = visual.Circle(win,
                      radius=sy * .05,
                      pos=leftPos,
                      fillColor="cyan",
                      lineWidth=5)
h = visual.TextStim(win, text='H', height=40, pos=leftPos)

#tails coins
rightPos = (sx * .25, 0)
tails = visual.Circle(win,
                      radius=sy * .05,
                      pos=rightPos,
                      fillColor="orange",
                      lineWidth=5)
t = visual.TextStim(win, text='T', height=40, pos=rightPos)

#Text for COIN prediction phase
coinPredText = visual.TextStim(win,
def main(win, globalClock):
    
    all_changes = []
    size_ecc_pxl = resY * Eccentricity_size
    
    ################################ Stimuli prepation ################################
    
    # Make two wedges (in opposite contrast) and alternate them for flashing
    grating_texture = np.tile([[1,-1],[-1,1]], (8,8))#(4,64))
    wedge1 = visual.RadialStim(win, tex=grating_texture, color=1, units='pix', size=size_ecc_pxl,
                               radialCycles=1, angularCycles=2, interpolate=False,
                               autoLog=False)       #, mask=radius)
    wedge2 = copy.copy(wedge1)
    wedge2.color = -1
    
    position_from_center = np.linspace(0,size_ecc_pxl,Mask_positions_number).reshape((-1,1))
    

    # fixation cross
    fixation = visual.ShapeStim(win,vertices=((0,-1),(0,1),(0,0),(-1,0),(1,0)),lineWidth=4, units="pix",
        size=(20,20),closeShape=False,lineColor='red',autoDraw=True)
    
    # Spyder network
    web_circle = visual.Circle(win=win,radius=1,edges=200,units='norm',pos=[0, 0],lineWidth=1,opacity=1,interpolate=True,
                            lineColor=[1.0, 1.0, 1.0],lineColorSpace='rgb',fillColor=None,fillColorSpace='rgb')
    web_dimension = (screenCorrection(win,Web_size[0]),Web_size[1])
    web_line = visual.Line(win,name='Line',start=(-1.4, 0),end=(1.4, 0),pos=[0, 0],lineWidth=1,
                           lineColor=[1.0, 1.0, 1.0],lineColorSpace='rgb',opacity=1,interpolate=True)
    
    # DEBUG stimuli
    if DEBUG_MODE:
        fps_text = visual.TextStim(win, units='norm', height=0.05,pos=(-0.98, +0.93), text='starting...',
                                  font=sans, alignHoriz='left', alignVert='bottom', color='yellow')    
        fps_text.autoDraw = True
        
        orientation_details_string = visual.TextStim(win, text = u"eccentricity..", units='norm', height=0.05,
                                             pos=(0.95, +0.93), alignHoriz='right', alignVert='bottom', 
                                             font=sans, color='yellow')
        orientation_details_string.autoDraw = True        

    # External Aperture (black ring)
    external_aperture_size = tuple([screenCorrection(win,External_ring_size),External_ring_size])
    external_aperture = visual.Aperture(win, size=external_aperture_size, shape='circle')
    external_aperture.enabled = False


    ################################ Definitions/Functions ################################    
    
    ## handle Rkey presses each frame
    def escapeCondition():              
        for key in event.getKeys():
            if key in ['escape', 'q']:
                return False
        return True

    
    ################################ Animation starts ################################    
    # display instructions and wait
    message1 = visual.TextStim(win, pos=[0,0.5],text='Hit a key when ready.')
    message1.draw()
    fixation.draw()
    win.flip()#to show our newly drawn 'stimuli'
    event.waitKeys()                #pause until there's a keypress

    # Scanner trigger wait
    message3 = visual.TextStim(win,pos=[0,0.25],text=scanner_message,font=serif,alignVert='center',
                               wrapWidth=1.5)
    message3.size = .5
    message3.draw()
    win.flip()

    if BUTTON_BOX:
        button_state = button_thread.button_state
        while 1:
            if(button_state['state'][-1]==0):
                break
    else:
        event.waitKeys()    #pause until there's a keypress

    
    # Wait Pre_post_stimuli_fixation_time before stimuli
    # Spyder network
    if Spyder_grid:
        for i_dim in range(Spyder_rings):
            web_circle.setSize(tuple([x*(i_dim+1) * 1./Spyder_rings for x in web_dimension]))
            web_circle.draw()
        for i_dim in range(2):
            web_line.setOri(i_dim * 90)
            web_line.draw()
    win.flip()
    core.wait(Pre_post_stimuli_fixation_time)


    t = last_fps_update = i_cycle = new_record = 0
    break_flag = True
    globalClock.reset()
    inizio = globalClock.getTime()
    logging.data('First cycle. Number %d/%d at %f (sec.)' % (i_cycle+1,Cycles_number,inizio))
    
    while (globalClock.getTime() < Total_time and break_flag==True):
        t = globalClock.getTime()
        
        # Spyder network
        if Spyder_grid:
            for i_dim in range(Spyder_rings):
                web_circle.setSize(tuple([x*(i_dim+1) * 1./Spyder_rings for x in web_dimension]))
                web_circle.draw()
            for i_dim in range(2):
                web_line.setOri(i_dim * 90)
                web_line.draw()

        # External ring
        external_aperture.enabled = True
                
        if t % Flash_period < Flash_period / 2.0:  # more accurate to count frames
            stim = wedge1
        else:
            stim = wedge2

        # Prepare moving mask
        if (t >= ((i_cycle+1)*Cycle_duration)):
            logging.data('Change orientation. Number %d/%d at %f (sec.)' % (i_cycle+1,Cycles_number,t))
            new_record = globalClock.getTime() - sum(all_changes)
            all_changes.append(new_record)        
        i_cycle = int(t/Cycle_duration)
        crown_pos_indx = int((Mask_positions_number / Cycle_duration/2) * (t % Cycle_duration))
        ## Try to understand when it changes and save it
        mask_begin = int(position_from_center[crown_pos_indx,0])
        mask_end = int(position_from_center[crown_pos_indx,0] + Thickness_multiplication_factor[crown_pos_indx] * Thickness_circular_crown)
                                      
        annulus_mask = np.zeros((int(size_ecc_pxl/2),1))
        annulus_mask[mask_begin : mask_end] += 1        #int(mask_end if mask_end <= size_ecc_pxl else size_ecc_pxl)] += 1      
        stim.setMask(annulus_mask)    
        stim.draw()


        # Fixation
        if Rotating_cross:
            fixation.ori = t * Rotation_cross_rate * 360.0  # set new rotation
        if Color_change_cross:
            if t % Color_change_rate < Color_change_rate / 2.0:  # more accurate to count frames
                fixation.lineColor = 'red'
            else:
                fixation.lineColor = 'green'        

        external_aperture.enabled = False
        
        if DEBUG_MODE:
            if t - last_fps_update > Fps_update_rate:         # update the fps text every second
                fps_text.text = "%.2f fps" % win.fps()
                last_fps_update += 1
            orientation_details_string.text = 'Pass: %d/%d at %.3f (sec.)' % (i_cycle+1,Cycles_number,np.sum(all_changes))

        win.flip()
        break_flag = escapeCondition()
        if break_flag == False: break


    logging.data('Total time spent: %.6f' % (globalClock.getTime() - inizio))
    logging.data('Every frame duration saved in %s' % (path_out+Frames_durations_name))
    logging.data('All durations: ' + str(all_changes))
    logging.data('Mean: ' + str(sum(all_changes)/(len(all_changes)+EPSILON)))

    if DEBUG_MODE:
        orientation_details_string.text = 'Ended at %.3f (sec.)' % (globalClock.getTime())

    win.flip()
    # Wait Pre_post_stimuli_fixation_time after stimuli
    core.wait(Pre_post_stimuli_fixation_time)
    return
예제 #25
0
파일: simple.py 프로젝트: psydabow/psychopy
    tracker = io.getDevice('tracker')

    # print("display: ", display.getCoordinateType())

    # run eyetracker calibration
    tracker.runSetupProcedure()

    win = visual.Window(display.getPixelResolution(),
                        units=display.getCoordinateType(),
                        fullscr=True,
                        allowGUI=False)

    win.setMouseVisible(True)

    gaze_ok_region = visual.Circle(win,
                                   lineColor='black',
                                   radius=300,
                                   units='pix')

    gaze_dot = visual.GratingStim(win,
                                  tex=None,
                                  mask='gauss',
                                  pos=(0, 0),
                                  size=(40, 40),
                                  color='green',
                                  units='pix')

    text_stim_str = 'Eye Position: %.2f, %.2f. In Region: %s\n'
    text_stim_str += 'Press space key to start next trial.'
    missing_gpos_str = 'Eye Position: MISSING. In Region: No\n'
    missing_gpos_str += 'Press space key to start next trial.'
    text_stim = visual.TextStim(win,
예제 #26
0
#Calculate size of stimuli in original experiment
OGWidth = 1024
OGHeight = 768
OGDiag = sqrt(OGWidth**2 + OGHeight**2)
OGDiagInch = 17
OGDiagCM = OGDiagInch * 2.54
OGpixelPerDegree = OGDiag / ((atan(OGDiagCM / 57.)) * (180 / np.pi))
print('OGPPD', OGpixelPerDegree)

radiusPix = 200
radius = radiusPix / OGpixelPerDegree  #circle radius
center = (0, 0)  #circle centre

fixSize = .1
fixation = visual.Circle(myWin,
                         radius=fixSize,
                         fillColor=(1, 1, 1),
                         units=units)

cueRadiusPix = 360
cueRadiusDeg = cueRadiusPix / OGpixelPerDegree
cue = visual.Circle(myWin,
                    radius=cueRadiusDeg,
                    fillColor=None,
                    lineColor=(1, 1, 1),
                    units=units)

instruction = visual.TextStim(myWin,
                              pos=(0, -(radius + 1)),
                              colorSpace='rgb',
                              color=(1, 1, 1),
                              alignHoriz='center',
예제 #27
0
    fixSizePix = 18 #2.6  #make fixation bigger so flicker more conspicuous
else: fixSizePix = 6

########################################
####Fixation and instruction stimuli####
########################################

fixColor = [1,1,1]
fixatnPtSize = 4
if exportImages: fixColor= [0,0,0]
fixatnTextureWidth = np.round(fixSizePix/4).astype(int)
fixatnNoiseTexture = np.round( np.random.rand(fixatnTextureWidth,fixatnTextureWidth) ,0 )   *2.0-1 #Can counterphase flicker  noise texture to create salient flicker if you break fixation

fixatn= visual.PatchStim(myWin, tex=fixatnNoiseTexture, size=(fixSizePix,fixSizePix), units='pix', mask='circle', interpolate=False, autoLog=False)
fixatnCounterphase= visual.PatchStim(myWin, tex= -1*fixatnNoiseTexture, size=(fixSizePix,fixSizePix), units='pix', mask='circle', interpolate=False, autoLog=False) #reverse contrast
fixatnPoint= visual.Circle(myWin,fillColorSpace='rgb',fillColor=(1,1,1),radius=fixatnPtSize,pos=[0,0],units='pix',autoLog=autoLogging)
                     
respPromptStim = visual.TextStim(myWin,pos=(0, -.8),colorSpace='rgb',color=(1,1,1),alignHoriz='center', alignVert='center',height=.1,units='norm',autoLog=autoLogging)
acceptTextStim = visual.TextStim(myWin,pos=(0, -.7),colorSpace='rgb',color=(1,1,1),alignHoriz='center', alignVert='center',height=.1,units='norm',autoLog=autoLogging)
acceptTextStim.setText('Hit ENTER to accept. Backspace to edit')
respStim = visual.TextStim(myWin,pos=(0,0),colorSpace='rgb',color=(1,1,0),alignHoriz='center', alignVert='center',height=.16,units='norm',autoLog=autoLogging)
clickSound, badKeySound = stringResponse.setupSoundsForResponse()
requireAcceptance = False
nextText = visual.TextStim(myWin,pos=(0, .1),colorSpace='rgb',color = (1,1,1),alignHoriz='center', alignVert='center',height=.1,units='norm',autoLog=autoLogging)
NextRemindCountText = visual.TextStim(myWin,pos=(0,.2),colorSpace='rgb',color= (1,1,1),alignHoriz='center', alignVert='center',height=.1,units='norm',autoLog=autoLogging)
screenshot= False; screenshotDone = False

instructions1 = visual.TextStim(myWin,pos=(0,0),colorSpace='rgb',color= (1,1,1),alignHoriz='center', alignVert='center',height=.5,units='deg',autoLog=autoLogging)
instructions2 = visual.TextStim(myWin,pos=(0,0),colorSpace='rgb',color= (1,1,1),alignHoriz='center', alignVert='center',height=.5,units='deg',autoLog=autoLogging)

instructionText1 = """
예제 #28
0
def doRSVPStim(trial):
    '''
    ONLY DOES ONE CUE AT THE MOMENT

    This function generates the stimuli for each trial. The word "frame" here refers to a set of simultaneous RSVP stimuli. I'll use "refresh" to refer to monitor refreshes.
    Using the parameters for the current trial:
        - Work out the temporal position of the cue(s)
        - Shuffle the order of the letters
        - Calculate the position and cortically-magnified size for each stream
        - draw and buffer preCues
        - Capture each stream's pixels on each frame using bufferImageStim
        - Collate each frame's pixels so that all stimuli are represented by the same matrix of pixels. Put the cue in there if it's the cued frame
        - pass the matrix of pixels to elementarraystim
    '''

    global cue

    nStreams = trial['nStreams']
    numTargets = trial['numToCue']

    cuedFrame = trial['cue0temporalPos']
    cuedStream = np.random.choice(np.arange(nStreams), 1)

    cue.pos = calcStreamPos(trial=trial,
                            cueOffsets=cueOffsets,
                            streami=cuedStream,
                            streamOrNoise=False)
    cue = corticalMagnification.corticalMagnification(
        cue, 0.9810000000000002,
        cue=True)  #this is the cuesize from the original experiment

    preCues = list()
    preCues.append(cue)

    if trial['cueSpatialPossibilities'] == 2:
        preCue = visual.Circle(
            myWin,
            radius=cueRadius,  #Martini used circles with diameter of 12 deg
            lineColorSpace='rgb',
            lineColor=letterColor,
            lineWidth=2.0,  #in pixels
            units='deg',
            fillColorSpace='rgb',
            fillColor=None,  #beware, with convex shapes fill colors don't work
            pos=[
                -5, -5
            ],  #the anchor (rotation and vertices are position with respect to this)
            interpolate=True,
            autoLog=False
        )  #this stim changes too much for autologging to be useful

        preCue.pos = calcStreamPos(trial=trial,
                                   cueOffsets=cueOffsets,
                                   streami=cuedStream - 4,
                                   streamOrNoise=False)

        preCue = corticalMagnification.corticalMagnification(
            preCue, 0.9810000000000002, cue=True)

        preCues.append(preCue)

    elif trial['cueSpatialPossibilities'] == 8:
        for i in range(1, 8):
            preCue = visual.Circle(
                myWin,
                radius=cueRadius,  #Martini used circles with diameter of 12 deg
                lineColorSpace='rgb',
                lineColor=letterColor,
                lineWidth=2.0,  #in pixels
                units='deg',
                fillColorSpace='rgb',
                fillColor=
                None,  #beware, with convex shapes fill colors don't work
                pos=[
                    -5, -5
                ],  #the anchor (rotation and vertices are position with respect to this)
                interpolate=True,
                autoLog=False
            )  #this stim changes too much for autologging to be useful

            preCue.pos = (calcStreamPos(trial=trial,
                                        cueOffsets=cueOffsets,
                                        streami=cuedStream - i,
                                        streamOrNoise=False))

            preCue = corticalMagnification.corticalMagnification(
                preCue, 0.9810000000000002, cue=True)
            preCues.append(preCue)

    print('cueFrame = ' + str(cuedFrame))

    preCueStim = preTrial[int(
        baseAngleCWfromEast / anglesMustBeMultipleOf)] + preCues

    preCueFrame = visual.BufferImageStim(win=myWin, stim=preCueStim)

    preCueFrame = np.flipud(
        np.array(preCueFrame.image)[..., 0]
    ) / 255.0 * 2.0 - 1.0  #Via djmannion. This converts the pixel values from [0,255] to [-1,1]. I think 0 is middle grey. I'll need to change this to match the background colour eventually

    preCueFrame = np.pad(
        array=preCueFrame,
        pad_width=pad_amounts,  #See 'Buffered image size dimensions' section
        mode="constant",
        constant_values=0.0)

    preCueFrame = visual.ElementArrayStim(win=myWin,
                                          units='pix',
                                          nElements=1,
                                          xys=[[0, 0]],
                                          sizes=preCueFrame.shape,
                                          elementTex=preCueFrame,
                                          elementMask='none')

    streamPositions = list(
    )  #Might need to pass this to elementArrayStim as xys. Might not though

    streamLetterIdxs = np.empty(  #use an array so I can select columns (frames) for buffering. This is an empty array that will eventually have the
        #letter indexes for each stream. Selecting a column gives us all streams at a particular frame. Selecting a row gives us
        #all frames for a particular stream
        shape=(nStreams, numLettersToPresent),
        dtype=int)

    streamLetterIdentities = np.empty(  #Letter identities for these streams
        shape=(nStreams, numLettersToPresent),
        dtype=str)

    for thisStream in xrange(nStreams):
        thisSequence = np.arange(24)
        np.random.shuffle(thisSequence)
        theseIdentities = [potentialLetters[idx] for idx in thisSequence]
        streamLetterIdxs[thisStream, :] = thisSequence
        streamLetterIdentities[thisStream, :] = theseIdentities
        #print('For stream %(streamN)d the letters are: %(theseLetters)s' % {'streamN':thisStream, 'theseLetters':''.join(theseIdentities)})

    correctIdx = streamLetterIdxs[cuedStream, cuedFrame]
    print('correctIdx')
    print(correctIdx)
    correctLetter = alphabetHelpers.numberToLetter(
        correctIdx, potentialLetters)  #potentialLetters is global

    frameStimuli = list(
    )  #A list of elementArrayStim objects, each represents a frame. Drawing one of these objects will draw the letters and the cue for that frame

    for thisFrame in xrange(numLettersToPresent):
        theseStimuli = streamLetterIdxs[:,
                                        thisFrame]  #The alphabetical indexes of stimuli to be shown on this frame

        stimuliToDraw = list()  #Can pass a list to bufferimageStim!
        stimuliToDraw.append(fixatn)
        stimuliToDrawCounterPhase = list()
        stimuliToDrawCounterPhase.append(fixatnCounterphase)

        for thisStream in xrange(nStreams):
            cueThisFrame = thisStream == cuedStream and thisFrame == cuedFrame  #If true, draw the cue and capture that too

            thisLetterIdx = theseStimuli[
                thisStream]  #The letter index for this particular stream on this particular frame

            thisStreamStimulus = streamTextObjects[
                thisStream, thisLetterIdx]  #The text object for this stream

            thisPos = calcStreamPos(trial=trial,
                                    cueOffsets=cueOffsets,
                                    streami=thisStream,
                                    streamOrNoise=False)

            thisStreamStimulus.pos = thisPos

            stimuliToDraw.append(thisStreamStimulus)
            stimuliToDrawCounterPhase.append(thisStreamStimulus)

            if cueThisFrame and cueType == 'exogenousRing':
                stimuliToDraw.append(cue)
                stimuliToDrawCounterPhase.append(cue)

        buff = visual.BufferImageStim(  #Buffer these stimuli
            win=myWin, stim=stimuliToDraw)

        buff = np.flipud(
            np.array(buff.image)[..., 0]
        ) / 255.0 * 2.0 - 1.0  #Via djmannion. This converts the pixel values from [0,255] to [-1,1]. I think 0 is middle grey. I'll need to change this to match the background colour eventually

        buff = np.pad(
            array=buff,
            pad_width=pad_amounts,  #See 'Buffered image size dimensions' section
            mode="constant",
            constant_values=0.0)

        thisFrameStimuli = visual.ElementArrayStim(  #A stimulus representing this frame with the fixation at full luminance
            win=myWin,
            units='pix',
            nElements=1,
            xys=[[0, 0]],
            sizes=buff.shape,
            elementTex=buff,
            elementMask='none')

        buff = visual.BufferImageStim(  #Buffer these stimuli
            win=myWin, stim=stimuliToDrawCounterPhase)

        buff = np.flipud(
            np.array(buff.image)[..., 0]
        ) / 255.0 * 2.0 - 1.0  #Via djmannion. This converts the pixel values from [0,255] to [-1,1]. I think 0 is middle grey. I'll need to change this to match the background colour eventually

        buff = np.pad(
            array=buff,
            pad_width=pad_amounts,  #See 'Buffered image size dimensions' section
            mode="constant",
            constant_values=0.0)

        thisFrameStimuliCounterPhase = visual.ElementArrayStim(  #A stimulus representing this frame with the fixation phase reversed
            win=myWin,
            units='pix',
            nElements=1,
            xys=[[0, 0]],
            sizes=buff.shape,
            elementTex=buff,
            elementMask='none')

        frameStimuli.append([thisFrameStimuli, thisFrameStimuliCounterPhase])

    ts = []

    waiting = True
    myMouse.setVisible(waiting)

    while waiting:
        startTrialStimuli.draw()
        startTrialBox.draw()
        myWin.flip()
        if myMouse.isPressedIn(startTrialBox):
            waiting = False

    myMouse.setVisible(waiting)

    if eyetracking:
        tracker.startEyeTracking(nDone, True, widthPix,
                                 heightPix)  #start recording with eyetracker

    myWin.flip()
    myWin.flip(
    )  #Make sure raster at top of screen (unless not in blocking mode), and give CPU a chance to finish other tasks
    preCueFrame.draw()
    myWin.flip()
    core.wait(.25)
    myWin.flip
    core.wait(.5)
    fixatn.draw()
    myWin.flip()
    core.wait(1)

    t0 = trialClock.getTime()
    for n in xrange(trialDurFrames):
        oneFrameOfStim(n, frameStimuli)
        myWin.flip()
        ts.append(trialClock.getTime() - t0)

    if eyetracking:
        tracker.stopEyeTracking()
        print('stopped tracking')
    return streamLetterIdxs, streamLetterIdentities, correctLetter, ts, cuedStream, cuedFrame
    txt.setAutoDraw(True)
    fixation.setAutoDraw(False)
    win.flip()

    event.waitKeys(keyList = ['right'])

    txt.setAutoDraw(False)
    win.flip()


oddBallStim1 = visual.Circle(myWin,
                    radius=oddBallMaxRadius1,  # Martini used circles with diameter of 12 deg
                    lineColorSpace='rgb',
                    lineColor=stimColor,
                    lineWidth=2.0,  # in pixels
                    units='deg',
                    fillColorSpace='rgb',
                    fillColor=stimColor,  # beware, with convex shapes fill colors don't work
                    # the anchor (rotation and vertices are position with respect to this)
                    pos=[0,0],
                    interpolate=True,
                    autoLog=False)  # this stim changes too much for autologging to be useful

oddBallStim2 = visual.Circle(myWin,
                    radius=oddBallMaxRadius1,  # Martini used circles with diameter of 12 deg
                    lineColorSpace='rgb',
                    lineColor='blue',
                    lineWidth=2.0,  # in pixels
                    units='deg',
                    fillColorSpace='rgb',
                    fillColor='blue',  # beware, with convex shapes fill colors don't work
                    # the anchor (rotation and vertices are position with respect to this)
예제 #30
0
파일: exercise6_2.py 프로젝트: REEEYZ/LCNL
from psychopy import visual, event, core
import random

win = visual.Window([800, 600], color = 'black', units = 'pix')
locations = [[-15, 0], [15, 0]]
flip = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
flipPoint = random.choice(range(16))
flip[flipPoint] = 1; 
isFlip = True;

for i in range(16):
    if flip[i] == 1:
        isFlip = False
    circle = visual.Circle(win, size = 20)
    circle.setPos(locations[0])
    square = visual.Rect(win, size = 40)
    square.setPos(locations[1])
    
    if i % 2 == 0:
        if isFlip:
            circle.setFillColor('red')
            circle.setLineColor('red')
            circle.setPos([30 * i - 240, 0])
            circle.draw()
        else:
            square.setFillColor('red')
            square.setLineColor('red')
            square.setPos([30 * i - 240, 0])
            square.draw()
    else:
        if isFlip: