def run(self):
        p = pyaudio.PyAudio()
        time_stamped = False
        stream = p.open(
            format=self.format,
            channels=self.channels,
            rate=self.rate,
            input=self.input,
            frames_per_buffer=self.frames_per_buffer,
        )

        print "* recording"
        all = []
        start_time = VisionEgg.time_func()
        i = 0
        while (i <= self.rate / self.chunk * self.time) and (
            (not time_stamped) or (VisionEgg.time_func() < end_time + 2)
        ):
            # for i in range(0, self.rate / self.chunk * self.time):
            data = stream.read(self.chunk)
            samps = numpy.fromstring(data, dtype=numpy.int16)
            all.append(data)
            loud = loudness(samps)
            # print str(i) + "   " + str(loud)
            if (not time_stamped) and loud > self.sound_threshold:
                end_time = VisionEgg.time_func()
                self.q.put(start_time)
                self.q.put(end_time)
                # self.f.write("%s\t%f\t%f\t%f\t" % (self.item, end_time-start_time, start_time, end_time))
                # self.f.flush()
                print "Crossed Threshold!"
                time_stamped = True
            i = i + 1

        if not time_stamped:
            self.q.put(start_time)
            self.q.put(10000000)
            # self.f.write("%s\t%f\t%f\t%f\t" % (self.item, 10000000, start_time, 10000000.0))

        print "* done recording"
        stream.close()
        p.terminate()

        # write data to WAVE file
        data = "".join(all)
        wf = wave.open(self.file_name, "wb")
        wf.setnchannels(self.channels)
        wf.setsampwidth(p.get_sample_size(self.format))
        wf.setframerate(self.rate)
        wf.writeframes(data)
        wf.close()
    def run(self, ID=0):
        self.ID = ID
        self.sound_fired = 0
        super(RMLTrial, self).run()
        while not self.stopped:
            self.run_time = VisionEgg.time_func() - self.start_time
            if self.phase == 0:
                self.pre_experiment_time = VisionEgg.time_func()
                # this trial phase is ended with a enter press or TR pulse
                if self.ID != 0:
                    self.phase_forward()
            if self.phase == 1:
                self.pre_stimulus_time = VisionEgg.time_func()
                if (self.pre_stimulus_time - self.pre_experiment_time) > self.phase_durations[1]:
                    self.phase_forward()
            if self.phase == 2:
                self.stimulus_time = VisionEgg.time_func()
                if (self.stimulus_time - self.pre_stimulus_time) > self.phase_durations[2]:
                    self.phase_forward()
            if self.phase == 3:
                self.tone_time = VisionEgg.time_func()
                if self.sound_fired == 0:
                    if self.tracker != None:
                        self.tracker.sendMessage(
                            "trial "
                            + str(self.ID)
                            + " sound "
                            + str(self.parameters["sound"])
                            + " at "
                            + str(self.tone_time)
                        )
                    if self.parameters["sound"] == 0:
                        self.session.play_np_sound(self.noise_tone_array)
                    elif self.parameters["sound"] == 1:
                        self.session.play_sound(sound_index="reward")
                    self.sound_fired = 1
                    # this trial phase is timed
                if (self.tone_time - self.stimulus_time) > self.phase_durations[3]:
                    self.stopped = True

                    # events and draw
            self.event()
            self.draw()

        self.stop()
Пример #3
0
 def __init__(self, **kw):
     VisionEgg.Core.Stimulus.__init__(self,**kw)
     # store positions normalized around 0 so that re-sizing is ok
     num_dots = self.constant_parameters.num_dots # shorthand
     self.centers = np.random.standard_normal((3,num_dots))
     self.colors = np.ones((num_dots,4))
     self.colors[:self.constant_parameters.num_dark,:3] = 0
     self.last_time_sec = VisionEgg.time_func()
     self.start_times_sec = None # setup variable, assign later
Пример #4
0
 def __init__(self, **kw):
     VisionEgg.Core.Stimulus.__init__(self,**kw)
     # store positions normalized between 0 and 1 so that re-sizing is ok
     num_dots = self.constant_parameters.num_dots # shorthand
     self.x_positions = RandomArray.uniform(0.0,1.0,(num_dots,))
     self.y_positions = RandomArray.uniform(0.0,1.0,(num_dots,))
     self.random_directions_radians = RandomArray.uniform(0.0,2*math.pi,(num_dots,))
     self.last_time_sec = VisionEgg.time_func()
     self.start_times_sec = None # setup variable, assign later
     self._gave_alpha_warning = 0
	def run(self, ID = 0):
		self.ID = ID
		super(DetectTrial, self).run()
		while not self.stopped:
			self.run_time = VisionEgg.time_func() - self.start_time
			if self.phase == 0:
				self.prestimulation_time = VisionEgg.time_func()
				# this trial phase is ended with a space press on the first trial of a run, but timed on all other trials of a run.
				if ( self.prestimulation_time - self.start_time ) > self.phase_durations[1] and self.ID != 0:
					self.phase_forward()
			elif self.phase == 1:
				self.adaptation_time = VisionEgg.time_func()
				# this trial phase is timed
				if ( self.adaptation_time  - self.prestimulation_time ) > self.phase_durations[1]:
					self.phase_forward()
			elif self.phase == 2:
				# this trial phase is timed
				self.post_adaptation_time = VisionEgg.time_func()
				if ( self.post_adaptation_time  - self.adaptation_time ) > self.phase_durations[2]:
					self.session.play_sound( sound_index = 1 )
					self.phase_forward()
			elif self.phase == 3:
				# this trial phase is timed
				self.first_test_time = VisionEgg.time_func()
				if ( self.first_test_time  - self.post_adaptation_time ) > self.phase_durations[3]:
					self.phase_forward()
			elif self.phase == 4:
				# this trial phase is timed
				self.inter_test_time = VisionEgg.time_func()
				if ( self.inter_test_time  - self.first_test_time ) > self.phase_durations[4]:
					self.session.play_sound( sound_index = 1 )
					self.phase_forward()
			elif self.phase == 5:
				# this trial phase is timed
				self.last_test_time = VisionEgg.time_func()
				if ( self.last_test_time  - self.inter_test_time ) > self.phase_durations[5]:
					self.phase_forward()
			elif self.phase == 6:
				self.answer_time = VisionEgg.time_func() - self.last_test_time
			elif self.phase == 7:
				self.post_answer_time = VisionEgg.time_func() - self.answer_time
			
			# events and draw
			self.event()
			self.draw()
		
		# we have stopped. 
		self.stop()
 def event(self):
     for event in pygame.event.get():
         super(RMLTrial, self).key_event(event)
         if event.type == KEYDOWN:
             if event.key == pygame.locals.K_ESCAPE:
                 self.events.append([-99, VisionEgg.time_func() - self.start_time])
                 self.stopped = True
                 self.session.stopped = True
                 # it handles both numeric and lettering modes
             elif (
                 event.key == pygame.locals.K_RETURN or event.key == pygame.locals.K_t
             ):  # press enter (or TR pulse) to start experiment
                 self.events.append([0, VisionEgg.time_func() - self.start_time])
                 if self.phase == 0:
                     self.phase_forward()
             elif event.key == pygame.locals.K_SPACE:
                 if self.phase != 0:  # only register space bar presses after experiment has started
                     self.events.append(
                         [1, VisionEgg.time_func() - self.start_time]
                     )  # register space bar presses with '1' and save timestamp
                     self.session.reversal_keypresses += (
                         1
                     )  # save self.reversal_keypresses to be able to print it in the terminal later
Пример #7
0
    def draw(self):
        # XXX This method is not speed-optimized. I just wrote it to
        # get the job done. (Nonetheless, it seems faster than the C
        # version commented out above.)

        p = self.parameters # shorthand

        now_sec = VisionEgg.time_func()
        if self.start_times_sec is not None:
            # compute extinct dots and generate new positions
            replace_indices = Numeric.nonzero( Numeric.greater( now_sec - self.start_times_sec, p.dot_lifespan_sec) )
            Numeric.put( self.start_times_sec, replace_indices, now_sec )

            new_centers = np.random.standard_normal((3,len(replace_indices)))
            for i in range(3):
                Numeric.put( self.centers[i,:], replace_indices, new_centers[i,:] )
        else:
            # initialize dot extinction values to random (uniform) distribution
            self.start_times_sec = RandomArray.uniform( now_sec - p.dot_lifespan_sec, now_sec,
                                                        (self.constant_parameters.num_dots,))

        time_delta_sec = now_sec - self.last_time_sec
        self.last_time_sec = now_sec # reset for next loop
        self.centers = self.centers + np.array(p.signal_vec)[:,np.newaxis]*time_delta_sec

        xyz = self.centers*p.start_position_variance + np.array(p.start_position_mean)[:,np.newaxis]
        xs = xyz[0,:]
        ys = xyz[1,:]
        zs = xyz[2,:]

        if p.on:
            gl.glEnable( gl.GL_POINT_SMOOTH )
            # allow max_alpha value to control blending
            gl.glEnable( gl.GL_BLEND )
            gl.glBlendFunc( gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA )

            gl.glPointSize(p.dot_size)

            # Clear the modeview matrix
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glPushMatrix()

            gl.glDisable(gl.GL_TEXTURE_2D)

            draw_dots(xs,ys,zs,self.colors)
            gl.glDisable( gl.GL_POINT_SMOOTH ) # turn off
            gl.glPopMatrix()
