def testCallWithMonitorName(self): tobii_helper = calibrator.TobiiHelper() tobii_helper.disableLogging() tobii_helper.setMonitor(monitors.getAllMonitors()[0]) self.assertEqual(monitors.getAllMonitors()[0], tobii_helper.getMonitorName()) screen = pyglet.window.get_platform().get_default_display().get_default_screen(); self.assertEqual((screen.width, screen.height), tobii_helper.getMonitorDimensions())
def _createPsychopyCalibrationFile(self): display_config = self.getConfiguration() override_using_psycho_settings = display_config.get( 'override_using_psycho_settings', False) psychopy_monitor_name = display_config.get('psychopy_monitor_name', None) if psychopy_monitor_name is None or psychopy_monitor_name == 'None': return False from psychopy import monitors existing_monitors = monitors.getAllMonitors() psychoMonitor = None override = override_using_psycho_settings is True if override and psychopy_monitor_name in existing_monitors: psychoMonitor = monitors.Monitor(psychopy_monitor_name) px, py = self.getPixelResolution() mwidth = psychoMonitor.getWidth() * 10.0 aspect_ratio = px / float(py) mheight = mwidth / aspect_ratio display_config['physical_dimensions']['width'] = mwidth display_config['physical_dimensions']['height'] = mheight display_config['physical_dimensions']['unit_type'] = 'mm' display_config['default_eye_distance'][ 'surface_center'] = psychoMonitor.getDistance() * 10.0 display_config['default_eye_distance']['unit_type'] = 'mm' else: stim_area = display_config.get('physical_dimensions') dwidth = stim_area['width'] # switch from mm to cm if required dw_unit_type = stim_area['unit_type'] if dw_unit_type == 'mm': dwidth = dwidth / 10.0 ddist = self.getDefaultEyeDistance() unit_type = self.getConfiguration()['default_eye_distance']\ ['unit_type'] # switch from mm to cm if required if unit_type == 'mm': ddist = ddist / 10.0 psychoMonitor = monitors.Monitor(psychopy_monitor_name, width=dwidth, distance=ddist, gamma=1.0) psychoMonitor.setSizePix(list(self.getPixelResolution())) psychoMonitor.save() self._psychopy_monitor = psychoMonitor return True
def _createPsychopyCalibrationFile(self): display_config = self.getConfiguration() override_using_psycho_settings = display_config.get( 'override_using_psycho_settings', False) psychopy_monitor_name = display_config.get( 'psychopy_monitor_name', None) if psychopy_monitor_name is None or psychopy_monitor_name == 'None': return False from psychopy import monitors existing_monitors = monitors.getAllMonitors() psychoMonitor = None override = override_using_psycho_settings is True if override and psychopy_monitor_name in existing_monitors: psychoMonitor = monitors.Monitor(psychopy_monitor_name) px, py = self.getPixelResolution() mwidth = psychoMonitor.getWidth() * 10.0 aspect_ratio = px / float(py) mheight = mwidth / aspect_ratio display_config['physical_dimensions']['width'] = mwidth display_config['physical_dimensions']['height'] = mheight display_config['physical_dimensions']['unit_type'] = 'mm' display_config['default_eye_distance'][ 'surface_center'] = psychoMonitor.getDistance() * 10.0 display_config['default_eye_distance']['unit_type'] = 'mm' else: stim_area = display_config.get('physical_dimensions') dwidth = stim_area['width'] # switch from mm to cm if required dw_unit_type = stim_area['unit_type'] if dw_unit_type == 'mm': dwidth = dwidth / 10.0 ddist = self.getDefaultEyeDistance() unit_type = self.getConfiguration()['default_eye_distance']\ ['unit_type'] # switch from mm to cm if required if unit_type == 'mm': ddist = ddist / 10.0 psychoMonitor = monitors.Monitor( psychopy_monitor_name, width=dwidth, distance=ddist, gamma=1.0) psychoMonitor.setSizePix(list(self.getPixelResolution())) psychoMonitor.save() self._psychopy_monitor = psychoMonitor return True
def window_creation(fullscreen, background_color): if fullscreen: m = monitors.Monitor(monitors.getAllMonitors()[0]) win = visual.Window(units='pix', monitor=m, color=background_color, colorSpace="rgb255", fullscr=True) wsize = win.size scrwidth = wsize[0] scrheight = wsize[1] else: scrwidth = 1280 scrheight = 720 win = visual.Window([scrwidth,scrheight], units='pix', monitor='testMonitor', color=background_color, colorSpace="rgb255") return win, scrwidth, scrheight
def makeMonitor(monitor_constants): """ :param monitor_constants: a dict with the following keys: :param name: name of the monitor, useful to recall settings or to override existing settings :param res: resolution in pixels; list containing [width, height] :param diag: diagonal of the screen [inch] :param width: width of the screen [cm] """ mon = monitors.Monitor( monitor_constants['name']) # save or load the monitor if 'res' in monitor_constants: mon.setSizePix( monitor_constants['res'] ) # if one would like to change the resolution of the screen factor = math.sqrt( 1 + mon.getSizePix()[1] / mon.getSizePix()[0]) # for convenience if 'diag' in monitor_constants: mon.setNotes(dict(diag=monitor_constants['diag'])) mon.setWidth( mon.getNotes()['diag'] * inch * 100 / factor ) # compute width [cm] from screen diagonal [inches] and pixel size elif 'width' in monitor_constants: mon.setWidth = monitor_constants['width'] mon.setNotes(dict(diag=mon.getWidth() * factor / inch / 100)) if 'viewing_distance' in monitor_constants: mon.setDistance( monitor_constants['viewing_distance']) # distance to monitor in cm print( 'Using monitor {mon:s} of {diag:d}" {pix_w:d}×{pix_h:d} pixels, viewed at a distance of {dist:d} cm' .format(mon=mon.name, diag=mon.getNotes()['diag'], pix_w=mon.getSizePix()[0], pix_h=mon.getSizePix()[1], dist=mon.getDistance())) all_monitors = monitors.getAllMonitors() if mon.name in all_monitors: save = input( 'A monitor with this name already exists. Do you want to save the new configuration to disk under the name {}? [[Y]]es / [N]o / [R]ename ' .format(mon.name)).upper() if save in {'Y', ''}: mon.save() elif save == 'R': mon.name = input('Specify the new monitor name: ') print('Monitor succesfully saved under {}'.format(mon.name)) return mon
def _createPsychopyCalibrationFile(self): display_config = self.getConfiguration() override_using_psycho_settings = display_config.get("override_using_psycho_settings", False) psychopy_monitor_name = display_config.get("psychopy_monitor_name", None) if psychopy_monitor_name is None or psychopy_monitor_name == "None": return False from psychopy import monitors existing_monitors = monitors.getAllMonitors() psychoMonitor = None if override_using_psycho_settings is True and psychopy_monitor_name in existing_monitors: psychoMonitor = monitors.Monitor(psychopy_monitor_name) px, py = self.getPixelResolution() mwidth = psychoMonitor.getWidth() * 10.0 aspect_ratio = px / float(py) mheight = mwidth / aspect_ratio display_config["physical_dimensions"]["width"] = mwidth display_config["physical_dimensions"]["height"] = mheight display_config["physical_dimensions"]["unit_type"] = "mm" display_config["default_eye_distance"]["surface_center"] = psychoMonitor.getDistance() * 10.0 display_config["default_eye_distance"]["unit_type"] = "mm" else: stim_area = display_config.get("physical_dimensions") dwidth = stim_area["width"] # switch from mm to cm if required dw_unit_type = stim_area["unit_type"] if dw_unit_type == "mm": dwidth = dwidth / 10.0 ddist = self.getDefaultEyeDistance() unit_type = self.getConfiguration()["default_eye_distance"]["unit_type"] # switch from mm to cm if required if unit_type == "mm": ddist = ddist / 10.0 psychoMonitor = monitors.Monitor(psychopy_monitor_name, width=dwidth, distance=ddist, gamma=1.0) psychoMonitor.setSizePix(list(self.getPixelResolution())) psychoMonitor.saveMon() self._psychopy_monitor = psychoMonitor return True
def updateMonList(self): #refresh list of all available monitors on path monList = monitors.getAllMonitors() self.ctrlMonList.Set(monList) #if we had selected a monitor, make sure it's still selected if len(monList)>0: if self.currentMonName!=None: self.ctrlMonList.SetStringSelection(self.currentMonName) else: self.ctrlMonList.SetSelection(0) self.onChangeMonSelection(event=-1) #do we need to update the calibList always after this? return 1 else: #there are no monitors - create an empty one to popoulate the fields self.currentMon = monitors.Monitor('',verbose=False) self.currentMonName=None return 0 #there were no monitors on the path
def updateMonList(self): #refresh list of all available monitors on path monList = monitors.getAllMonitors() self.ctrlMonList.Set(monList) #if we had selected a monitor, make sure it's still selected if len(monList) > 0: if self.currentMonName != None: self.ctrlMonList.SetStringSelection(self.currentMonName) else: self.ctrlMonList.SetSelection(0) self.onChangeMonSelection(event=-1) #do we need to update the calibList always after this? return 1 else: #there are no monitors - create an empty one to popoulate the fields self.currentMon = monitors.Monitor('', verbose=False) self.currentMonName = None return 0 #there were no monitors on the path
# -*- coding: utf-8 -*- """ Often you can control monitors simply from the Monitor Center in the PsychoPy application, but you can also create/control them using scripts. This allow you to override certain values for the current run: : mon = monitors.Monitor('testMonitor') # load the testMonitor mon.setDistance(120) # change distance in this run (don't save) Or you can load a specific calibration of that monitor: mon.setCurrent(-1) is the last (alphabetical) calibration mon.setCurrent('2015_05_21 11:42') # use a specific named calibration More info is available at http: //www.psychopy.org/api/monitors.html """ from __future__ import division from __future__ import print_function from psychopy import monitors names = monitors.getAllMonitors() for thisName in names: thisMon = monitors.Monitor(thisName) print(thisMon.getDistance()) # The contents of this file are in the public domain.
# import time import copy import random import csv import os import glob from psychopy import visual, core, data, event, gui, monitors, logging, info, parallel import matplotlib.pyplot as plt from pygame import time from ctypes import windll P = windll.inpoutx64 random.seed(2) mon = monitors.Monitor("testMonitor", width=53.2, distance=65.0) for mon in monitors.getAllMonitors(): print(mon, monitors.Monitor(mon).getSizePix()) # if mon = "testMonitor": # monitorSize = monitors.Monitor(mon).getSizePix() screenSize = [1920, 1080] # screenRatio = screenSize[0] / screenSize[1] # if screenSize == monitorSize: # print("Screen size has been set correctly") # get a list of stimuli # test list of stimuli #filepath = 'generatestimuli/Subj' +str(partInfo[0]) +'/' filepath = 'generatestimuli/Formal/Subj44/' extension = 'csv' os.chdir(filepath) files = glob.glob('*.{}'.format(extension)) #print(files) #rawpath = 'C:/Users/EEGExp/Desktop/Project_GMD/pro/'
#stimSize = 384 ############## If you want to change from left/right arrow ################# responseKeys = ['left', 'right'] ###################### Number of images ######################## numImages = 100 # if you want to do fewer than all 100, lower this ################### Timing info #################### stimDuration = 1 #seconds fixationBaseTime = 0.5 #seconds fixationDelta = 0.7 #seconds responseTimeout = 7 #seconds ################### Monitor setup ###################### localMonitors = monitors.getAllMonitors() ################## Subject setup ################# runInfo = {'Subject': 'test', 'Run number': 1} infoDlg = gui.DlgFromDict(dictionary=runInfo, order=['Subject', 'Run number']) if infoDlg.OK: print runInfo else: print 'User cancelled' #file for storing subject responses if not os.path.exists('response_data'): os.makedirs('response_data') outputFile = os.path.join( 'response_data', 'FAOT_%s_run%02d_%04d%02d%02d_%02d%02d.txt' % (runInfo['Subject'], runInfo['Run number'], nowTime.year, nowTime.month,
def setup_params(stim_fname): """ Configures the parameters of stimulus presentation. """ # Take view settings view_settings_file = os.path.join( os.path.dirname(os.path.dirname(stim_fname)), 'view_settings.txt') f_handle = open(view_settings_file, 'r') view_settings = {} for line in f_handle: line = re.sub('\n', '', line) line = re.sub('\r', '', line) line = line.split('\t') if line[0]: # If there is input view_settings[line[0]] = float(line[1]) # Put them in a gui so they can be modified and seen before stimulation options_panel = gui.Dlg(title="PyStim options") options_panel.addText('Enter desired run options') options_panel.addText( "Below are default options determined from view_setting.txt") options_panel.addField('Monitor settings:', choices=monitors.getAllMonitors()) # idx: 0 options_panel.addText( "Check monitor settings from PsychoPy app and make sure that \n they are correct." ) # DLP and NIDAQ options_panel.addField('use DLP:', initial=True) # idx: 1 options_panel.addField('use NIDAQ:', initial=True) # idx: 2 # Screen settings options_panel.addText("Settings for the screen") options_panel.addField('Refresh rate:', view_settings['screen_refresh_rate']) # idx: 3 options_panel.addText("Refresh rate has to match with the screen's") # Stimulus window settings options_panel.addText("Settings for the stimulus window") options_panel.addField('Stim win pos X:', view_settings['stim_pos_x']) # idx: 4 options_panel.addField('Stim win pos Y:', view_settings['stim_pos_y']) # idx: 5 # Presentation settings options_panel.addText("Settings for the stimulus presentation") options_panel.addField('Stim units:', choices=["deg", "degFlat", "degFlatPos"]) # idx: 6 options_panel.addField('Bit depth:', 6) # idx: 7 options_panel.addField('use warper:', initial=True) # idx: 8 options_panel.addField('view scale X:', view_settings['view_scale_x']) # idx: 9 options_panel.addField('view scale Y:', view_settings['view_scale_y']) # idx: 10 user_entry = options_panel.show() mon = monitors.Monitor(user_entry[0]) stim_size_X = np.arctan((mon.getWidth() / 2) / mon.getDistance()) stim_size_X = abs(np.degrees(stim_size_X)) * 2 # we need the full extend stim_size_Y = np.arctan((mon.getWidth() / 2) / mon.getDistance()) stim_size_Y = abs(np.degrees(stim_size_Y)) * 2 proj_params = { "unit": user_entry[6], "bit_depth": float(user_entry[7]), "warper": user_entry[8], "sizeX": stim_size_X, "sizeY": stim_size_Y, "posX": float(user_entry[4]), "posY": float(user_entry[5]), "win_width_pix": mon.getSizePix()[0], # Pixel size from the monitor center "win_height_pix": mon.getSizePix()[1], "onDLP": int(user_entry[1]), # 1 is for DLP 0 is for PC monitors "monitorName": mon.name, "monitorSizePix": mon.getSizePix(), "monitorWidthcm": mon.getWidth(), "observerDistancecm": mon.getDistance(), "monitorRefreshRate": float(user_entry[3]), "viewScale": [float(user_entry[9]), float(user_entry[10])] } print(proj_params) return proj_params, user_entry[2]
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Often you can control monitors simply from the Monitor Center in the PsychoPy application, but you can also create/control them using scripts. This allow you to override certain values for the current run: : mon = monitors.Monitor('testMonitor') # load the testMonitor mon.setDistance(120) # change distance in this run (don't save) Or you can load a specific calibration of that monitor: mon.setCurrent(-1) is the last (alphabetical) calibration mon.setCurrent('2015_05_21 11:42') # use a specific named calibration More info is available at http: //www.psychopy.org/api/monitors.html """ from __future__ import division from psychopy import monitors names = monitors.getAllMonitors() for thisName in names: thisMon = monitors.Monitor(thisName) print(thisMon.getDistance()) # The contents of this file are in the public domain.
def get_available_monitors(): from psychopy import monitors return monitors.getAllMonitors()
import sys from collections import OrderedDict sys.path.append('c:\workspace') import dUtils.configFiles as configFiles sys.path.append('./submodules') from psychopy import monitors monList = monitors.getAllMonitors() obj = monitors.Monitor(monList[0]) output = '### loading monitors ###\n' output += 'import %s\n' % obj.__class__.__module__ default = monitors.Monitor(' ') for nameStr in monList: mon = monitors.Monitor(nameStr) name = 'mon_%s' % (nameStr) diff = configFiles.dictDiff(mon.currentCalib, default.currentCalib) output += '%s = %s.%s(name="%s")\n' % (name, mon.__class__.__module__, mon.__class__.__name__, nameStr) diff = [i for i in diff.__dir__() if i[:2] != '__'] diff.sort() for k in diff: output += '%s.currentCalib[%r] = %r\n' % (name, k, mon.currentCalib[k]) output += '\n' configFiles.saveModule('config.py', output)
def testCallWithFloatDimensions(self): tobii_helper = calibrator.TobiiHelper() tobii_helper.disableLogging() tobii_helper.setMonitor(dimensions = (1366.0, 768.0)) self.assertEqual(monitors.getAllMonitors()[0], tobii_helper.getMonitorName()) self.assertEqual((1366.0, 768.0), tobii_helper.getMonitorDimensions())
if __name__ == '__main__': # Define new monitors # ------------------- # My Lenovo P51 monitor my_monitor = monitors.Monitor(name='p51') my_monitor.setSizePix((3840, 2160)) my_monitor.setWidth(34.6) # width of display in cm my_monitor.setDistance(50) # distance of eyes from screen in cm my_monitor.saveMon() # My Dell Latitude 7490 monitor my_monitor = monitors.Monitor(name='latitude7490') my_monitor.setSizePix((1920, 1080)) my_monitor.setWidth(30) my_monitor.setDistance(50) # distance of eyes from screen in cm my_monitor.saveMon() # Eizo Foris monitor in the lab my_monitor = monitors.Monitor(name='eizoforis') my_monitor.setSizePix((2560, 1440)) my_monitor.setWidth(60) my_monitor.setDistance(50) # distance of eyes from screen in cm my_monitor.saveMon() # Add new monitor below # Print all available monitors print(monitors.getAllMonitors())
from serial import Serial from datetime import datetime logging.console.setLevel(logging.CRITICAL) def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): return [atoi(c) for c in re.split('(\d+)', text)] monitor_list = monitors.getAllMonitors() print(monitor_list) parser = optparse.OptionParser() parser.add_option('-i', '--animalid', action='store', dest='animalid', default='', help='Animal ID') parser.add_option('-S', '--session', action='store', dest='session', default='', help='session dir (format: YYYMMDD')
#import Image, ImageSequence import re import glob #import h5py import cPickle as pkl from datetime import datetime logging.console.setLevel(logging.CRITICAL) def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): return [ atoi(c) for c in re.split('(\d+)', text) ] monitor_list = monitors.getAllMonitors() parser = optparse.OptionParser() parser.add_option('--no-camera', action="store_false", dest="acquire_images", default=True, help="just run PsychoPy protocol") parser.add_option('--save-images', action="store_true", dest="save_images", default=False, help="save camera frames to disk") parser.add_option('--output-path', action="store", dest="output_path", default="/tmp/", help="out path directory [default: /tmp/frames]") parser.add_option('--output-format', action="store", dest="output_format", type="choice", choices=['tiff', 'npz'], default='tiff', help="out file format, tiff or npz [default: tiff]") parser.add_option('--use-pvapi', action="store_true", dest="use_pvapi", default=True, help="use the pvapi") parser.add_option('--use-opencv', action="store_false", dest="use_pvapi", help="use some other camera") parser.add_option('--fullscreen', action="store_true", dest="fullscreen", default=True, help="display full screen [defaut: True]") parser.add_option('--debug-window', action="store_false", dest="fullscreen", help="don't display full screen, debug mode") parser.add_option('--write-process', action="store_true", dest="save_in_separate_process", default=True, help="spawn process for disk-writer [default: True]") parser.add_option('--write-thread', action="store_false", dest="save_in_separate_process", help="spawn threads for disk-writer") parser.add_option('--monitor', action="store", dest="whichMonitor", default="testMonitor", help=str(monitor_list)) parser.add_option('--subjectID', action="store", dest="subjectID", default="testRun", help="Subject ID for paradigm files") (options, args) = parser.parse_args()
def __init__(self, params=None, reportobj=None, subroutines=[]): logging.LogFile(params['cwd'] + os.sep + params['logfile'], level=logging.INFO, filemode='w') logging.LogFile(level=logging.ERROR) logging.info('Using Python ' + sys.version) self.args = sys.argv self.params = self.update_params(self.args, params) self.win = None self.model = None self.routines = subroutines self.thisExp = None self.name = params['name'] self.cwd = params['cwd'] self.reportobj = reportobj if params['monitor'] not in monitors.getAllMonitors(): logging.error('monitor not found: ' + params.monitor) logging.info('available monitors: ' + ' '.join(monitors.getAllMonitors())) logging.info('Define monitor in monitor center.') logging.info('To launch monitor center, type:\n' 'python -m psychopy.monitors.MonitorCenter') core.quit() else: self.monitor = monitors.Monitor( '', width=None, distance=self.params['viewing_distance'], gamma=None, notes=None, useBits=None, verbose=True, currentCalib=None, autoLog=True) self.monitor.setSizePix((1920, 1280)) self.monitor.setWidth(54.15) logging.exp('using monitor: ' + self.params['monitor'] + ' with viewing_distance=' + str(self.params['viewing_distance']) + ' cm\n' + ' resolution (pixel/deg): ' + str(deg2pix(1, self.monitor))) # TODO: change screen_pixel_size back to calculation from monitor # TODO: change the monitor definition width so that screen_pixel_size=0.282 if 'screen_pixel_size' not in self.params['model']: self.params['model']['screen_pixel_size'] = pix2cm( 1, self.monitor) * 10.0 #self.params['model']['screen_pixel_size'] = 0.282 self.params['model'][ 'viewing_distance'] = self.params['viewing_distance'] / 2.54 self.expInfo = params['exp_info'] self.expInfo['date'] = data.getDateStr() # Ensure that relative paths start from the same directory as this script _thisDir = os.path.dirname(os.path.abspath(__file__)) os.chdir(_thisDir) # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc runsubject = self.params['runsubject'] if runsubject: self.filename = self.cwd + os.sep + u'data' + os.sep + '%s_%s_%s' % ( self.expInfo['participant'], params['name'], self.expInfo['date']) else: self.filename = self.cwd + os.sep + u'data' + os.sep + 'model-' + params[ 'expName']