Beispiel #1
0
                           anchor = 'center',
                           size = (width*scale,height*scale),
                           mipmaps_enabled = 0,
                           texture_min_filter=gl.GL_LINEAR)

texture_object = stimulus.parameters.texture.get_texture_object()
def update_movie():
    # While movie.play() decompresses the movie to pygame surface
    # in a separate thread, this sends the data to OpenGL.
    texture_object.put_sub_image( pygame_surface )
    
viewport = Viewport(screen=screen,
                    stimuli=[stimulus,text])

p = Presentation(go_duration=('forever',),
                 viewports=[viewport],
                 handle_event_callbacks=[(pygame.locals.QUIT, quit),
                                         (pygame.locals.KEYDOWN, keydown)],
                 )

p.add_controller(None,None,FunctionController(during_go_func=update_movie,
                                              temporal_variables=TIME_INDEPENDENT))

movie.play()
#p.go()
import cProfile,pstats
cProfile.run('p.go()','mpeg_profile')
p = pstats.Stats('mpeg_profile')
p.sort_stats('cumulative')
p.print_stats()
Beispiel #2
0
coherence_controller = FunctionController(during_go_func=setCoherence)
direction_controller = FunctionController(during_go_func=setDirection)
inst_controller = FunctionController(during_go_func=changeInstructions)
inst_on_controller = FunctionController(during_go_func=setInstructions)
inst3_on_controller = FunctionController(during_go_func=setTimeOn)
inst3_position_controller = FunctionController(during_go_func=setTimePos)
fixation_texture_controller = FunctionController(
    during_go_func=setFixationTexture)
samplefix_controller = FunctionController(during_go_func=setSampleFix)

state_controller = FunctionController(during_go_func=getState)

#######################################################
#  Connect the controllers with objects they control  #
#######################################################
p.add_controller(p, 'trigger_go_if_armed', trigger_in_controller)

# on or off before pres
p.add_controller(str_instruct_1, 'on', stimulus_off_controller)
p.add_controller(str_instruct_2, 'text', inst_controller)
p.add_controller(str_instruct_2, 'on', stimulus_on_controller)
p.add_controller(str_instruct_2, 'on', inst_on_controller)
p.add_controller(dotStim, 'on', stimulus_on_controller)
p.add_controller(fixation, 'on', stimulus_on_controller)

# on or off during pres
p.add_controller(fixation, 'max_alpha', fixation_controller)
p.add_controller(dotStim, 'on', dot_controller)
p.add_controller(dotStim, 'signal_fraction', coherence_controller)
p.add_controller(dotStim, 'signal_direction_deg', direction_controller)
p.add_controller(fixation, 'texture', fixation_texture_controller)
Beispiel #3
0
    print "----------------------"
    print "PROBLEM: %s" % problem
    print "SOLUTION: %s " % solution
    print "----------------------"

    ns = [n1, n2]

    # default values for misfiring voice key
    misfire = 0
    ACC = 1

    # BLOCK 1 - Problem & RESPONSE

    p = Presentation(go_duration=("forever",), viewports=[expPort])
    p.add_controller(
        None, None, FunctionController(during_go_func=problem_controller, temporal_variables=FRAMES_ABSOLUTE)
    )
    p.go()

    # BLOCK 2 - STRATEGY SELECTION & GRADING
    p2 = Presentation(go_duration=(1.5, "seconds"), viewports=[fixCross])
    p2.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN, key_handler)]
    p2.go()

    if ACC == 0:
        problemQ = [n1, n2, stim]
        error = Presentation(go_duration=(1, "seconds"), viewports=[errorPort])
        error.go()
    else:
        problemQ = []
Beispiel #4
0
	problem.go()

	p3 = Presentation(go_duration=(blankTime, 'seconds'), viewports=[fixCross])
	p3.go()

	p = Presentation(go_duration=('forever', ), viewports=[vr])
	p.parameters.handle_event_callbacks=[(pygame.locals.KEYDOWN, key_handler)]  
	p.go()

	
	subject.inputData(trial, "RT", RT)
	subject.inputData(trial, "ACC", ACC)
	
	#BLOCK 2 - STRATEGY SELECTION
	p2 = Presentation(go_duration=('forever', ), viewports=[stratPort])
	p2.add_controller(None, None, FunctionController(during_go_func=strategy_controller, temporal_variables = FRAMES_ABSOLUTE))
	p2.parameters.handle_event_callbacks=[(pygame.locals.KEYDOWN, key_handler)]        
	p2.go()
	
	subject.inputData(trial, "cur_strat", strategy)
	
	#BLOCK 3 - BLANK SCREEN
	p3 = Presentation(go_duration=(0.5, 'seconds'), viewports=[fixCross])
	p3.go()
	
	trial = trial + 1
	
	subject.printData()
	
subject.preserve()
Beispiel #5
0
import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()

from VisionEgg.Core import *
from VisionEgg.FlowControl import Presentation
from VisionEgg.Gratings import *
import VisionEgg.Daq
from VisionEgg.DaqLPT import *

# Normal stuff (from grating demo):
screen = get_default_screen()
stimulus = SinGrating2D(position         = ( screen.size[0]/2.0, screen.size[1]/2.0 ),
                        anchor           = 'center',
                        size             = ( 300.0 , 300.0 ),
                        spatial_freq     = 10.0 / screen.size[0], # units of cycles/pixel
                        temporal_freq_hz = 5.0,
                        orientation      = 45.0 )
viewport = Viewport( screen=screen, stimuli=[stimulus] )
p = Presentation(go_duration=(5.0,'seconds'),viewports=[viewport])

# Create a trigger output controller
trigger_out_controller = LPTTriggerOutController()

# Add the trigger output controller to the presentation's list of controllers
p.add_controller(None,None,trigger_out_controller)

# Go!
p.go()
class Simulation:
    def __init__(self, screen):
        self.state = SimulationState()
        self.state.v = 15
        self.screen = screen
        self.center = screen.size[0] / 2.0
        self.doneSetup = False
        self.quit = False

    def init_state(self):
        self.state.th = 0
        self.state.x = 0
        self.state.z = 0

    def wait_for_key(self, t):
        #event = pygame.event.poll()
        #while event != pygame.NOEVENT:
        #	if event == pygame.KEYDOWN:
        #		self.askForNext.quit = True
        #	event = pygame.event.poll()
        pygame.event.pump()
        if any(pygame.key.get_pressed()):
            print "Got key"
            self.askForNext.parameters.quit = True
        self.askForNext.parameters.enter_go_loop = True

    def update(self, t):

        # Estimate the current frame rate
        try:
            dt = self.frame_timer.get_average_ifi_sec()
        except RuntimeError:
            dt = 0.01

        # Map the pointer position to angular velocity of +/- 90 degrees/s
        curr_pos = pygame.mouse.get_pos()
        self.pos_ring.add(curr_pos[0])
        pos = self.pos_ring.head()
        center = self.center

        self.state.th = self.state.th + dt * (-(math.pi) / 2.0 *
                                              (pos - center) / center)

        # Update steering wheel
        self.wheel.set(angle=-90.0 * (curr_pos[0] - center) / center)

        th = self.state.th
        x = self.state.x
        z = self.state.z

        self.outf.write("%f\t%u\t%u\t%u\t%f\t%f\t%f\n" %
                        (t, curr_pos[0], curr_pos[1], pos, th, x, z))

        # this is a left handed camera transform, the right handed ones that are
        # built in to visionegg were not working for me.
        # Translate, then rotate about the y-axis by our current heading angle
        viewXfrm = numpy.matrix([[math.cos(th), 0.0,
                                  math.sin(th), 0.0], [0.0, 1.0, 0.0, 0.0],
                                 [-math.sin(th), 0.0,
                                  math.cos(th), 0.0],
                                 [
                                     -x * math.cos(th) + z * math.sin(th), 0.0,
                                     -x * math.sin(th) - z * math.cos(th), 1.0
                                 ]])

        # Make a step in the direction of current heading
        self.state.x = x + self.state.v * dt * math.sin(-th)
        self.state.z = z - self.state.v * dt * math.cos(-th)

        self.camera_matrix.parameters.matrix = viewXfrm

    def doSim(self, trial, road, duration, tau, doEyetrack):

        # Measure sample rate in order to calculate delay buffer
        sample_rate = self.screen.measure_refresh_rate(2.0)
        print "Sample rate: " + str(sample_rate)
        #sample_rate = 60

        self.doEyetrack = doEyetrack

        self.pos_ring = RingBuffer(self.center,
                                   int(math.floor(tau * sample_rate)) + 1)
        print("Ring Buffer:: size: " + str(self.pos_ring.size))

        if doEyetrack:
            import pylink
            from EyeLinkCoreGraphicsVE import EyeLinkCoreGraphicsVE

            self.tracker = pylink.EyeLink()
            if self.tracker == None:
                print "Error: Eyelink is not connected"
                sys.exit()

            genv = EyeLinkCoreGraphicsVE(self.screen, self.tracker)
            pylink.openGraphicsEx(genv)

            #Opens the EDF file.
            edfFileName = "TRIAL" + str(trial) + ".EDF"
            self.tracker.openDataFile(edfFileName)

            pylink.flushGetkeyQueue()

            self.tracker.sendCommand("screen_pixel_coords =	0 0 %d %d" %
                                     (VisionEgg.config.VISIONEGG_SCREEN_W,
                                      VisionEgg.config.VISIONEGG_SCREEN_H))

            tracker_software_ver = 0
            eyelink_ver = self.tracker.getTrackerVersion()
            if eyelink_ver == 3:
                tvstr = self.tracker.getTrackerVersionString()
                vindex = tvstr.find("EYELINK CL")
                tracker_software_ver = int(
                    float(tvstr[(vindex + len("EYELINK CL")):].strip()))

            if eyelink_ver >= 2:
                self.tracker.sendCommand("select_parser_configuration 0")
                if eyelink_ver == 2:  #turn off scenelink camera stuff
                    self.tracker.sendCommand("scene_camera_gazemap = NO")
            else:
                self.tracker.sendCommand("saccade_velocity_threshold = 35")
                self.tracker.sendCommand(
                    "saccade_acceleration_threshold = 9500")

            # set EDF file contents
            self.tracker.sendCommand(
                "file_event_filter = LEFT,RIGHT,FIXATION,SACCADE,BLINK,MESSAGE,BUTTON"
            )
            if tracker_software_ver >= 4:
                self.tracker.sendCommand(
                    "file_sample_data	= LEFT,RIGHT,GAZE,AREA,GAZERES,STATUS,HTARGET"
                )
            else:
                self.tracker.sendCommand(
                    "file_sample_data	= LEFT,RIGHT,GAZE,AREA,GAZERES,STATUS")

            # set link data (used for gaze cursor)
            self.tracker.sendCommand(
                "link_event_filter = LEFT,RIGHT,FIXATION,SACCADE,BLINK,BUTTON")
            if tracker_software_ver >= 4:
                self.tracker.sendCommand(
                    "link_sample_data	= LEFT,RIGHT,GAZE,GAZERES,AREA,STATUS,HTARGET"
                )
            else:
                self.tracker.sendCommand(
                    "link_sample_data	= LEFT,RIGHT,GAZE,GAZERES,AREA,STATUS")

            if not self.doneSetup:
                self.tracker.doTrackerSetup()
                self.doneSetup = True
            else:
                while 1:
                    try:
                        error = self.tracker.doDriftCorrect(
                            self.screen.size[0] / 2, self.screen.size[1] / 2,
                            1, 1)
                        if error != 27:  # ?? from example
                            break
                        else:
                            self.tracker.doTrackerSetup()
                    except:
                        break

        self.screen.parameters.bgcolor = 106.0 / 255.0, 147.0 / 255.0, 0.0
        # Load road data from file and create an image
        roadArray = numpy.loadtxt('road' + str(road) + '.txt')

        # Convert to a Path
        roadPath = ImagePath.Path(
            map(lambda xy: (xy[0], xy[1]), roadArray.tolist()))

        # Use Path to create a plot of the road
        im = Image.new("RGB", (2000, 100), (50, 50, 50))
        draw = ImageDraw.Draw(im)

        # draw each side of the road separately
        draw.line(roadPath[:4000], fill=(200, 200, 200))
        draw.line(roadPath[4000:], fill=(200, 200, 200))

        del draw

        # Lay out a road texture in the x-z plane
        roadTexture = Texture(im)

        del im

        eye_height = 2.5

        vertices = [(-10, -eye_height, 0), (-10, -eye_height, -1000),
                    (10, -eye_height, 0), (10, -eye_height, -1000)]

        rect = TextureStimulus3D(texture=roadTexture,
                                 lowerleft=vertices[0],
                                 lowerright=vertices[1],
                                 upperleft=vertices[2],
                                 upperright=vertices[3])

        # We will use these later for our camera transforms
        self.camera_matrix = ModelView()
        self.frame_timer = FrameTimer()

        self.outf = open(
            'steersim-' + str(trial) + '-' + str(road) + '-out.txt', 'wb')

        # Vewport for the road
        viewport3D = Viewport(
            screen=self.screen,
            projection=SimplePerspectiveProjection(fov_x=75.2),
            camera_matrix=self.camera_matrix,
            stimuli=[rect])

        # Construct a sky
        sky_l = 0
        sky_r = self.screen.size[0]
        sky_t = self.screen.size[1]
        sky_b = self.screen.size[1] / 2

        sky_vertices = [(sky_l, sky_t, 0), (sky_r, sky_t, 0),
                        (sky_r, sky_b, 0), (sky_l, sky_b, 0)]

        sky = Rectangle3D(color=(144.0 / 255.0, 190.0 / 255.0, 1.0),
                          vertex1=sky_vertices[0],
                          vertex2=sky_vertices[1],
                          vertex3=sky_vertices[2],
                          vertex4=sky_vertices[3])

        wheelTexture = Texture('wheel.png')
        self.wheel = TextureStimulus(texture=wheelTexture,
                                     internal_format=gl.GL_RGBA,
                                     position=(self.center, -75),
                                     anchor='center')

        # display the sky in its own viewport
        viewport2D = Viewport(screen=self.screen)
        viewport2D.parameters.stimuli = [sky, self.wheel]

        self.init_state()

        askText = Text(text='Press a key to start',
                       anchor='center',
                       position=(self.center, self.screen.size[1] / 2))
        splash = Viewport(screen=self.screen)
        splash.parameters.stimuli = [askText]
        self.askForNext = Presentation(go_duration=(0.5, 'seconds'),
                                       viewports=[splash])
        self.askForNext.add_controller(
            None, None, FunctionController(during_go_func=self.wait_for_key))
        self.askForNext.parameters.enter_go_loop = True
        self.askForNext.run_forever()

        self.simPres = Presentation(go_duration=(duration, 'seconds'),
                                    viewports=[viewport3D, viewport2D],
                                    handle_event_callbacks=[
                                        (pygame.KEYDOWN, self.check_keypress)
                                    ])
        self.simPres.add_controller(
            None, None, FunctionController(during_go_func=self.update))

        if doEyetrack:
            startTime = pylink.currentTime()
            self.tracker.sendMessage("SYNCTIME %d" %
                                     (pylink.currentTime() - startTime))
            error = self.tracker.startRecording(1, 1, 1, 1)
            self.tracker.sendMessage("PRES %d START" % (trial))

        self.simPres.go()

        if doEyetrack:
            self.tracker.sendMessage("PRES %d END" % (trial))
            self.tracker.stopRecording()

            # File transfer and cleanup!
            self.tracker.setOfflineMode()
            pylink.msecDelay(500)
            #Close the file and transfer it to Display PC
            self.tracker.closeDataFile()
            self.tracker.receiveDataFile(edfFileName, edfFileName)

        self.outf.close()

        if self.quit:
            raise SystemExit

    def check_keypress(self, event):

        if event.key == pygame.K_q:
            self.quit = True
            self.simPres.set(go_duration=(0.0, 'seconds'))
        elif event.key == pygame.K_n:
            self.simPres.set(go_duration=(0.0, 'seconds'))
        elif event.key == pygame.K_UP:
            self.state.v += 1
        elif event.key == pygame.K_DOWN:
            self.state.v -= 1