Пример #8
0
    def __init__(self, **kw):
        VisionEgg.Core.Stimulus.__init__(self,**kw)
        # store positions normalized between 0 and 1 so that re-sizing is ok
        num_dots = self.constant_parameters.num_dots # shorthand
        self.x_positions = RandomArray.uniform(0.0,1.0,(num_dots,))
        self.y_positions = RandomArray.uniform(0.0,1.0,(num_dots,))
        if self.parameters.mode == "wind":
            self.random_directions_radians = RandomArray.uniform(0.0,2*math.pi,(num_dots,))
            self.velocities = RandomArray.uniform(self.parameters.velocity_max-1, self.parameters.velocity_max,(num_dots,))            

        elif self.parameters.mode == "Gaussian":    
            self.random_directions_radians = numpy.random.normal(self.parameters.signal_direction_deg/180.0*math.pi, self.parameters.signal_fraction,(num_dots,))
            self.velocities = RandomArray.uniform(self.parameters.velocity_min, self.parameters.velocity_max,(num_dots,))

        self.last_time_sec = VisionEgg.time_func()
        self.start_times_sec = None # setup variable, assign later
        self._gave_alpha_warning = 0
Пример #9
0
	def event(self):
		for event in pygame.event.get():
			if event.type == KEYDOWN:
				if event.key == pygame.locals.K_ESCAPE:
					self.events.append([-99,VisionEgg.time_func()-self.start_time])
					self.parameters.update({'correct': 0})
					self.stopped = True
					self.session.stopped = True
				# it handles both numeric and lettering modes 
				elif event.key == pygame.locals.K_SPACE:
					self.events.append([0,VisionEgg.time_func()-self.start_time])
					if self.phase in (0, 4):
						self.phase_forward()
					# else:
					# 	self.stopped = True	
				elif event.key == pygame.locals.K_LEFT:
					self.events.append([1,VisionEgg.time_func()-self.start_time])
					if self.version == 1:
						if self.phase == 2:
							self.parameters.update({'answer':1})
							if self.parameters['target_present_in_stimulus'] == 0:
								self.parameters['correct']= 1
							else:
								self.parameters['correct']= 0
							if self.phase == 2:
								self.phase_forward()
					if self.version == 2:
						if self.phase == 2:
							self.parameters.update({'answer':1})
							if self.parameters['target_present_in_stimulus'] == 1:
								self.parameters['correct']= 1
							else:
								self.parameters['correct']= 0
							if self.phase == 2:
								self.phase_forward()
				elif event.key == pygame.locals.K_RIGHT:
					self.events.append([-1,VisionEgg.time_func()-self.start_time])
					if self.version == 1:
						if self.phase == 2:
							self.parameters.update({'answer':-1})
							if self.parameters['target_present_in_stimulus'] == 1:
								self.parameters['correct']= 1
							else:
								self.parameters['correct']= 0
							if self.phase == 2:
								self.phase_forward()
					if self.version == 2:
						if self.phase == 2:
							self.parameters.update({'answer':-1})
							if self.parameters['target_present_in_stimulus'] == 0:
								self.parameters['correct']= 1
							else:
								self.parameters['correct']= 0
							if self.phase == 2:
								self.phase_forward()				
				elif event.key == pygame.locals.K_a:
					if self.phase > 3:
						self.parameters['confidence'] = 0
					if self.phase == 4:
						self.phase_forward()
				elif event.key == pygame.locals.K_s:
					if self.phase > 3:
						self.parameters['confidence'] = 1
					if self.phase == 4:
						self.phase_forward()
				elif event.key == pygame.locals.K_d:
					if self.phase > 3:
						self.parameters['confidence'] = 2
					if self.phase == 4:
						self.phase_forward()
				elif event.key == pygame.locals.K_f:
					if self.phase > 3:
						self.parameters['confidence'] = 3
					if self.phase == 4:
						self.phase_forward()

			super(DetectTrial, self).key_event( event )
Пример #10
0
    def draw(self):
        # XXX This method is not speed-optimized. I just wrote it to
        # get the job done. (Nonetheless, it seems faster than the C
        # version commented out above.)

        p = self.parameters  # shorthand
        if p.center is not None:
            if not hasattr(VisionEgg.config, "_GAVE_CENTER_DEPRECATION"):
                logger = logging.getLogger('VisionEgg.Dots')
                logger.warning("Specifying DotArea2D by deprecated "
                               "'center' parameter deprecated.  Use "
                               "'position' parameter instead.  (Allows "
                               "use of 'anchor' parameter to set to "
                               "other values.)")
                VisionEgg.config._GAVE_CENTER_DEPRECATION = 1
            p.anchor = 'center'
            p.position = p.center[0], p.center[
                1]  # copy values (don't copy ref to tuple)
        if p.on:
            # calculate center
            center = VisionEgg._get_center(p.position, p.anchor, p.size)

            if p.anti_aliasing:
                if len(p.color) == 4 and not self._gave_alpha_warning:
                    if p.color[3] != 1.0:
                        logger = logging.getLogger('VisionEgg.Dots')
                        logger.warning("The parameter anti_aliasing is "
                                       "set to true in the DotArea2D "
                                       "stimulus class, but the color "
                                       "parameter specifies an alpha "
                                       "value other than 1.0.  To "
                                       "acheive the best anti-aliasing, "
                                       "ensure that the alpha value for "
                                       "the color parameter is 1.0.")
                        self._gave_alpha_warning = 1
                gl.glEnable(gl.GL_POINT_SMOOTH)
                # allow max_alpha value to control blending
                gl.glEnable(gl.GL_BLEND)
                gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
            else:
                gl.glDisable(gl.GL_BLEND)

            now_sec = VisionEgg.time_func()
            if self.start_times_sec is not None:
                # compute extinct dots and generate new positions
                replace_indices = Numeric.nonzero(
                    Numeric.greater(now_sec - self.start_times_sec,
                                    p.dot_lifespan_sec))
                Numeric.put(self.start_times_sec, replace_indices, now_sec)

                new_x_positions = RandomArray.uniform(0.0, 1.0,
                                                      (len(replace_indices), ))
                Numeric.put(self.x_positions, replace_indices, new_x_positions)

                new_y_positions = RandomArray.uniform(0.0, 1.0,
                                                      (len(replace_indices), ))
                Numeric.put(self.y_positions, replace_indices, new_y_positions)

                new_random_directions_radians = RandomArray.uniform(
                    0.0, 2 * math.pi, (len(replace_indices), ))
                Numeric.put(self.random_directions_radians, replace_indices,
                            new_random_directions_radians)
            else:
                # initialize dot extinction values to random (uniform) distribution
                self.start_times_sec = RandomArray.uniform(
                    now_sec - p.dot_lifespan_sec, now_sec,
                    (self.constant_parameters.num_dots, ))

            signal_num_dots = int(
                round(p.signal_fraction * self.constant_parameters.num_dots))
            time_delta_sec = now_sec - self.last_time_sec
            self.last_time_sec = now_sec  # reset for next loop
            x_increment_normalized = math.cos(
                p.signal_direction_deg / 180.0 * math.pi
            ) * p.velocity_pixels_per_sec / p.size[0] * time_delta_sec
            y_increment_normalized = -math.sin(
                p.signal_direction_deg / 180.0 * math.pi
            ) * p.velocity_pixels_per_sec / p.size[1] * time_delta_sec
            self.x_positions[:signal_num_dots] += x_increment_normalized
            self.y_positions[:signal_num_dots] += y_increment_normalized

            num_random_dots = self.constant_parameters.num_dots - signal_num_dots
            random_x_increment_normalized = Numeric.cos(
                self.random_directions_radians[signal_num_dots:]
            ) * p.velocity_pixels_per_sec / p.size[0] * time_delta_sec
            random_y_increment_normalized = -Numeric.sin(
                self.random_directions_radians[signal_num_dots:]
            ) * p.velocity_pixels_per_sec / p.size[1] * time_delta_sec
            self.x_positions[signal_num_dots:] += random_x_increment_normalized
            self.y_positions[signal_num_dots:] += random_y_increment_normalized

            self.x_positions = Numeric.fmod(self.x_positions, 1.0)  # wrap
            self.y_positions = Numeric.fmod(self.y_positions, 1.0)

            self.x_positions = Numeric.fmod(self.x_positions + 1,
                                            1.0)  # wrap again for values < 1
            self.y_positions = Numeric.fmod(self.y_positions + 1, 1.0)

            xs = (self.x_positions - 0.5) * p.size[0] + center[0]
            ys = (self.y_positions - 0.5) * p.size[1] + center[1]

            if len(p.color) == 3:
                gl.glColor3f(*p.color)
            elif len(p.color) == 4:
                gl.glColor4f(*p.color)
            gl.glPointSize(p.dot_size)

            # Clear the modeview matrix
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glPushMatrix()

            gl.glDisable(gl.GL_TEXTURE_2D)

            if p.depth is None:
                depth = 0.0
            else:
                gl.glEnable(gl.GL_DEPTH_TEST)
                depth = p.depth
            zs = (depth, ) * len(xs)  # make N tuple with repeat value of depth
            draw_dots(xs, ys, zs)
            if p.anti_aliasing:
                gl.glDisable(gl.GL_POINT_SMOOTH)  # turn off
            gl.glPopMatrix()
