本文整理汇总了Python中VisionEgg类的典型用法代码示例。如果您正苦于以下问题:Python VisionEgg类的具体用法?Python VisionEgg怎么用?Python VisionEgg使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了VisionEgg类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main():
"""Launch VisionEgg and demo the WrappedText object"""
import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()
import VisionEgg.FlowControl
screen = VisionEgg.Core.get_default_screen()
message="""Hello.
This is a demonstration of the WrappedText object, which was created to allow users of VisionEgg to include large blocks of text in their programs. While this stimulus has many limitations, it should be useful for presenting on-screen instructions in experiments.
While you are welcome to modify this file to extend its functionality, I hope you consider sharing any such modifications with the VisionEgg community.
Eamon Caddigan,\nUniversity of Illinois\n15 November 2007"""
wt = WrappedText(text=message, position=(50,screen.size[1]-50),
size=(screen.size[0]-100, screen.size[1]-100))
viewport = VisionEgg.Core.Viewport(screen=screen, stimuli=[wt])
# Frame-based presentation duration makes it easier to use pdb
p = VisionEgg.FlowControl.Presentation(viewports=[viewport],
go_duration=(VisionEgg.config.VISIONEGG_MONITOR_REFRESH_HZ*30,'frames'))
p.go()
screen.close() # Called explicitly to behave better in interactive shells
示例2: run
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()
示例3: _draw
def _draw(self):
p = self.parameters
side = p.side
height = side * numpy.sqrt(3) / 2.
center = VisionEgg._get_center(p.position, p.anchor, (side, height))
position = numpy.array(center)
hh = height / 2
ll = position - (hh, hh)
lr = position - (-hh, hh)
u = position + (0., hh)
gl.glDisable(gl.GL_DEPTH_TEST)
gl.glDisable(gl.GL_TEXTURE_2D)
gl.glDisable(gl.GL_BLEND)
gl.glColor(p.color)
gl.glBegin(gl.GL_TRIANGLES)
self._draw_vertices(ll, lr, u)
gl.glEnd()
gl.glColor(p.color_edge)
if p.anti_aliasing:
gl.glEnable(gl.GL_LINE_SMOOTH)
gl.glLineWidth(p.width)
gl.glBegin(gl.GL_LINE_STRIP)
self._draw_vertices(ll, lr, u, ll)
gl.glEnd()
gl.glDisable(gl.GL_LINE_SMOOTH)
示例4: run
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()
示例5: __init__
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
示例6: __init__
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"""
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)) # this opens up a pygame window
WIDTH, HEIGHT = screen.get_size()
pygame.quit() # close this pygame window, or else it interferes w/ VE
VisionEgg.config.VISIONEGG_SCREEN_W = WIDTH
VisionEgg.config.VISIONEGG_SCREEN_H = HEIGHT
self.screen = get_default_screen()
self.keys = []
self.presses = []
self.releases = []
示例7: run
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()
示例8: __init__
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 = []
示例9: go
def go(self,duration=None,prestim=None,poststim=None,RSTART=False):
# pre stimulation go
if prestim is not None:
if RSTART:
remote_start_controller = RemoteStartController()
self.add_controller(None,None,remote_start_controller)
self.parameters.go_duration = (prestim, 'seconds')
super(FrameSweep, self).go()
if RSTART:
self.remove_controller(None,None,remote_start_controller)
# stimulation go
if duration is not None:
self.parameters.go_duration = duration
else:
self.parameters.go_duration = ('forever','')
self.add_controllers()
# use VisionEgg timing function which handles platform specific problems
sweep_begin = VisionEgg.true_time_func()
super(FrameSweep, self).go()
sweep_end = VisionEgg.true_time_func()
sweep_duration = sweep_end - sweep_begin
# remove all stimuli so that post presentation will show nothing.
self.remove_stimuli()
# the RemoveViewportController should be moved, otherwise post go will quit directly.
self.remove_controller(None,None,None)
# post stimulation go
if poststim is not None:
if RSTART:
self.add_controller(None,None,RemoteStopController())
self.parameters.go_duration = (poststim, 'seconds')
super(FrameSweep, self).go()
if self.interrupted:
self.logger.warning('Stimulation was interrupted before completion.')
else:
self.logger.info('Stimulation completes successfully.')
self.logger.info('Actual stimulus duration: %s' %str(TimeFormat(sweep_duration)))
示例10: event
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
示例11: draw
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()
示例12: __init__
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
示例13: black
#!/usr/bin/env python
"""Draw dots and save movie using your own event loop.
This bypasses the VisionEgg.FlowControl.Presentation class. It may be easier
to create simple scripts this way."""
import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()
from VisionEgg.Core import *
import pygame
from pygame.locals import *
from VisionEgg.Text import *
from VisionEgg.Dots import *
screen = get_default_screen()
screen.parameters.bgcolor = (0.0,0.0,0.0,0.0) # black (RGBA)
dots = DotArea2D( position = ( screen.size[0]/2.0, screen.size[1]/2.0 ),
size = ( 300.0 , 300.0 ),
signal_fraction = 0.1,
signal_direction_deg = 180.0,
velocity_pixels_per_sec = 10.0,
dot_lifespan_sec = 5.0,
dot_size = 3.0,
num_dots = 100)
text = Text( text = "Vision Egg makeMovie2 demo.",
position = (screen.size[0]/2,2),
anchor = 'bottom',
示例14: draw
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)
示例15: getState
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