def setup(self): self.win = Window((128, 128), pos=(50, 50), monitor="testMonitor", allowGUI=False, autoLog=False) self.error = _BaseErrorHandler() self.textbox = TextBox2( self.win, "A PsychoPy zealot knows a smidge of wx, but JavaScript is the question.", "Noto Sans", alignment="top left", lineSpacing=1, pos=(0, 0), size=(1, 1), units='height', letterHeight=0.1, colorSpace="rgb") self.obj = self.textbox # point to textbox for mixin tests # Pixel which is the border color self.borderPoint = (0, 0) self.borderUsed = True # Pixel which is the fill color self.fillPoint = (2, 2) self.fillUsed = True # Textbox foreground is too unreliable due to fonts for pixel analysis self.foreUsed = False
def play_sound(self, window: visual.Window): """ Uniformly choses a frequency to play according to the number of repetitions for each one and plays it. :param window: :return: """ total_repetitions = sum(self._repetitions) if total_repetitions == 0: self._repetitions = self._original_reps total_repetitions = sum(self._repetitions) probs = [float(rep) / total_repetitions for rep in self._repetitions] sound_index = np.random.choice(range(len(self._freqs)), p=probs) window.flip() new_sound = sound.Sound(self._freqs[sound_index], secs=self._duration) data_logger.record_data( ['Play sound', main_clock.getTime()], ParallelData.SOUND_START) new_sound.play() data_logger.record_data( ['Sound end', main_clock.getTime()], ParallelData.SOUND_START) window.flip() self._repetitions[sound_index] -= 1
def __init__(self, logfile, imgDir, screenType, trialDuration, ISI, trialsPer, selfPaced, practiceTrials, inputButtons, pauseButton): self.logfile = logfile self.trialDuration = trialDuration self.selfPaced = selfPaced self.ISI = ISI self.trialsPer = trialsPer self.numTrials = (self.trialsPer * 4) #Trials/phase = 4x trials/cond self.imgDir = imgDir self.imgIdx = 0 self.runPracticeTrials = practiceTrials self.leftButton = inputButtons[0] self.rightButton = inputButtons[1] self.pauseButton = pauseButton if (screenType == 'Windowed'): screenSelect = False elif (screenType == 'Fullscreen'): screenSelect = True self.window = Window(fullscr=screenSelect, units='pix', color='White', allowGUI=False) self.imageWidth = self.window.size[1] / 6 #Window must be set up before imgs, as img position based on window size self.imageList = self.SegmentImages() self.clock = Clock() #Initialize scorelist for 4 categories;; [correct,inc,resp] self.scoreList = [] for i in range(0, 4): self.scoreList.append([0, 0, 0])
def __init__(self, port=ImageServer.default_port, start_server=True, *args, **kwargs): self.logger = logging.getLogger(self.__class__.__name__) self.rect = None # selected rectangular region to serve (default: entire image) self.server = ImageServer(port=port, start_server=start_server) # RPC-exports self, can start a server thread (what about other args to ImageServer?) if self.gui and not kwargs.get('fullscr', True): # NOTE can't rely on self.is_Fullscr Window.__init__() hasn't been called yet cv2.namedWindow(self.imageWinName) # try to open this before the pyglet window so that it doesn't steal focus cv2.waitKey(1) Window.__init__(self, *args, **kwargs) # NOTE this likely calls flip a few times to calibrate, so we need everything to be initialized beforehand
def setup_class(self): self.win = Window(monitor='LightCrafter4500', screen=2, fullscr=True, color='gray', useFBO=True) self.win.setRecordFrameIntervals() self.packer = ProjectorFramePacker(self.win)
def test_StaticPeriod_recordFrameIntervals(): win = Window(autoLog=False) static = StaticPeriod(screenHz=60, win=win) static.start(.002) assert win.recordFrameIntervals is False static.complete() assert static._winWasRecordingIntervals == win.recordFrameIntervals win.close()
def _create_window(self): """ Creates a window based on the settings and calculates framerate. """ win = Window(monitor=self.monitor.name, **self.settings['window']) win.flip(clearBuffer=True) self.actual_framerate = win.getActualFrameRate() t_per_frame = 1. / self.actual_framerate logging.warn(f"Actual framerate: {self.actual_framerate:.5f} " f"(1 frame = {t_per_frame:.5f})") return win
def fixate(window: visual.Window, text: str = None): visual.TextStim( win=window, text=text, pos=[0, 5], ).draw() visual.GratingStim(win=window, size=0.2, sf=0).draw() window.flip() event.waitKeys(keyList="space", maxWait=5)
def setup_class(self): self.win = Window([128, 128], pos=[50, 50], allowGUI=False, autoLog=False) self.winpix = Window([128, 128], pos=[50, 50], allowGUI=False, units='pix', autoLog=False) self.r = RatingScale(self.win, autoLog=False)
def _create_window(self): """ Creates a window based on the settings and calculates framerate. """ win = Window(monitor=self.monitor.name, **self.settings['window']) win.flip(clearBuffer=True) self.actual_framerate = win.getActualFrameRate() if self.actual_framerate is None: logging.warn("framerate not measured, substituting 60 by default") self.actual_framerate = 60.0 t_per_frame = 1. / self.actual_framerate logging.warn(f"Actual framerate: {self.actual_framerate:.5f} " f"(1 frame = {t_per_frame:.5f})") return win
def __init__(self, logfile, imgDir, screenType, expVariant, trialDuration, ISI, trialsPer, selfPaced, practiceTrials, inputButtons, pauseButton): self.logfile = logfile self.expVariant = expVariant self.trialDuration = trialDuration self.selfPaced = selfPaced self.ISI = ISI self.trialsPer = trialsPer self.imgDir = imgDir self.leftOvers = [] self.splitLures = self.SplitLures() self.splitSingles = self.SplitSingles() self.runPracticeTrials = practiceTrials self.leftButton = inputButtons[0] self.rightButton = inputButtons[1] self.pauseButton = pauseButton if (screenType == 'Windowed'): screenSelect = False elif (screenType == 'Fullscreen'): screenSelect = True self.window = Window(fullscr=screenSelect, units='pix', color='White', allowGUI=False) self.imageWidth = self.window.size[1] / 3 #Define the black box that appears in the lower left, to signal EEG rW = 110 #Width rH = 60 #Height rectVertices = [[rW, -rH], [-rW, -rH], [-rW, rH], [rW, rH]] rectCenter = [(-self.window.size[0] / 2 + rW), (-self.window.size[1] / 2) + rH] self.blackBox = ShapeStim(self.window, fillColor='black', units='pix', fillColorSpace='rgb', vertices=rectVertices, closeShape=True, interpolate=True, pos=rectCenter) self.rangeITI = numpy.arange(1, 1.4, .001) self.clock = Clock() #Initialize scorelist for 4 categories|| [correct,incorrect,response] self.scoreList = [] for i in range(0, 4): self.scoreList.append([0, 0, 0])
def main(): groups = create_stim_sequence(BLOCK1, BLOCK2, BLOCK3, TRIALREPEATS) print groups disp = Window(size=SIZE, monitor=MON, units='deg', color=BACKCOL, screen=1, fullscr=True) mouse = Mouse() fixmark = Circle(disp, radius=0.05, edges=32, pos=CENTER, lineColor=FIXCOL) images = [] for item in CIRCLES.keys(): image = ImageStim(disp, image=CIRCLES[item][1], pos=CIRCLES[item][0], size=CIRCLES[item][3]) images.append(image) fixmark.draw() draw_group(images) disp.flip() while True: button = mouse.getPressed() if button[0]: break for item in groups: flashes = [] for i in item: flash = ImageStim(disp, image=CIRCLES[i][2], pos=CIRCLES[i][0], size=CIRCLES[i][3]) flashes.append(flash) fixmark.draw() draw_group(images) draw_group(flashes) disp.flip() wait(FLASH) fixmark.draw() draw_group(images) wait(PAUSE) disp.flip() disp.close()
def testStaticPeriod(): static = StaticPeriod() static.start(0.1) wait(0.05) assert static.complete() == 1 static.start(0.1) wait(0.11) assert static.complete() == 0 win = Window(autoLog=False) static = StaticPeriod(screenHz=60, win=win) static.start(.002) assert win.recordFrameIntervals == False static.complete() assert static._winWasRecordingIntervals == win.recordFrameIntervals win.close() # Test if screenHz parameter is respected, i.e., if after completion of the # StaticPeriod, 1/screenHz seconds are still remaining, so the period will # complete after the next flip. refresh_rate = 100.0 period_duration = 0.1 timer = CountdownTimer() win = Window(autoLog=False) static = StaticPeriod(screenHz=refresh_rate, win=win) static.start(period_duration) timer.reset(period_duration) static.complete() assert np.allclose(timer.getTime(), 1.0 / refresh_rate, atol=0.001) win.close()
def setup_class(self): self.win = Window([128, 128], pos=[50, 50], allowGUI=False, autoLog=False) self.error = _BaseErrorHandler() self.textbox = TextBox2(self.win, "", "Noto Sans", pos=(0, 0), size=(1, 1), units='height', letterHeight=0.1, colorSpace="rgb")
class Test_class_WindowWarp: def setup_class(self): self.win = Window(monitor='testMonitor', screen=1, fullscr=True, color='gray', useFBO = True) self.warper = Warper (self.win, warp='spherical', warpfile = "", warpGridsize = 128, eyepoint = [0.5, 0.5], flipHorizontal = False, flipVertical = False) self.warper.dist_cm=15 self.g = ProjectionsLinesAndCircles(self.win, self.warper) def teardown_class(self): self.win.close() def draw_projection (self, frames=120): self.g.updateInfo() for i in range(frames): self.g.update_sweep() def test_spherical(self): self.warper.changeProjection('spherical') self.draw_projection() def test_cylindrical(self): self.warper.changeProjection('cylindrical') self.draw_projection() def test_warpfile(self): self.warper.changeProjection('warpfile', warpfile="") #jayb todo self.draw_projection() def test_distance(self): self.test_spherical() for i in range (1, 50, 2): self.warper.dist_cm = i self.warper.changeProjection(self.warper.warp) self.g.updateInfo() self.g.update_sweep() self.test_cylindrical() for i in range (1, 50, 2): self.warper.dist_cm = i self.warper.changeProjection(self.warper.warp) self.g.updateInfo() self.g.update_sweep() def test_flipHorizontal(self): self.warper.changeProjection(self.warper.warp, self.warper.warpfile, flipHorizontal = not self.warper.flipHorizontal) self.draw_projection() def test_flipVertical(self): self.warper.changeProjection(self.warper.warp, self.warper.warpfile, flipVertical = not self.warper.flipVertical) self.draw_projection()
class Test_class_WindowWarp: def setup_class(self): self.win = Window(monitor='testMonitor', screen=1, fullscr=True, color='gray', useFBO = True, autoLog=False) self.warper = Warper (self.win, warp='spherical', warpfile = "", warpGridsize = 128, eyepoint = [0.5, 0.5], flipHorizontal = False, flipVertical = False) self.warper.dist_cm=15 self.g = ProjectionsLinesAndCircles(self.win, self.warper) def teardown_class(self): self.win.close() def draw_projection (self, frames=120): self.g.updateInfo() for i in range(frames): self.g.update_sweep() def test_spherical(self): self.warper.changeProjection('spherical') self.draw_projection() def test_cylindrical(self): self.warper.changeProjection('cylindrical') self.draw_projection() def test_warpfile(self): self.warper.changeProjection('warpfile', warpfile="") #jayb todo self.draw_projection() def test_distance(self): self.test_spherical() for i in range (1, 50, 2): self.warper.dist_cm = i self.warper.changeProjection(self.warper.warp) self.g.updateInfo() self.g.update_sweep() self.test_cylindrical() for i in range (1, 50, 2): self.warper.dist_cm = i self.warper.changeProjection(self.warper.warp) self.g.updateInfo() self.g.update_sweep() def test_flipHorizontal(self): self.warper.changeProjection(self.warper.warp, self.warper.warpfile, flipHorizontal = not self.warper.flipHorizontal) self.draw_projection() def test_flipVertical(self): self.warper.changeProjection(self.warper.warp, self.warper.warpfile, flipVertical = not self.warper.flipVertical) self.draw_projection()
def __init__(self,iohub_display,res=None,color=[128,128,128], colorSpace='rgb255', winType='pyglet',gamma=1.0,fullscr=True,allowGUI=False, waitBlanking=True): if res == None: res=iohub_display.getPixelResolution() Window.__init__(self,res,monitor=iohub_display.getPsychopyMonitorName(), units=iohub_display.getCoordinateType(), color=color, colorSpace=colorSpace, fullscr=fullscr, allowGUI=allowGUI, screen=iohub_display.getIndex(), waitBlanking=waitBlanking, winType=winType, gamma=gamma )
def setup_class(self): self.win = Window(monitor='testMonitor', screen=1, fullscr=True, color='gray', useFBO=True) self.warper = Warper(self.win, warp='spherical', warpfile="", warpGridsize=128, eyepoint=[0.5, 0.5], flipHorizontal=False, flipVertical=False) self.warper.dist_cm = 15 self.g = ProjectionsLinesAndCircles(self.win, self.warper)
class Test_textbox(object): def setup_class(self): self.win = Window([128, 128], pos=[50, 50], allowGUI=False, autoLog=False) def teardown_class(self): self.win.close() def test_basic(self): pass def test_something(self): # to-do: test visual display, char position, etc pass
def setup_class(self): self.win = Window([128, 128], winType='pygame', pos=[50, 50], autoLog=False) assert pygame.display.get_init() == 1 assert event.havePygame
def __init__(self, dispsize=settings.DISPSIZE, fgc=settings.FGC, bgc=settings.BGC, screennr=settings.SCREENNR, monitor = None, screen=None, **args): # See _display.basedisplay.BaseDisplay for documentation # try to import copy docstring (but ignore it if it fails, as we do # not need it for actual functioning of the code) try: copy_docstr(BaseDisplay, PsychoPyDisplay) except: # we're not even going to show a warning, since the copied # docstring is useful for code editors; these load the docs # in a non-verbose manner, so warning messages would be lost pass self.dispsize = dispsize self.fgc = fgc self.bgc = bgc self.screennr = screennr self.mousevis = False self.monitor = monitor # create window pygaze.expdisplay = Window(size=self.dispsize, pos=None, color=rgb2psychorgb(self.bgc), colorSpace='rgb', fullscr=settings.FULLSCREEN, monitor=self.monitor, screen=self.screennr, units='pix') # set mouse visibility pygaze.expdisplay.setMouseVisible(self.mousevis) # get screen in window if screen: for s in screen.screen: s.draw()
def set_screen(): # screen properties global win, start_text, left_label, right_label, center_disp, instruction_page, left_bg, right_bg, ok_button, ok_text win = Window([1280, 1000], color='Black', fullscr=fullscreen, screen=0, units='pix', allowGUI=True) # 1280 1024 text_left = 'nein' text_right = 'ja' h_dist = 80 v_dist = -190 left_bg = Rect(win, fillColor='red', pos=[-h_dist, v_dist - 7], width=130, height=85) right_bg = Rect(win, fillColor='green', pos=[h_dist, v_dist - 7], width=130, height=85) left_label = TextStim(win, color='white', font='Verdana', text=text_left, pos=[-h_dist, v_dist], height=50, alignHoriz='center') right_label = TextStim(win, color='white', font='Verdana', text=text_right, pos=[h_dist, v_dist], height=50, alignHoriz='center') center_disp = TextStim(win, color='white', font='Arial', text='', height=55) instruction_page = TextStim(win, wrapWidth=1200, pos=[0, 35], height=28, font='Verdana', color=instruction_color) ok_button = Rect(win, fillColor='black', lineColor=instruction_color, pos=[0, -345], width=80, height=50) ok_text = TextStim(win, text='OK', bold=True, color=instruction_color, pos=(0, -345), height=30)
def test_StaticPeriod_screenHz(): """Test if screenHz parameter is respected, i.e., if after completion of the StaticPeriod, 1/screenHz seconds are still remaining, so the period will complete after the next flip. """ refresh_rate = 100.0 period_duration = 0.1 timer = CountdownTimer() win = Window(autoLog=False) static = StaticPeriod(screenHz=refresh_rate, win=win) static.start(period_duration) timer.reset(period_duration) static.complete() assert np.allclose(timer.getTime(), 1.0 / refresh_rate, atol=0.001) win.close()
def setup_class(self): mon = monitors.Monitor('testMonitor') mon.setDistance(10.0) #exagerate the effect of flatness by setting the monitor close mon.setWidth(40.0) mon.setSizePix([1024,768]) self.win = Window([128,128], monitor=mon, winType='pyglet', pos=[50,50], autoLog=False) if havePygame: assert pygame.display.get_init() == 0
def print_message(window: visual.Window, message: str = "Initializing..."): """Draws a message on the display window using default config. Parameters ---------- window (object): Psychopy Window Object, should be the same as the one used in the experiment parameters (dict): Dictionary of session parameters Returns ------- TextStim object """ message_stim = visual.TextStim(win=window, text=message) message_stim.draw() window.flip() return message_stim
def __init__(self, logfile, imgDir, subjectNum, screenType, numStim, numBlocks, trialDuration, ISI, selfPaced, runPractice, inputButtons, pauseButton): self.logfile = logfile self.imgDir = imgDir self.subjectNum = subjectNum self.numStim = numStim self.numBlocks = numBlocks self.trialDuration = trialDuration self.selfPaced = selfPaced self.ISI = ISI self.numCats = 4 self.trialsPer = int((self.numStim / self.numCats) / 2) self.runPractice = runPractice self.leftButton = inputButtons[0] self.rightButton = inputButtons[1] self.pauseButton = pauseButton #Set up window, center, left and right image sizes + positions if (screenType == 'Windowed'): screenSelect = False elif (screenType == 'Fullscreen'): screenSelect = True self.window = Window(fullscr=screenSelect, units='pix', color='White', allowGUI=False) self.imageWidth = self.window.size[1] / 5.5 self.centerImage = ImageStim(self.window) self.centerImage.setSize((self.imageWidth, self.imageWidth)) self.leftImage = ImageStim(self.window) self.leftImage.setPos((-1.5 * self.imageWidth, 0)) self.leftImage.setSize((self.imageWidth, self.imageWidth)) self.rightImage = ImageStim(self.window) self.rightImage.setPos((1.5 * self.imageWidth, 0)) self.rightImage.setSize((self.imageWidth, self.imageWidth)) self.clock = Clock() #Init score list for 4 categories: [correct,incorrect,response] self.scoreList = [] for i in range(0, 4): self.scoreList.append([0, 0, 0])
def setup_window(): win = Window(fullscr=True, allowGUI=False, screen=1, units='height', monitor='testMonitor', colorSpace='rgb255', winType='pyglet') return win
class Test_textbox(object): def setup_class(self): self.win = Window([128, 128], pos=[50, 50], allowGUI=False, autoLog=False) def teardown_class(self): self.win.close() def test_basic(self): for units in ['norm', 'pix']: self.win.units = units tb = TextBox(self.win, size=(1, .5), pos=(0, -.25)) tb.setBackgroundColor('white') text = 'abc DEF' self.win.flip() tb.setText(text) tb.draw() self.win.flip() assert tb.getText() == tb.getDisplayedText() == text def test_something(self): # to-do: test visual display, char position, etc pass
def testStaticPeriod(): static = StaticPeriod() static.start(0.1) wait(0.05) assert static.complete()==1 static.start(0.1) wait(0.11) assert static.complete()==0 win = Window(autoLog=False) static = StaticPeriod(screenHz=60, win=win) static.start(.002) assert win.recordFrameIntervals == False static.complete() assert static._winWasRecordingIntervals == win.recordFrameIntervals win.close() # Test if screenHz parameter is respected, i.e., if after completion of the # StaticPeriod, 1/screenHz seconds are still remaining, so the period will # complete after the next flip. refresh_rate = 100.0 period_duration = 0.1 timer = CountdownTimer() win = Window(autoLog=False) static = StaticPeriod(screenHz=refresh_rate, win=win) static.start(period_duration) timer.reset(period_duration ) static.complete() assert np.allclose(timer.getTime(), 1.0/refresh_rate, atol=0.001) win.close()
def setup_class(self): self.win = Window([128, 128], pos=[50, 50], allowGUI=False, autoLog=False) self.error = _BaseErrorHandler() self.textbox = TextBox2(self.win, "", "Noto Sans", pos=(0, 0), size=(1, 1), units='height', letterHeight=0.1, colorSpace="rgb") self.obj = self.textbox # point to textbox for mixin tests # Pixel which is the border color self.borderPoint = (0, 0) self.borderUsed = True # Pixel which is the fill color self.fillPoint = (2, 2) self.fillUsed = True # Textbox foreground is too unreliable due to fonts for pixel analysis self.foreUsed = False
def quick_task(win=None) -> 'FabFruitTask': """bare min""" from soapy.task import FabFruitTask from soapy.seeded import update_boxes from soapy.info import FabFruitInfo from soapy.task_types import TimeTypes if win is None: from psychopy.visual import Window win = Window([800, 600]) i = FabFruitInfo(alwaysTiming=False) i = update_boxes(i, 'fruits', '/tmp/soapy') task = FabFruitTask(win, i, timing_method=TimeTypes.block) return task
def __enter__(self): comp = self.component from psychopy.visual import Window # eats some time window = Window( (comp.pixel_x, comp.pixel_y), useFBO=True, # units='deg', monitor=self.monitor.instance, allowStencil=True, screen=comp.screen, fullscr=comp.fullscr) self.instance = window self.flip = window.flip return self
def testStaticPeriod(): static = StaticPeriod() static.start(0.1) wait(0.05) assert static.complete() == 1 static.start(0.1) wait(0.11) assert static.complete() == 0 win = Window(autoLog=False) static = StaticPeriod(screenHz=60, win=win) static.start(.002) assert win.recordFrameIntervals == False static.complete() assert static._winWasRecordingIntervals == win.recordFrameIntervals
class Test_class_ProjectorFramePacker(object): """ """ def setup_class(self): self.win = Window(monitor='LightCrafter4500', screen=2, fullscr=True, color='gray', useFBO = True) self.win.setRecordFrameIntervals() self.packer = ProjectorFramePacker (self.win) def teardown_class(self): self.win.close() def flip (self, frames=120): for i in range(frames): self.win.flip()
class Test_textbox(object): def setup_class(self): self.win = Window([128,128], pos=[50,50], allowGUI=False, autoLog=False) def teardown_class(self): self.win.close() def test_basic(self): for units in ['norm', 'pix']: self.win.units = units tb = TextBox(self.win, size=(1,.5), pos=(0,-.25)) tb.setBackgroundColor('white') text = 'abc DEF' self.win.flip() tb.setText(text) tb.draw() self.win.flip() assert tb.getText() == tb.getDisplayedText() == text def test_something(self): # to-do: test visual display, char position, etc pass
print('Supported syringe types: %s' % qmix.syringeTypes) print('Supported volume units: %s' % qmix.volumeUnits) print('Supported flow rate units: %s' % qmix.flowRateUnits) # Initialize the first pump (index 0). We assume the pump is # equipped with a 50 mL glass syringe. pump = qmix.Pump(index=0, volumeUnit='mL', flowRateUnit='mL/s', syringeType='50 mL glass') print('Max. flow rate: .3%f %s' % (pump.maxFlowRate, pump.flowRateUnit)) win = Window() msg = ('Press one of the following keys: \n\n' ' F – Fill Syringe at 1 mL/s\n' ' E – Empty Syringe at 1 mL/s\n' ' A – Aspirate 1 mL at 1 mL/s\n' ' D – Dispense 1 mL at 1 mL/s\n' '\n' ' Q – Quit') t = TextStim(win, msg) event.clearEvents() while True: t.draw() win.flip() # Retrieve keypresses. The user can completely fill or empty the syringe,
class TestGLobalEventKeys(object): @classmethod def setup_class(self): self.win = Window([128, 128], winType='pyglet', pos=[50, 50], autoLog=False) @classmethod def teardown_class(self): self.win.close() def setup_method(self, test_method): # Disable auto-creation of shutdown key. prefs.general['shutdownKey'] = '' def _func(self, *args, **kwargs): return [args, kwargs] def test_shutdownKey_prefs(self): key = 'escape' modifiers = ('ctrl', 'alt') prefs.general['shutdownKey'] = key prefs.general['shutdownKeyModifiers'] = modifiers global_keys = event._GlobalEventKeys() e = list(global_keys)[0] assert key, modifiers == e assert global_keys[e].func == core.quit def test_add(self): key = 'a' func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func) assert global_keys[key, ()].func == func assert global_keys[key, ()].name == func.__name__ def test_add_key_twice(self): key = 'a' func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func) with pytest.raises(ValueError): global_keys.add(key=key, func=func) def test_add_name(self): key = 'a' name = 'foo' func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func, name=name) assert global_keys[key, ()].name == name def test_add_args(self): key = 'a' func = self._func args = (1, 2, 3) global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func, func_args=args) assert global_keys[key, ()].func_args == args def test_add_kwargs(self): key = 'a' func = self._func kwargs = dict(foo=1, bar=2) global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func, func_kwargs=kwargs) assert global_keys[key, ()].func_kwargs == kwargs def test_add_args_and_kwargs(self): key = 'a' func = self._func args = (1, 2, 3) kwargs = dict(foo=1, bar=2) global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func, func_args=args, func_kwargs=kwargs) assert global_keys[key, ()].func_args == args assert global_keys[key, ()].func_kwargs == kwargs def test_add_invalid_key(self): key = 'foo' func = self._func global_keys = event._GlobalEventKeys() with pytest.raises(ValueError): global_keys.add(key=key, func=func) def test_add_invalid_modifiers(self): key = 'a' modifiers = ('foo', 'bar') func = self._func global_keys = event._GlobalEventKeys() with pytest.raises(ValueError): global_keys.add(key=key, modifiers=modifiers, func=func) def test_remove(self): keys = ['a', 'b', 'c'] modifiers = ('ctrl',) func = self._func global_keys = event._GlobalEventKeys() [global_keys.add(key=key, modifiers=modifiers, func=func) for key in keys] global_keys.remove(keys[0], modifiers) with pytest.raises(KeyError): _ = global_keys[keys[0], modifiers] def test_remove_modifiers_list(self): key = 'a' modifiers = ['ctrl', 'alt'] func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, modifiers=modifiers, func=func) global_keys.remove(key, modifiers) with pytest.raises(KeyError): _ = global_keys[key, modifiers] def test_remove_invalid_key(self): key = 'a' global_keys = event._GlobalEventKeys() with pytest.raises(KeyError): global_keys.remove(key) def test_remove_all(self): keys = ['a', 'b', 'c'] func = self._func global_keys = event._GlobalEventKeys() [global_keys.add(key=key, func=func) for key in keys] global_keys.remove('all') assert len(global_keys) == 0 def test_getitem(self): key = 'escape' modifiers = ('ctrl', 'alt') func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, modifiers=modifiers, func=func) assert global_keys[key, modifiers] == global_keys._events[key, modifiers] def test_getitem_string(self): key = 'escape' func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func) assert global_keys[key] == global_keys._events[key, ()] def test_getitem_modifiers_list(self): key = 'escape' modifiers = ['ctrl', 'alt'] func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, modifiers=modifiers, func=func) assert (global_keys[key, modifiers] == global_keys._events[key, tuple(modifiers)]) def test_setitem(self): keys = 'a' modifiers = () global_keys = event._GlobalEventKeys() with pytest.raises(NotImplementedError): global_keys[keys, modifiers] = None def test_delitem(self): key = 'escape' modifiers = ('ctrl', 'alt') func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, modifiers=modifiers, func=func) del global_keys[key, modifiers] with pytest.raises(KeyError): _ = global_keys[key, modifiers] def test_delitem_string(self): key = 'escape' func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func) del global_keys[key] with pytest.raises(KeyError): _ = global_keys[key] def test_len(self): prefs.general['shutdownKey'] = '' key = 'escape' func = self._func global_keys = event._GlobalEventKeys() assert len(global_keys) == 0 global_keys.add(key=key, func=func) assert len(global_keys) == 1 del global_keys[key, ()] assert len(global_keys) == 0 def test_event_processing(self): key = 'a' modifiers = 0 func = self._func args = (1, 2, 3) kwargs = dict(foo=1, bar=2) event.globalKeys.add(key=key, func=func, func_args=args, func_kwargs=kwargs) r = event._process_global_event_key(key, modifiers) assert r[0] == args assert r[1] == kwargs def test_index_keys(self): key = 'escape' modifiers = ('ctrl', 'alt') func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, modifiers=modifiers, func=func) index_key = list(global_keys.keys())[-1] assert index_key.key == key assert index_key.modifiers == modifiers def test_numlock(self): key = 'a' modifiers = ('numlock',) func = self._func global_keys = event._GlobalEventKeys() with pytest.raises(ValueError): global_keys.add(key=key, modifiers=modifiers, func=func)
def close(self): self.server.stop() Window.close(self)
def flip(self,clearBuffer=True): Window.flip(self,clearBuffer) return Computer.getTime()
def __init__(self, exp_info, file_name): """ Initialize experiment - read XML file, setup window, connect to netstation and tobii exp_info - experiment information file_name - name of XML file containing experiment definition """ self.exp_info = exp_info self.name = None self.type = None self.num_blocks = 0 self.blocks = {} self.block_order = [] # Window to use wintype = 'pyglet' # use pyglet if possible, it's faster at event handling # Add 14cm to distance - this is distance from eyetracker to monitor mon = monitors.Monitor(exp_info['monitor'], distance=float(exp_info['monitor distance'])) self.win = Window( [1280, 1024], monitor=mon, screen=SCREEN, units="deg", fullscr=True, #fullscr=False, color=[-1, -1, -1], winType=wintype) self.win.setMouseVisible(False) event.clearEvents() # Measure frame rate self.mean_ms_per_frame, std_ms_per_frame, median_ms_per_frame = visual.getMsPerFrame(self.win, nFrames=60, showVisual=True) self.debug_sq=None if exp_info['monitor']=='tobii': self.debug_sq=psychopy.visual.Rect(self.win, width=30, height=30, units='pix') self.debug_sq.setFillColor((1,1,1)) self.debug_sq.setPos((630,-500)) # Compute distractor duration in frames based on frame rate distractor_duration_frames = int(2000.0/self.mean_ms_per_frame) # Initialize set of distractors self.distractor_set = DistractorSet(os.path.join(DATA_DIR, 'images', 'distractors', 'space'), os.path.join(DATA_DIR, 'sounds', 'distractors'), os.path.join(DATA_DIR, 'movies', 'distractors'), os.path.join(DATA_DIR, 'images', 'distractors', 'star-cartoon.jpg'), distractor_duration_frames, self.win) # Connect to nestation self.ns = None if exp_info['eeg']: # connect to netstation self.ns = egi.Netstation() ms_localtime = egi.ms_localtime self.eye_tracker = None mouse_visible = False if exp_info['eyetracking source'] == 'tobii': # Initialize eyetracker self.eye_tracker = TobiiController(self.win) self.eye_tracker.waitForFindEyeTracker() self.eye_tracker.activate(EYETRACKER_NAME) elif exp_info['eyetracking source'] == 'mouse': mouse_visible = True # Initialize mouse self.mouse = event.Mouse(visible=mouse_visible, win=self.win) self.gaze_debug=None if self.exp_info['debug mode']: self.gaze_debug=psychopy.visual.Circle(self.win, radius=1, fillColor=(1.0,-1.0,-1.0)) self.read_xml(file_name) # Initialize netstation and eyetracker self.initialize()
def setup_class(self): self.win = Window(monitor='LightCrafter4500', screen=2, fullscr=True, color='gray', useFBO = True) self.win.setRecordFrameIntervals() self.packer = ProjectorFramePacker (self.win)
def setup_class(self): self.win = Window(monitor='testMonitor', screen=1, fullscr=True, color='gray', useFBO = True) self.warper = Warper (self.win, warp='spherical', warpfile = "", warpGridsize = 128, eyepoint = [0.5, 0.5], flipHorizontal = False, flipVertical = False) self.warper.dist_cm=15 self.g = ProjectionsLinesAndCircles(self.win, self.warper)
def setup_class(self): self.win = Window([128,128], pos=[50,50], allowGUI=False, autoLog=False)
class Experiment: """ Base experiment class """ def __init__(self, exp_info, file_name): """ Initialize experiment - read XML file, setup window, connect to netstation and tobii exp_info - experiment information file_name - name of XML file containing experiment definition """ self.exp_info = exp_info self.name = None self.type = None self.num_blocks = 0 self.blocks = {} self.block_order = [] # Window to use wintype = 'pyglet' # use pyglet if possible, it's faster at event handling # Add 14cm to distance - this is distance from eyetracker to monitor mon = monitors.Monitor(exp_info['monitor'], distance=float(exp_info['monitor distance'])) self.win = Window( [1280, 1024], monitor=mon, screen=SCREEN, units="deg", fullscr=True, #fullscr=False, color=[-1, -1, -1], winType=wintype) self.win.setMouseVisible(False) event.clearEvents() # Measure frame rate self.mean_ms_per_frame, std_ms_per_frame, median_ms_per_frame = visual.getMsPerFrame(self.win, nFrames=60, showVisual=True) self.debug_sq=None if exp_info['monitor']=='tobii': self.debug_sq=psychopy.visual.Rect(self.win, width=30, height=30, units='pix') self.debug_sq.setFillColor((1,1,1)) self.debug_sq.setPos((630,-500)) # Compute distractor duration in frames based on frame rate distractor_duration_frames = int(2000.0/self.mean_ms_per_frame) # Initialize set of distractors self.distractor_set = DistractorSet(os.path.join(DATA_DIR, 'images', 'distractors', 'space'), os.path.join(DATA_DIR, 'sounds', 'distractors'), os.path.join(DATA_DIR, 'movies', 'distractors'), os.path.join(DATA_DIR, 'images', 'distractors', 'star-cartoon.jpg'), distractor_duration_frames, self.win) # Connect to nestation self.ns = None if exp_info['eeg']: # connect to netstation self.ns = egi.Netstation() ms_localtime = egi.ms_localtime self.eye_tracker = None mouse_visible = False if exp_info['eyetracking source'] == 'tobii': # Initialize eyetracker self.eye_tracker = TobiiController(self.win) self.eye_tracker.waitForFindEyeTracker() self.eye_tracker.activate(EYETRACKER_NAME) elif exp_info['eyetracking source'] == 'mouse': mouse_visible = True # Initialize mouse self.mouse = event.Mouse(visible=mouse_visible, win=self.win) self.gaze_debug=None if self.exp_info['debug mode']: self.gaze_debug=psychopy.visual.Circle(self.win, radius=1, fillColor=(1.0,-1.0,-1.0)) self.read_xml(file_name) # Initialize netstation and eyetracker self.initialize() def calibrate_eyetracker(self): """ Run eyetracker calibration routine """ retval = 'retry' while retval == 'retry': waitkey = True retval = None can_accept = self.eye_tracker.doCalibration(EYETRACKER_CALIBRATION_POINTS) while waitkey: for key in psychopy.event.getKeys(): if can_accept: num_entered=True try: calib_idx=int(key) can_accept = self.eye_tracker.doCalibration([EYETRACKER_CALIBRATION_POINTS[calib_idx-1]], calib=self.eye_tracker.calib) except: num_entered=False if not num_entered and key == 'a': retval = 'accept' waitkey = False elif key == 'r': retval = 'retry' waitkey = False elif key == 'escape': retval = 'abort' waitkey = False self.eye_tracker.calresult.draw() self.eye_tracker.calresultmsg.draw() for point_label in self.eye_tracker.point_labels: point_label.draw() self.win.flip() if retval == 'abort': self.eye_tracker.closeDataFile() self.eye_tracker.destroy() self.win.close() core.quit() def initialize(self): """ Start netstation recording, calibrate eyetracker """ if self.ns is not None: try: self.ns.initialize(NETSTATION_IP, 55513) self.ns.BeginSession() self.ns.StartRecording() except: print('Could not connect with NetStation!') # Initialize logging logfile = os.path.join(DATA_DIR, 'logs', self.exp_info['experiment'], '%s_%s_%s.log' % (self.exp_info['child_id'], self.exp_info['date'], self.exp_info['session'])) if self.eye_tracker is not None: self.eye_tracker.setDataFile(logfile, self.exp_info) else: datafile = open(logfile, 'w') datafile.write('Recording date:\t' + datetime.datetime.now().strftime('%Y/%m/%d') + '\n') datafile.write('Recording time:\t' + datetime.datetime.now().strftime('%H:%M:%S') + '\n') datafile.write('Recording resolution\t%d x %d\n' % tuple(self.win.size)) for key, data in self.exp_info.iteritems(): datafile.write('%s:\t%s\n' % (key, data)) datafile.close() # Create random block order n_repeats = int(self.num_blocks/len(self.blocks.keys())) for i in range(n_repeats): subblock_order = copy.copy(self.blocks.keys()) np.random.shuffle(subblock_order) self.block_order.extend(subblock_order) # Synch with netstation in between trials if self.ns is not None: self.ns.sync() if self.eye_tracker is not None: self.eye_tracker.startTracking() def close(self): """ Disconnect from eyetracker and netstation """ if self.eye_tracker is not None: self.eye_tracker.stopTracking() self.eye_tracker.closeDataFile() # close netstation connection if self.ns: self.ns.StopRecording() self.ns.EndSession() self.ns.finalize() self.win.close() core.quit() if self.eye_tracker is not None: self.eye_tracker.destroy() def run(self): """ Run task ns - netstation connection """ pass def read_xml(self, file_name): """ Read experiment definition file :param file_name: file to read definition from """ pass
pngs = map(str, pngs) self.masks = [ImageStim(image = img, **kwargs) for img in pngs] self._ix = 0 def draw(self): """ Draws a single mask """ self.masks[self._ix].draw() self._ix = (self._ix + 1) % len(self.masks) if self._ix == 0: shuffle(self.masks) def setPos(self, pos): """ Change the position for all masks""" for mask in self.masks: mask.setPos(pos) if __name__ == '__main__': """ Demo of the dynamic mask in action """ from psychopy import core from psychopy.visual import Window window = Window(size = (500, 500), units = 'pix', monitor = 'testMonitor') dynamic_mask = DynamicMask(win = window, size = (200, 200)) for _ in xrange(25): dynamic_mask.draw() window.flip() core.wait(0.05)
def flip(self, clearBuffer=True): Window.flip(self, clearBuffer=False) # draw everything, but don't clear buffer yet so that we can capture it self.updatePygletImage() # TODO use Window._getFrame() instead? or _getRegionOfFrame? if clearBuffer: Window.clearBuffer(self) # now that we have captured the image, clear the buffer
def setup_class(self): self.win = Window([128, 128], winType='pyglet', pos=[50, 50], autoLog=False)