Beispiel #7
0
# Normal stuff (from grating demo):
screen = get_default_screen()
stimulus = SinGrating2D(
    on=0,  # turn grating is off when not in go loop
    position=(screen.size[0] / 2.0, screen.size[1] / 2.0),
    anchor='center',
    size=(300.0, 300.0),
    spatial_freq=10.0 / screen.size[0],
    temporal_freq_hz=5.0,
    orientation=45.0)
viewport = Viewport(screen=screen, stimuli=[stimulus])
p = Presentation(
    go_duration=(5.0, 'seconds'),
    trigger_go_if_armed=0,  # wait for trigger
    viewports=[viewport])

# Stimulus on controller
stimulus_on_controller = ConstantController(during_go_value=1,
                                            between_go_value=0)

# Create a trigger input controller
trigger_in_controller = LPTTriggerInController()

# Add the trigger output controller to the presentation's list of controllers
p.add_controller(stimulus, 'on', stimulus_on_controller)
p.add_controller(p, 'trigger_go_if_armed', trigger_in_controller)

# Go!
p.go()
class SimpleVisionEgg:
    keyboard_controller = None
    trigger_controller = None
    screen = None
    presentation = None
    keys = None
    presses = None
    releases = None

    def __init__(self):
        """We break up initialization a bit as we need to go back and forth with
        some information.  In this case, we need screen size before specifying
        the stimuli"""
        
        # pasted in from where it used to be at the beginning of the script
        # used to be outside of any methods...
        VisionEgg.start_default_logging()
        VisionEgg.watch_exceptions()
        # get screen size for setting fullscreen resolution
        # comment this block out if you don't want to use full-screen.
        screen = pygame.display.set_mode((0,0))
        WIDTH, HEIGHT = screen.get_size()
        pygame.quit()
        VisionEgg.config.VISIONEGG_SCREEN_W = WIDTH
        VisionEgg.config.VISIONEGG_SCREEN_H = HEIGHT

        self.screen = get_default_screen()
        self.keys = []
        self.presses = []
        self.releases = []

    def set_stimuli(self, stimuli, trigger=None, kb_controller=False):
        """Now that we have our stimuli, we initialize everything we can"""
        viewport = Viewport(screen=self.screen, size=self.screen.size, 
                           stimuli=stimuli)

        # We disable "check_events" so that we don't lose "instantaneous" key
        # presses and can check these in our Response classes
        self.presentation = Presentation(viewports=[viewport],
                check_events=False)

        if trigger:
            trigger_controller = KeyboardTriggerInController(trigger)
            self.presentation.add_controller(self.presentation, 
                                    'trigger_go_if_armed', trigger_controller)
            self.presentation.set(trigger_go_if_armed=0)

        if kb_controller:
            self.keyboard_controller = KeyboardResponseController()
            self.presentation.add_controller(None, None, self.keyboard_controller)


    def set_functions(self, update=None, pause_update=None):
        """Interface for cognac.StimulusController or similar"""
        self.presentation.add_controller(None, None,
                     FunctionController(during_go_func=update, 
                                        between_go_func=pause_update,
                                        return_type=NoneType) )


    def go(self, go_duration=('forever',)):
        self.presentation.parameters.go_duration = go_duration
        self.presentation.go()

    def pause(self):
        self.presentation.parameters.go_duration = (0, 'frames')

    def get_new_response(self, t, min_interval=2.0 / 60, releases=False):
        """(key, press) = get_new_response(self, t, min_interval=2.0 / 60)

        DEPRECATED!

        Use this function to get responses from the keyboard controller in real
        time.

        Returns (None, None) if no new response is available.
        Maintains three instance variables - keys, presses and releases, which
        you can also access directly (but they won't be updated during loops
        where you don't call this function)

        This function makes a number of assumptions and is a little brittle
        right now.  By not hard-coding the min_interval and maybe using key
        presses and release events directly, we'd have a much better function.
        But I don't really care right now.

        DJC
        """
        raise DeprecationWarning("please use pygame directly, as in" +
                                 "StimController.Response")
        # Note - this is deprecated anyway, but it'd probably make more sense to
        # use the keyboard_controller.get_responses() to simply get the keys
        # that are down _right_now_
        press_time = self.keyboard_controller.get_time_last_response_since_go()
        key = self.keyboard_controller.get_last_response_since_go()

        # Our first response!
        if len(self.keys) == 0:
            if key:
                self.keys.append(key)
                self.presses.append(press_time)
                self.releases.append(None)

                if releases:
                    return (key, None)
                else:
                    return (key, press_time)

            else:
                return (None, None)

                    
        # We haven't seen a key press for min_interval
        if t >= press_time + min_interval and not self.releases[-1]:
            # This is only approximate!
            self.releases[-1] = t 
            if releases:
                return (self.keys[-1], t)
            else:
                return (None, None)

        # We've seen a release, or we see a new key
        if (self.releases[-1] and press_time > self.releases[-1]) or \
                key != self.keys[-1]:
            if not self.releases[-1]:
                self.releases[-1] = press_time
            self.keys.append(key)
            self.presses.append(press_time)
            self.releases.append(None)

            if releases:
                return (key, None)
            else:
                return (key, press_time)

        return (None, None)

    def get_responses(self, timeToSubtract=0, min_interval=2.0/60):
        """
        Use this function to post-process the results of a KeyboardController

        VisionEgg's keyboard libraries records a keypress and timestamp every
        time something is down.  So if a key is held down for 100 ms, there will
        be an entry in the keylist for every sample during that 100ms.  This is
        a bit much; I'd rather just save onsets and offsets for every key.  This
        function evaluates that.
        """

        ''' 
        If we're using the FORP, this isn't necessary, as events have no duration; 
        they are represented as instantaneous keypresses.

        -- John
        '''

        response = self.keyboard_controller.get_responses_since_go()
        responseTime = self.keyboard_controller.get_time_responses_since_go()

        # If I've only got one item in my response list, then it's silly to worry about onset/offset.  Just keep it.
        if len(response) < 2:
            return (response,responseTime)
        
        # Save the first response, as by definition that's the first onset:
        goodResp = [response[0]]
        goodRespTime = [responseTime[0]-timeToSubtract]

        # Now step through every other item in the response list to check for unique-ness.
        for i in range(1,len(responseTime)):

            if (not(response[i] == response[i-1]) or \
                    (responseTime[i] - responseTime[i-1] > \
                         min_interval)):
                # ie, if something changed, or we have a long gap:
                
                offsetResp = [] # we might want to save an offset
                for item in response[i-1]: # loop through last item's data
                    if (responseTime[i] - responseTime[i-1] < \
                            min_interval) and \
                            not(item in response[i]):
                        # Bit clunky.  Basically, holding down a key while pressing another creates
                        # a unique response.  So if you only let up one of those keys, code the
                        # offset just for that key.
                        offsetResp.append(item+'_Off')
                    else:
                        # it's been long enough that everything that was on should be called off.
                        offsetResp.append(item+'_Off')

                if len(offsetResp) > 0:
                    # If there's offset stuff to worry about, save it.
                    goodResp.append(offsetResp)
                    goodRespTime.append(responseTime[i-1]-timeToSubtract)
                
                # Save the new (onset) response.
                goodResp.append(response[i])
                goodRespTime.append(responseTime[i]-timeToSubtract)

        # The final event should be an offset for whatever was down.
        offsetResp = []
        for item in response[-1]:
            offsetResp.append(item+'_Off')
        goodResp.append(offsetResp) #goodResp.append(response[-1]+'_Off')
        goodRespTime.append(responseTime[-1]-timeToSubtract)

        return (goodResp, goodRespTime)