Пример #11
0
	def run(self, ID = 0):
		self.ID = ID
		super(DetectTrial, self).run()
		sound_played = False
		# self.start_time = VisionEgg.time_func()
		while not self.stopped:
			self.run_time = VisionEgg.time_func() - self.start_time
			if self.phase == 0:
				self.prestimulation_time = VisionEgg.time_func()
				if self.ID % 15 != 0:
					if ( self.prestimulation_time  - self.start_time ) > self.phase_durations[0]:
						self.phase_forward()
				# this trial phase is ended with a space press on the first trial of a run, but timed on all other trials of a run.
			elif self.phase == 1:	# first delay
				self.delay_1_time = VisionEgg.time_func()
				# this trial phase is timed
				if ( self.delay_1_time - self.prestimulation_time ) > self.phase_durations[1] - 0.1 and sound_played == False:
					self.session.play_sound( sound_index = 1 )
					sound_played = True
				if ( self.delay_1_time - self.prestimulation_time ) > self.phase_durations[1]:
					self.phase_forward()
			elif self.phase == 2:	# stimulus presentation
				# this trial phase is timed
				self.test_time = VisionEgg.time_func()
				if ( self.test_time  - self.delay_1_time ) > self.phase_durations[2]:
					self.phase_forward()
			elif self.phase == 3:	# second delay
				# this trial phase is timed
				self.delay_2_time = VisionEgg.time_func()
				if ( self.delay_2_time  - self.test_time ) > self.phase_durations[3]:
					this_prob = np.random.rand()
					# print this_prob, self.ID
					if (this_prob < 0.1 or self.parameters['correct'] == -1) and not hasattr(self, 'has_been_extended'):
						self.phase_durations[3] = self.phase_durations[3] + 2.0
						self.has_been_extended = True
					else:
						self.stopped = True
						return
					if this_prob < 0.1:
						if self.version == 1:
							if self.parameters['correct'] == 1:
								self.session.play_sound( sound_index = 2 )
							elif self.parameters['correct'] == 0:
								self.session.play_sound( sound_index = 0 )
						if self.version == 2:
							if self.parameters['correct'] == 1:
								self.session.play_sound( sound_index = 0 )
							elif self.parameters['correct'] == 0:
								self.session.play_sound( sound_index = 2 )
					if self.parameters['correct'] == -1:
						self.session.play_sound( sound_index = 3 )
			
			
			
			
			
			# elif self.phase == 4:	# confidence
			# 	self.confidence_time = VisionEgg.time_func()
			# elif self.phase == 5:	# third delay
			# 	self.delay_3_time = VisionEgg.time_func()
			# 	if ( self.delay_3_time  - self.confidence_time ) > self.phase_durations[5]:
			# 		self.feedback_given = False
			# 		self.phase_forward()
			# elif self.phase == 6:	# feedback
			# 	self.feedback_time = VisionEgg.time_func()
			# 	if self.feedback_given == False and ( self.feedback_time  - self.delay_3_time ) > 0.1:
			# 		if self.version == 1:
			# 			if self.parameters['correct'] == 1:
			# 				self.session.play_sound( sound_index = 2 )
			# 			elif self.parameters['correct'] == 0:
			# 				self.session.play_sound( sound_index = 0 )
			# 		if self.version == 2:
			# 			if self.parameters['correct'] == 1:
			# 				self.session.play_sound( sound_index = 0 )
			# 			elif self.parameters['correct'] == 0:
			# 				self.session.play_sound( sound_index = 2 )
			# 		elif self.parameters['correct'] == -1:
			# 			self.session.play_sound( sound_index = 3 )
			# 		self.feedback_given = True
			# 	if ( self.feedback_time  - self.delay_3_time ) > self.phase_durations[6]:
			# 		self.phase_forward()
			# elif self.phase == 7:	# fourth delay
			# 	self.delay_4_time = VisionEgg.time_func()
			# 	if ( self.delay_4_time  - self.feedback_time ) > self.phase_durations[7]:
			# 		self.stopped = True

			# events and draw
			self.event()
			self.draw()

		# we have stopped. 
		self.stop()
Пример #12
0
	def event(self):
		for event in pygame.event.get():
			if event.type == KEYDOWN:
				if event.key == pygame.locals.K_ESCAPE:
					self.events.append([-99,VisionEgg.time_func()-self.start_time])
					self.parameters.update({'correct': 0})
					self.stopped = True
					self.session.stopped = True
				# it handles both numeric and lettering modes 
				elif event.key == pygame.locals.K_SPACE:
					self.events.append([0,VisionEgg.time_func()-self.start_time])
					if self.phase in (0, 4):
						self.phase_forward()
					# else:
					# 	self.stopped = True	
				elif event.key == pygame.locals.K_LEFT:
					self.events.append([1,VisionEgg.time_func()-self.start_time])
					if self.version == 1:
						if self.phase == 2:
							self.parameters.update({'answer':1})
							if self.parameters['target_present_in_stimulus'] == 0:
								self.parameters['correct']= 1
							else:
								self.parameters['correct']= 0
							if self.phase == 2:
								self.phase_forward()
					if self.version == 2:
						if self.phase == 2:
							self.parameters.update({'answer':1})
							if self.parameters['target_present_in_stimulus'] == 1:
								self.parameters['correct']= 1
							else:
								self.parameters['correct']= 0
							if self.phase == 2:
								self.phase_forward()
					if self.phase == 0:
						self.nr_buttons_pressed = self.nr_buttons_pressed + 1
						self.tracker.sendCommand('record_status_message "Trial %d, Buttonpress %d"'%(self.ID, self.nr_buttons_pressed))
				elif event.key == pygame.locals.K_RIGHT:
					self.events.append([-1,VisionEgg.time_func()-self.start_time])
					if self.version == 1:
						if self.phase == 2:
							self.parameters.update({'answer':-1})
							if self.parameters['target_present_in_stimulus'] == 1:
								self.parameters['correct']= 1
							else:
								self.parameters['correct']= 0
							if self.phase == 2:
								self.phase_forward()
					if self.version == 2:
						if self.phase == 2:
							self.parameters.update({'answer':-1})
							if self.parameters['target_present_in_stimulus'] == 0:
								self.parameters['correct']= 1
							else:
								self.parameters['correct']= 0
							if self.phase == 2:
								self.phase_forward()
					if self.phase == 0:
						self.nr_buttons_pressed = self.nr_buttons_pressed + 1
						self.tracker.sendCommand('record_status_message "Trial %d, Buttonpress %d"'%(self.ID, self.nr_buttons_pressed))
				if event.key == pygame.locals.K_c:
					if self.ID % 15 == 0:
						self.session.tracker_setup(auto_trigger_calibration = True, calibration_type = 'HV5', sample_rate = 1000)
				elif event.key == pygame.locals.K_a:
					if self.phase > 3:
						self.parameters['confidence'] = 0
					if self.phase == 4:
						self.phase_forward()
				elif event.key == pygame.locals.K_s:
					if self.phase > 3:
						self.parameters['confidence'] = 1
					if self.phase == 4:
						self.phase_forward()
				elif event.key == pygame.locals.K_d:
					if self.phase > 3:
						self.parameters['confidence'] = 2
					if self.phase == 4:
						self.phase_forward()
				elif event.key == pygame.locals.K_f:
					if self.phase > 3:
						self.parameters['confidence'] = 3
					if self.phase == 4:
						self.phase_forward()

			super(DetectTrial, self).key_event( event )
