def __enter__(self): from psychopy.monitors import Monitor comp = self.component monitor = Monitor(comp.name, width=comp.width, distance=comp.dist, gamma=comp.gamma) #comp.gamma) monitor.setSizePix((comp.pixel_x, comp.pixel_y)) self.instance = monitor return self
def __init__(self, params): """Extracts monitor information from params file and monitors.py.""" try: mod = __import__("monitors") except ImportError: sys.exit("Could not import monitors.py in this directory.") try: minfo = getattr(mod, params.monitor_name.replace("-", "_")) except IndexError: sys.exit("Monitor not found in monitors.py") fullscreen = params.get("full_screen", True) size = minfo["size"] if fullscreen else (800, 600) monitor = Monitor(name=minfo["name"], width=minfo["width"], distance=minfo["distance"]) monitor.setSizePix(minfo["size"]) try: monitor.setGamma(minfo["gamma"]) except AttributeError: warnings.warn("Could not set monitor gamma table.") # Convert from cd/m^2 to psychopy rgb color # Note that this ignores the min luminance of the monitor window_color = params.mean_luminance / minfo["max_luminance"] * 2 - 1 # Allow for horizontal mirror view of the whole window if params.fmri and params.get("fmri_mirror_horizontal", False): viewscale = [-1, 1] else: viewscale = [1, 1] info = dict(units=params.get("monitor_units", "deg"), screen=params.get("screen", 0), fullscr=fullscreen, allowGUI=not fullscreen, color=window_color, size=size, monitor=monitor, viewScale=viewscale) if hasattr(params, "blend_mode"): info["blendMode"] = params.blend_mode if params.blend_mode == "add": info["useFBO"] = True if "refresh_hz" in minfo: self.refresh_hz = minfo["refresh_hz"] self.name = params.monitor_name self.__dict__.update(info) self.window_kwargs = info
def monitor(self): """Stores a monitor object for the experiment so that it doesn't have to be fetched from disk repeatedly""" # remember to set _monitor to None periodically (start of script build?) # so that we do reload occasionally if not self._monitor: self._monitor = Monitor(self.params['Monitor'].val) return self._monitor
def __init__(self, mode="mono++", **kwargs): self.monitor = Monitor('Display++', width=80, distance=57) self.monitor.setSizePix((1920, 1080)) portName = kwargs.pop('portName', '/dev/ttyACM0') gamma = kwargs.pop('gamma', 'hardware') kwargs.setdefault('screen', 1) kwargs['useFBO'] = True kwargs['size'] = (1920, 1080) kwargs['monitor'] = self.monitor super(dppWindow, self).__init__(**kwargs) self.dpp = DisplayPlusPlus(self, portName=portName, gamma=gamma, mode=mode, checkConfigLevel=1)
class TestWin(object): """ Creates a false window with necessary attributes for converting component Parameters to pixels. """ def __init__(self, exp, monitor): self.useRetina = True self.exp = exp self.monitor = Monitor(monitor) self.size = self.monitor.getSizePix()
def plot_category_exemplars_2(x, y, xpos, ypos, contrast=None): '''plot sine-wave gratings at x CPD and at y degrees orientation in stimulus space --- cat, x, and y should be lists of the same length.''' # NOTE: Screen coordinate system has origin in the middle of the screen with # positive numbers going right and negative number going left screen_size = 600 x_max = np.max(xpos) y_max = np.max(ypos) x_min = np.min(xpos) y_min = np.min(ypos) # NOTE: convert stimulus coordinates into screen coordinates xp = ((xpos - np.min(xpos)) / np.max(xpos - np.min(xpos))) * (screen_size) - screen_size / 2.0 yp = ((ypos - np.min(ypos)) / np.max(ypos - np.min(ypos))) * (screen_size) - screen_size / 2.0 win = visual.Window(size=(screen_size + 150, screen_size + 150), fullscr=False, screen=0, allowGUI=False, allowStencil=False, monitor='testMonitor', color=[0, 0, 0], colorSpace='rgb', blendMode='avg', useFBO=False) mon = Monitor('testMonitor') mon.setWidth(29.0) mon.setSizePix((1440, 900)) cm_per_pix = pix2cm(1, mon) n = x.shape[0] if contrast is None: cont = [1] * n else: cont = contrast stim = [] for i in range(n): grating = visual.GratingStim(win, units='pix', mask='circle', sf=x[i] * cm_per_pix, ori=y[i], pos=(xp[i], yp[i]), contrast=cont[i], size=(2 / cm_per_pix, 2 / cm_per_pix)) stim.append(grating) [i.draw() for i in stim] win.flip() event.waitKeys(keyList=['escape'])
def test_pos_size(self): # If this test object has no obj, skip if not self.obj: return # Setup window for this test monitor = Monitor("testMonitor") monitor.setSizePix((256, 128)) monitor.setWidth(4) monitor.setDistance(50) win = visual.Window(size=(256, 128), monitor=monitor) win.useRetina = False # Setup object for this test obj = copy(self.obj) obj.win = win if hasattr(obj, "fillColor"): obj.fillColor = 'red' if hasattr(obj, "foreColor"): obj.foreColor = 'blue' if hasattr(obj, 'borderColor'): obj.borderColor = 'green' if hasattr(obj, 'opacity'): obj.opacity = 1 # Run positions through each size exemplar for size in self.sizeExemplars + self.sizeTykes: for pos in self.posExemplars + self.posTykes: for units in set(list(pos) + list(size)): if units == 'suffix': continue # Set pos and size obj.units = units obj.size = size[units] obj.pos = pos[units] # Draw obj.draw() # Compare screenshot filename = f"{self.__class__.__name__}_{size['suffix']}_{pos['suffix']}.png" #win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) utils.compareScreenshot(filename, win, crit=7) win.flip() # Cleanup win.close() del obj del win
def get(name, dist_cm=120): """ Returns configured monitor object for known monitor names. """ name = name.lower() if name not in _LAB_MONITORS: raise ValueError("Unknown monitor '%s'. Expecting %s" % _LAB_MONITORS.keys()) try: mon = Monitor(name) except Exception as exc: raise IOError("Could not initialize monitor '%s': %s" % (name, exc)) mon.setDistance(dist_cm) mon.setSizePix(_LAB_MONITORS[name]['resolution']) mon.setWidth(_LAB_MONITORS[name]['diagonal']) return mon
def save_stim(x, y, contrast, name): screen_size = 100 win = visual.Window(size=(screen_size, screen_size), fullscr=False, screen=0, allowGUI=False, allowStencil=False, monitor='testMonitor', color=[0, 0, 0], colorSpace='rgb', blendMode='avg', useFBO=False) mon = Monitor('testMonitor') mon.setWidth(29.0) mon.setSizePix((1440, 900)) cm_per_pix = pix2cm(1, mon) cont = contrast grating = visual.GratingStim(win, units='pix', mask='circle', sf=x * cm_per_pix, ori=y, pos=(0, 0), contrast=cont, size=(2 / cm_per_pix, 2 / cm_per_pix), interpolate=True, texRes=2048) grating.draw() win.flip() win.getMovieFrame() win.saveMovieFrames(name)
def _create_monitor(self): """ Creates the monitor based on settings and save to disk. """ monitor = Monitor(**self.settings['monitor']) monitor.setSizePix(self.settings['window']['size']) monitor.save() # needed for iohub eyetracker return monitor
def _create_monitor(self): monitor = Monitor(**self.settings['monitor']) monitor.save() # needed for iohub eyetracker return monitor
def TransformStim(xin, yin): #initialize variable, transfer labels trans_y = np.zeros(np.shape(xin)[0]) # Convert x values; as long as input's x-values are in 0-100 space, this # line linearly transforms those values to -1:2 space; to choose # a different range, simply change the linear scaling, but be sure to # change the scaling for the y transformation as well so the ratio of the # axes remains the same. trans_x = (xin / 100) * 3 - 0.5 # trans_x = (xin / 100) * 3 - 1 # Nonlinear conversion of x values: trans_x exponentiated, resulting in a # range of .5-4 for CPD. DO NOT CHANGE. trans_x = 2**trans_x # Y values should also be in 0-100; negative values in particular cause # problems. if np.any(xin < 0) or np.any(yin < 0): print('Negative value for input!') # Linear conversion of y values to pi/11:(3*pi/8+pi/11) space. Again, # different ranges and bounds can be chosen at this step. # y = (yin / 100) * ((3 * np.pi / 8) + (np.pi / 11)) y = (yin / 100) * ((3 * np.pi / 8) + (np.pi / 9)) # The remainder of the code performs the nonlinear transformation on the y # values, which remain in the same space, but warped. DO NOT CHANGE. ind = np.argsort(y) sort_y = y[ind] z = 4.7 * np.sin(sort_y)**2 trans_y[0] = np.sqrt(sort_y[0]**2 + z[0]**2) for i in range(1, np.shape(sort_y)[0]): trans_y[i] = trans_y[i - 1] + np.sqrt( np.power(sort_y[i] - sort_y[i - 1], 2) + np.power(z[i] - z[i - 1], 2)) range_trans_y = np.amax(trans_y) - np.amin(trans_y) range_sort_y = np.amax(sort_y) - np.amin(sort_y) trans_y = trans_y / range_trans_y * range_sort_y trans_y = trans_y - np.min(trans_y) + np.min(sort_y) # NOTE: Convert radians to degrees trans_y = trans_y * 180 / np.pi xout = trans_x yout = np.zeros(np.shape(xin)[0]) for i in range(0, len(ind)): yout[ind[i]] = trans_y[i] # NOTE: Convert Cycles per degree to cycles per cm mon = Monitor('testMonitor') mon.distance = 20.0 # viewing distance in cm xout = xout * (pix2deg(1, mon) / pix2cm(1, mon)) # xout = (xin / 100) * 5 + 1 # yout = (yin / 100) * 90 return ([xout, yout])
from psychopy import core from psychopy import misc from psychopy.visual.windowwarp import Warper from psychopy.monitors import Monitor from psychopy.visual.grating import GratingStim from psychopy.visual.window import Window mon = Monitor('GenericMonitor', width=33.169, distance=10) mon.setSizePix((1440, 900)) win = Window((1440, 900), monitor=mon, fullscr=True, useFBO=True, allowStencil=True) warper = Warper(win, warp='spherical', warpGridsize=300, eyepoint=[0.5, 0.5]) stim = GratingStim(win=win, units='deg', tex='sin', sf=0.1, size=misc.pix2deg(win.size, win.monitor)) print win.size print 'win size', win.size print 'mon size', win.monitor.getSizePix() print 'as deg', misc.pix2deg(win.size, win.monitor) stim.draw() win.flip() core.wait(0.5) win.close()
def __init__(self, exp, monitor): self.useRetina = True self.exp = exp self.monitor = Monitor(monitor) self.size = self.monitor.getSizePix()
def launch_window(self, test_refresh=True, test_tol=.5): """Load window info""" #taken from Mwaskom cregg try: mod = __import__("monitors") except ImportError: sys.exit("Could not import monitors.py in this directory.") try: minfo = getattr(mod, self.monitor_name) except IndexError: sys.exit("Monitor not found in monitors.py") fullscreen = self.full_screen size = minfo["size"] if fullscreen else (800, 600) monitor = Monitor(name=minfo["name"], width=minfo["width"], distance=minfo["distance"]) monitor.setSizePix(minfo["size"]) info = dict(units=self.monitor_units, fullscr=fullscreen, color=self.window_color, size=size, monitor=monitor) if "framerate" in minfo: self.framerate = minfo["framerate"] self.name = self.monitor_name self.__dict__.update(info) self.window_kwargs = info """Open up a presentation window and measure the refresh rate.""" stated_refresh_hz = self.framerate # Initialize the Psychopy window object win = visual.Window(**self.window_kwargs) # Record the refresh rate we are currently achieving if self.test_refresh or stated_refresh_hz is None: win.setRecordFrameIntervals(True) logging.console.setLevel(logging.CRITICAL) flip_time, _, _ = visual.getMsPerFrame(win) observed_refresh_hz = 1000 / flip_time print('observed_refresh_hz', observed_refresh_hz) # Possibly test the refresh rate against what we expect if self.test_refresh and stated_refresh_hz is not None: refresh_error = np.abs(stated_refresh_hz - observed_refresh_hz) print('refresh_error', refresh_error) if refresh_error > test_tol: msg = ( "Observed refresh rate differs from expected by {:.3f} Hz". format(refresh_error)) raise RuntimeError(msg) # Set the refresh rate to use in the experiment if stated_refresh_hz is None: msg = "Monitor configuration does not have refresh rate information" warnings.warn(msg) win.framerate = observed_refresh_hz else: win.framerate = stated_refresh_hz return win
from psychopy import prefs from psychopy.monitors import Monitor # avoids delay in movie3 audio seek prefs.hardware["audioLib"] = ["sounddevice"] # prefs.hardware['general'] = ['glfw'] OUTPUT_DIR = "output" EYETRACKING_ROI = (60, 30, 660, 450) EXP_SCREEN_XRANDR_NAME = "eDP-1" EXP_MONITOR = Monitor( name='__blank__', width=55, distance=180, ) EXP_WINDOW = dict( size=(1280, 1024), screen=1, fullscr=True, gammaErrorPolicy="warn", #waitBlanking=False, ) EXP_MONITOR.setSizePix(EXP_WINDOW['size']) CTL_WINDOW = dict( size=(1280, 1024),
# monitor_name = '2208WFP' # screen_res = (1680, 1050) # Keyboard response keys response_keys = ['z', 'slash'] # Order: left, right. # Settings for Roeterseiland computers elif 'HOMEPATH' in os.environ and os.environ['HOMEPATH'] == '\\Users\\User': from psychopy.monitors import Monitor screen_res = (1920, 1080) distance = 55 # Create Monitor cur_mon = Monitor(name='benq', width=53.1, distance=distance, notes='Dynamically created in standard_parameters. ' 'You might read a warning if the monitor ' 'specification does not already exist.') cur_mon.setSizePix(screen_res) cur_mon.saveMon() monitor_name = 'benq' response_keys = ['z', 'slash'] elif 'HOMEPATH' in os.environ and os.environ['USERNAME'] == 'psyuser': from psychopy.monitors import Monitor screen_res = (1920, 1080) distance = 86 # Create Monitor cur_mon = Monitor(name='asus', width=55,
from psychopy import core, visual, event, monitors from psychopy.monitors import Monitor from settings import exp, db from exputils import getFrameRate, trim_df from utils import trim, to_percent if os.name == 'nt' and exp['use trigger']: from ctypes import windll # setup monitor monitor = "testMonitor" if exp['lab monitor']: distance = exp['participant distance'] monitor = Monitor('BenQ', width=53.136, distance=distance) monitor.setSizePix((1920, 1080)) # create a window # --------------- winkeys = { 'units': 'deg', 'fullscr': exp['full_screen'], 'useFBO': True, 'blendMode': 'add', 'monitor': monitor, 'size': (1920, 1080) } if exp['two screens']: winkeys.update({'screen': 1}) win = visual.Window(**winkeys)
from psychopy import core, visual, event, monitors from psychopy.monitors import Monitor from settings import exp, db from exputils import getFrameRate, trim_df from utils import trim, to_percent if os.name == 'nt' and exp['use trigger']: from ctypes import windll # setup monitor monitor = "testMonitor" if exp['lab monitor']: distance = exp['participant distance'] monitor = Monitor('BenQ', width=53.136, distance=distance) monitor.setSizePix((1920, 1080)) # create a window # --------------- winkeys = {'units': 'deg', 'fullscr': exp['full_screen'], 'useFBO': True, 'blendMode': 'add', 'monitor': monitor, 'size': (1920, 1080)} if exp['two screens']: winkeys.update({'screen': 1}) win = visual.Window(**winkeys) win.setMouseVisible(False) stim = dict() stim['window'] = win
# These are constants used for PyGaze. Note that these are automatically calculated using the values entered in # standard_parameters and Monitor - no need to edit anything here. from __future__ import division from psychopy.monitors import Monitor from standard_parameters import monitor_name, background_color mon = Monitor(monitor_name) mon_width = mon.getWidth() mon_size_pix = mon.getSizePix() mon_height = mon_size_pix[1] * mon_width / mon_size_pix[0] #BGC = 'grey' SCREENSIZE = (int(mon_width), int(mon_height)) DISPSIZE = (int(mon_size_pix[0]), int(mon_size_pix[1]))
return r + c DIR = os.getcwd() FLASH = 0.0625 # duration of flash, s PAUSE = 0.0625 TRIALREPEATS = 5 # cycles of flashes SIZE = (1536, 864) #(1680,1050)# resolution (1280,720) CENTER = (0, 0) # fixmark coordinates, deg DISTANCE = 75 # distance between subject and screen, cm WIDTH = 47.4 # screen width , cm (31) #STIMSIZE= [0.4, 1.0, 2.0] # size of stimuli, deg LETTERSIZE = [0.8, 1.85, 3.3] # size of letter images, deg MON = Monitor('Dell') MON.setWidth(WIDTH) MON.setDistance(DISTANCE) MON.setSizePix(SIZE) BACKCOL = (-0.5, -0.5, -0.5) #background color FIXCOL = (1, 1, 1) #fixation mark color C1 = [(0, -1.500), (-0.964, -1.149), (-1.477, -0.260), (-1.299, 0.750), (-0.513, 1.410), (0.513, 1.410), (1.299, 0.750), (1.477, -0.260), (0.964, -1.149)] # coordinates of inner circle, deg C2 = [(0, 3.500), (2.250, 2.681), (3.447, 0.608), (3.031, -1.750), (1.197, -3.289), (-1.197, -3.289), (-3.031, -1.750), (-3.447, 0.608), (-2.250, 2.681)] # coordinates of middle circle, deg C3 = [(0, -7.000), (-4.500, -5.362), (-6.894, -1.216), (-6.062, 3.500), (-2.394, 6.578), (2.394, 6.578), (6.062, 3.500), (6.894, -1.216),