Beispiel #9
0
                        color2           = (1.0, 0.5,  0.1), # RGB (alpha ignored if given)
                        contrast         = 0.2,
                        pedestal         = 0.1,
                        mask             = mask, # optional
                        position         = ( screen.size[0]/2.0, screen.size[1]/2.0 ),
                        anchor           = 'center',
                        size             = ( 300.0 , 300.0 ),
                        spatial_freq     = 20.0 / screen.size[0], # units of cycles/pixel
                        temporal_freq_hz = 1.0,
                        orientation      = 270.0 )

def pedestal_func(t):
    # Calculate pedestal over time. (Pedestal range [0.1,0.9] and
    # contrast = 0.2 limits total range to [0.0,1.0])
    temporal_freq_hz = 0.2
    return 0.4 * sin(t*2*pi * temporal_freq_hz) + 0.5

###############################################################
#  Create viewport - intermediary between stimuli and screen  #
###############################################################

viewport = Viewport( screen=screen, stimuli=[stimulus] )

########################################
#  Create presentation object and go!  #
########################################

p = Presentation(go_duration=(10.0,'seconds'),viewports=[viewport])
p.add_controller(stimulus,'pedestal',FunctionController(during_go_func=pedestal_func))
p.go()
Beispiel #10
0
VisionEgg.start_default_logging()
VisionEgg.watch_exceptions()

from VisionEgg.Core import *
from VisionEgg.FlowControl import Presentation
from VisionEgg.Gratings import *
from VisionEgg.PyroHelpers import *

pyro_server = PyroServer()

# get visionegg stimulus ready to go
screen = get_default_screen()
stimulus = SinGrating2D(temporal_freq_hz=0.0)
viewport = Viewport(screen=screen, stimuli=[stimulus])
p = Presentation(go_duration=(5.0, 'seconds'), viewports=[viewport])

# make a controller, serve it via pyro, and glue it to the Presentation
tf_controller = PyroConstantController(during_go_value=0.0)
pyro_server.connect(tf_controller, 'tf_controller')
p.add_controller(stimulus, 'temporal_freq_hz', tf_controller)

quit_controller = PyroConstantController(during_go_value=0)
pyro_server.connect(quit_controller, 'quit_controller')
p.add_controller(p, 'quit', quit_controller)

# get listener controller and register it
p.add_controller(None, None, pyro_server.create_listener_controller())

# initialize graphics to between presentations state
p.run_forever()
Beispiel #11
0
viewport = Viewport(
    screen=screen,
    stimuli=[static_checkerboard, dynamic_checkerboard, fixation_spot])

p = Presentation(go_duration=(dynamic_time + static_time, 'seconds'),
                 viewports=[viewport])

# Use a controller to hook into go loop, but control texture buffer
# through direct manipulation.
dynamic_texture_object = dynamic_checkerboard.parameters.texture.get_texture_object(
)
width, height = dynamic_checkerboard_size
# (Note: numpy arrays have indices flipped from images, thus the re-ordering)
flipped_shape = (height, width)


def control_dynamic(t):
    if t <= dynamic_time:
        random_data = numpy.random.randint(
            0,
            2,
            size=(dynamic_checkerboard_size[1],
                  dynamic_checkerboard_size[0])) * 255
        dynamic_texture_object.put_sub_image(random_data)


p.add_controller(None, None,
                 FunctionController(during_go_func=control_dynamic))

p.go()
Beispiel #12
0
drum = SpinningDrum(texture=texture, shrink_texture_ok=1)
fixation_spot = FixationSpot(position=(screen.size[0] / 2, screen.size[1] / 2),
                             anchor='center')

perspective = SimplePerspectiveProjection(fov_x=90.0)
perspective_viewport = Viewport(screen=screen,
                                projection=perspective,
                                stimuli=[drum])

flat_viewport = Viewport(screen=screen, stimuli=[fixation_spot])

p = Presentation(viewports=[perspective_viewport, flat_viewport])
gui_window = DrumGui(idle_func=p.between_presentations)

p.add_controller(
    fixation_spot, 'on',
    FunctionController(during_go_func=lambda t: gui_window.fixation_spot.get(),
                       eval_frequency=Controller.TRANSITIONS))
p.add_controller(
    p, 'go_duration',
    FunctionController(during_go_func=lambda t:
                       (gui_window.duration.get(), 'seconds'),
                       eval_frequency=Controller.TRANSITIONS))
p.add_controller(
    drum, 'angular_position',
    FunctionController(during_go_func=gui_window.positionFunction))
p.add_controller(
    drum, 'contrast',
    FunctionController(during_go_func=gui_window.contrastFunction))

gui_window.mainloop()
Beispiel #13
0
    anchor='center',
    position=(screen.size[0] / 2, screen.size[1] / 2),
)

cur_time = Text(
    text="",
    font_size=15,
    color=(.75, .75, .75),
    anchor='lowerleft',
    position=(0, 0),
)

viewport_instructions = Viewport(screen=screen,
                                 stimuli=[instructions, cur_time])
p1 = Presentation(go_duration=('forever', ), viewports=[viewport_instructions])
p1.add_controller(None, None, FunctionController(during_go_func=displayTime))
p1.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN, waitForTrigger)
                                        ]

# setup main experimental loop
loadStims = 0
wrote_response = 0

stimulus = TextureStimulus(
    anchor='center',
    size=stimuli_size,
    position=(screen.size[0] / 2.0, screen.size[1] / 2.0),
    texture_min_filter=gl.GL_LINEAR,
    shrink_texture_ok=1,
    # PW 2012/11/26
    mipmaps_enabled=False)
class TRStimController:
    """This is a relatively simple controller that simply updates what's on the
    screen every TR (which is the next occurrence of keyboard input of '5' after
    the TR length is exceeded.  Currently it sets one stimulus on, and all
    others off, though we may want to change that to turn a list of stimuli on
    eventually"""
    # 3T laptop forp sends TTL pulses as "5"; buttons as "1","2","3","4"
    # John used to do things this way:
    # trigger_in_controller = KeyboardTriggerInController(pygame.locals.K_5)
    
    # Expected length of 1 TR
    TR = 2.0
    # Time interval after which we assume we missed the trigger
    eps = 0.1

    t = 0
    trial_times = None
    missed_trigs = None
    stim_list = []
    stim_dict = {}
    stim_seq = []

    keyboard_controller = None
    presentation = None
    screen = None

    def __init__(self, TR=None, eps=None):
        # Get the initial setup
        if TR:
            self.TR = TR 
        if eps:
            self.eps = eps

        self.trial_times = []
        self.missed_trigs = []
        self.state = self.state_generator()

        self.screen = get_default_screen()

        # background black (RGBA)
        self.screen.parameters.bgcolor = (0.0,0.0,0.0,0.0)

        self.keyboard_controller = KeyboardResponseController()
        self.firstTTL_trigger = KeyboardTriggerInController(K_5)
        
    def set_stims(self, stim_list, stim_dict, stim_seq_file): 
        self.stim_list = stim_list
        self.stim_dict = stim_dict
        self.stim_seq = yaml.load(stim_seq_file)

        viewport = Viewport(screen=self.screen,
                    size=self.screen.size,
                    stimuli=self.stim_list)

        # Need to at least wait for the first trigger if this is going to work.
        go_duration = (self.TR * len(self.stim_seq), 'seconds')
        self.presentation = Presentation(go_duration=go_duration,
                trigger_go_if_armed=0,
                viewports=[viewport])

        self.presentation.add_controller(None, None, 
                FunctionController(during_go_func=self.update) )
        self.presentation.add_controller(None, None, self.keyboard_controller)
        # Adding this so that we can start the stimuli ahead of time
        self.presentation.add_controller(self.presentation,'trigger_go_if_armed',
                                    self.firstTTL_trigger)

    def run(self):
        self.presentation.go()
        self.screen.close()    

    def update(self, t):
        self.t = t
        try:
            self.state.next()
        except StopIteration:
            # shouldn't really happen, what with epsilon and all...
            self.blank_all_stims()

    def blank_all_stims(self):
        for stim in self.stim_list:
            stim.parameters.on=False

    def state_generator(self):
        for stim_info in self.stim_seq:
            self.trial_times.append(self.t)
            self.blank_all_stims()
            try:
                for stim_name, params in stim_info.items():
                    stim = self.stim_dict[stim_name]
                    stim.parameters.on = True
                    try:
                        for name, value in params.items():
                            setattr(stim.parameters, name, value)
                    except AttributeError:
                        # params was None or something else we don't deal with
                        pass
            except AttributeError:
                # We assume a no-colon single token / key
                self.stim_dict[stim_info].parameters.on = True


            # Don't even bother 'til we're close to the expected TR time
            while self.t - self.trial_times[-1] < self.TR - 2*self.eps:
                yield

            while self.t - self.trial_times[-1] < self.TR + self.eps:
                # Handle the rare case when a key might register between
                # function calls - THIS WOULD NEVER HAPPEN WITH VisionEgg as
                # written!
                while True:
                    keys = self.keyboard_controller.get_responses_since_go()
                    times = \
                        self.keyboard_controller.get_time_responses_since_go()
                    if len(keys) == len(times):
                        break

                i = None
                try:
                    # Find the last value of '5' without inline reversal of keys/times
                    # VisionEgg returns "responses" as a list of lists of chars, not just a list of chars...
                    i = len(keys)-1-list(reversed(keys)).index(['5'])
                except ValueError:
                    pass
                
                # If anybody presses the escape key, quit entirely.
                try:
                    needToQuit = keys.index(['escape'])
                    #self.presentation = None
                    #exit()
                except ValueError:
                    pass

                if i and times[i] > self.trial_times[-1]:
                    break
                else:
                    yield

            if self.t - self.trial_times[-1] >= self.TR + self.eps:
                # We missed a TR (we think)
                self.missed_trigs.append(self.t)
                self.t = self.trial_times[-1] + self.TR


    def get_responses(self, timeToSubtract=0, min_interval=2.0/60):
        """
        This function isn't especially elegant, but it's functional.

        VisionEgg's keyboard libraries records a keypress and timestamp every
        time something is down.  So if a key is held down for 100 ms, there will
        be an entry in the keylist for every sample during that 100ms.  This is
        a bit much; I'd rather just save onsets and offsets for every key.  This
        function evaluates that.
        """

        ''' 
        If we're using the FORP, this isn't necessary, as events have no duration; 
        they are represented as instantaneous keypresses.

        -- John
        '''

        response = self.keyboard_controller.get_responses_since_go()
        responseTime = self.keyboard_controller.get_time_responses_since_go()

        # If I've only got one item in my response list, then it's silly to worry about onset/offset.  Just keep it.
        if len(response) < 2:
            return (response,responseTime)
        
        # Save the first response, as by definition that's the first onset:
        goodResp = [response[0]]
        goodRespTime = [responseTime[0]-timeToSubtract]

        # Now step through every other item in the response list to check for unique-ness.
        for i in range(1,len(responseTime)):

            if (not(response[i] == response[i-1]) or \
                    (responseTime[i] - responseTime[i-1] > \
                         min_interval)):
                # ie, if something changed, or we have a long gap:
                
                offsetResp = [] # we might want to save an offset
                for item in response[i-1]: # loop through last item's data
                    if (responseTime[i] - responseTime[i-1] < \
                            min_interval) and \
                            not(item in response[i]):
                        # Bit clunky.  Basically, holding down a key while pressing another creates
                        # a unique response.  So if you only let up one of those keys, code the
                        # offset just for that key.
                        offsetResp.append(item+'_Off')
                    else:
                        # it's been long enough that everything that was on should be called off.
                        offsetResp.append(item+'_Off')

                if len(offsetResp) > 0:
                    # If there's offset stuff to worry about, save it.
                    goodResp.append(offsetResp)
                    goodRespTime.append(responseTime[i-1]-timeToSubtract)
                
                # Save the new (onset) response.
                goodResp.append(response[i])
                goodRespTime.append(responseTime[i]-timeToSubtract)

        # The final event should be an offset for whatever was down.
        offsetResp = []
        for item in response[-1]:
            offsetResp.append(item+'_Off')
        goodResp.append(offsetResp) #goodResp.append(response[-1]+'_Off')
        goodRespTime.append(responseTime[-1]-timeToSubtract)

        return (goodResp, goodRespTime)