Пример #13
0
screen = get_default_screen()
screen.parameters.bgcolor = (0.0,0.0,0.2) # background blue (RGB)

text=VisionEgg.Text.PangoText(
    color=(1.0,1.0,1.0), # alpha is ignored (set with max_alpha_param)
    position=(0,screen.size[1]/2),
    size = (screen.size[0],max(screen.size[0]/10,10)),
    anchor='left')

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

# The main loop below is an alternative to using the
# VisionEgg.FlowControl.Presentation class.

frame_timer = FrameTimer()
quit_now = 0
while not quit_now:
    for event in pygame.event.get():
        if event.type in (QUIT,KEYDOWN,MOUSEBUTTONDOWN):
            quit_now = 1

    idx = int(VisionEgg.time_func()%len(language))
    text.parameters.text = "%s: %s"%(language[idx],phrase[idx])
    screen.clear()
    viewport.draw()
    swap_buffers()
    frame_timer.tick()
frame_timer.log_histogram()
Пример #14
0
    def draw(self):
        p = self.parameters # shorthand
        if p.on:
            # calculate center
            center = VisionEgg._get_center(p.position,p.anchor,p.size)
            if p.mask:
                gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB)
            gl.glBindTexture(gl.GL_TEXTURE_1D,self._texture_object_id)

            gl.glEnable(gl.GL_TEXTURE_1D)
            gl.glDisable(gl.GL_TEXTURE_2D)
            if p.bit_depth != self.cached_bit_depth:
                self.calculate_bit_depth_dependencies()

            # Clear the modeview matrix
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glPushMatrix()

            # Rotate about the center of the texture
            gl.glTranslate(center[0],
                           center[1],
                           0)
            gl.glRotate(p.orientation,0,0,1)

            if p.depth is None:
                gl.glDisable(gl.GL_DEPTH_TEST)
                depth = 0.0
            else:
                gl.glEnable(gl.GL_DEPTH_TEST)
                depth = p.depth

            # allow max_alpha value to control blending
            gl.glEnable( gl.GL_BLEND )
            gl.glBlendFunc( gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA )

            if p.color2:
                gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_BLEND)
                gl.glTexEnvfv(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_COLOR, p.color2)
                ## alpha is ignored because the texture base internal format is luminance
            else:
                gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE)

            if p.t0_time_sec_absolute is None and not p.ignore_time:
                p.t0_time_sec_absolute = VisionEgg.time_func()

            w = p.size[0]
            inc = w/float(p.num_samples)
            if p.ignore_time:
                phase = p.phase_at_t0
            else:
                t_var = VisionEgg.time_func() - p.t0_time_sec_absolute
                phase = t_var*p.temporal_freq_hz*-360.0 + p.phase_at_t0
            if p.recalculate_phase_tolerance is None or abs(self._last_phase - phase) > p.recalculate_phase_tolerance:
                self._last_phase = phase # we're re-drawing the phase at this angle
                floating_point_sin = numpy.sin(2.0*math.pi*p.spatial_freq*numpy.arange(0.0,w,inc,dtype=numpy.float)+(phase/180.0*math.pi))*0.5*p.contrast+p.pedestal
                floating_point_sin = numpy.clip(floating_point_sin,0.0,1.0) # allow square wave generation if contrast > 1
                texel_data = (floating_point_sin*self.max_int_val).astype(self.numpy_dtype)
                # PyOpenGL 2.0.1.09 has a bug, so use our own wrapper
                _vegl.veglTexSubImage1D(gl.GL_TEXTURE_1D, # target
                                        0,                # level
                                        0,                # x offset
                                        p.num_samples,    # width
                                        self.format,      # format of new texel data
                                        self.gl_type,     # type of new texel data
                                        texel_data)       # new texel data
                if 0:
                    compare_array = numpy.empty(texel_data.shape,dtype=texel_data.dtype)
                    pixels = _vegl.veglGetTexImage(gl.GL_TEXTURE_1D, # target
                                                   0, # level
                                                   self.format, # format
                                                   self.gl_type, # type
                                                   compare_array)
                    assert numpy.allclose( compare_array, texel_data )

            h_w = p.size[0]/2.0
            h_h = p.size[1]/2.0

            l = -h_w
            r = h_w
            b = -h_h
            t = h_h

            # in the case of only color1,
            # the texel data multiplies color1 to produce a color

            # with color2,
            # the texel data linearly interpolates between color1 and color2

            gl.glColor4f(p.color1[0],p.color1[1],p.color1[2],p.max_alpha)

            if p.mask:
                p.mask.draw_masked_quad(0.0,1.0,0.0,1.0, # l,r,b,t for texture coordinates
                                        l,r,b,t, # l,r,b,t in eye coordinates
                                        depth ) # also in eye coordinates
            else:
                # draw unmasked quad
                gl.glBegin(gl.GL_QUADS)

                gl.glTexCoord2f(0.0,0.0)
                gl.glVertex3f(l,b,depth)

                gl.glTexCoord2f(1.0,0.0)
                gl.glVertex3f(r,b,depth)

                gl.glTexCoord2f(1.0,1.0)
                gl.glVertex3f(r,t,depth)

                gl.glTexCoord2f(0.0,1.0)
                gl.glVertex3f(l,t,depth)
                gl.glEnd() # GL_QUADS

            gl.glDisable(gl.GL_TEXTURE_1D)
            gl.glPopMatrix()
def getState(t):
    global ISI, next_stim_time, direction, last_direction, arrow_scale, score
    global first_loop, start_time, StimCount, stimVis, fbVis, stimText
    global score_factor, arrowColor, leftText, rightText
    global left_strings, right_strings, stimulus_strings, show_array
    global currentTime, currentShow, currentSign, currentTR

    # CC added for TCPIP and detrends
    global tcp_dist, dist_detrend, dist_array, time_array, dist
    global startDetrend, detrendLag
    global ALPHA_MAX, ALPHA_SCALE
    global lumina_dev

    currentTime = t

    if (first_loop == 1) and (p.parameters.trigger_go_if_armed):
        first_loop = 0
        start_time = VisionEgg.time_func()
        if TCPIP:
            tcp_listener.buffer="" # reset buffer

    if t > next_stim_time:
        StimCount = StimCount + 1
        currentShow = int(np.abs(show_array[StimCount]))
        currentSign = int(np.sign(show_array[StimCount]))
        stimText = stimulus_strings[StimCount]
        leftText = left_strings[StimCount]
        rightText = right_strings[StimCount]

        next_stim_time = next_stim_time + ISI

        if StimCount > detrendLag:
            startDetrend=True

####    # note: When run with SVR testing, the input values
####    #       will range from (-inf,inf), most likely (-5,5) 
    if TCPIP:
        tcp_buffer=str(tcp_listener.buffer)
        #print "%s (%s)" %('tcp_data', tcp_buffer)
        tcp_data=tcp_buffer.replace('\000', ''); # remove null byte
        #print "%s (%s) (%s)" %('tcp_data', tcp_data, tcp_buffer)

        if tcp_data != '\000' and tcp_data != "" and \
            "nan" not in tcp_data.lower():

            vals=tcp_data.split(",")
            if len(vals) > 1:
                tcp_dist=float(vals[1])
            else:
                tcp_dist=float(tcp_data)

            tcp_listener.buffer="" # reset buffer
            dist_array = dist_array + [tcp_dist]
            time_array = time_array + [t]
            if DETREND == 1: 
                if startDetrend:
                    dist_detrend = detrendDist(time_array, dist_array)
                else:
                    dist_detrend = tcp_dist
                arrow_scale=dist_detrend
            else:
                arrow_scale=tcp_dist

            if currentShow == 9999 or FEEDBACK == 0:
                fbVis = 0
                score = 90.0
                arrowColor = 0
            else:
                fbVis = 1
                arrowColor = 1
                # increment the score
                score = score - currentSign*arrow_scale*score_factor
                if score < 0:
                    score = 0
                elif score > 180:
                    score = 180
    
            log.write("%5.3f; STIM; %s; %s; %s; %d; %d; %5.3f; %5.3f; %5.3f\n" \
                %(t, leftText, rightText, stimText, currentShow, \
                  currentSign, tcp_dist, arrow_scale, score))

    # handle anything that comes in on the button boxes
    #print "About to test LUMINA",
    #print lumina_dev
    if LUMINA == 1:
        lumina_dev.poll_for_response()
        while lumina_dev.response_queue_size() > 0:
            response = lumina_dev.get_next_response() 
            if response["pressed"]: 
                print "Lumina received: %s, %d"%(response["key"],response["key"])
                if response["key"] == 4:
                    log.write("%5.3f; TR; %s\n"%(currentTime,currentTR))
                    currentTR=currentTR+1
                else:
                    log.write("%5.3f; LUMINA; %d\n"%(currentTime,response["key"]))

    #print "TESTED LUMINA"
    return 1