Beispiel #15
0
    p3 = Presentation(go_duration=(blankTime, 'seconds'), viewports=[fixCross])
    p3.go()

    p = Presentation(go_duration=('forever', ), viewports=[vr])
    p.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN, key_handler)
                                           ]
    p.go()

    subject.inputData(trial, "RT", RT)
    subject.inputData(trial, "ACC", ACC)

    #BLOCK 2 - STRATEGY SELECTION
    p2 = Presentation(go_duration=('forever', ), viewports=[stratPort])
    p2.add_controller(
        None, None,
        FunctionController(during_go_func=strategy_controller,
                           temporal_variables=FRAMES_ABSOLUTE))
    p2.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN,
                                             key_handler)]
    p2.go()

    #BLOCK 3 - BLANK SCREEN
    p3 = Presentation(go_duration=(0.5, 'seconds'), viewports=[fixCross])
    p3.go()

    subject.inputData(trial, "ACC", ACC)
    subject.inputData(trial, "strategy", strategy)

    ns.sort()
    lastns = copy.deepcopy(ns)
    lastlastns = copy.deepcopy(lastns)
Beispiel #16
0
from VisionEgg.Core import *
from VisionEgg.FlowControl import Presentation, FunctionController
from VisionEgg.Textures import *
import math, os

max_speed = 100.0 # degrees per second

def angle_as_function_of_time(t):
    return max_speed*math.cos(t)

def contrast_as_function_of_time(t):
    return abs(math.cos(2*math.pi*t*0.2))

filename = os.path.join(config.VISIONEGG_SYSTEM_DIR,"data","panorama.jpg")
texture = Texture(filename)

screen = get_default_screen()
projection = SimplePerspectiveProjection(fov_x=90.0)
stimulus = SpinningDrum(texture=texture,shrink_texture_ok=1)
viewport = Viewport(screen=screen,
                    size=screen.size,
                    projection=projection,
                    stimuli=[stimulus])
p = Presentation(go_duration=(10.0,'seconds'),viewports=[viewport])
p.add_controller(stimulus,'angular_position', FunctionController(during_go_func=angle_as_function_of_time))
p.add_controller(stimulus,'contrast', FunctionController(during_go_func=contrast_as_function_of_time))
p.go()


def aplicacion():
    global p, inten, coord
    pos = [0.4, 0.5, 0.6, 0.7, 0.8]
    pos2 = [1.3, 1.4, 1.5, 1.6, 1.7, 1.8]
    rellenar()
    shuffle(coord)
    i = len(coord) - 1
    target.parameters.position = coord[i][:2]
    (xpos, ypos) = target.parameters.position
    x = xpos - screen.size[0] / 2
    y = ypos - screen.size[1] / 2
    anrad = math.atan2(y, x)
    angrad = math.degrees(anrad)

    if angrad >= 0:
        if angrad <= 90:
            orientacion = -45
            xx = 2.0
            yy = 2.0
        else:
            orientacion = -135
            xx = -2.0
            yy = 2.0
    else:
        aux = angrad * (-1)
        if aux <= 90:
            orientacion = 45
            xx = 2.0
            yy = -2.0
        else:
            orientacion = 135
            xx = -2.0
            yy = -2.0

    fixpoint.parameters.position = ((screen.size[0] / 2.0) + xx,
                                    (screen.size[1] / 2.0) + yy)
    fixpoint.parameters.orientation = orientacion

    viewport = Viewport(screen=screen, stimuli=[fixpoint, fixcirc])
    p = Presentation(go_duration=(1.0, 'seconds'), viewports=[viewport])
    p.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN, keydown),
                                           (pygame.locals.KEYUP, keyup),
                                           (pygame.locals.QUIT, quit_app)]
    p.add_controller(None, None, FunctionController(during_go_func=settings))
    #winsound.PlaySound('instruccion',winsound.SND_FILENAME)
    p.go()

    while len(coord) != 0:
        if end:
            break
        i = len(coord) - 1
        target.parameters.position = coord[i][:2]
        dur = pos[random.randrange(0, 4, 1)]
        (xpos, ypos) = target.parameters.position
        x = xpos - screen.size[0] / 2
        y = ypos - screen.size[1] / 2
        anrad = math.atan2(y, x)
        angrad = math.degrees(anrad)
        #fixpoint.parameters.orientation=(-angrad)
        if angrad >= 0:
            if angrad <= 90:
                orientacion = -45
                xx = 2.0
                yy = 2.0
            else:
                orientacion = -135
                xx = -2.0
                yy = 2.0
        else:
            aux = angrad * (-1)
            if aux <= 90:
                orientacion = 45
                xx = 2.0
                yy = -2.0
            else:
                orientacion = 135
                xx = -2.0
                yy = -2.0

        fixpoint.parameters.position = ((screen.size[0] / 2.0) + xx,
                                        (screen.size[1] / 2.0) + yy)
        fixpoint.parameters.orientation = orientacion

        viewport = Viewport(screen=screen, stimuli=[fixpoint, fixcirc])
        p = Presentation(go_duration=(dur, 'seconds'), viewports=[viewport])
        p.parameters.handle_event_callbacks = [(pygame.locals.QUIT, quit_app)]

        p.add_controller(None, None,
                         FunctionController(during_go_func=settings))
        p.go()

        inten = coord[i][-1]
        target.parameters.color = (
            1.0, 1.0, 1.0, inten
        )  #Se muestra el estimulo Duracion 0.3 segundos
        viewport = Viewport(screen=screen, stimuli=[target, fixpoint, fixcirc])
        p = Presentation(go_duration=(0.3, 'seconds'), viewports=[viewport])
        p.parameters.handle_event_callbacks = [(pygame.locals.QUIT, quit_app)]

        p.add_controller(None, None,
                         FunctionController(during_go_func=settings))
        p.go()
        target.parameters.color = (
            0.0, 0.0, 0.0, 1.0)  #Desaparece el estimulo tiempo para registrar
        viewport = Viewport(screen=screen, stimuli=[target, fixpoint, fixcirc])
        dur2 = pos[random.randrange(0, 4, 1)]
        p = Presentation(go_duration=(dur2, 'seconds'), viewports=[viewport])
        p.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN,
                                                keydown),
                                               (pygame.locals.KEYUP, keyup),
                                               (pygame.locals.QUIT, quit_app)]
        p.add_controller(None, None,
                         FunctionController(during_go_func=settings))
        p.go()
        coord.pop()
Beispiel #18
0
import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()

from VisionEgg.Core import *
from VisionEgg.FlowControl import Presentation
from VisionEgg.Gratings import *
from VisionEgg.PyroHelpers import *

pyro_server = PyroServer()

# get visionegg stimulus ready to go
screen = get_default_screen()
stimulus = SinGrating2D(temporal_freq_hz=0.0)
viewport = Viewport(screen=screen,stimuli=[stimulus])
p = Presentation(go_duration=(5.0,'seconds'),viewports=[viewport])

# make a controller, serve it via pyro, and glue it to the Presentation
tf_controller = PyroConstantController(during_go_value=0.0)
pyro_server.connect(tf_controller,'tf_controller')
p.add_controller(stimulus,'temporal_freq_hz', tf_controller)

quit_controller = PyroConstantController(during_go_value=0)
pyro_server.connect(quit_controller,'quit_controller')
p.add_controller(p,'quit', quit_controller)

# get listener controller and register it
p.add_controller(None,None, pyro_server.create_listener_controller())

# initialize graphics to between presentations state
p.run_forever()
Beispiel #19
0
	anchor = 'center',
    position = (screen.size[0]/2, screen.size[1]/2),
)


cur_time = Text(
	text		= "",
	font_size 	= 15,
	color		= (.75,.75,.75),
	anchor		= 'lowerleft',
	position	= (0,0),
	)

viewport_instructions = Viewport( screen=screen, stimuli = [ instructions, cur_time ] )
p1 = Presentation(go_duration=('forever',), viewports=[viewport_instructions])
p1.add_controller(None,None,FunctionController(during_go_func=displayTime))
p1.parameters.handle_event_callbacks =  [ (pygame.locals.KEYDOWN, waitForTrigger) ]

# setup main experimental loop
loadStims 		= 0
wrote_response 	= 0

stimulus =      TextureStimulus(
                    anchor                  = 'center',
                    size                    = stimuli_size,
                    position                = (screen.size[0]/2.0, screen.size[1]/2.0),
                    texture_min_filter      = gl.GL_LINEAR,
                    shrink_texture_ok       = 1,
		    # PW 2012/11/26
                    mipmaps_enabled = False
                )
Beispiel #20
0
stimulus_on_controller = ConstantController(during_go_value=1,
                                            between_go_value=0)
stimulus_off_controller = ConstantController(during_go_value=0,
                                             between_go_value=1)