Пример #16
0
    def draw(self):
        p = self.parameters  # shorthand
        if p.on:
            if p.mask:
                gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB)
            if p.depth_test:
                gl.glEnable(gl.GL_DEPTH_TEST)
            else:
                gl.glDisable(gl.GL_DEPTH_TEST)
            if p.polygon_offset_enabled:
                gl.glEnable(gl.GL_POLYGON_OFFSET_EXT)
                gl.glPolygonOffset(p.polygon_offset_factor, p.polygon_offset_units)
            gl.glBindTexture(gl.GL_TEXTURE_1D, self._texture_object_id)
            gl.glEnable(gl.GL_TEXTURE_1D)
            gl.glDisable(gl.GL_TEXTURE_2D)
            if p.bit_depth != self.cached_bit_depth:
                self.calculate_bit_depth_dependencies()

            # allow max_alpha value to control blending
            gl.glEnable(gl.GL_BLEND)
            gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

            if p.color2:
                gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_BLEND)
                gl.glTexEnvfv(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_COLOR, p.color2)
                ## alpha is ignored because the texture base internal format is luminance
            else:
                gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE)

            if p.t0_time_sec_absolute is None and not p.ignore_time:
                p.t0_time_sec_absolute = VisionEgg.time_func()

            w = p.size[0]
            inc = w / float(p.num_samples)
            if p.ignore_time:
                phase = p.phase_at_t0
            else:
                t_var = VisionEgg.time_func() - p.t0_time_sec_absolute
                phase = t_var * p.temporal_freq_hz * -360.0 + p.phase_at_t0
            if p.recalculate_phase_tolerance is None or abs(self._last_phase - phase) > p.recalculate_phase_tolerance:
                self._last_phase = phase  # we're re-drawing the phase at this angle
                floating_point_sin = (
                    numpy.sin(
                        2.0 * math.pi * p.spatial_freq * numpy.arange(0.0, w, inc, dtype=numpy.float)
                        + (phase / 180.0 * math.pi)
                    )
                    * 0.5
                    * p.contrast
                    + p.pedestal
                )
                floating_point_sin = numpy.clip(
                    floating_point_sin, 0.0, 1.0
                )  # allow square wave generation if contrast > 1
                texel_data = (floating_point_sin * self.max_int_val).astype(self.numpy_dtype).tostring()

                gl.glTexSubImage1D(
                    gl.GL_TEXTURE_1D,  # target
                    0,  # level
                    0,  # x offset
                    p.num_samples,  # width
                    self.format,  # format of new texel data
                    self.gl_type,  # type of new texel data
                    texel_data,
                )  # new texel data

            # in the case of only color1,
            # the texel data multiplies color1 to produce a color

            # with color2,
            # the texel data linearly interpolates between color1 and color2

            gl.glColor4f(p.color1[0], p.color1[1], p.color1[2], p.max_alpha)

            if p.mask:
                p.mask.draw_masked_quad_3d(
                    0.0, 1.0, 0.0, 1.0, p.lowerleft, p.lowerright, p.upperright, p.upperleft  # for texture coordinates
                )
            else:
                # draw unmasked quad
                gl.glBegin(gl.GL_QUADS)

                gl.glTexCoord2f(0.0, 0.0)
                gl.glVertex(*p.lowerleft)

                gl.glTexCoord2f(1.0, 0.0)
                gl.glVertex(*p.lowerright)

                gl.glTexCoord2f(1.0, 1.0)
                gl.glVertex(*p.upperright)

                gl.glTexCoord2f(0.0, 1.0)
                gl.glVertex(*p.upperleft)
                gl.glEnd()  # GL_QUADS

            gl.glDisable(gl.GL_TEXTURE_1D)
            if p.polygon_offset_enabled:
                gl.glDisable(gl.GL_POLYGON_OFFSET_EXT)
Пример #17
0
    def draw(self):
        p = self.parameters  # shorthand
        if p.on:
            # calculate center
            center = VisionEgg._get_center(p.position, p.anchor, p.size)
            if p.mask:
                gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB)
            gl.glBindTexture(gl.GL_TEXTURE_1D, self._texture_object_id)

            gl.glEnable(gl.GL_TEXTURE_1D)
            gl.glDisable(gl.GL_TEXTURE_2D)
            if p.bit_depth != self.cached_bit_depth:
                self.calculate_bit_depth_dependencies()

            # Clear the modeview matrix
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glPushMatrix()

            # Rotate about the center of the texture
            gl.glTranslate(center[0], center[1], 0)
            gl.glRotate(p.orientation, 0, 0, 1)

            if p.depth is None:
                gl.glDisable(gl.GL_DEPTH_TEST)
                depth = 0.0
            else:
                gl.glEnable(gl.GL_DEPTH_TEST)
                depth = p.depth

            # allow max_alpha value to control blending
            gl.glEnable(gl.GL_BLEND)
            gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

            if p.color2:
                gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_BLEND)
                gl.glTexEnvfv(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_COLOR, p.color2)
                ## alpha is ignored because the texture base internal format is luminance
            else:
                gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE)

            if p.t0_time_sec_absolute is None and not p.ignore_time:
                p.t0_time_sec_absolute = VisionEgg.time_func()

            w = p.size[0]
            inc = w / float(p.num_samples)
            if p.ignore_time:
                phase = p.phase_at_t0
            else:
                t_var = VisionEgg.time_func() - p.t0_time_sec_absolute
                phase = t_var * p.temporal_freq_hz * -360.0 + p.phase_at_t0
            if p.recalculate_phase_tolerance is None or abs(self._last_phase - phase) > p.recalculate_phase_tolerance:
                self._last_phase = phase  # we're re-drawing the phase at this angle
                floating_point_sin = (
                    numpy.sin(
                        2.0 * math.pi * p.spatial_freq * numpy.arange(0.0, w, inc, dtype=numpy.float)
                        + (phase / 180.0 * math.pi)
                    )
                    * 0.5
                    * p.contrast
                    + p.pedestal
                )
                floating_point_sin = numpy.clip(
                    floating_point_sin, 0.0, 1.0
                )  # allow square wave generation if contrast > 1
                texel_data = (floating_point_sin * self.max_int_val).astype(self.numpy_dtype)
                # PyOpenGL 2.0.1.09 has a bug, so use our own wrapper
                _vegl.veglTexSubImage1D(
                    gl.GL_TEXTURE_1D,  # target
                    0,  # level
                    0,  # x offset
                    p.num_samples,  # width
                    self.format,  # format of new texel data
                    self.gl_type,  # type of new texel data
                    texel_data,
                )  # new texel data
                if 0:
                    compare_array = numpy.empty(texel_data.shape, dtype=texel_data.dtype)
                    pixels = _vegl.veglGetTexImage(
                        gl.GL_TEXTURE_1D,  # target
                        0,  # level
                        self.format,  # format
                        self.gl_type,  # type
                        compare_array,
                    )
                    assert numpy.allclose(compare_array, texel_data)

            h_w = p.size[0] / 2.0
            h_h = p.size[1] / 2.0

            l = -h_w
            r = h_w
            b = -h_h
            t = h_h

            # in the case of only color1,
            # the texel data multiplies color1 to produce a color

            # with color2,
            # the texel data linearly interpolates between color1 and color2

            gl.glColor4f(p.color1[0], p.color1[1], p.color1[2], p.max_alpha)

            if p.mask:
                p.mask.draw_masked_quad(
                    0.0,
                    1.0,
                    0.0,
                    1.0,  # l,r,b,t for texture coordinates
                    l,
                    r,
                    b,
                    t,  # l,r,b,t in eye coordinates
                    depth,
                )  # also in eye coordinates
            else:
                # draw unmasked quad
                gl.glBegin(gl.GL_QUADS)

                gl.glTexCoord2f(0.0, 0.0)
                gl.glVertex3f(l, b, depth)

                gl.glTexCoord2f(1.0, 0.0)
                gl.glVertex3f(r, b, depth)

                gl.glTexCoord2f(1.0, 1.0)
                gl.glVertex3f(r, t, depth)

                gl.glTexCoord2f(0.0, 1.0)
                gl.glVertex3f(l, t, depth)
                gl.glEnd()  # GL_QUADS

            gl.glDisable(gl.GL_TEXTURE_1D)
            gl.glPopMatrix()