left_choice_controller = FunctionController(during_go_func=replaceLeftText)
right_choice_controller = FunctionController(during_go_func=replaceRightText)
left_choice2_controller = FunctionController(during_go_func=replaceLeftText2)
right_choice2_controller = FunctionController(during_go_func=replaceRightText2)
state_controller = FunctionController(during_go_func=getState)
fixation_controller = FunctionController(during_go_func=controlFix,
                                         between_go_func=hideStim)
newset_controller = FunctionController(during_go_func=showNewSet,
                                       between_go_func=hideStim)
taskend_controller = FunctionController(during_go_func=showTaskEnd)

p.add_controller(p, 'trigger_go_if_armed', trigger_in_controller)
p.add_controller(title, 'on', stimulus_off_controller)
p.add_controller(title2, 'on', stimulus_off_controller)
p.add_controller(left_choice, 'on', stimulus_on_controller)
p.add_controller(right_choice, 'on', stimulus_on_controller)
p.add_controller(left_choice2, 'on', stimulus_on_controller)
p.add_controller(right_choice2, 'on', stimulus_on_controller)
p.add_controller(left_choice, 'text', left_choice_controller)
p.add_controller(left_choice2, 'text', left_choice2_controller)
p.add_controller(right_choice, 'text', right_choice_controller)
p.add_controller(right_choice2, 'text', right_choice2_controller)
p.add_controller(fixation, 'on', fixation_controller)
p.add_controller(newset, 'on', newset_controller)
p.add_controller(taskend, 'on', taskend_controller)
p.add_controller(p, 'trigger_go_if_armed', state_controller)
Beispiel #21
0
    ))

other_text = []
other_text.append(
    Text(
        text='Pixel positions (x,y) calculated from 3D coordinates',
        position=(screen.size[0] / 2, screen.size[1]),
        anchor='top',
    ))

other_text.append(Text(
    text='----> x',
    position=(10, 10),
    anchor='left',
))

other_text.append(
    Text(
        text='----> y',
        angle=90.0,
        position=(10, 10),
        anchor='left',
    ))

viewport2D.parameters.stimuli = vertex_labels + other_text

p = Presentation(go_duration=(10.0, 'seconds'),
                 viewports=[viewport3D, viewport2D])
p.add_controller(None, None, FunctionController(during_go_func=update))
p.go()
Beispiel #22
0
from VisionEgg.Gratings import *
import VisionEgg.Daq
from VisionEgg.DaqLPT import *

# Normal stuff (from grating demo):
screen = get_default_screen()
stimulus = SinGrating2D(on               = 1, # turn grating is off when not in go loop
                        position         = ( screen.size[0]/2.0, screen.size[1]/2.0 ),
                        anchor           = 'center',
                        size             = ( 300.0 , 300.0 ),
                        spatial_freq     = 10.0 / screen.size[0],
                        temporal_freq_hz = 5.0,
                        orientation      = 45.0 )
viewport = Viewport( screen=screen, stimuli=[stimulus] )
p = Presentation(go_duration=(5.0,'seconds'),
                 trigger_go_if_armed=0, # wait for trigger
                 viewports=[viewport])

# Stimulus on controller
stimulus_on_controller = ConstantController(during_go_value=0,between_go_value=1)

# Create a trigger input controller
trigger_in_controller = LPTTriggerInController()

# Add the trigger output controller to the presentation's list of controllers
p.add_controller(stimulus,'on',stimulus_on_controller)
p.add_controller(p,'trigger_go_if_armed',trigger_in_controller)

# Go!
p.go()
Beispiel #23
0
projection2 = SimplePerspectiveProjection(fov_x=55.0,
                                          aspect_ratio=(float(mid_x)/screen.size[1]))

camera_matrix = ModelView() # Parameters set in realtime, so no need to specify here

# Get a texture
filename = os.path.join(config.VISIONEGG_SYSTEM_DIR,"data","panorama.jpg")
texture = Texture(filename)

stimulus = SpinningDrum(texture=texture,shrink_texture_ok=1)
viewport1 = Viewport(screen=screen,
                     position=(0,0),
                     anchor='lowerleft',
                     size=(mid_x,screen.size[1]),
                     projection=projection1,
                     stimuli=[stimulus])
viewport2 = Viewport(screen=screen,
                     position=(mid_x,0),
                     anchor='lowerleft',
                     size=(mid_x,screen.size[1]),
                     projection=projection2,
                     camera_matrix=camera_matrix,
                     stimuli=[stimulus])

p = Presentation(go_duration=(10.0,'seconds'),viewports=[viewport1,viewport2])

p.add_controller(stimulus,'angular_position', FunctionController(during_go_func=angle_as_function_of_time))
p.add_controller(camera_matrix,'matrix', FunctionController(during_go_func=cam_matrix_f))

p.go()
Beispiel #24
0
    print "----------------------"
    print "PROBLEM: %s" % problem
    print "SOLUTION: %s " % solution
    print "----------------------"

    ns = [n1, n2]

    #default values for misfiring voice key
    misfire = 0
    ACC = 1

    #BLOCK 1 - Problem & RESPONSE

    p = Presentation(go_duration=('forever', ), viewports=[expPort])
    p.add_controller(
        None, None,
        FunctionController(during_go_func=problem_controller,
                           temporal_variables=FRAMES_ABSOLUTE))
    p.go()

    #BLOCK 2 - STRATEGY SELECTION & GRADING
    p2 = Presentation(go_duration=(1.5, 'seconds'), viewports=[fixCross])
    p2.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN,
                                             key_handler)]
    p2.go()

    if ACC == 0:
        problemQ = [n1, n2, stim]
        error = Presentation(go_duration=(1, 'seconds'), viewports=[errorPort])
        error.go()
    else:
        problemQ = []
Beispiel #25
0
"""Use frame information to display stimuli."""

import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()

from VisionEgg.Core import get_default_screen, Viewport
from VisionEgg.FlowControl import Presentation, FunctionController, FRAMES_ABSOLUTE
from VisionEgg.Text import Text

screen = get_default_screen()
screen.parameters.bgcolor = (0.0,0.0,1.0) # background blue (RGB)

textvar = Text(color=(1.0,1.0,1.0), # alpha is ignored (set with max_alpha_param)
               position=(screen.size[0]/4,screen.size[1]/2),
               font_size=50,
               anchor='left')

def text_func(f_abs):
    return "framecount: % 4d"%f_abs

t_controller = FunctionController(during_go_func=text_func,
                                  temporal_variables = FRAMES_ABSOLUTE)

viewport = Viewport(screen=screen,
                    size=screen.size,
                    stimuli=[textvar])