Пример #18
0
                           shrink_texture_ok=True,
                           internal_format=gl.GL_RGBA,
                           )

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

frame_timer = FrameTimer()
quit_now = False
spinning = True
while not quit_now and spinning:
    for event in pygame.event.get():
        if event.type == QUIT:
            quit_now = True
        elif event.type in (KEYDOWN,MOUSEBUTTONDOWN):
            spinning = False
    screen.clear()
    stimulus.parameters.angle = (VisionEgg.time_func()*-180.0)%360.0 # rotate
    viewport.draw()
    swap_buffers()
    frame_timer.tick()
while not quit_now:
    for event in pygame.event.get():
        if event.type in (QUIT,KEYDOWN,MOUSEBUTTONDOWN):
            quit_now = True
    screen.clear()
    viewport.draw()
    swap_buffers()
    frame_timer.tick()
frame_timer.log_histogram()
Пример #19
0
def go(mode, time=2):
    global x
    global escape_code 
    quit_now = False
    response = None
    other_responses = []
    rt = -1000
    frame_timer = FrameTimer()
    if mode == "isi":
        time = stimulus.isi_time
    elif mode == "ippi":
        time = stimulus.ippi_time
    elif mode == "prime":
        time = stimulus.prime_time
    elif mode == "probe":
        time = stimulus.probe_time


    if(mode == "prime"):

        x = x + 1
        print "collecting " + str(x)
        ac = Audio_collection(FORMAT, CHANNELS, RATE, SOUND_THRESHOLD, stimulus.itemNumber, True, \
                         chunk, outputdir + "audio"+ str(subjectID) +"/" + EXPERIMENT_CODE + str(subjectID)+stimulus.itemNumber+".wav", prime_time, chunk, q)
        ac.start()

    start_time = VisionEgg.time_func()
    while not quit_now:





        # Process keyboard inputs
        for event in pygame.event.get():
            if event.type == pygame.locals.QUIT:
                quit_now = True
            elif event.type == pygame.locals.KEYDOWN:
                if event.key == pygame.locals.K_BACKQUOTE :
                    quit_now = True
                    escape_code = True
                    f.close()
                    screen.close()
                    #screen2.close()
                    sys.exit()
                    
                elif event.key == response_key_1 :
                    if response==None:
                        rt = VisionEgg.time_func() - start_time
                        response = "LeftResponse"
                        if click_through_stimuli:
                            quit_now = True
                    else :
                        other_responses.append(str(event.key) + " " + str(VisionEgg.time_func() - start_time))
                elif event.key == response_key_2 :
                    if response==None:
                        rt = VisionEgg.time_func() - start_time
                        response = "RightResponse"
                        if click_through_stimuli:
                            quit_now = True
                    else :
                        other_responses.append(str(event.key) + " " + str(VisionEgg.time_func() - start_time))


                elif event.key == pygame.locals.K_BACKQUOTE:
                    quit_now =  True
                else :
                        other_responses.append(str(event.key) + " " + str(VisionEgg.time_func() - start_time))
                    #text.parameters.text+=event.unicode
        screen.clear()
        viewport.draw()
        swap_buffers()
        frame_timer.tick()
        time_since_start = VisionEgg.time_func()
        if((time_since_start - start_time > time) ):
            quit_now = True
        if (mode == "prime") and not (ac.is_alive()):
            quit_now = True


    

    if(mode=="prime"):
        ac.join()
        #while threading.activeCount() > 2: # This is sheer magic.  I'm not sure why there are two threads active at this point, so it could break at any moment.
        #    print threading.activeCount()
    
        audio_start_time = q.get()
        audio_end_time = q.get()

        if not (audio_end_time == 10000000):
            f.write("%s\t%f\t%f\t%f\t%s\t%d\t%s\t%f\t%f\t%s\n" % (stimulus.itemNumber, audio_end_time-audio_start_time, audio_start_time, \
                                                                audio_end_time, \
                                                                stimulus.pretty_name(timings=False), \
                                                                subjectID, mode, start_time, time_since_start-start_time, \
                                                                " . ".join(other_responses)))
        else:
            f.write("%s\t%f\t%f\t%f\t%s\t%d\t%s\t%f\t%f\t%s\n" % (stimulus.itemNumber, audio_end_time, audio_start_time, \
                                                                audio_end_time, \
                                                                stimulus.pretty_name(timings=False), \
                                                                subjectID, mode, start_time, time_since_start-start_time, \
                                                                " . ".join(other_responses)))

        f.flush()
Пример #20
0
                         camera_matrix=drum_camera_matrix,
                         stimuli=[drum])

##############################################################
#  Main loop (not using VisionEgg.FlowControl.Presentation)  #
##############################################################

# save time
frame_timer = VisionEgg.Core.FrameTimer()