p = Presentation(go_duration=(5.0,'seconds'),viewports=[viewport])
p.add_controller(textvar,'text',t_controller)
p.go()
Beispiel #26
0
        sub.inputData(trial, "blueButton", blueB)

        print color

        if block == "overlapping":
            phase = ""
            fname = "%s_%s_%s_%s_%s_OL.bmp" % (ratio, n1, color, size,
                                               exemplar)

            t = Texture(Image.open(os.path.join(stimLib, fname)))
            s = TextureStimulus(texture=t, position=(x, y), anchor='center')
            texture_object = s.parameters.texture.get_texture_object()
            v = Viewport(screen=screen, stimuli=[s])
            p = Presentation(go_duration=('forever', ), viewports=[v])
            p.add_controller(
                None, None,
                FunctionController(during_go_func=put_image_overlapping,
                                   temporal_variables=TIME_SEC_ABSOLUTE))
            p.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN,
                                                    keyFunc)]
            p.go()

        else:
            if side == "large":
                fname1 = "%s_%s_%s_%s_%s_S2.bmp" % (ratio, n1, color, size,
                                                    exemplar)
                fname2 = "%s_%s_%s_%s_%s_S1.bmp" % (ratio, n1, color, size,
                                                    exemplar)
            else:
                fname1 = "%s_%s_%s_%s_%s_S1.bmp" % (ratio, n1, color, size,
                                                    exemplar)
                fname2 = "%s_%s_%s_%s_%s_S2.bmp" % (ratio, n1, color, size,
class Stimulation:
    global TopRate, BotRate, LeftRate, RightRate, HSize, VSize
    global numTrial, order_appear
    global duration_init, duration_cue, duration_target, duration_trial, total_time
    # Set up stimulus's frequency
    TopRate =   5              # Hz
    BotRate = 10
    LeftRate = 15
    RightRate = 20

    # Set dimension of the targets
    HSize = 100
    VSize = 50

    # Experiment parameters
    numTrial = 4
    order_appear = np.uint16(4*np.random.random(numTrial)+1)
    duration_init = 2
    duration_target = 3
    duration_cue = 2
    duration_trial = duration_target + duration_cue
    total_time = duration_init + duration_trial*numTrial

    def __init__(self):
        global w, h
        self._running = True

        # Initialize screen
        # TODO
        # Set fullscreen
        self.screen = get_default_screen()

        # Get dimension of the screen
        w = self.screen.size[0]
        h = self.screen.size[1]

        # Initialize Targets
        self.TopTarget = Target2D()
        self.BotTarget = Target2D()
        self.LeftTarget = Target2D()
        self.RightTarget = Target2D()

        # Message
        self.mess = Text(text='Please wait for next trial...',
                         color=(1.0, 0.5, 0.5),
                         position=(w/2, h*0.8),
                         font_size=50,
                         anchor='center',
                         on=True)

        # Arrows
        self.arrow = TextureStimulus()

        # Viewports to stick graphical objects to screen
        self.viewport1 = Viewport(screen=self.screen,
                                  stimuli=[self.TopTarget, self.BotTarget, self.LeftTarget, self.RightTarget])      # For Targets
        self.viewport2 = Viewport(screen=self.screen,
                                  stimuli=[self.arrow])                                                  # For cue (and other things)
        self.viewport3 = Viewport(screen=self.screen,
                                  stimuli=[self.mess])                                                  # For cue (and other things)

        # Presentations (for controlling timing)
        self.initialize = Presentation(go_duration=(duration_init, 'seconds'), viewports=[self.viewport3])
        self.targetShow = Presentation(go_duration=(duration_target, 'seconds'), viewports=[self.viewport1])
        self.cueShow = Presentation(go_duration=(duration_cue, 'seconds'), viewports=[self.viewport2])

        # For result
        self.TargetLog = np.zeros((numTrial, 2))     # First column: target code,

    def on_init(self):
        # Set screen's background color
        self.screen.set(bgcolor=(0., 0., 0.)) # black

        # Set target's properties
        self.TopTarget.set(size=(HSize, VSize),
                           color= (1.0, 1.0, 1.0, 1.0),
                           position=(w/2, h*0.8))
        self.BotTarget.set(size=(HSize, VSize),
                           color=(1.0, 1.0, 1.0, 1.0),
                           position=(w/2, h*0.2))
        self.LeftTarget.set(size=(VSize, HSize),
                            color=(1.0, 1.0, 1.0, 1.0),
                            position=(w*0.2, h/2))
        self.RightTarget.set(size=(VSize, HSize),
                             color=(1.0, 1.0, 1.0, 1.0),
                             position=(w*0.8, h/2))

        # Message
        # self.text.set(text='Please wait for next trial...',
        #               color=(1.0, 0.5, 0.5),
        #               position=(w/2, h*0.8),
        #               font_size=50,
        #               anchor='center',
        #               on=False)

        # Arrows
        self.arrow.set(texture=Texture('images\left2.bmp'),
                        position=(w/2, h/2),
                        anchor='center',
                        on=False)

        # Show initializing message
        self.initialize.add_controller(self.mess, 'text',     FunctionController(during_go_func=self.showMess))

        # Set control's parameters and corresponding function. Controlling targers
        self.targetShow.add_controller(self.TopTarget, 'on',     FunctionController(during_go_func=self.topFlick))
        self.targetShow.add_controller(self.BotTarget, 'on',     FunctionController(during_go_func=self.botFlick))
        self.targetShow.add_controller(self.LeftTarget, 'on',    FunctionController(during_go_func=self.leftFlick))
        self.targetShow.add_controller(self.RightTarget, 'on',   FunctionController(during_go_func=self.rightFlick))

        # Controlling others
        # self.p2.add_controller(self.text, 'on',         FunctionController(during_go_func=self.appear))
        self.cueShow.add_controller(self.arrow, 'on',        FunctionController(during_go_func=self.arrow_appear))
        self.cueShow.add_controller(self.arrow, 'texture',   FunctionController(during_go_func=self.random_cue))


    def on_execute(self):
        if self.on_init() == False:
            self._running = False

        # Prompting
        self.initialize.go()

        # Experiment goes..
        for i in range(0,numTrial):
            self.cueShow.go()
            self.targetShow.go()

        self.on_writing()

    # TODO
    # Maybe we need a method for closing the program


    #################################################
    # Controlling methods: Flickering               #
    #################################################
    def topFlick(self,t):
        return int(t*TopRate*2.0) % 2

    def botFlick(self,t):
        return int(t*BotRate*2.0) % 2

    def leftFlick(self,t):
        return int(t*LeftRate*2.0) % 2

    def rightFlick(self,t):
        return int(t*RightRate*2.0) % 2

    def arrow_appear(self, t):
        flag = True
        if flag:
            #self.writedata(t, 1)
            flag = False

        if self.targetShow.is_in_go_loop():
            return False
        else:
            return True

    def random_cue(self,t):
        start_time = self.cueShow.last_go_loop_start_time_absolute_sec
        # TODO
        # Add try catch to handle errors regarding start_time's type problem
        # TODO
        # Add event so that the transition processes only taken place once

        if not isinstance(start_time, type(None)):
            i = int((start_time-duration_init)/duration_trial)  # eliminate initializing duration factor
            cur_target = order_appear[i]        # current target
            self.TargetLog[i, :] = np.array([cur_target, start_time])   # return real time
            if cur_target == 1:
                return Texture('images/up2.bmp')
            elif cur_target == 2:
                return Texture('images/left2.bmp')
            elif cur_target == 3:
                return Texture('images/right2.bmp')
            elif cur_target == 4:
                return Texture('images/down2.bmp')
        else:
            return Texture('images/left2.bmp')  # Just return something, add_controller need it

    def showMess(self, t):
        return 'Ready ...'


    #################################################
    # Writing data methods                          #
    #################################################
    def on_writing(self):
        # Open file for writing data
        file = open("Recordingfile.txt", "w")

        for i in range(self.TargetLog.shape[0]):
            target = self.TargetLog[i, 0]
            time = self.TargetLog[i, 1]
            line = str(target) + '\t' + str(time) + '\n'
            file.write(line)
right_label_controller = FunctionController(during_go_func=myRightLabel)
left_label_controller = FunctionController(during_go_func=myLeftLabel)
task_controller = FunctionController(during_go_func=myFixation)
arrow_direction_controller = FunctionController( \
                           during_go_func=get_arrow_direction)

arrow_position_controller = FunctionController( \
                           during_go_func=get_arrow_position)
arrow_color_controller = FunctionController(during_go_func=get_arrow_color)
myArrowOnControl = FunctionController(during_go_func=myArrowOn)

#############################################################
#  Connect the controllers with the variables they control  #
#############################################################
# Actually listens to the TCP socket
if TCPIP: p.add_controller(None, None, tcp_listener)

p.add_controller(p,'trigger_go_if_armed',trigger_in_controller)
p.add_controller(textAA,'on', stimulus_off_controller )
#p.add_controller(textA,'on', stimulus_off_controller )
#p.add_controller(textB,'on', stimulus_off_controller )
#p.add_controller(textC,'on', stimulus_off_controller )
#p.add_controller(textD,'on', stimulus_off_controller )
p.add_controller(taskStimulus,'on', stimulus_on_controller)
p.add_controller(centerStim,'on', stimulus_on_controller)
p.add_controller(taskStimulus,'text', task_controller)
p.add_controller(p, 'trigger_go_if_armed', state_controller)
p.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN, keydown)]

#######################
#  Run the stimulus!  #
Beispiel #29
0
import math, os

max_speed = 100.0  # degrees per second


def angle_as_function_of_time(t):
    return max_speed * math.cos(t)


def contrast_as_function_of_time(t):
    return abs(math.cos(2 * math.pi * t * 0.2))


filename = os.path.join(config.VISIONEGG_SYSTEM_DIR, "data", "panorama.jpg")
texture = Texture(filename)

screen = get_default_screen()
projection = SimplePerspectiveProjection(fov_x=90.0)
stimulus = SpinningDrum(texture=texture, shrink_texture_ok=1)
viewport = Viewport(screen=screen,
                    size=screen.size,
                    projection=projection,
                    stimuli=[stimulus])
p = Presentation(go_duration=(10.0, 'seconds'), viewports=[viewport])
p.add_controller(stimulus, 'angular_position',
                 FunctionController(during_go_func=angle_as_function_of_time))
p.add_controller(
    stimulus, 'contrast',
    FunctionController(during_go_func=contrast_as_function_of_time))
p.go()
Beispiel #30
0
viewport = Viewport(screen=screen, stimuli=[stimulus])

########################################
#  Create presentation object and go!  #
########################################

p = Presentation(go_duration=(5.0, 'seconds'), viewports=[viewport])

##############################################
#  Connect the controller with the stimulus  #
##############################################

keyboard_response = KeyboardResponseController()

# Add the keyboard controller to the presentation's list of controllers
p.add_controller(None, None, keyboard_response)

########
#  Go  #
########

for i in range(3):
    p.go()

    # Print responses collected during the presentation
    #   print "all       =",keyboard_response.get_responses_since_go()
    #   print "all_time  =",keyboard_response.get_time_responses_since_go()
    print "first     =", keyboard_response.get_first_response_since_go()
    print "first_time=", keyboard_response.get_time_first_response_since_go()
#   print "last      =",keyboard_response.get_last_response_since_go()
#   print "last_time =",keyboard_response.get_time_last_response_since_go()
Beispiel #31
0
import VisionEgg
VisionEgg.start_default_logging()
VisionEgg.watch_exceptions()

from VisionEgg.Core import *
from VisionEgg.FlowControl import Presentation
from VisionEgg.Gratings import *
import VisionEgg.Daq
from VisionEgg.DaqLPT import *

# Normal stuff (from grating demo):
screen = get_default_screen()
stimulus = SinGrating2D(
    position=(screen.size[0] / 2.0, screen.size[1] / 2.0),
    anchor='center',
    size=(300.0, 300.0),
    spatial_freq=10.0 / screen.size[0],  # units of cycles/pixel
    temporal_freq_hz=5.0,
    orientation=45.0)
viewport = Viewport(screen=screen, stimuli=[stimulus])
p = Presentation(go_duration=(5.0, 'seconds'), viewports=[viewport])

# Create a trigger output controller
trigger_out_controller = LPTTriggerOutController()

# Add the trigger output controller to the presentation's list of controllers
p.add_controller(None, None, trigger_out_controller)

# Go!
p.go()
Beispiel #32
0
    tcp_name="go",
    initial_controller=ConstantController(during_go_value=0)
    )

# Create the instance SinGrating with appropriate parameters
stimulus = SinGrating2D(anchor='center')

# Create a viewport (with default pixel coordinate system)
# with stimulus
viewport = Viewport( screen=screen, stimuli=[stimulus] )

# Create an instance of the Presentation class
p = Presentation(viewports=[viewport],check_events=1)

# Register the controller functions, connecting them with the parameters they control
p.add_controller(None,None, tcp_listener) # Actually listens to the TCP socket
p.add_controller(stimulus,'on', on_controller)
p.add_controller(stimulus,'contrast', contrast_controller)
p.add_controller(stimulus,'position', center_controller)
p.add_controller(stimulus,'size', size_controller)
p.add_controller(stimulus,'spatial_freq', spatial_freq_controller)
p.add_controller(stimulus,'temporal_freq_hz', temporal_freq_controller)
p.add_controller(stimulus,'phase_at_t0', phase_controller)
p.add_controller(stimulus,'orientation', orientation_controller)
p.add_controller(stimulus,'num_samples', num_samples_controller)
p.add_controller(stimulus,'bit_depth', bit_depth_controller)
p.add_controller(p,'go_duration', go_duration_controller)
p.add_controller(p,'enter_go_loop', go_controller)

# Go!
p.run_forever()
Beispiel #33
0
                                      texture_min_filter=gl.GL_NEAREST,
                                      texture_mag_filter=gl.GL_NEAREST,
                                      )

fixation_spot = FixationSpot(position=(screen.size[0]/2,screen.size[1]/2),
                             anchor='center',
                             color=(255,0,0,0),
                             size=(4,4))

viewport = Viewport(screen=screen,
                    stimuli=[static_checkerboard,
                             dynamic_checkerboard,
                             fixation_spot])

p = Presentation(go_duration=(dynamic_time+static_time,'seconds'),
                 viewports=[viewport])

# Use a controller to hook into go loop, but control texture buffer
# through direct manipulation.
dynamic_texture_object = dynamic_checkerboard.parameters.texture.get_texture_object()
width,height = dynamic_checkerboard_size
# (Note: numpy arrays have indices flipped from images, thus the re-ordering)
flipped_shape = (height,width)
def control_dynamic(t):
    if t <= dynamic_time:
        random_data = numpy.random.randint(0,2,size=(dynamic_checkerboard_size[1],dynamic_checkerboard_size[0]))*255
        dynamic_texture_object.put_sub_image( random_data )
p.add_controller(None,None,FunctionController(during_go_func=control_dynamic))

p.go()
Beispiel #34
0
texture_object = stimulus.parameters.texture.get_texture_object()


def update_movie():
    # While movie.play() decompresses the movie to pygame surface
    # in a separate thread, this sends the data to OpenGL.
    texture_object.put_sub_image(pygame_surface)


viewport = Viewport(screen=screen, stimuli=[stimulus, text])

p = Presentation(
    go_duration=('forever', ),
    viewports=[viewport],
    handle_event_callbacks=[(pygame.locals.QUIT, quit),
                            (pygame.locals.KEYDOWN, keydown)],
)

p.add_controller(
    None, None,
    FunctionController(during_go_func=update_movie,
                       temporal_variables=TIME_INDEPENDENT))

movie.play()
#p.go()
import cProfile, pstats
cProfile.run('p.go()', 'mpeg_profile')
p = pstats.Stats('mpeg_profile')
p.sort_stats('cumulative')
p.print_stats()
Beispiel #35
0
# calculate a few variables we need
mid_x = screen.size[0] / 2.0
mid_y = screen.size[1] / 2.0
max_vel = min(screen.size[0], screen.size[1]) * 0.4


# define position as a function of time
def get_target_position(t):
    global mid_x, mid_y, max_vel
    return (
        max_vel * sin(0.1 * 2.0 * pi * t) + mid_x,  # x
        max_vel * sin(0.1 * 2.0 * pi * t) + mid_y)  # y


# Create an instance of the Controller class
target_position_controller = FunctionController(
    during_go_func=get_target_position)

#############################################################
#  Connect the controllers with the variables they control  #
#############################################################

p.add_controller(target, 'position', target_position_controller)

#######################
#  Run the stimulus!  #
#######################

p.go()
Beispiel #36
0
from VisionEgg.FlowControl import Presentation
from VisionEgg.Gratings import *
from VisionEgg.PyroHelpers import *

pyro_server = PyroServer()

# get visionegg stimulus ready to go
screen = get_default_screen()
stimulus = SinGrating2D()
viewport = Viewport(screen=screen,stimuli=[stimulus])
p = Presentation(viewports=[viewport])

# make a controller, serve it via pyro, and glue it to the Presentation
tf_controller = PyroConstantController(during_go_value=0.0)
pyro_server.connect(tf_controller,'tf_controller')
p.add_controller(stimulus,'temporal_freq_hz', tf_controller)

sf_controller = PyroConstantController(during_go_value=0.0)
pyro_server.connect(sf_controller,'sf_controller')
p.add_controller(stimulus,'spatial_freq', sf_controller)

contrast_controller = PyroConstantController(during_go_value=0.0)
pyro_server.connect(contrast_controller,'contrast_controller')
p.add_controller(stimulus,'contrast', contrast_controller)

orient_controller = PyroConstantController(during_go_value=0.0)
pyro_server.connect(orient_controller,'orient_controller')
p.add_controller(stimulus,'orientation', orient_controller)

duration_controller = PyroConstantController(during_go_value=(5.0,'seconds'))
pyro_server.connect(duration_controller,'duration_controller')
mid_x = screen.size[0]/2.0
mid_y = screen.size[1]/2.0
max_vel = min(screen.size[0],screen.size[1]) * 0.4

# define target position as a function of time
def get_target_position(t):
    global mid_x, mid_y, max_vel
    return ( max_vel*sin(0.1*2.0*pi*t) + mid_x , # x
             max_vel*sin(0.1*2.0*pi*t) + mid_y ) # y

def get_drum_angle(t):
    return 10.0*t

# Create instances of the Controller class
target_position_controller = FunctionController(during_go_func=get_target_position)
drum_angle_controller = FunctionController(during_go_func=get_drum_angle)

#############################################################
#  Connect the controllers with the variables they control  #
#############################################################

p.add_controller(target,'position', target_position_controller )
p.add_controller(drum,'angular_position', drum_angle_controller )

#######################
#  Run the stimulus!  #
#######################

p.go()

Beispiel #38
0
dot_controller = FunctionController(during_go_func=setDots)
coherence_controller = FunctionController(during_go_func=setCoherence)
direction_controller = FunctionController(during_go_func=setDirection)
inst_controller = FunctionController(during_go_func=changeInstructions)
inst_on_controller = FunctionController(during_go_func=setInstructions)
inst3_on_controller = FunctionController(during_go_func=setTimeOn)
inst3_position_controller = FunctionController(during_go_func=setTimePos)
fixation_texture_controller = FunctionController(during_go_func=setFixationTexture)
samplefix_controller = FunctionController(during_go_func=setSampleFix)

state_controller = FunctionController(during_go_func=getState)

#######################################################
#  Connect the controllers with objects they control  #
#######################################################
p.add_controller(p,'trigger_go_if_armed',trigger_in_controller)

# on or off before pres
p.add_controller(str_instruct_1,'on', stimulus_off_controller)
p.add_controller(str_instruct_2,'text', inst_controller)
p.add_controller(str_instruct_2,'on', stimulus_on_controller)
p.add_controller(str_instruct_2,'on', inst_on_controller)
p.add_controller(dotStim,'on', stimulus_on_controller)
p.add_controller(fixation,'on', stimulus_on_controller)

# on or off during pres
p.add_controller(fixation,'max_alpha', fixation_controller)
p.add_controller(dotStim,'on', dot_controller)
p.add_controller(dotStim,'signal_fraction', coherence_controller)
p.add_controller(dotStim,'signal_direction_deg', direction_controller)
p.add_controller(fixation,'texture', fixation_texture_controller)
Beispiel #39
0
)

cur_time = Text(
    text="",
    font_size=15,
    color=(.75, .75, .75),
    anchor='lowerleft',
    position=(0, 0),
)

viewport_instructions = Viewport(screen=screen,
                                 stimuli=[instructions, cur_time])
attend_face = Viewport(screen=screen, stimuli=[instructions_attendFACE])
attend_scene = Viewport(screen=screen, stimuli=[instructions_attendSCENE])
p1 = Presentation(go_duration=('forever', ), viewports=[viewport_instructions])
p1.add_controller(None, None, FunctionController(during_go_func=displayTime))
p1.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN, waitForTrigger)
                                        ]

# setup main experimental loop
loadStims = 0
wrote_response = 0

stimulus = TextureStimulus(
    anchor='center',
    size=stimuli_size,
    position=(screen.size[0] / 2.0, screen.size[1] / 2.0),
    texture_min_filter=gl.GL_LINEAR,
    shrink_texture_ok=1,
    # PW 2012/11/26
    mipmaps_enabled=False)
def aplicacion():
  global p,inten,coord
  pos=[0.4,0.5,0.6,0.7,0.8]
  pos2=[1.3,1.4,1.5,1.6,1.7,1.8]
  rellenar()
  shuffle(coord)
  i = len(coord)-1
  target.parameters.position = coord[i][:2]
  (xpos,ypos)=target.parameters.position
  x=xpos-screen.size[0]/2
  y=ypos-screen.size[1]/2
  anrad=math.atan2(y, x)
  angrad=math.degrees(anrad)
 
  if angrad>=0:
      if angrad<=90: 
        orientacion=-45
        xx=2.0
        yy=2.0
      else:
       orientacion=-135
       xx=-2.0
       yy=2.0
  else:
      aux=angrad*(-1)
      if aux<=90:
        orientacion=45
        xx=2.0
        yy=-2.0
      else:
        orientacion=135
        xx=-2.0
        yy=-2.0
  
  fixpoint.parameters.position=((screen.size[0]/2.0)+xx, (screen.size[1]/2.0)+yy)
  fixpoint.parameters.orientation=orientacion
  
  
  viewport = Viewport(screen=screen, stimuli=[fixpoint,fixcirc])
  p = Presentation(go_duration=(1.0,'seconds'),viewports=[viewport])
  p.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN, keydown),
                                       (pygame.locals.KEYUP, keyup),
                                       (pygame.locals.QUIT, quit_app)]
  p.add_controller(None, None, FunctionController(during_go_func=settings))
  #winsound.PlaySound('instruccion',winsound.SND_FILENAME)
  p.go()
  
  while len(coord)!= 0:
    if end:
        break
    i = len(coord)-1
    target.parameters.position = coord[i][:2]
    dur=pos[random.randrange(0,4,1)]
    (xpos,ypos)=target.parameters.position
    x=xpos-screen.size[0]/2
    y=ypos-screen.size[1]/2
    anrad=math.atan2(y, x)
    angrad=math.degrees(anrad)
    #fixpoint.parameters.orientation=(-angrad) 
    if angrad>=0:
      if angrad<=90: 
        orientacion=-45
        xx=2.0
        yy=2.0
      else:
       orientacion=-135
       xx=-2.0
       yy=2.0
    else:
      aux=angrad*(-1)
      if aux<=90:
        orientacion=45
        xx=2.0
        yy=-2.0
      else:
        orientacion=135
        xx=-2.0
        yy=-2.0
  
    fixpoint.parameters.position=((screen.size[0]/2.0)+xx, (screen.size[1]/2.0)+yy)
    fixpoint.parameters.orientation=orientacion
    
  
    viewport = Viewport(screen=screen, stimuli=[fixpoint,fixcirc])
    p = Presentation(go_duration=(dur,'seconds'),viewports=[viewport])
    p.parameters.handle_event_callbacks = [ (pygame.locals.QUIT, quit_app)]
	
    
    p.add_controller(None, None, FunctionController(during_go_func=settings))
    p.go()

    inten = coord[i][-1]
    target.parameters.color = (1.0,1.0,1.0,inten)      #Se muestra el estimulo Duracion 0.3 segundos
    viewport = Viewport(screen=screen, stimuli=[target,fixpoint,fixcirc])
    p = Presentation(go_duration=(0.3,'seconds'),viewports=[viewport])
    p.parameters.handle_event_callbacks = [ (pygame.locals.QUIT, quit_app)]
                          
    p.add_controller(None, None, FunctionController(during_go_func=settings))
    p.go()
    target.parameters.color = (0.0,0.0,0.0,1.0)  #Desaparece el estimulo tiempo para registrar
    viewport = Viewport(screen=screen, stimuli=[target,fixpoint,fixcirc])
    dur2=pos[random.randrange(0,4,1)]
    p = Presentation(go_duration=(dur2,'seconds'),viewports=[viewport])
    p.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN, keydown),
                                       (pygame.locals.KEYUP, keyup),
                                       (pygame.locals.QUIT, quit_app)]
    p.add_controller(None, None, FunctionController(during_go_func=settings))
    p.go()
    coord.pop()
Beispiel #41
0
		fname2 = "%s_%s_%s_%s_%s_S2.bmp" % (ratio, n1, color, size, exemplar)
		
	####
	t1 = Texture(Image.open(os.path.join(stimLib,fname1)))
	t2 = Texture(Image.open(os.path.join(stimLib,fname2)))
	
	phase = ""
	s1 = TextureStimulus(texture = t1, position = (x, y), anchor = 'center')
	s2 = TextureStimulus(texture = t2, position = (x * 3, y), anchor = 'center')	

	texture_object1 = s1.parameters.texture.get_texture_object()
	texture_object2 = s2.parameters.texture.get_texture_object()

	v = Viewport(screen=screen, stimuli=[s1,s2])
	p = Presentation(go_duration=('forever', ), viewports=[v])
	p.add_controller(None, None, FunctionController(during_go_func=put_image_dual, temporal_variables = TIME_SEC_ABSOLUTE))

	if response == "voice":
		p.parameters.handle_event_callbacks=[(pygame.locals.MOUSEBUTTONDOWN, mouseGrade), (pygame.locals.KEYDOWN, quitHandler)]
	else:
		p.parameters.handle_event_callbacks=[(pygame.locals.MOUSEBUTTONDOWN, mouseFunc), (pygame.locals.KEYDOWN, quitHandler)]

	p.go()
	
	if response == "voice":
		sub.inputData(trial, "misfire", misfire)


	if trial % break_trial == 0 and trial != trials:
		print trial, "BREAK TIME"
		experiments.showImage(screen, os.path.join(basePath, "break.BMP"), 0)