quit_now = 0
while not quit_now:
    for event in pygame.event.get():
        if event.type in (QUIT, KEYDOWN, MOUSEBUTTONDOWN):
            quit_now = 1
    t = VisionEgg.time_func()

    # update parameters (could also be done with VisionEgg.FlowControl.Controllers)
    color_grating.parameters.pedestal = pedestal_func(t)
    drum.parameters.angular_position = angle_as_function_of_time(t)
    drum_camera_matrix.parameters.matrix = cam_matrix_f(t)

    # do drawing, etc.  (can be done with Presentation.go() method)
    screen.clear()  # clear the back buffer
    drum_viewport.draw()  # draw spinning drum
    viewport_2d.draw()  # draw 2D stimuli

    pixels = numpy.random.randint(0, 256, size=(20, 20, 3)).astype(numpy.uint8)
    screen.put_pixels(
        pixels,
        scale_x=5.0,
Пример #21
0
def getState(t):
    global ISI, next_stim_time, direction, last_direction, arrow_scale, score
    global first_loop, start_time, StimCount, stimVis, fbVis, stimText
    global score_factor, arrowColor, leftText, rightText
    global left_strings, right_strings, stimulus_strings, show_array
    global currentTime, currentShow, currentSign, currentTR

    # CC added for TCPIP and detrends
    global tcp_dist, dist_detrend, dist_array, time_array, dist
    global startDetrend, detrendLag
    global ALPHA_MAX, ALPHA_SCALE
    global lumina_dev

    currentTime = t

    if (first_loop == 1) and (p.parameters.trigger_go_if_armed):
        first_loop = 0
        start_time = VisionEgg.time_func()
        if TCPIP:
            tcp_listener.buffer = ""  # reset buffer

    if t > next_stim_time:
        StimCount = StimCount + 1
        currentShow = int(np.abs(show_array[StimCount]))
        currentSign = int(np.sign(show_array[StimCount]))
        stimText = stimulus_strings[StimCount]
        leftText = left_strings[StimCount]
        rightText = right_strings[StimCount]

        next_stim_time = next_stim_time + ISI

        if StimCount > detrendLag:
            startDetrend = True


####    # note: When run with SVR testing, the input values
####    #       will range from (-inf,inf), most likely (-5,5)
    if TCPIP:
        tcp_buffer = str(tcp_listener.buffer)
        #print "%s (%s)" %('tcp_data', tcp_buffer)
        tcp_data = tcp_buffer.replace('\000', '')
        # remove null byte
        #print "%s (%s) (%s)" %('tcp_data', tcp_data, tcp_buffer)

        if tcp_data != '\000' and tcp_data != "" and \
            "nan" not in tcp_data.lower():

            vals = tcp_data.split(",")
            if len(vals) > 1:
                tcp_dist = float(vals[1])
            else:
                tcp_dist = float(tcp_data)

            tcp_listener.buffer = ""  # reset buffer
            dist_array = dist_array + [tcp_dist]
            time_array = time_array + [t]
            if DETREND == 1:
                if startDetrend:
                    dist_detrend = detrendDist(time_array, dist_array)
                else:
                    dist_detrend = tcp_dist
                arrow_scale = dist_detrend
            else:
                arrow_scale = tcp_dist

            if currentShow == 9999 or FEEDBACK == 0:
                fbVis = 0
                score = 90.0
                arrowColor = 0
            else:
                fbVis = 1
                arrowColor = 1
                # increment the score
                score = score - currentSign * arrow_scale * score_factor
                if score < 0:
                    score = 0
                elif score > 180:
                    score = 180

            log.write("%5.3f; STIM; %s; %s; %s; %d; %d; %5.3f; %5.3f; %5.3f\n" \
                %(t, leftText, rightText, stimText, currentShow, \
                  currentSign, tcp_dist, arrow_scale, score))

    # handle anything that comes in on the button boxes
    #print "About to test LUMINA",
    #print lumina_dev
    if LUMINA == 1:
        lumina_dev.poll_for_response()
        while lumina_dev.response_queue_size() > 0:
            response = lumina_dev.get_next_response()
            if response["pressed"]:
                print "Lumina received: %s, %d" % (response["key"],
                                                   response["key"])
                if response["key"] == 4:
                    log.write("%5.3f; TR; %s\n" % (currentTime, currentTR))
                    currentTR = currentTR + 1
                else:
                    log.write("%5.3f; LUMINA; %d\n" %
                              (currentTime, response["key"]))

    #print "TESTED LUMINA"
    return 1
Пример #22
0
	def run(self, ID = 0):
		self.ID = ID
		super(DetectTrial, self).run()
		sound_played = False
		while not self.stopped:
			self.run_time = VisionEgg.time_func() - self.start_time
			if self.phase == 0:
				self.prestimulation_time = VisionEgg.time_func()
				# this trial phase is ended with a space press on the first trial of a run, but timed on all other trials of a run.
				self.start_time = VisionEgg.time_func()
			elif self.phase == 1:	# first delay
				self.delay_1_time = VisionEgg.time_func()
				# this trial phase is timed
				if ( self.delay_1_time - self.prestimulation_time ) > self.phase_durations[1] - 0.1 and sound_played == False:
					self.session.play_sound( sound_index = 1 )
					sound_played = True
				if ( self.delay_1_time - self.prestimulation_time ) > self.phase_durations[1]:
					self.phase_forward()
			elif self.phase == 2:	# stimulus presentation
				# this trial phase is timed
				self.test_time = VisionEgg.time_func()
				if ( self.test_time  - self.delay_1_time ) > self.phase_durations[2]:
					self.phase_forward()
			elif self.phase == 3:	# second delay
				# this trial phase is timed
				self.delay_2_time = VisionEgg.time_func()
				if ( self.delay_2_time  - self.test_time ) > self.phase_durations[3]:
					self.phase_forward()
			elif self.phase == 4:	# confidence
				self.confidence_time = VisionEgg.time_func()
			elif self.phase == 5:	# third delay
				self.delay_3_time = VisionEgg.time_func()
				if ( self.delay_3_time  - self.confidence_time ) > self.phase_durations[5]:
					self.feedback_given = False
					self.phase_forward()
			elif self.phase == 6:	# feedback
				self.feedback_time = VisionEgg.time_func()
				if self.feedback_given == False and ( self.feedback_time  - self.delay_3_time ) > 0.1:
					if self.version == 1:
						if self.parameters['correct'] == 1:
							self.session.play_sound( sound_index = 2 )
						elif self.parameters['correct'] == 0:
							self.session.play_sound( sound_index = 0 )
					if self.version == 2:
						if self.parameters['correct'] == 1:
							self.session.play_sound( sound_index = 0 )
						elif self.parameters['correct'] == 0:
							self.session.play_sound( sound_index = 2 )
					elif self.parameters['correct'] == -1:
						self.session.play_sound( sound_index = 3 )
					self.feedback_given = True
				if ( self.feedback_time  - self.delay_3_time ) > self.phase_durations[6]:
					self.phase_forward()
			elif self.phase == 7:	# fourth delay
				self.delay_4_time = VisionEgg.time_func()
				if ( self.delay_4_time  - self.feedback_time ) > self.phase_durations[7]:
					self.stopped = True

			# events and draw
			self.event()
			self.draw()

		# we have stopped. 
		self.stop()
Пример #23
0
    shrink_texture_ok=True,
    internal_format=gl.GL_RGBA,
)

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

frame_timer = FrameTimer()
quit_now = False
spinning = True
while not quit_now and spinning:
    for event in pygame.event.get():
        if event.type == QUIT:
            quit_now = True
        elif event.type in (KEYDOWN, MOUSEBUTTONDOWN):
            spinning = False
    screen.clear()
    stimulus.parameters.angle = (VisionEgg.time_func() *
                                 -180.0) % 360.0  # rotate
    viewport.draw()
    swap_buffers()
    frame_timer.tick()
while not quit_now:
    for event in pygame.event.get():
        if event.type in (QUIT, KEYDOWN, MOUSEBUTTONDOWN):
            quit_now = True
    screen.clear()
    viewport.draw()
    swap_buffers()
    frame_timer.tick()
frame_timer.log_histogram()
Пример #24
0
    def draw(self):
        # XXX This method is not speed-optimized. I just wrote it to
        # get the job done. (Nonetheless, it seems faster than the C
        # version commented out above.)

        p = self.parameters # shorthand
        if p.center is not None:
            if not hasattr(VisionEgg.config,"_GAVE_CENTER_DEPRECATION"):
                logger = logging.getLogger('VisionEgg.Dots')
                logger.warning("Specifying DotArea2D by deprecated "
                               "'center' parameter deprecated.  Use "
                               "'position' parameter instead.  (Allows "
                               "use of 'anchor' parameter to set to "
                               "other values.)")
                VisionEgg.config._GAVE_CENTER_DEPRECATION = 1
            p.anchor = 'center'
            p.position = p.center[0], p.center[1] # copy values (don't copy ref to tuple)
        if p.on:
            # calculate center
            center = VisionEgg._get_center(p.position,p.anchor,p.size)

            if p.anti_aliasing:
                if len(p.color) == 4 and not self._gave_alpha_warning:
                    if p.color[3] != 1.0:
                        logger = logging.getLogger('VisionEgg.Dots')
                        logger.warning("The parameter anti_aliasing is "
                                       "set to true in the DotArea2D "
                                       "stimulus class, but the color "
                                       "parameter specifies an alpha "
                                       "value other than 1.0.  To "
                                       "acheive the best anti-aliasing, "
                                       "ensure that the alpha value for "
                                       "the color parameter is 1.0.")
                        self._gave_alpha_warning = 1
                gl.glEnable( gl.GL_POINT_SMOOTH )
                # allow max_alpha value to control blending
                gl.glEnable( gl.GL_BLEND )
                gl.glBlendFunc( gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA )
            else:
                gl.glDisable( gl.GL_BLEND )

            now_sec = VisionEgg.time_func()
            if self.start_times_sec is not None:
                # compute extinct dots and generate new positions
                replace_indices = Numeric.nonzero( Numeric.greater( now_sec - self.start_times_sec, p.dot_lifespan_sec) )
                Numeric.put( self.start_times_sec, replace_indices, now_sec )

                new_x_positions = RandomArray.uniform(0.0,1.0,
                                                      (len(replace_indices),))
                Numeric.put( self.x_positions, replace_indices, new_x_positions )

                new_y_positions = RandomArray.uniform(0.0,1.0,
                                                      (len(replace_indices),))
                Numeric.put( self.y_positions, replace_indices, new_y_positions )

                new_random_directions_radians = RandomArray.uniform(0.0,2*math.pi,
                                                                    (len(replace_indices),))
                Numeric.put( self.random_directions_radians, replace_indices, new_random_directions_radians )
            else:
                # initialize dot extinction values to random (uniform) distribution
                self.start_times_sec = RandomArray.uniform( now_sec - p.dot_lifespan_sec, now_sec,
                                                            (self.constant_parameters.num_dots,))

            signal_num_dots = int(round(p.signal_fraction * self.constant_parameters.num_dots))
            time_delta_sec = now_sec - self.last_time_sec
            self.last_time_sec = now_sec # reset for next loop
            x_increment_normalized =  math.cos(p.signal_direction_deg/180.0*math.pi) * p.velocity_pixels_per_sec / p.size[0] * time_delta_sec
            y_increment_normalized = -math.sin(p.signal_direction_deg/180.0*math.pi) * p.velocity_pixels_per_sec / p.size[1] * time_delta_sec
            self.x_positions[:signal_num_dots] += x_increment_normalized
            self.y_positions[:signal_num_dots] += y_increment_normalized

            num_random_dots = self.constant_parameters.num_dots - signal_num_dots
            random_x_increment_normalized =  Numeric.cos(self.random_directions_radians[signal_num_dots:]) * p.velocity_pixels_per_sec / p.size[0] * time_delta_sec
            random_y_increment_normalized = -Numeric.sin(self.random_directions_radians[signal_num_dots:]) * p.velocity_pixels_per_sec / p.size[1] * time_delta_sec
            self.x_positions[signal_num_dots:] += random_x_increment_normalized
            self.y_positions[signal_num_dots:] += random_y_increment_normalized

            self.x_positions = Numeric.fmod( self.x_positions, 1.0 ) # wrap
            self.y_positions = Numeric.fmod( self.y_positions, 1.0 )

            self.x_positions = Numeric.fmod( self.x_positions+1, 1.0 ) # wrap again for values < 1
            self.y_positions = Numeric.fmod( self.y_positions+1, 1.0 )

            xs = (self.x_positions - 0.5) * p.size[0] + center[0]
            ys = (self.y_positions - 0.5) * p.size[1] + center[1]

            if len(p.color)==3:
                gl.glColor3f(*p.color)
            elif len(p.color)==4:
                gl.glColor4f(*p.color)
            gl.glPointSize(p.dot_size)

            # Clear the modeview matrix
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glPushMatrix()

            gl.glDisable(gl.GL_TEXTURE_2D)

            if p.depth is None:
                depth = 0.0
            else:
                gl.glEnable(gl.GL_DEPTH_TEST)
                depth = p.depth
            zs = (depth,)*len(xs) # make N tuple with repeat value of depth
            draw_dots(xs,ys,zs)
            if p.anti_aliasing:
                gl.glDisable( gl.GL_POINT_SMOOTH ) # turn off
            gl.glPopMatrix()
Пример #25
0
    def draw(self):
        p = self.parameters # shorthand
        if p.on:
            if p.mask:
                gl.glActiveTextureARB(gl.GL_TEXTURE0_ARB)
            if p.depth_test:
                gl.glEnable(gl.GL_DEPTH_TEST)
            else:
                gl.glDisable(gl.GL_DEPTH_TEST)
            if p.polygon_offset_enabled:
                gl.glEnable(gl.GL_POLYGON_OFFSET_EXT)
                gl.glPolygonOffset(p.polygon_offset_factor, p.polygon_offset_units)
            gl.glBindTexture(gl.GL_TEXTURE_1D,self._texture_object_id)
            gl.glEnable(gl.GL_TEXTURE_1D)
            gl.glDisable(gl.GL_TEXTURE_2D)
            if p.bit_depth != self.cached_bit_depth:
                self.calculate_bit_depth_dependencies()

            # allow max_alpha value to control blending
            gl.glEnable( gl.GL_BLEND )
            gl.glBlendFunc( gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA )

            if p.color2:
                gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_BLEND)
                gl.glTexEnvfv(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_COLOR, p.color2)
                ## alpha is ignored because the texture base internal format is luminance
            else:
                gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE)

            if p.t0_time_sec_absolute is None and not p.ignore_time:
                p.t0_time_sec_absolute = VisionEgg.time_func()

            w = p.size[0]
            inc = w/float(p.num_samples)
            if p.ignore_time:
                phase = p.phase_at_t0
            else:
                t_var = VisionEgg.time_func() - p.t0_time_sec_absolute
                phase = t_var*p.temporal_freq_hz*-360.0 + p.phase_at_t0
            if p.recalculate_phase_tolerance is None or abs(self._last_phase - phase) > p.recalculate_phase_tolerance:
                self._last_phase = phase # we're re-drawing the phase at this angle
                floating_point_sin = numpy.sin(2.0*math.pi*p.spatial_freq*numpy.arange(0.0,w,inc,dtype=numpy.float)+(phase/180.0*math.pi))*0.5*p.contrast+p.pedestal
                floating_point_sin = numpy.clip(floating_point_sin,0.0,1.0) # allow square wave generation if contrast > 1
                texel_data = (floating_point_sin*self.max_int_val).astype(self.numpy_dtype).tostring()

                gl.glTexSubImage1D(gl.GL_TEXTURE_1D, # target
                                   0,                # level
                                   0,                # x offset
                                   p.num_samples,    # width
                                   self.format,      # format of new texel data
                                   self.gl_type,     # type of new texel data
                                   texel_data)       # new texel data

            # in the case of only color1,
            # the texel data multiplies color1 to produce a color

            # with color2,
            # the texel data linearly interpolates between color1 and color2

            gl.glColor4f(p.color1[0],p.color1[1],p.color1[2],p.max_alpha)

            if p.mask:
                p.mask.draw_masked_quad_3d(0.0,1.0,0.0,1.0, # for texture coordinates
                                           p.lowerleft,p.lowerright,p.upperright,p.upperleft)
            else:
                # draw unmasked quad
                gl.glBegin(gl.GL_QUADS)

                gl.glTexCoord2f(0.0,0.0)
                gl.glVertex(*p.lowerleft)

                gl.glTexCoord2f(1.0,0.0)
                gl.glVertex(*p.lowerright)

                gl.glTexCoord2f(1.0,1.0)
                gl.glVertex(*p.upperright)

                gl.glTexCoord2f(0.0,1.0)
                gl.glVertex(*p.upperleft)
                gl.glEnd() # GL_QUADS

            gl.glDisable(gl.GL_TEXTURE_1D)
            if p.polygon_offset_enabled:
                gl.glDisable(gl.GL_POLYGON_OFFSET_EXT)
	def event(self):
		for event in pygame.event.get():
			if event.type == KEYDOWN:
				if event.key == pygame.locals.K_ESCAPE:
					self.events.append([-99,VisionEgg.time_func()-self.start_time])
					self.parameters.update({'correct': 0})
					self.stopped = True
					self.session.stopped = True
				# it handles both numeric and lettering modes 
				elif event.key == pygame.locals.K_SPACE:
					self.events.append([0,VisionEgg.time_func()-self.start_time])
					if self.ID == 0 and self.phase == 0:
						self.phase_forward()
				
				
				elif event.key == pygame.locals.K_LEFT:
					self.events.append([1,VisionEgg.time_func()-self.start_time])
					self.parameters.update({'answer':1})
					if self.parameters['which_signal_test'] == 0:
						self.parameters.update({'correct': 1})
					else:
						self.parameters.update({'correct': 0})
					if self.phase == 6:
						# if self.session.index_number == 0:
							# feedback when we're practicing
						# self.feedback(self.parameters['answer'], self.parameters['which_signal_test'])
						if self.version == 1:
							if self.parameters['correct'] == 0:
								self.session.play_sound( sound_index = 0 )
							else:
								self.session.play_sound( sound_index = 2 )
						if self.version == 2:
							if self.parameters['correct'] == 0:
								self.session.play_sound( sound_index = 2 )
							else:
								self.session.play_sound( sound_index = 0 )
						self.stopped = True
						# else:
							# self.phase_forward()
				elif event.key == pygame.locals.K_RIGHT:
					self.events.append([-1,VisionEgg.time_func()-self.start_time])
					self.parameters.update({'answer':-1})
					if self.parameters['which_signal_test'] == 1:
						self.parameters.update({'correct': 1})
					else:
						self.parameters.update({'correct': 0})
					if self.phase == 6:
						# if self.session.index_number == 0:
							# feedback when we're practicing
						# self.feedback(self.parameters['answer'], self.parameters['which_signal_test'])
						if self.version == 1:
							if self.parameters['correct'] == 0:
								self.session.play_sound( sound_index = 0 )
							else:
								self.session.play_sound( sound_index = 2 )
						if self.version == 2:
							if self.parameters['correct'] == 0:
								self.session.play_sound( sound_index = 2 )
							else:
								self.session.play_sound( sound_index = 0 )
						self.stopped = True
						# else:
							# self.phase_forward()
				# elif event.key == pygame.locals.K_a:
				# 					if self.phase == 7:
				# 						self.parameters.update({'confidence':0})
				# 						self.stopped = True
				# 				elif event.key == pygame.locals.K_s:
				# 					if self.phase == 7:
				# 						self.parameters.update({'confidence':1})
				# 						self.stopped = True
				# 				elif event.key == pygame.locals.K_d:
				# 					if self.phase == 7:
				# 						self.parameters.update({'confidence':2})
				# 						self.stopped = True
				# 				elif event.key == pygame.locals.K_f:
				# 					if self.phase == 7:
				# 						self.parameters.update({'confidence':3})
				# 						self.stopped = True
				# 				elif event.key == pygame.locals.K_g:
				# 					if self.phase == 7:
				# 						self.parameters.update({'confidence':4})
				# 						self.stopped = True
			
			super(DetectTrial, self).key_event( event )