Beispiel #42
0
instructions_attendSCENE = Text(
    text="Attend to SCENES",
    font_size=32,
    color=(1, 1, 1),
    anchor="center",
    position=(screen.size[0] / 2, screen.size[1] / 2),
)

cur_time = Text(text="", font_size=15, color=(0.75, 0.75, 0.75), anchor="lowerleft", position=(0, 0))

viewport_instructions = Viewport(screen=screen, stimuli=[instructions, cur_time])
attend_face = Viewport(screen=screen, stimuli=[instructions_attendFACE])
attend_scene = Viewport(screen=screen, stimuli=[instructions_attendSCENE])
p1 = Presentation(go_duration=("forever",), viewports=[viewport_instructions])
p1.add_controller(None, None, FunctionController(during_go_func=displayTime))
p1.parameters.handle_event_callbacks = [(pygame.locals.KEYDOWN, waitForTrigger)]

# setup main experimental loop
loadStims = 0
wrote_response = 0

stimulus = TextureStimulus(
    anchor="center",
    size=stimuli_size,
    position=(screen.size[0] / 2.0, screen.size[1] / 2.0),
    texture_min_filter=gl.GL_LINEAR,
    shrink_texture_ok=1,
    # PW 2012/11/26
    mipmaps_enabled=False,
)
Beispiel #43
0
# define target position as a function of time
def get_target_position(t):
    global mid_x, mid_y, max_vel
    return (
        max_vel * sin(0.1 * 2.0 * pi * t) + mid_x,  # x
        max_vel * sin(0.1 * 2.0 * pi * t) + mid_y)  # y


def get_drum_angle(t):
    return 50.0 * math.cos(0.2 * 2 * math.pi * t)


# Create instances of the Controller class
target_position_controller = FunctionController(
    during_go_func=get_target_position)
drum_angle_controller = FunctionController(during_go_func=get_drum_angle)

#############################################################
#  Connect the controllers with the variables they control  #
#############################################################

p.add_controller(target, 'position', target_position_controller)
p.add_controller(drum, 'angular_position', drum_angle_controller)

#######################
#  Run the stimulus!  #
#######################

p.go()
# Generate some images
image_list = []
for i in range(num_images):
    image = Image.new("RGB",image_size,(0,0,255)) # Blue background
    draw = ImageDraw.Draw(image)
    line_x = image_size[0]/float(num_images) * i
    draw.line((line_x, 0, line_x, image_size[1]), fill=(255,255,255))
    image_list.append(image)

texture_list = map(Texture,image_list) # create instances of Texture from images

screen = get_default_screen()

stimulus = TextureStimulus(texture=texture_list[0],
                           position = (screen.size[0]/2.0,screen.size[1]/2.0),
                           anchor='center',
                           size=image_size)

viewport = Viewport(screen=screen,
                    stimuli=[stimulus])

p = Presentation(go_duration=(num_images*duration_per_image,'seconds'),viewports=[viewport])

def put_image(t):
    i = int(t/duration_per_image) # choose image
    stimulus.parameters.texture = texture_list[i]
p.add_controller(None,None,FunctionController(during_go_func=put_image))

p.go()
right_label_controller = FunctionController(during_go_func=myRightLabel)
left_label_controller = FunctionController(during_go_func=myLeftLabel)
task_controller = FunctionController(during_go_func=myFixation)
arrow_direction_controller = FunctionController( \
                           during_go_func=get_arrow_direction)

arrow_position_controller = FunctionController( \
                           during_go_func=get_arrow_position)
arrow_color_controller = FunctionController(during_go_func=get_arrow_color)
myArrowOnControl = FunctionController(during_go_func=myArrowOn)

#############################################################
#  Connect the controllers with the variables they control  #
#############################################################
# Actually listens to the TCP socket
if TCPIP: p.add_controller(None, None, tcp_listener)

p.add_controller(p,'trigger_go_if_armed',trigger_in_controller)
p.add_controller(textAA,'on', stimulus_off_controller )
#p.add_controller(textA,'on', stimulus_off_controller )
#p.add_controller(textB,'on', stimulus_off_controller )
#p.add_controller(textC,'on', stimulus_off_controller )
#p.add_controller(textD,'on', stimulus_off_controller )
p.add_controller(taskStimulus,'on', stimulus_on_controller)
p.add_controller(centerStim,'on', stimulus_on_controller)
p.add_controller(tach1,'on', stimulus_on_controller)
p.add_controller(tach2,'on', stimulus_on_controller)
p.add_controller(tach3,'on', stimulus_on_controller)
p.add_controller(tach4,'on', stimulus_on_controller)
p.add_controller(tach5,'on', stimulus_on_controller)
p.add_controller(tach6,'on', stimulus_on_controller)
viewport = Viewport(screen=screen, stimuli=[stimulus])

########################################
#  Create presentation object and go!  #
########################################

p = Presentation(go_duration=(5.0,'seconds'), viewports=[viewport])

##############################################
#  Connect the controller with the stimulus  #
##############################################

keyboard_response = KeyboardResponseController()

# Add the keyboard controller to the presentation's list of controllers
p.add_controller(None, None, keyboard_response)

########
#  Go  #
########

for i in range(3):
    p.go()

    # Print responses collected during the presentation
#   print "all       =",keyboard_response.get_responses_since_go()
#   print "all_time  =",keyboard_response.get_time_responses_since_go()
    print "first     =",keyboard_response.get_first_response_since_go()
    print "first_time=",keyboard_response.get_time_first_response_since_go()
#   print "last      =",keyboard_response.get_last_response_since_go()
#   print "last_time =",keyboard_response.get_time_last_response_since_go()
Beispiel #47
0
right_label_controller = FunctionController(during_go_func=myRightLabel)
left_label_controller = FunctionController(during_go_func=myLeftLabel)
task_controller = FunctionController(during_go_func=myFixation)
arrow_direction_controller = FunctionController( \
                           during_go_func=get_arrow_direction)

arrow_position_controller = FunctionController( \
                           during_go_func=get_arrow_position)
arrow_color_controller = FunctionController(during_go_func=get_arrow_color)
myArrowOnControl = FunctionController(during_go_func=myArrowOn)

#############################################################
#  Connect the controllers with the variables they control  #
#############################################################
# Actually listens to the TCP socket
if TCPIP: p.add_controller(None, None, tcp_listener)

p.add_controller(p, 'trigger_go_if_armed', trigger_in_controller)
p.add_controller(textAA, 'on', stimulus_off_controller)
#p.add_controller(textA,'on', stimulus_off_controller )
#p.add_controller(textB,'on', stimulus_off_controller )
#p.add_controller(textC,'on', stimulus_off_controller )
#p.add_controller(textD,'on', stimulus_off_controller )
p.add_controller(taskStimulus, 'on', stimulus_on_controller)
p.add_controller(centerStim, 'on', stimulus_on_controller)
p.add_controller(tach1, 'on', stimulus_on_controller)
p.add_controller(tach2, 'on', stimulus_on_controller)
p.add_controller(tach3, 'on', stimulus_on_controller)
p.add_controller(tach4, 'on', stimulus_on_controller)
p.add_controller(tach5, 'on', stimulus_on_controller)
p.add_controller(tach6, 'on', stimulus_on_controller)
Beispiel #48
0
max_vel = min(screen.size[0],screen.size[1]) * 0.4

# define position as a function of time
def get_target_position(t):
    global mid_x, mid_y, max_vel
    return ( max_vel*sin(0.1*2.0*pi*t) + mid_x , # x
             max_vel*sin(0.1*2.0*pi*t) + mid_y ) # y

# Create an instance of the Controller class
target_position_controller = FunctionController(during_go_func=get_target_position)

#############################################################
#  Connect the controllers with the variables they control  #
#############################################################

p.add_controller(target,'position', target_position_controller )

#######################
#  Run the stimulus!  #
#######################

base_dir = VisionEgg.config.VISIONEGG_USER_DIR
if not os.path.isdir(base_dir):
    base_dir = VisionEgg.config.VISIONEGG_SYSTEM_DIR
save_directory = os.path.join(base_dir,'movie')
if not os.path.isdir(save_directory):
    os.mkdir(save_directory)
    if not os.path.isdir(save_directory):
        print "Error: cannot make movie directory '%s'."%save_directory
print "Saving movie to directory '%s'."%save_directory
basename = "movie_"+os.path.splitext(os.path.basename(sys.argv[0]))[0]
Beispiel #49
0
    draw = ImageDraw.Draw(image)
    line_x = image_size[0] / float(num_images) * i
    draw.line((line_x, 0, line_x, image_size[1]), fill=(255, 255, 255))
    image_list.append(image)

texture_list = map(Texture,
                   image_list)  # create instances of Texture from images

screen = get_default_screen()

stimulus = TextureStimulus(texture=texture_list[0],
                           position=(screen.size[0] / 2.0,
                                     screen.size[1] / 2.0),
                           anchor='center',
                           size=image_size)

viewport = Viewport(screen=screen, stimuli=[stimulus])

p = Presentation(go_duration=(num_images * duration_per_image, 'seconds'),
                 viewports=[viewport])


def put_image(t):
    i = int(t / duration_per_image)  # choose image
    stimulus.parameters.texture = texture_list[i]


p.add_controller(None, None, FunctionController(during_go_func=put_image))

p.go()
   # indicate begining of a block
   sendCommand(beginBlock,0)
   p.go()

   #par.setData(fixationOnOffTrig)
   #time.sleep(.001)

   imageStim = TextureStimulus(texture=imageTex,
                               position = (screen.size[0]/2.0,screen.size[1]/2.0),
                               anchor='center', size=(width*scale,height*scale),
                               mipmaps_enabled = 0, texture_min_filter=gl.GL_LINEAR)

   texture_object = imageStim.parameters.texture.get_texture_object()
              
   texture_object.put_sub_image( curImList[0] )
   p.add_controller(None, None, FunctionController(during_go_func=every_frame_func) )
#   p.parameters.go_duration = ((numImsPerBlock + 1)/float(presentationFreq),'seconds')
   p.parameters.go_duration = (3*(numImsPerBlock + 1)/float(presentationFreq),'seconds') # DJ: Why *3?
   viewport.parameters.stimuli=[imageStim]
   p.go();
   if (run_as_standalone == 0):
      par.setData(0)

   # indicate the results
   sendCommand(endBlock,0)
   internalState = 0

   # fixation cross
   p.parameters.go_duration = (1,'seconds')
   p.controllers = []
   viewport.parameters.stimuli=[fixPt]
Beispiel #51
0
        )

other_text = []
other_text.append(
    Text(text='Pixel positions (x,y) calculated from 3D coordinates',
         position=(screen.size[0]/2,screen.size[1]),
         anchor='top',
         )
    )

other_text.append(
    Text(text='----> x',
         position=(10,10),
         anchor='left',
         )
    )

other_text.append(
    Text(text='----> y',
         angle=90.0,
         position=(10,10),
         anchor='left',
         )
    )

viewport2D.parameters.stimuli = vertex_labels + other_text

p = Presentation(go_duration=(10.0,'seconds'),viewports=[viewport3D,viewport2D])
p.add_controller(None, None, FunctionController(during_go_func=update))
p.go()