id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
5,600
__init__.py
psychopy_psychopy/psychopy/experiment/components/parallelOut/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy.experiment.components import BaseComponent, Param, _translate from psychopy import prefs class ParallelOutComponent(BaseComponent): """A class for sending signals from the parallel port""" categories = ['I/O', 'EEG'] targets = ['PsychoPy'] iconFile = Path(__file__).parent / 'parallel.png' tooltip = _translate('Parallel out: send signals from the parallel port') def __init__(self, exp, parentName, name='p_port', startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim='', address=None, register='EIO', startData="1", stopData="0", syncScreen=True): super(ParallelOutComponent, self).__init__( exp, parentName, name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'ParallelOut' self.url = "https://www.psychopy.org/builder/components/parallelout.html" self.exp.requirePsychopyLibs(['parallel']) # params self.order += [ 'startData', 'stopData', # Data tab 'address', 'register', # Hardware tab ] # main parameters addressOptions = prefs.hardware['parallelPorts'] + [u'LabJack U3'] + [u'USB2TTL8'] if not address: address = addressOptions[0] msg = _translate("Parallel port to be used (you can change these " "options in preferences>general)") self.params['address'] = Param( address, valType='str', inputType="choice", allowedVals=addressOptions, categ='Hardware', hint=msg, label=_translate("Port address")) self.depends.append( {"dependsOn": "address", # must be param name "condition": "=='LabJack U3'", # val to check for "param": "register", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) msg = _translate("U3 Register to write byte to") self.params['register'] = Param(register, valType='str', inputType="choice", allowedVals=['EIO', 'FIO'], categ='Hardware', hint=msg, label=_translate("U3 register")) self.params['startData'] = Param( startData, valType='code', inputType="single", allowedTypes=[], categ='Data', hint=_translate("Data to be sent at 'start'"), label=_translate("Start data")) self.params['stopData'] = Param( stopData, valType='code', inputType="single", allowedTypes=[], categ='Data', hint=_translate("Data to be sent at 'end'"), label=_translate("Stop data")) msg = _translate("If the parallel port data relates to visual " "stimuli then sync its pulse to the screen refresh") self.params['syncScreen'] = Param( syncScreen, valType='bool', inputType="bool", categ='Data', allowedVals=[True, False], updates='constant', allowedUpdates=[], hint=msg, label=_translate("Sync to screen")) def writeInitCode(self, buff): if self.params['address'].val == 'LabJack U3': code = ("from psychopy.hardware import labjacks\n" "%(name)s = labjacks.U3()\n" "%(name)s.status = None\n" % self.params) buff.writeIndentedLines(code) elif self.params['address'].val == 'USB2TTL8': code = ("from psychopy.hardware import labhackers\n" "%(name)s = labhackers.USB2TTL8()\n" "%(name)s.status = None\n" % self.params) buff.writeIndentedLines(code) else: code = ("%(name)s = parallel.ParallelPort(address=%(address)s)\n" % self.params) buff.writeIndented(code) def writeFrameCode(self, buff): """Write the code that will be called every frame """ routineClockName = self.exp.flow._currentRoutine._clockName buff.writeIndented("# *%s* updates\n" % (self.params['name'])) # writes an if statement to determine whether to draw etc indented = self.writeStartTestCode(buff) if indented: buff.writeIndented("%(name)s.status = STARTED\n" % self.params) if self.params['address'].val == 'LabJack U3': if not self.params['syncScreen'].val: code = "%(name)s.setData(int(%(startData)s), address=%(register)s)\n" % self.params else: code = ("win.callOnFlip(%(name)s.setData, int(%(startData)s), address=%(register)s)\n" % self.params) else: if not self.params['syncScreen'].val: code = "%(name)s.setData(int(%(startData)s))\n" % self.params else: code = ("win.callOnFlip(%(name)s.setData, int(%(startData)s))\n" % self.params) buff.writeIndented(code) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) # test for stop (only if there was some setting for duration or stop) indented = self.writeStopTestCode(buff) if indented: if self.params['address'].val == 'LabJack U3': if not self.params['syncScreen'].val: code = "%(name)s.setData(int(%(stopData)s), address=%(register)s)\n" % self.params else: code = ("win.callOnFlip(%(name)s.setData, int(%(stopData)s), address=%(register)s)\n" % self.params) else: if not self.params['syncScreen'].val: code = "%(name)s.setData(int(%(stopData)s))\n" % self.params else: code = ("win.callOnFlip(%(name)s.setData, int(%(stopData)s))\n" % self.params) buff.writeIndented(code) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) # dedent # buff.setIndentLevel(-dedentAtEnd, relative=True)#'if' statement of the # time test and button check def writeRoutineEndCode(self, buff): # make sure that we do switch to stopData if the routine has been # aborted before our 'end' buff.writeIndented("if %(name)s.status == STARTED:\n" % self.params) if self.params['address'].val == 'LabJack U3': if not self.params['syncScreen'].val: code = " %(name)s.setData(int(%(stopData)s), address=%(register)s)\n" % self.params else: code = (" win.callOnFlip(%(name)s.setData, int(%(stopData)s), address=%(register)s)\n" % self.params) else: if not self.params['syncScreen'].val: code = " %(name)s.setData(int(%(stopData)s))\n" % self.params else: code = (" win.callOnFlip(%(name)s.setData, int(%(stopData)s))\n" % self.params) buff.writeIndented(code) # get parent to write code too (e.g. store onset/offset times) super().writeRoutineEndCode(buff)
7,841
Python
.py
150
39.293333
108
0.566227
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,601
__init__.py
psychopy_psychopy/psychopy/experiment/components/joyButtons/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy.experiment.components import BaseComponent, Param, _translate from psychopy.experiment import CodeGenerationException, valid_var_re class JoyButtonsComponent(BaseComponent): """An event class for checking the joyButtons at given timepoints""" # an attribute of the class, determines the section in components panel categories = ['Responses'] targets = ['PsychoPy'] iconFile = Path(__file__).parent / 'joyButtons.png' tooltip = _translate('JoyButtons: check and record joystick/gamepad button presses') def __init__(self, exp, parentName, name='button_resp', allowedKeys="0,1,2,3,4", store='last key', forceEndRoutine=True, storeCorrect=False, correctAns="", startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal='', startEstim='', durationEstim='', deviceNumber='0', syncScreenRefresh=True): super(JoyButtonsComponent, self).__init__( exp, parentName, name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'JoyButtons' self.url = "https://www.psychopy.org/builder/components/joyButtons.html" self.exp.requirePsychopyLibs(['gui']) self.order += ['forceEndRoutine', # Basic tab 'allowedKeys', 'store', 'storeCorrect', 'correctAns', # Data tab 'deviceNumber', # Hardware tab ] msg = _translate( "A comma-separated list of button numbers, such as " "0,1,2,3,4") self.params['allowedKeys'] = Param( allowedKeys, valType='list', inputType="single", allowedTypes=[], categ='Data', updates='constant', allowedUpdates=['constant', 'set every repeat'], hint=(msg), label=_translate("Allowed buttons")) msg = _translate("Choose which (if any) responses to store at the " "end of a trial") self.params['store'] = Param( store, valType='str', inputType="choice", allowedTypes=[], categ='Data', allowedVals=['last key', 'first key', 'all keys', 'nothing'], updates='constant', direct=False, hint=msg, label=_translate("Store")) msg = _translate("Should a response force the end of the Routine " "(e.g end the trial)?") self.params['forceEndRoutine'] = Param( forceEndRoutine, valType='bool', inputType="bool", allowedTypes=[], categ='Basic', updates='constant', hint=msg, label=_translate("Force end of Routine")) msg = _translate("Do you want to save the response as " "correct/incorrect?") self.params['storeCorrect'] = Param( storeCorrect, valType='bool', inputType="bool", allowedTypes=[], categ='Data', updates='constant', hint=msg, label=_translate("Store correct")) self.depends += [ # allows params to turn each other off/on {"dependsOn": "storeCorrect", # must be param name "condition": "== True", # val to check for "param": "correctAns", # param property to alter "true": "enable", # what to do with param if condition is True "false": "disable", # permitted: hide, show, enable, disable } ] msg = _translate( "What is the 'correct' key? Might be helpful to add a " "correctAns column and use $correctAns to compare to the key " "press.") self.params['correctAns'] = Param( correctAns, valType='list', inputType="single", allowedTypes=[], categ='Data', updates='constant', hint=msg, label=_translate("Correct answer")) msg = _translate( "A reaction time to a visual stimulus should be based on when " "the screen flipped") self.params['syncScreenRefresh'] = Param( syncScreenRefresh, valType='bool', inputType="bool", categ='Data', updates='constant', hint=msg, label=_translate("Sync RT with screen")) msg = _translate( "Device number, if you have multiple devices which" " one do you want (0, 1, 2...)") self.params['deviceNumber'] = Param( deviceNumber, valType='int', inputType="int", allowedTypes=[], categ='Hardware', updates='constant', allowedUpdates=[], hint=msg, label=_translate("Device number")) def writeStartCode(self, buff): code = ("from psychopy.hardware import joystick as joysticklib " "# joystick/gamepad accsss\n" "from psychopy.experiment.components.joyButtons import " "virtualJoyButtons as virtualjoybuttonslib\n") buff.writeIndentedLines(code % self.params) def writeInitCode(self, buff): code = ("%(name)s = type('', (), {})() " "# Create an object to use as a name space\n" "%(name)s.device = None\n" "%(name)s.device_number = %(deviceNumber)s\n" "\n" "try:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("numJoysticks = joysticklib.getNumJoysticks()\n" "if numJoysticks > 0:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("%(name)s.device = joysticklib.Joystick(%(deviceNumber)s)\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) buff.setIndentLevel(+1, relative=True) code = ("try:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("joystickCache\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("except NameError:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("joystickCache={}\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("if not %(deviceNumber)s in joystickCache:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("joystickCache[%(deviceNumber)s] = joysticklib.Joystick(%(deviceNumber)s)\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("%(name)s.device = joystickCache[%(deviceNumber)s]\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("else:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("%(name)s.device = virtualjoybuttonslib.VirtualJoyButtons(%(deviceNumber)s)\n" "logging.warning(\"joystick_{}: " "Using keyboard emulation 'ctrl' + 'Alt' + digit.\".format(%(name)s.device_number))\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) buff.setIndentLevel(-1, relative=True) code = ("except Exception:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("pass\n\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("if not %(name)s.device:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("logging.error('No joystick/gamepad device found.')\n" "core.quit()\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("\n" "%(name)s.status = None\n" "%(name)s.clock = core.Clock()\n" "%(name)s.numButtons = %(name)s.device.getNumButtons()\n") buff.writeIndentedLines(code % self.params) buff.writeIndented("\n") def writeRoutineStartCode(self, buff): code = ("{name}.oldButtonState = {name}.device.getAllButtons()[:]\n" "{name}.keys = []\n" "{name}.rt = []\n" ) buff.writeIndentedLines(code.format(**self.params)) if (self.params['store'].val == 'nothing' and self.params['storeCorrect'].val == False): # the user doesn't want to store anything so don't bother return def writeFrameCode(self, buff): """Write the code that will be called every frame """ # some shortcuts store = self.params['store'].val storeCorr = self.params['storeCorrect'].val forceEnd = self.params['forceEndRoutine'].val allowedKeys = self.params['allowedKeys'].val.strip() buff.writeIndented("\n") buff.writeIndented("# *%s* updates\n" % self.params['name']) # writes an if statement to determine whether to draw etc allowedKeysIsVar = (valid_var_re.match(str(allowedKeys)) and not allowedKeys == 'None') indented = self.writeStartTestCode(buff) if indented: if allowedKeysIsVar: # if it looks like a variable, check that the variable is suitable # to eval at run-time code = ("# AllowedKeys looks like a variable named `{0}`\n" "if not type({0}) in [list, tuple, np.ndarray]:\n") buff.writeIndentedLines(code.format(allowedKeys)) buff.setIndentLevel(1, relative=True) code = ("if type({0}) == int:\n") buff.writeIndentedLines(code.format(allowedKeys)) buff.setIndentLevel(1, relative=True) code = ("{0} = [{0}]\n") buff.writeIndentedLines(code.format(allowedKeys)) buff.setIndentLevel(-1, relative=True) code = ("elif not (isinstance({0}, str) " "or isinstance({0}, unicode)):\n") buff.writeIndentedLines(code.format(allowedKeys)) buff.setIndentLevel(1, relative=True) code = ("logging.error('AllowedKeys variable `{0}` is " "not string- or list-like.')\n" "core.quit()\n") buff.writeIndentedLines(code.format(allowedKeys)) buff.setIndentLevel(-1, relative=True) code = ( "elif not ',' in {0}: {0} = eval(({0},))\n" "else: {0} = eval({0})\n") buff.writeIndentedLines(code.format(allowedKeys)) buff.setIndentLevel(-1, relative=True) buff.writeIndented("# joyButtons checking is just starting\n") if store != 'nothing': if self.params['syncScreenRefresh'].val: code = ("win.callOnFlip(%(name)s.clock.reset) # t=0 on next" " screen flip\n") % self.params else: code = "%(name)s.clock.reset() # now t=0\n" % self.params buff.writeIndented(code) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) # test for stop (only if there was some setting for duration or stop) indented = self.writeStopTestCode(buff) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) buff.writeIndented("if %(name)s.status == STARTED:\n" % self.params) buff.setIndentLevel(1, relative=True) # to get out of if statement dedentAtEnd = 1 # keep track of how far to dedent later # do we need a list of keys? (variable case is already handled) if allowedKeys in [None, "none", "None", "", "[]", "()"]: keyList=[] elif not allowedKeysIsVar: keyList = self.params['allowedKeys'] code1 = ("{name}.newButtonState = {name}.device.getAllButtons()[:]\n" "{name}.pressedButtons = []\n" "{name}.releasedButtons = []\n" "{name}.newPressedButtons = []\n" "if {name}.newButtonState != {name}.oldButtonState:\n") code2 = ("{name}.pressedButtons = [i for i in range({name}.numButtons) " "if {name}.newButtonState[i] and not {name}.oldButtonState[i]]\n" "{name}.releasedButtons = [i for i in range({name}.numButtons) " "if not {name}.newButtonState[i] and {name}.oldButtonState[i]]\n" "{name}.oldButtonState = {name}.newButtonState\n" "{name}.newPressedButtons = " "[i for i in {0} if i in {name}.pressedButtons]\n" "[logging.data(\"joystick_{{}}_button: {{}}\".format(" "{name}.device_number,i)) for i in {name}.pressedButtons]\n" ) if allowedKeysIsVar: buff.writeIndentedLines(code1.format(allowedKeys, **self.params)) buff.setIndentLevel(+1, relative=True) buff.writeIndentedLines(code2.format(allowedKeys, **self.params)) buff.setIndentLevel(-1, relative=True) else: if keyList == []: buff.writeIndentedLines(code1.format(allowedKeys, **self.params)) buff.setIndentLevel(+1, relative=True) buff.writeIndentedLines(code2.format( "range({name}.numButtons)".format(**self.params), **self.params)) buff.setIndentLevel(-1, relative=True) else: buff.writeIndentedLines(code1.format(allowedKeys, **self.params)) buff.setIndentLevel(+1, relative=True) buff.writeIndentedLines( code2.format("{}".format(keyList), **self.params)) buff.setIndentLevel(-1, relative=True) code = ( "theseKeys = %(name)s.newPressedButtons\n" ) buff.writeIndented(code % self.params) if self.exp.settings.params['Enable Escape'].val: code = ('\n# check for quit:\n' 'if "escape" in theseKeys:\n' ' endExpNow = True\n') # how do we store it? if store != 'nothing' or forceEnd: # we are going to store something code = "if len(theseKeys) > 0: # at least one key was pressed\n" buff.writeIndented(code) buff.setIndentLevel(1, True) dedentAtEnd += 1 # indent by 1 if store == 'first key': # then see if a key has already been pressed code = ("if %(name)s.keys == []: # then this was the first " "keypress\n") % self.params buff.writeIndented(code) buff.setIndentLevel(1, True) dedentAtEnd += 1 # indent by 1 code = ("%(name)s.keys = theseKeys[0] # just the first key pressed\n" "%(name)s.rt = %(name)s.clock.getTime()\n") buff.writeIndentedLines(code % self.params) elif store == 'last key': code = ("%(name)s.keys = theseKeys[-1] # just the last key pressed\n" "%(name)s.rt = %(name)s.clock.getTime()\n") buff.writeIndentedLines(code % self.params) elif store == 'all keys': code = ("%(name)s.keys.extend(theseKeys) # storing all keys\n" "%(name)s.rt.append(%(name)s.clock.getTime())\n") buff.writeIndentedLines(code % self.params) if storeCorr: code = ("# was this 'correct'?\n" "if (str(%(name)s.keys) == str(%(correctAns)s)):\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("%(name)s.corr = 1\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("else:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("%(name)s.corr = 0\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) if forceEnd == True: code = ("# a response ends the routine\n" "continueRoutine = False\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-(dedentAtEnd), relative=True) def writeRoutineEndCode(self, buff): # some shortcuts name = self.params['name'] store = self.params['store'].val if store == 'nothing': return if len(self.exp.flow._loopList): currLoop = self.exp.flow._loopList[-1] # last (outer-most) loop else: currLoop = self.exp._expHandler # write the actual code code = ("# check responses\n" "if %(name)s.keys in ['', [], None]: # No response was made\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("%(name)s.keys=None\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) if self.params['storeCorrect'].val: # check for correct NON-repsonse buff.setIndentLevel(1, relative=True) code = ("# was no response the correct answer?!\n" "if str(%(correctAns)s).lower() == 'none':\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(1, relative=True) code = ("%(name)s.corr = 1; # correct non-response\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("else:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(1, relative=True) code = ("%(name)s.corr = 0; # failed to respond (incorrectly)\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-2, relative=True) code = ("# store data for %s (%s)\n") buff.writeIndentedLines(code % (currLoop.params['name'], currLoop.type)) if currLoop.type in ['StairHandler', 'MultiStairHandler']: # data belongs to a Staircase-type of object if self.params['storeCorrect'].val is True: code = ("%s.addResponse(%s.corr, level)\n" % (currLoop.params['name'], name) + "%s.addOtherData('%s.rt', %s.rt)\n" % (currLoop.params['name'], name, name)) buff.writeIndentedLines(code) else: # always add keys buff.writeIndented("%s.addData('%s.keys',%s.keys)\n" % (currLoop.params['name'], name, name)) if self.params['storeCorrect'].val == True: buff.writeIndented("%s.addData('%s.corr', %s.corr)\n" % (currLoop.params['name'], name, name)) # only add an RT if we had a response code = ("if %(name)s.keys != None: # we had a response\n" % self.params + " %s.addData('%s.rt', %s.rt)\n" % (currLoop.params['name'], name, name)) buff.writeIndentedLines(code)
20,163
Python
.py
386
39.209845
103
0.568189
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,602
virtualJoyButtons.py
psychopy_psychopy/psychopy/experiment/components/joyButtons/virtualJoyButtons.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). # Support for fake joystick/gamepad during development # if no 'real' joystick/gamepad is available use keyboard emulation # 'ctrl' + 'alt' + numberKey from psychopy import event class VirtualJoyButtons: def __init__(self, device_number): self.device_number = device_number self.numberKeys=['0','1','2','3','4','5','6','7','8','9'] self.modifierKeys=['ctrl','alt'] self.mouse = event.Mouse() event.Mouse(visible=False) # Create .corr property with placeholder value self.corr = False def getNumButtons(self): return len(self.numberKeys) def getAllButtons(self): keys = event.getKeys(keyList=self.numberKeys, modifiers=True) values = [key for key, modifiers in keys if all([modifiers[modKey] for modKey in self.modifierKeys])] self.state = [key in values for key in self.numberKeys] mouseButtons = self.mouse.getPressed() self.state[:len(mouseButtons)] = [a or b != 0 for (a,b) in zip(self.state, mouseButtons)] return self.state
1,288
Python
.py
27
41.851852
109
0.680223
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,603
__init__.py
psychopy_psychopy/psychopy/experiment/components/brush/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy.experiment.components import BaseVisualComponent, Param, getInitVals, _translate class BrushComponent(BaseVisualComponent): """ This component is a freehand drawing tool. """ categories = ['Responses'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'brush.png' tooltip = _translate('Brush: a drawing tool') def __init__(self, exp, parentName, name='brush', lineColor='$[1,1,1]', lineColorSpace='rgb', lineWidth=1.5, opacity=1, buttonRequired=True, startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim=''): super(BrushComponent, self).__init__( exp, parentName, name=name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Brush' self.url = "https://www.psychopy.org/builder/components/brush.html" self.exp.requirePsychopyLibs(['visual']) self.order.remove("opacity") # Move opacity to the end self.order += [ "lineWidth", "lineColor", "lineColorSpace", "opacity" # Appearance tab ] # params msg = _translate("Fill color of this brush") self.params['lineColor'] = Param( lineColor, valType='color', inputType="color", allowedTypes=[], categ='Appearance', updates='constant', allowedUpdates=['constant', 'set every repeat'], hint=msg, label= _translate("Brush color")) msg = _translate("Width of the brush's line (always in pixels and limited to 10px max width)") self.params['lineWidth'] = Param( lineWidth, valType='num', inputType="spin", allowedTypes=[], categ='Appearance', updates='constant', allowedUpdates=['constant', 'set every repeat'], hint=msg, label= _translate("Brush size")) self.params['lineColorSpace'] = self.params['colorSpace'] del self.params['colorSpace'] msg = _translate("The line opacity") self.params['opacity'].hint=msg msg = _translate("Whether a button needs to be pressed to draw (True/False)") self.params['buttonRequired'] = Param( buttonRequired, valType='bool', inputType="bool", allowedTypes=[], categ='Basic', updates='constant', allowedUpdates=['constant', 'set every repeat'], hint=msg, label= _translate("Press button")) # Remove BaseVisual params which are not needed del self.params['color'] # because color is defined by lineColor del self.params['fillColor'] del self.params['borderColor'] del self.params['size'] # because size determined by lineWidth del self.params['ori'] del self.params['pos'] del self.params['units'] # always in pix def writeInitCode(self, buff): inits = getInitVals(self.params) inits['depth'] = -self.getPosInRoutine() code = ( "{name} = visual.Brush(win=win, name='{name}',\n" " lineWidth={lineWidth},\n" " lineColor={lineColor},\n" " lineColorSpace={lineColorSpace},\n" " opacity={opacity},\n" " buttonRequired={buttonRequired},\n" " depth={depth}\n" ")" ).format(**inits) buff.writeIndentedLines(code) def writeInitCodeJS(self, buff): # JS code does not use Brush class params = getInitVals(self.params) params['depth'] = -self.getPosInRoutine() code = ("{name} = {{}};\n" "get{name} = function() {{\n" " return ( new visual.ShapeStim({{\n" " win: psychoJS.window,\n" " vertices: [[0, 0]],\n" " lineWidth: {lineWidth},\n" " lineColor: new util.Color({lineColor}),\n" " opacity: {opacity},\n" " closeShape: false,\n" " autoLog: false,\n" " depth: {depth}\n" " }}))\n" "}}\n\n").format(**params) buff.writeIndentedLines(code) # add reset function code = ("{name}Reset = {name}.reset = function() {{\n" " if ({name}Shapes.length > 0) {{\n" " for (let shape of {name}Shapes) {{\n" " shape.setAutoDraw(false);\n" " }}\n" " }}\n" " {name}AtStartPoint = false;\n" " {name}Shapes = [];\n" " {name}CurrentShape = -1;\n" "}}\n\n").format(name=params['name']) buff.writeIndentedLines(code) # Define vars for drawing code = ("{name}CurrentShape = -1;\n" "{name}BrushPos = [];\n" "{name}Pointer = new core.Mouse({{win: psychoJS.window}});\n" "{name}AtStartPoint = false;\n" "{name}Shapes = [];\n").format(name=params['name']) buff.writeIndentedLines(code) def writeRoutineStartCode(self, buff): # Write update code super(BrushComponent, self).writeRoutineStartCode(buff) # Reset shapes for each trial buff.writeIndented("{}.reset()\n".format(self.params['name'])) def writeRoutineStartCodeJS(self, buff): # Write update code # super(BrushComponent, self).writeRoutineStartCodeJS(buff) # Reset shapes for each trial buff.writeIndented("{}Reset();\n".format(self.params['name'])) def writeFrameCodeJS(self, buff): code = ("if ({name}Pointer.getPressed()[0] === 1 && {name}AtStartPoint != true) {{\n" " {name}AtStartPoint = true;\n" " {name}BrushPos = [];\n" " {name}Shapes.push(get{name}());\n" " {name}CurrentShape += 1;\n" " {name}Shapes[{name}CurrentShape].setAutoDraw(true);\n" "}}\n" "if ({name}Pointer.getPressed()[0] === 1) {{\n" " {name}BrushPos.push({name}Pointer.getPos());\n" " {name}Shapes[{name}CurrentShape].setVertices({name}BrushPos);\n" "}} else {{\n" " {name}AtStartPoint = false;\n" "}}\n".format(name=self.params['name'])) buff.writeIndentedLines(code)
6,848
Python
.py
144
36.006944
102
0.554841
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,604
__init__.py
psychopy_psychopy/psychopy/experiment/components/slider/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2015 Jonathan Peirce # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy.experiment.components import BaseVisualComponent, Param, \ getInitVals, _translate from psychopy.experiment import py2js from psychopy import logging from psychopy.data import utils from psychopy.tools.stimulustools import sliderStyles, sliderStyleTweaks import copy __author__ = 'Jon Peirce' knownStyles = sliderStyles knownStyleTweaks = sliderStyleTweaks # ticks = (1, 2, 3, 4, 5), # labels = None, # pos = None, # size = None, # units = None, # flip = False, # style = 'rating', # granularity = 0, # textSize = 1.0, # readOnly = False, # color = 'LightGray', # textFont = 'Helvetica Bold', class SliderComponent(BaseVisualComponent): """A class for presenting a rating scale as a builder component """ categories = ['Responses'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'slider.png' tooltip = _translate('Slider: A simple, flexible object for getting ratings') def __init__(self, exp, parentName, name='slider', labels='', ticks="(1, 2, 3, 4, 5)", initVal="", size='(1.0, 0.1)', pos='(0, -0.4)', flip=False, style='rating', styleTweaks=[], granularity=0, color="LightGray", fillColor='Red', borderColor='White', font="Open Sans", letterHeight=0.05, startType='time (s)', startVal='0.0', stopType='condition', stopVal='', startEstim='', durationEstim='', forceEndRoutine=True, storeRating=True, storeRatingTime=True, storeHistory=False, readOnly=False): super(SliderComponent, self).__init__( exp, parentName, name, pos=pos, size=size, color=color, fillColor=fillColor, borderColor=borderColor, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Slider' self.url = "https://www.psychopy.org/builder/components/slider.html" self.exp.requirePsychopyLibs(['visual', 'event']) # params self.order += ['forceEndRoutine', # Basic tab 'contrast', 'styles', 'styleTweaks', # Appearance tab 'font', # Formatting tab 'flip', # Layout tab 'ticks', 'labels', 'granularity', 'readOnly', # Data tab ] self.order.insert(self.order.index("colorSpace"), "style") self.order.insert(self.order.index("units"), "Item Padding") # normal params: # = the usual as inherited from BaseVisual plus: self.params['ticks'] = Param( ticks, valType='list', inputType="single", allowedTypes=[], categ='Basic', updates='constant', hint=_translate("Tick positions (numerical) on the scale, " "separated by commas"), label=_translate("Ticks")) self.depends.append( { # if... "dependsOn": "styles", # meets... "condition": "=='radio'", # then... "param": "ticks", # should... "true": "disable", # otherwise... "false": "enable", } ) self.params['labels'] = Param( labels, valType='list', inputType="single", allowedTypes=[], categ='Basic', updates='constant', hint=_translate("Labels for the tick marks on the scale, " "separated by commas"), label=_translate("Labels")) self.params['initVal'] = Param( initVal, valType='code', inputType="single", categ='Basic', hint=_translate("Value of the slider befre any response, leave blank to hide the marker until clicked on"), label=_translate("Starting value") ) self.params['granularity'] = Param( granularity, valType='num', inputType="single", allowedTypes=[], categ='Basic', updates='constant', hint=_translate("Specifies the minimum step size " "(0 for a continuous scale, 1 for integer " "rating scale)"), label=_translate("Granularity")) self.depends.append( { # if... "dependsOn": "styles", # meets... "condition": "=='radio'", # then... "param": "granularity", # should... "true": "disable", # otherwise... "false": "enable", } ) self.params['forceEndRoutine'] = Param( forceEndRoutine, valType='bool', inputType="bool", allowedTypes=[], categ='Basic', updates='constant', allowedUpdates=[], hint=_translate("Should setting a rating (releasing the mouse) " "cause the end of the Routine (e.g. trial)?"), label=_translate("Force end of Routine")) self.params['readOnly'] = Param( readOnly, valType='bool', allowedTypes=[], categ='Data', updates='constant', allowedUpdates=[], hint=_translate("Should participant be able to change the rating on the Slider?"), label=_translate("Read only")) # advanced params: self.params['flip'] = Param( flip, valType='bool', inputType="bool", categ='Layout', updates='constant', allowedUpdates=[], hint=_translate( "By default the labels will be on the bottom or " "left of the scale, but this can be flipped to the " "other side."), label=_translate("Flip")) # Color changes self.params['color'].label = _translate("Label color") self.params['color'].hint = _translate("Color of all labels on this slider (might be overridden by the style setting)") self.params['fillColor'].label = _translate("Marker color") self.params['fillColor'].hint = _translate("Color of the marker on this slider (might be overridden by the style setting)") self.params['borderColor'].label = _translate("Line color") self.params['borderColor'].hint = _translate("Color of all lines on this slider (might be overridden by the style setting)") self.params['font'] = Param( font, valType='str', inputType="single", categ='Formatting', updates='constant', hint=_translate( "Font for the labels"), label=_translate("Font")) self.params['letterHeight'] = Param( letterHeight, valType='num', inputType="single", categ='Formatting', updates='constant', hint=_translate( "Letter height for text in labels"), label=_translate("Letter height")) self.params['styles'] = Param( style, valType='str', inputType="choice", categ='Basic', updates='constant', allowedVals=knownStyles, hint=_translate( "Discrete styles to control the overall appearance of the slider."), label=_translate("Styles")) self.params['styleTweaks'] = Param( styleTweaks, valType='list', inputType="multiChoice", categ='Appearance', updates='constant', allowedVals=knownStyleTweaks, hint=_translate( "Tweaks to change the appearance of the slider beyond its style."), label=_translate("Style tweaks")) # data params self.params['storeRating'] = Param( storeRating, valType='bool', inputType="bool", allowedTypes=[], categ='Data', updates='constant', allowedUpdates=[], hint=_translate("store the rating"), label=_translate("Store rating")) self.params['storeRatingTime'] = Param( storeRatingTime, valType='bool', inputType="bool", allowedTypes=[], categ='Data', updates='constant', allowedUpdates=[], hint=_translate("Store the time taken to make the choice (in " "seconds)"), label=_translate("Store rating time")) self.params['storeHistory'] = Param( storeHistory, valType='bool', inputType="bool", allowedTypes=[], categ='Data', updates='constant', allowedUpdates=[], hint=_translate("store the history of (selection, time)"), label=_translate("Store history")) def writeInitCode(self, buff): inits = getInitVals(self.params) # check units if inits['units'].val == 'from exp settings': inits['units'].val = None inits['depth'] = -self.getPosInRoutine() # Use None as a start value if none set inits['initVal'] = inits['initVal'] or None # build up an initialization string for Slider(): initStr = ( "{name} = visual.Slider(win=win, name='{name}',\n" " startValue={initVal}, size={size}, pos={pos}, units={units},\n" " labels={labels}," ) if inits['styles'] == "radio": # If style is radio, granularity should always be 1 initStr += "ticks=None, granularity=1,\n" else: initStr += ( " ticks={ticks}, granularity={granularity},\n" ) initStr += ( " style={styles}, styleTweaks={styleTweaks}, opacity={opacity},\n" " labelColor={color}, markerColor={fillColor}, lineColor={borderColor}, colorSpace={colorSpace},\n" " font={font}, labelHeight={letterHeight},\n" " flip={flip}, ori={ori}, depth={depth}, readOnly={readOnly})\n" ) initStr = initStr.format(**inits) buff.writeIndented(initStr) def writeInitCodeJS(self, buff): inits = getInitVals(self.params) for param in inits: if inits[param].val in ['', None, 'None', 'none']: inits[param].val = 'undefined' # Check for unsupported units if inits['units'].val == 'from exp settings': inits['units'] = copy.copy(self.exp.settings.params['Units']) if inits['units'].val in ['cm', 'deg', 'degFlatPos', 'degFlat']: msg = ("'{units}' units for your '{name}' Slider are not currently supported for PsychoJS: " "switching units to 'height'. Note, this will affect the size and positioning of '{name}'.") logging.warning(msg.format(units=inits['units'].val, name=inits['name'].val)) inits['units'].val = "height" boolConverter = {False: 'false', True: 'true'} sliderStyles = {'slider': 'SLIDER', 'scrollbar': 'SLIDER', '()': 'RATING', 'rating': 'RATING', 'radio': 'RADIO', 'labels45': 'LABELS_45', 'whiteOnBlack': 'WHITE_ON_BLACK', 'triangleMarker': 'TRIANGLE_MARKER', 'choice': 'RADIO'} # If no style given, set default 'rating' as list if len(inits['styles'].val) == 0: inits['styles'].val = 'rating' # reformat styles for JS # concatenate styles and tweaks tweaksList = utils.listFromString(self.params['styleTweaks'].val) if type(inits['styles'].val) == list: # from an experiment <2021.1 stylesList = inits['styles'].val + tweaksList else: stylesList = [inits['styles'].val] + tweaksList stylesListJS = [sliderStyles[this] for this in stylesList] # if not isinstance(inits['styleTweaks'].val, (tuple, list)): # inits['styleTweaks'].val = [inits['styleTweaks'].val] # inits['styleTweaks'].val = ', '.join(["visual.Slider.StyleTweaks.{}".format(adj) # for adj in inits['styleTweaks'].val]) # convert that to string and JS-ify inits['styles'].val = py2js.expression2js(str(stylesListJS)) inits['styles'].valType = 'code' inits['depth'] = -self.getPosInRoutine() # build up an initialization string for Slider(): initStr = ( "{name} = new visual.Slider({{\n" " win: psychoJS.window, name: '{name}',\n" " startValue: {initVal},\n" " size: {size}, pos: {pos}, ori: {ori}, units: {units},\n" " labels: {labels}, fontSize: {letterHeight}," ) if "radio" in str(inits['styles']).lower(): # If style is radio, make sure the slider is marked as categorical initStr += ( " ticks: [],\n" " granularity: 1, style: {styles},\n" ) else: initStr += ( " ticks: {ticks},\n" " granularity: {granularity}, style: {styles},\n" ) initStr += ( " color: new util.Color({color}), markerColor: new util.Color({fillColor}), lineColor: new util.Color({borderColor}), \n" " opacity: {opacity}, fontFamily: {font}, bold: true, italic: false, depth: {depth}, \n" ) initStr = initStr.format(**inits) initStr += (" flip: {flip},\n" "}});\n\n").format(flip=boolConverter[inits['flip'].val]) buff.writeIndentedLines(initStr) def writeRoutineStartCode(self, buff): buff.writeIndented("%(name)s.reset()\n" % (self.params)) self.writeParamUpdates(buff, 'set every repeat') def writeRoutineStartCodeJS(self, buff): buff.writeIndented("%(name)s.reset()\n" % (self.params)) self.writeParamUpdates(buff, 'set every repeat') def writeFrameCode(self, buff): super(SliderComponent, self).writeFrameCode(buff) # Write basevisual frame code forceEnd = self.params['forceEndRoutine'].val if forceEnd: code = ("\n# Check %(name)s for response to end Routine\n" "if %(name)s.getRating() is not None and %(name)s.status == STARTED:\n" " continueRoutine = False") buff.writeIndentedLines(code % (self.params)) def writeFrameCodeJS(self, buff): super(SliderComponent, self).writeFrameCodeJS(buff) # Write basevisual frame code forceEnd = self.params['forceEndRoutine'].val if forceEnd: code = ("\n// Check %(name)s for response to end Routine\n" "if (%(name)s.getRating() !== undefined && %(name)s.status === PsychoJS.Status.STARTED) {\n" " continueRoutine = false; }\n") buff.writeIndentedLines(code % (self.params)) def writeRoutineEndCode(self, buff): name = self.params['name'] if len(self.exp.flow._loopList): currLoop = self.exp.flow._loopList[-1] # last (outer-most) loop else: currLoop = self.exp._expHandler # write the actual code storeTime = self.params['storeRatingTime'].val if self.params['storeRating'].val or storeTime: if currLoop.type in ['StairHandler', 'QuestHandler']: msg = ("# NB PsychoPy doesn't handle a 'correct answer' " "for Slider events so doesn't know what to " "tell a StairHandler (or QuestHandler)\n") buff.writeIndented(msg) elif currLoop.type in ['TrialHandler', 'ExperimentHandler']: loopName = currLoop.params['name'] else: loopName = 'thisExp' if self.params['storeRating'].val == True: code = "%s.addData('%s.response', %s.getRating())\n" buff.writeIndented(code % (loopName, name, name)) if self.params['storeRatingTime'].val == True: code = "%s.addData('%s.rt', %s.getRT())\n" buff.writeIndented(code % (loopName, name, name)) if self.params['storeHistory'].val == True: code = "%s.addData('%s.history', %s.getHistory())\n" buff.writeIndented(code % (loopName, name, name)) # get parent to write code too (e.g. store onset/offset times) super().writeRoutineEndCode(buff) def writeRoutineEndCodeJS(self, buff): name = self.params['name'] if len(self.exp.flow._loopList): currLoop = self.exp.flow._loopList[-1] # last (outer-most) loop else: currLoop = self.exp._expHandler # write the actual code storeTime = self.params['storeRatingTime'].val if self.params['storeRating'].val or storeTime: if currLoop.type in ['StairHandler', 'QuestHandler']: msg = ("/* NB PsychoPy doesn't handle a 'correct answer' " "for Slider events so doesn't know what to " "tell a StairHandler (or QuestHandler)*/\n") buff.writeIndented(msg) if self.params['storeRating'].val == True: code = "psychoJS.experiment.addData('%s.response', %s.getRating());\n" buff.writeIndented(code % (name, name)) if self.params['storeRatingTime'].val == True: code = "psychoJS.experiment.addData('%s.rt', %s.getRT());\n" buff.writeIndented(code % (name, name)) if self.params['storeHistory'].val == True: code = "psychoJS.experiment.addData('%s.history', %s.getHistory());\n" buff.writeIndented(code % (name, name))
18,514
Python
.py
368
37.108696
134
0.54905
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,605
__init__.py
psychopy_psychopy/psychopy/experiment/components/serialOut/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from copy import copy from pathlib import Path from psychopy.tools import stringtools as st from psychopy.experiment.components import BaseComponent, Param, _translate, getInitVals class SerialOutComponent(BaseComponent): """A class for sending signals from the parallel port""" categories = ['I/O', 'EEG'] targets = ['PsychoPy'] version = "2022.2.0" iconFile = Path(__file__).parent / 'serial.png' tooltip = _translate('Serial out: send signals from a serial port') beta = True def __init__(self, exp, parentName, name='serialPort', startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim='', port="COM3", baudrate=9600, bytesize=8, stopbits=1, parity='N', startdata=1, stopdata=0, timeout="", getResponse=False, syncScreenRefresh=False): super(SerialOutComponent, self).__init__( exp, parentName, name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim, syncScreenRefresh=syncScreenRefresh) self.type = 'SerialOut' self.url = "https://www.psychopy.org/builder/components/serialout.html" self.exp.requireImport('serial') self.params['port'] = Param( port, valType='str', inputType="single", categ='Basic', hint=_translate("Serial port to connect to"), label=_translate("Port") ) self.params['baudrate'] = Param( baudrate, valType='int', inputType="single", categ='Hardware', hint=_translate("The baud rate, or speed, of the connection."), label=_translate("Baud rate") ) self.params['bytesize'] = Param( bytesize, valType='int', inputType="single", categ='Hardware', hint=_translate("Size of bits to be sent."), label=_translate("Data bits") ) self.params['stopbits'] = Param( stopbits, valType='int', inputType="single", categ='Hardware', hint=_translate("Size of bits to be sent on stop."), label=_translate("Stop bits") ) self.params['parity'] = Param( parity, valType='str', inputType="choice", categ='Hardware', allowedVals=('N', 'E', 'O', 'M', 'S'), allowedLabels=("None", "Even", "Off", "Mark", "Space"), hint=_translate("Parity mode."), label=_translate("Parity") ) self.params['timeout'] = Param( timeout, valType='int', inputType="single", allowedTypes=[], categ='Hardware', hint=_translate("Time at which to give up listening for a response (leave blank for no limit)"), label=_translate("Timeout")) self.params['startdata'] = Param( startdata, valType='str', inputType="single", allowedTypes=[], categ='Basic', hint=_translate("Data to be sent at start of pulse. Data will be converted to bytes, so to specify a" "numeric value directly use $chr(...)."), label=_translate("Start data")) self.params['stopdata'] = Param( stopdata, valType='str', inputType="single", allowedTypes=[], categ='Basic', hint=_translate("String data to be sent at end of pulse. Data will be converted to bytes, so to specify a" "numeric value directly use $chr(...)."), label=_translate("Stop data")) self.params['getResponse'] = Param( getResponse, valType='bool', inputType='bool', categ="Data", hint=_translate("After sending a signal, should PsychoPy read and record a response from the port?"), label=_translate("Get response?") ) def writeRunOnceInitCode(self, buff): inits = getInitVals(self.params, "PsychoPy") # Get device-based variable name inits['varName'] = self.getDeviceVarName() # Create object for serial device code = ( "# Create serial object for device at port %(port)s\n" "%(varName)s = serial.Serial(\n" ) for key in ('port', 'baudrate', 'bytesize', 'parity', 'stopbits', 'timeout'): if self.params[key].val is not None: code += ( f" {key}=%({key})s,\n" ) code += ( ")\n" ) buff.writeOnceIndentedLines(code % inits) def writeInitCode(self, buff): inits = getInitVals(self.params, "PsychoPy") # Get device-based variable name inits['varName'] = self.getDeviceVarName() # Point component name to device object code = ( "\n" "# point %(name)s to device at port %(port)s and make sure it's open\n" "%(name)s = %(varName)s\n" "%(name)s.status = NOT_STARTED\n" "if not %(name)s.is_open:\n" " %(name)s.open()\n" ) buff.writeIndentedLines(code % inits) def writeFrameCode(self, buff): params = copy(self.params) # Get containing loop params['loop'] = self.currentLoop # On component start, send start bits indented = self.writeStartTestCode(buff) if indented: if self.params['syncScreenRefresh']: code = ( "win.callOnFlip(%(name)s.write, bytes(%(startdata)s, 'utf8'))\n" ) else: code = ( "%(name)s.write(bytes(%(startdata)s, 'utf8'))\n" ) buff.writeIndented(code % params) # Update status code = ( "%(name)s.status = STARTED\n" ) buff.writeIndented(code % params) # If we want responses, get them if self.params['getResponse']: code = ( "%(loop)s.addData('%(name)s.startResp', %(name)s.read())\n" ) buff.writeIndented(code % params) # Dedent buff.setIndentLevel(-indented, relative=True) # On component stop, send stop pulse indented = self.writeStopTestCode(buff) if indented: if self.params['syncScreenRefresh']: code = ( "win.callOnFlip(%(name)s.write, bytes(%(stopdata)s, 'utf8'))\n" ) else: code = ( "%(name)s.write(bytes(%(stopdata)s, 'utf8'))\n" ) buff.writeIndented(code % params) # Update status code = ( "%(name)s.status = FINISHED\n" ) buff.writeIndented(code % params) # If we want responses, get them if self.params['getResponse']: code = ( "%(loop)s.addData('%(name)s.stopResp', %(name)s.read())\n" ) buff.writeIndented(code % params) # Dedent buff.setIndentLevel(-indented, relative=True) def writeExperimentEndCode(self, buff): # Close the port code = ( "# Close %(name)s\n" "if %(name)s.is_open:\n" " %(name)s.close()\n" ) buff.writeIndentedLines(code % self.params) def getDeviceVarName(self, case="camel"): """ Create a variable name from the port address of this component's device. Parameters ---------- case : str Format of the variable name (see stringtools.makeValidVarName for info on accepted formats) """ # Add "serial_" in case port name is all numbers name = "serial_%(port)s" % self.params # Make valid varName = st.makeValidVarName(name, case=case) return varName
8,236
Python
.py
187
32.470588
118
0.55622
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,606
__init__.py
psychopy_psychopy/psychopy/experiment/components/image/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy.experiment.components import BaseVisualComponent, Param, getInitVals from psychopy.localization import _translate class ImageComponent(BaseVisualComponent): """An event class for presenting image-based stimuli""" categories = ['Stimuli'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'image.png' tooltip = _translate('Image: present images (bmp, jpg, tif...)') def __init__(self, exp, parentName, name='image', image='', mask='', interpolate='linear', units='from exp settings', color='$[1,1,1]', colorSpace='rgb', pos=(0, 0), size=(0.5, 0.5), anchor="center", ori=0, texRes='128', flipVert=False, flipHoriz=False, draggable=False, startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim=''): super(ImageComponent, self).__init__( exp, parentName, name=name, units=units, color=color, colorSpace=colorSpace, pos=pos, size=size, ori=ori, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Image' self.url = "https://www.psychopy.org/builder/components/image.html" self.exp.requirePsychopyLibs(['visual']) # params self.order += ['image', # Basic tab 'mask', 'texture resolution', # Texture tab ] msg = _translate( "The image to be displayed - a filename, including path") self.params['image'] = Param( image, valType='file', inputType="file", allowedTypes=[], categ='Basic', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Image")) msg = _translate( "An image to define the alpha mask through which the image is " "seen - gauss, circle, None or a filename (including path)") self.params['mask'] = Param( mask, valType='str', inputType="file", allowedTypes=[], categ='Texture', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Mask")) msg = _translate("Resolution of the mask if one is used.") self.params['texture resolution'] = Param( texRes, valType='num', inputType="choice", categ='Texture', allowedVals=['32', '64', '128', '256', '512'], updates='constant', allowedUpdates=[], hint=msg, label=_translate("Texture resolution")) msg = _translate( "How should the image be interpolated if/when rescaled") self.params['interpolate'] = Param( interpolate, valType='str', inputType="choice", allowedVals=['linear', 'nearest'], categ='Texture', updates='constant', allowedUpdates=[], hint=msg, direct=False, label=_translate("Interpolate")) msg = _translate( "Should the image be flipped vertically (top to bottom)?") self.params['flipVert'] = Param( flipVert, valType='bool', inputType="bool", categ='Layout', updates='constant', allowedUpdates=[], hint=msg, label=_translate("Flip vertically")) msg = _translate( "Should the image be flipped horizontally (left to right)?") self.params['flipHoriz'] = Param( flipHoriz, valType='bool', inputType="bool", categ='Layout', updates='constant', allowedUpdates=[], hint=msg, label=_translate("Flip horizontally")) self.params['anchor'] = Param( anchor, valType='str', inputType="choice", categ='Layout', allowedVals=['center', 'top-center', 'bottom-center', 'center-left', 'center-right', 'top-left', 'top-right', 'bottom-left', 'bottom-right', ], updates='constant', hint=_translate("Which point on the stimulus should be anchored to its exact position?"), label=_translate("Anchor")) self.params['draggable'] = Param( draggable, valType="code", inputType="bool", categ="Layout", updates="constant", label=_translate("Draggable?"), hint=_translate( "Should this stimulus be moveble by clicking and dragging?" ) ) del self.params['fillColor'] del self.params['borderColor'] def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # replace variable params with defaults inits = getInitVals(self.params, 'PsychoPy') code = ("{inits[name]} = visual.ImageStim(\n" " win=win,\n" " name='{inits[name]}', {units}\n" " image={inits[image]}, mask={inits[mask]}, anchor={inits[anchor]},\n" " ori={inits[ori]}, pos={inits[pos]}, draggable={inits[draggable]}, size={inits[size]},\n" " color={inits[color]}, colorSpace={inits[colorSpace]}, opacity={inits[opacity]},\n" " flipHoriz={inits[flipHoriz]}, flipVert={inits[flipVert]},\n" # no newline - start optional parameters " texRes={inits[texture resolution]}" .format(inits=inits, units=unitsStr)) if self.params['interpolate'].val == 'linear': code += ", interpolate=True" else: code += ", interpolate=False" depth = -self.getPosInRoutine() code += ", depth=%.1f)\n" % depth buff.writeIndentedLines(code) def writeInitCodeJS(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "units : undefined, " else: unitsStr = "units : %(units)s, " % self.params # replace variable params with defaults inits = getInitVals(self.params, 'PsychoJS') for paramName in inits: val = inits[paramName].val if val is True: inits[paramName] = 'true' elif val is False: inits[paramName] = 'false' elif val in [None, 'None', 'none', '', 'sin']: inits[paramName].valType = 'code' inits[paramName].val = 'undefined' code = ("{inits[name]} = new visual.ImageStim({{\n" " win : psychoJS.window,\n" " name : '{inits[name]}', {units}\n" " image : {inits[image]}, mask : {inits[mask]},\n" " anchor : {inits[anchor]},\n" " ori : {inits[ori]}, \n" " pos : {inits[pos]}, \n" " draggable: {inits[draggable]},\n" " size : {inits[size]},\n" " color : new util.Color({inits[color]}), opacity : {inits[opacity]},\n" " flipHoriz : {inits[flipHoriz]}, flipVert : {inits[flipVert]},\n" # no newline - start optional parameters " texRes : {inits[texture resolution]}" .format(inits=inits, units=unitsStr)) if self.params['interpolate'].val == 'linear': code += ", interpolate : true" else: code += ", interpolate : false" depth = -self.getPosInRoutine() code += (", depth : %.1f \n" "});\n" % (depth) ) buff.writeIndentedLines(code)
8,395
Python
.py
173
35.630058
111
0.541707
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,607
__init__.py
psychopy_psychopy/psychopy/experiment/components/settings/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from copy import deepcopy from pathlib import Path from xml.etree.ElementTree import Element import re from psychopy import logging, plugins from psychopy.experiment.components import Param, _translate from psychopy.experiment.components.settings.eyetracking import knownEyetrackerBackends from psychopy.experiment.routines import Routine, BaseStandaloneRoutine from psychopy.experiment.routines.eyetracker_calibrate import EyetrackerCalibrationRoutine from psychopy.experiment import utils as exputils from psychopy.monitors import Monitor from psychopy.alerts import alert from psychopy.tools.filetools import genDelimiter from psychopy.data.utils import parsePipeSyntax # for creating html output folders: import shutil import hashlib import ast # for doing literal eval to convert '["a","b"]' to a list try: import wx.__version__ wx_version = wx.__version__ except ModuleNotFoundError: wx_version = "4.2" # this won't matter if not in an app anyway! def readTextFile(relPath): fullPath = os.path.join(Path(__file__).parent, relPath) with open(fullPath, "r") as f: txt = f.read() return txt # used when writing scripts and in namespace: _numpyImports = ['sin', 'cos', 'tan', 'log', 'log10', 'pi', 'average', 'sqrt', 'std', 'deg2rad', 'rad2deg', 'linspace', 'asarray'] _numpyRandomImports = ['random', 'randint', 'normal', 'shuffle', 'choice as randchoice'] # Keyboard backend options keyboardBackendMap = { "ioHub": "iohub", "PsychToolbox": "ptb", "Pyglet": "event" } # # customize the Proj ID Param class to # class ProjIDParam(Param): # @property # def allowedVals(self): # from psychopy.app.projects import catalog # allowed = list(catalog.keys()) # # always allow the current val! # if self.val not in allowed: # allowed.append(self.val) # # always allow blank (None) # if '' not in allowed: # allowed.append('') # return allowed # @allowedVals.setter # def allowedVals(self, allowed): # pass class SettingsComponent: """This component stores general info about how to run the experiment """ categories = ['Custom'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'settings.png' tooltip = _translate("Edit settings for this experiment") def __init__( self, parentName, exp, expName='', fullScr=True, runMode=0, rush=False, winSize=(1024, 768), screen=1, monitor='testMonitor', winBackend='pyglet', showMouse=False, saveLogFile=True, showExpInfo=True, expInfo="{'participant':'f\"{randint(0, 999999):06.0f}\"', 'session':'001'}", units='height', logging="info", consoleLoggingLevel="warning", color='$[0,0,0]', colorSpace='rgb', enableEscape=True, measureFrameRate=True, frameRate="", frameRateMsg=_translate( "Attempting to measure frame rate of screen, please wait..." ), backgroundImg="", backgroundFit="none", blendMode='avg', sortColumns="time", colPriority={'thisRow.t': "priority.CRITICAL", 'expName': "priority.LOW"}, saveXLSXFile=False, saveCSVFile=False, saveHDF5File=False, saveWideCSVFile=True, savePsydatFile=True, savedDataFolder='', savedDataDelim='auto', clockFormat="float", useVersion='', expVersion='', eyetracker="None", mgMove='CONTINUOUS', mgBlink='MIDDLE_BUTTON', mgSaccade=0.5, gpAddress='127.0.0.1', gpPort=4242, elModel='EYELINK 1000 DESKTOP', elSimMode=False, elSampleRate=1000, elTrackEyes="RIGHT_EYE", elLiveFiltering="FILTER_LEVEL_OFF", elDataFiltering="FILTER_LEVEL_2", elTrackingMode='PUPIL_CR_TRACKING', elPupilMeasure='PUPIL_AREA', elPupilAlgorithm='ELLIPSE_FIT', elAddress='100.1.1.1', tbModel="", tbLicenseFile="", tbSerialNo="", tbSampleRate=60, plPupillometryOnly=False, plSurfaceName="psychopy_iohub_surface", plConfidenceThreshold=0.6, plPupilRemoteAddress="127.0.0.1", plPupilRemotePort=50020, plPupilRemoteTimeoutMs=1000, plPupilCaptureRecordingLocation="", plCompanionAddress="neon.local", plCompanionPort=8080, ecSampleRate='default', keyboardBackend="ioHub", filename=None, exportHTML='on Sync', endMessage=_translate("Thank you for your patience.") ): self.type = 'Settings' self.exp = exp # so we can access the experiment if necess self.exp.requirePsychopyLibs(['visual', 'gui', 'hardware']) self.parentName = parentName self.url = "https://www.psychopy.org/builder/settings.html" self._monitor = None # if filename is the default value fetch the builder pref for the # folder instead if filename is None: filename = ("u'xxxx/%s_%s_%s' % (expInfo['participant'], expName," " expInfo['date'])") if filename.startswith("u'xxxx"): folder = self.exp.prefsBuilder['savedDataFolder'].strip() filename = filename.replace("xxxx", folder) # params self.params = {} self.depends = [] self.order = [ 'expName', 'expVersion', 'Audio lib', 'Audio latency priority', "Force stereo", # Audio tab 'HTML path', 'exportHTML', 'Completed URL', 'Incomplete URL', 'End Message', 'Resources', # Online tab ] self.depends = [] # --- Basic params --- self.order += [ 'expName', 'runMode', 'Use version', 'Enable Escape', 'rush', 'Show info dlg', 'Experiment info', ] self.params['expName'] = Param( expName, valType='str', inputType="single", categ='Basic', hint=_translate( "Name of the entire experiment (taken by default from the filename on save)" ), label=_translate("Experiment name") ) self.params['expVersion'] = Param( expVersion, valType='str', inputType="single", categ='Basic', hint=_translate( "Version number of the experiment (a string). Just for your records if it's useful to store" ), label=_translate("Experiment version") ) self.params['runMode'] = Param( runMode, valType="code", inputType="choice", categ="Basic", allowedVals=[0, 1], allowedLabels=[_translate("Piloting"), _translate("Running")], label=_translate("Run mode"), hint=_translate( "In piloting mode, all of the settings from prefs->piloting are applied. This is " "recommended while the experiment is a work in progress." ) ) def getVersions(): """ Search for options locally available """ import psychopy.tools.versionchooser as versions available = versions._versionFilter(versions.versionOptions(), wx_version) available += [''] available += versions._versionFilter(versions.availableVersions(), wx_version) return available self.params['Use version'] = Param( useVersion, valType='str', inputType="choice", allowedVals=getVersions, hint=_translate( "The version of PsychoPy to use when running the experiment." ), label=_translate("Use PsychoPy version")) self.params['Enable Escape'] = Param( enableEscape, valType='bool', inputType="bool", categ="Basic", hint=_translate( "Enable the <esc> key, to allow subjects to quit / break out of the experiment" ), label=_translate("Enable escape key") ) self.params['rush'] = Param( rush, valType="bool", inputType="bool", categ="Basic", hint=_translate( "Enable 'rush' mode, which will raise CPU priority while the experiment is running" ), label=_translate("Enable 'rush' mode") ) self.params['Show info dlg'] = Param( showExpInfo, valType='bool', inputType="bool", categ='Basic', hint=_translate( "Start the experiment with a dialog to set info (e.g.participant or condition)" ), label=_translate("Show info dialog") ) self.depends.append( {"dependsOn": "Show info dlg", # must be param name "condition": "==True", # val to check for "param": "Experiment info", # param property to alter "true": "enable", # what to do with param if condition is True "false": "disable", # permitted: hide, show, enable, disable } ) self.params['Experiment info'] = Param( expInfo, valType='code', inputType="dict", categ='Basic', allowedLabels=(_translate("Field"), _translate("Default")), hint=_translate( "The info to present in a dialog box. Right-click to check syntax and preview " "the dialog box." ), label=_translate("Experiment info") ) # --- Screen params --- self.order += [ "Monitor", "winBackend", "Screen", "Full-screen window", "Show mouse", "Window size (pixels)", "Units", "color", "blendMode", "colorSpace", "backgroundImg", "backgroundFit", "measureFrameRate", "frameRate", "frameRateMsg", ] self.params['Full-screen window'] = Param( fullScr, valType='bool', inputType="bool", allowedTypes=[], hint=_translate("Run the experiment full-screen (recommended)"), label=_translate("Full-screen window"), categ='Screen') self.params['winBackend'] = Param( winBackend, valType='str', inputType="choice", categ="Screen", allowedVals=plugins.getWindowBackends(), hint=_translate("What Python package should be used behind the scenes for drawing to the window?"), label=_translate("Window backend") ) self.params['Window size (pixels)'] = Param( winSize, valType='list', inputType="single", allowedTypes=[], hint=_translate("Size of window (if not fullscreen)"), label=_translate("Window size (pixels)"), categ='Screen') self.params['Screen'] = Param( screen, valType='num', inputType="spin", allowedTypes=[], hint=_translate("Which physical screen to run on (1 or 2)"), label=_translate("Screen"), categ='Screen') self.params['Monitor'] = Param( monitor, valType='str', inputType="single", allowedTypes=[], hint=_translate("Name of the monitor (from Monitor Center). Right" "-click to go there, then copy & paste a monitor " "name here."), label=_translate("Monitor"), categ="Screen") self.params['color'] = Param( color, valType='color', inputType="color", allowedTypes=[], hint=_translate("Color of the screen (e.g. black, $[1.0,1.0,1.0]," " $variable. Right-click to bring up a " "color-picker.)"), label=_translate("Background color"), categ='Screen') self.params['colorSpace'] = Param( colorSpace, valType='str', inputType="choice", hint=_translate("Needed if color is defined numerically (see " "PsychoPy documentation on color spaces)"), allowedVals=['rgb', 'dkl', 'lms', 'hsv', 'hex'], label=_translate("Color space"), categ="Screen") self.params['backgroundImg'] = Param( backgroundImg, valType="str", inputType="file", categ="Screen", hint=_translate("Image file to use as a background (leave blank for no image)"), label=_translate("Background image") ) self.params['backgroundFit'] = Param( backgroundFit, valType="str", inputType="choice", categ="Screen", allowedVals=("none", "cover", "contain", "fill", "scale-down"), hint=_translate("How should the background image scale to fit the window size?"), label=_translate("Background fit") ) self.params['Units'] = Param( units, valType='str', inputType="choice", allowedTypes=[], allowedVals=['use prefs', 'deg', 'pix', 'cm', 'norm', 'height', 'degFlatPos', 'degFlat'], hint=_translate("Units to use for window/stimulus coordinates " "(e.g. cm, pix, deg)"), label=_translate("Units"), categ='Screen') self.params['blendMode'] = Param( blendMode, valType='str', inputType="choice", allowedVals=['add', 'avg', 'nofbo'], allowedLabels=['add', 'average', 'average (no FBO)'], hint=_translate("Should new stimuli be added or averaged with " "the stimuli that have been drawn already"), label=_translate("Blend mode"), categ='Screen') self.params['Show mouse'] = Param( showMouse, valType='bool', inputType="bool", allowedTypes=[], hint=_translate("Should the mouse be visible on screen? Only applicable for fullscreen experiments."), label=_translate("Show mouse"), categ='Screen') self.params['measureFrameRate'] = Param( measureFrameRate, valType="bool", inputType="bool", categ="Screen", label=_translate("Measure frame rate?"), hint=_translate( "Should we measure your frame rate at the start of the experiment? This is " "highly recommended for precise timing." ) ) self.params['frameRate'] = Param( frameRate, valType="code", inputType="single", categ="Screen", label=_translate("Frame rate"), hint=_translate( "Frame rate to store instead of measuring at the start of the experiment. Leave " "blank to store no frame rate, but be wary: This will lead to errors if frame rate " "isn't supplied by other means." ) ) self.depends.append({ "dependsOn": "measureFrameRate", # if... "condition": "", # meets... "param": "frameRate", # then... "true": "hide", # should... "false": "show", # otherwise... }) self.params['frameRateMsg'] = Param( frameRateMsg, valType="str", inputType="single", categ="Screen", label=_translate("Frame rate message"), hint=_translate( "Message to display while frame rate is measured. Leave blank for no message." ) ) self.depends.append({ "dependsOn": "measureFrameRate", # if... "condition": "", # meets... "param": "frameRateMsg", # then... "true": "show", # should... "false": "hide", # otherwise... }) # self.depends.append( # {"dependsOn": 'Full-screen window', # must be param name # "condition": "==True", # val to check for # "param": 'Show mouse', # param property to alter # "true": "show", # what to do with param if condition is True # "false": "hide", # permitted: hide, show, enable, disable # } # ) # sound params self.params['Force stereo'] = Param( enableEscape, valType='bool', inputType="bool", allowedTypes=[], categ="Audio", hint=_translate("Force audio to stereo (2-channel) output"), label=_translate("Force stereo")) self.params['Audio lib'] = Param( 'ptb', valType='str', inputType="choice", allowedVals=['ptb', 'pyo', 'sounddevice', 'pygame'], hint=_translate("Which Python sound engine do you want to play your sounds?"), label=_translate("Audio library"), categ='Audio') audioLatencyLabels = [ '0: ' + _translate('Latency not important'), '1: ' + _translate('Share low-latency driver'), '2: ' + _translate('Exclusive low-latency'), '3: ' + _translate('Aggressive low-latency'), '4: ' + _translate('Latency critical'), ] self.params['Audio latency priority'] = Param( '3', valType='str', inputType="choice", allowedVals=['0', '1', '2', '3', '4'], allowedLabels=audioLatencyLabels, hint=_translate("How important is audio latency for you? If essential then you may need to get all your sounds in correct formats."), label=_translate("Audio latency priority"), categ='Audio') # --- Data params --- self.order += [ "Data filename", "Data file delimiter", "sortColumns", "colPriority", "Save excel file", "Save log file", "Save csv file", "Save wide csv file", "Save psydat file", "Save hdf5 file", "logging level", "consoleLoggingLevel", "clockFormat", ] self.params['Data filename'] = Param( filename, valType='code', inputType="single", allowedTypes=[], hint=_translate("Code to create your custom file name base. Don" "'t give a file extension - this will be added."), label=_translate("Data filename"), categ='Data') self.params['Data file delimiter'] = Param( savedDataDelim, valType='str', inputType="choice", allowedVals=['auto', 'comma', 'semicolon', 'tab'], hint=_translate("What symbol should the data file use to separate columns? ""Auto"" will select a delimiter automatically from the filename."), label=_translate("Data file delimiter"), categ='Data' ) self.params['sortColumns'] = Param( sortColumns, valType="str", inputType="choice", categ="Data", allowedLabels=[_translate("Alphabetical"), _translate("Priority"), _translate("First added")], allowedVals=["alphabetical", "priority", "time"], label=_translate("Sort columns by..."), hint=_translate( "How should data file columns be sorted? Alphabetically, by priority, or simply in the order they were " "added?" ) ) self.params['colPriority'] = Param( colPriority, valType="dict", inputType="dict", categ="Data", allowedLabels=(_translate("Column"), _translate("Priority")), label=_translate("Column priority"), hint=_translate( "Assign priority values to certain columns. To use predefined values, you can do $priority.HIGH, " "$priority.MEDIUM, etc." ) ) self.params['Save log file'] = Param( saveLogFile, valType='bool', inputType="bool", allowedTypes=[], hint=_translate("Save a detailed log (more detailed than the " "Excel/csv files) of the entire experiment"), label=_translate("Save log file"), categ='Data') self.params['Save wide csv file'] = Param( saveWideCSVFile, valType='bool', inputType="bool", allowedTypes=[], hint=_translate("Save data from loops in comma-separated-value " "(.csv) format for maximum portability"), label=_translate("Save csv file (trial-by-trial)"), categ='Data') self.params['Save csv file'] = Param( saveCSVFile, valType='bool', inputType="bool", allowedTypes=[], hint=_translate("Save data from loops in comma-separated-value " "(.csv) format for maximum portability"), label=_translate("Save csv file (summaries)"), categ='Data') self.params['Save excel file'] = Param( saveXLSXFile, valType='bool', inputType="bool", allowedTypes=[], hint=_translate("Save data from loops in Excel (.xlsx) format"), label=_translate("Save Excel file"), categ='Data') self.params['Save psydat file'] = Param( savePsydatFile, valType='bool', inputType="bool", allowedVals=[True], hint=_translate("Save data from loops in psydat format. This is " "useful for Python programmers to generate " "analysis scripts."), label=_translate("Save psydat file"), categ='Data') self.params['Save hdf5 file'] = Param( saveHDF5File, valType='bool', inputType="bool", hint=_translate("Save data from eyetrackers in hdf5 format. This is " "useful for viewing and analyzing complex data in structures."), label=_translate("Save hdf5 file"), categ='Data') self.params['logging level'] = Param( logging, valType='code', inputType="choice", categ='Data', allowedVals=['error', 'warning', 'data', 'exp', 'info', 'debug'], hint=_translate( "How much output do you want in the log files? ('error' is fewest " "messages, 'debug' is most)" ), label=_translate("File logging level") ) self.params['consoleLoggingLevel'] = Param( consoleLoggingLevel, valType='code', inputType="choice", categ='Data', allowedVals=['error', 'warning', 'data', 'exp', 'info', 'debug'], hint=_translate( "How much output do you want displayed in the console / app? ('error' " "is fewest messages, 'debug' is most)" ), label=_translate("Console / app logging level") ) self.params['clockFormat'] = Param( clockFormat, valType="str", inputType="choice", categ="Data", allowedVals=["iso", "float"], allowedLabels=["Wall clock", "Experiment start"], label=_translate("Clock format"), hint=_translate( "Format to use for Routine start timestamps; either wall clock time (in ISO 8601 " "format) or seconds since experiment start (as a float)." ) ) # HTML output params # self.params['OSF Project ID'] = ProjIDParam( # '', valType='str', # automatically updates to allow choices # hint=_translate("The ID of this project (e.g. 5bqpc)"), # label="OSF Project ID", categ='Online') self.params['HTML path'] = Param( '', valType='str', inputType="single", allowedTypes=[], hint=_translate("Place the HTML files will be saved locally "), label=_translate("Output path"), categ='Online') self.params['Resources'] = Param( [], valType='list', inputType="fileList", allowedTypes=[], hint=_translate("Any additional resources needed"), label=_translate("Additional resources"), categ='Online') self.params['End Message'] = Param( endMessage, valType='str', inputType='single', hint=_translate("Message to display to participants upon completing the experiment"), label=_translate("End message"), categ='Online') self.params['Completed URL'] = Param( '', valType='str', inputType="single", hint=_translate("Where should participants be redirected after the experiment on completion, e.g.\n" "https://pavlovia.org/surveys/XXXXXX-XXXX-XXXXXXX?tab=0"), label=_translate("Completed URL"), categ='Online') self.params['Incomplete URL'] = Param( '', valType='str', inputType="single", hint=_translate("Where participants are redirected if they do not complete the task, e.g.\n" "https://pavlovia.org/surveys/XXXXXX-XXXX-XXXXXXX?tab=0"), label=_translate("Incomplete URL"), categ='Online') self.params['exportHTML'] = Param( exportHTML, valType='str', inputType="choice", allowedVals=['on Save', 'on Sync', 'manually'], hint=_translate("When to export experiment to the HTML folder."), label=_translate("Export HTML"), categ='Online') # Eyetracking params self.order += ["eyetracker", "gpAddress", "gpPort", "elModel", "elAddress", "elSimMode"] # Hide params when not relevant to current eyetracker trackerParams = { "MouseGaze": ["mgMove", "mgBlink", "mgSaccade"], "GazePoint": ["gpAddress", "gpPort"], "SR Research Ltd": ["elModel", "elSimMode", "elSampleRate", "elTrackEyes", "elLiveFiltering", "elDataFiltering", "elTrackingMode", "elPupilMeasure", "elPupilAlgorithm", "elAddress"], "Tobii Technology": ["tbModel", "tbLicenseFile", "tbSerialNo", "tbSampleRate"], "Pupil Labs": ["plPupillometryOnly", "plSurfaceName", "plConfidenceThreshold", "plPupilRemoteAddress", "plPupilRemotePort", "plPupilRemoteTimeoutMs", "plPupilCaptureRecordingLocation"], "Pupil Labs (Neon)": ["plCompanionAddress", "plCompanionPort"], "EyeLogic": ["ecSampleRate"], } for tracker in trackerParams: for depParam in trackerParams[tracker]: self.depends.append( {"dependsOn": "eyetracker", # must be param name "condition": "=='"+tracker+"'", # val to check for "param": depParam, # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) self.depends.append( {"dependsOn": "eyetracker", # must be param name "condition": f" in {list(trackerParams)}", # val to check for "param": "Save hdf5 file", # param property to alter "true": "enable", # what to do with param if condition is True "false": "disable", # permitted: hide, show, enable, disable } ) # arrays for eyetracker backends backendValues = ["None"] backendLabels = ["None"] # add known backends from plugins for key, cls in knownEyetrackerBackends.items(): backendValues.append(key) backendLabels.append(cls.label or key) # add backends via legacy detection method try: from psychopy.iohub import util as ioUtil for legLbl, legKey in ioUtil.getDeviceNames(device_name="eyetracker.hw"): if legKey not in backendValues: backendValues.append(legKey) backendLabels.append(legLbl) except: # if it doesn't work, just stick with the known backends from plugins pass self.params['eyetracker'] = Param( eyetracker, valType='str', inputType="choice", allowedVals=backendValues, allowedLabels=backendLabels, hint=_translate("What kind of eye tracker should PsychoPy use? Select 'MouseGaze' to use " "the mouse to simulate eye movement (for debugging without a tracker connected)"), label=_translate("Eyetracker device"), categ="Eyetracking" ) # add params from backends for backend in knownEyetrackerBackends.values(): # get params from backend params, order = backend.getParams() # append order self.order += order # iterate through params from this backend for paramName, param in params.items(): # add param self.params[paramName] = param # add dependency on eyetracker param self.depends.append({ 'dependsOn': "eyetracker", # if... 'condition': f"== '{backend.key}'", # meets... 'param': paramName, # then... 'true': "show", # should... 'false': "hide", # otherwise... }) # as users with old versions of the plugin won't have params added dynamically, add legacy # params here manually # gazepoint self.params['gpAddress'] = Param( gpAddress, valType='str', inputType="single", hint=_translate("IP Address of the computer running GazePoint Control."), label=_translate("GazePoint IP address"), categ="Eyetracking" ) self.params['gpPort'] = Param( gpPort, valType='num', inputType="single", hint=_translate("Port of the GazePoint Control server. Usually 4242."), label=_translate("GazePoint port"), categ="Eyetracking" ) # eyelink self.params['elModel'] = Param( elModel, valType='str', inputType="choice", allowedVals=['EYELINK 1000 DESKTOP', 'EYELINK 1000 TOWER', 'EYELINK 1000 REMOTE', 'EYELINK 1000 LONG RANGE'], hint=_translate("Eye tracker model."), label=_translate("Model name"), categ="Eyetracking" ) self.params['elSimMode'] = Param( elSimMode, valType='bool', inputType="bool", hint=_translate("Set the EyeLink to run in mouse simulation mode."), label=_translate("Mouse simulation mode"), categ="Eyetracking" ) self.params['elSampleRate'] = Param( elSampleRate, valType='num', inputType="choice", allowedVals=['250', '500', '1000', '2000'], hint=_translate("Eye tracker sampling rate."), label=_translate("Sampling rate"), categ="Eyetracking" ) self.params['elTrackEyes'] = Param( elTrackEyes, valType='str', inputType="choice", allowedVals=['LEFT_EYE', 'RIGHT_EYE', 'BOTH'], hint=_translate("Select with eye(s) to track."), label=_translate("Track eyes"), categ="Eyetracking" ) self.params['elLiveFiltering'] = Param( elLiveFiltering, valType='str', inputType="choice", allowedVals=['FILTER_LEVEL_OFF', 'FILTER_LEVEL_1', 'FILTER_LEVEL_2'], hint=_translate("Filter eye sample data live, as it is streamed to the driving device. " "This may reduce the sampling speed."), label=_translate("Live sample filtering"), categ="Eyetracking" ) self.params['elDataFiltering'] = Param( elDataFiltering, valType='str', inputType="choice", allowedVals=['FILTER_LEVEL_OFF', 'FILTER_LEVEL_1', 'FILTER_LEVEL_2'], hint=_translate("Filter eye sample data when it is saved to the output file. This will " "not affect the sampling speed."), label=_translate("Saved sample filtering"), categ="Eyetracking" ) self.params['elTrackingMode'] = Param( elTrackingMode, valType='str', inputType="choice", allowedVals=['PUPIL_CR_TRACKING', 'PUPIL_ONLY_TRACKING'], hint=_translate("Track Pupil-CR or Pupil only."), label=_translate("Pupil tracking mode"), categ="Eyetracking" ) self.params['elPupilAlgorithm'] = Param( elPupilAlgorithm, valType='str', inputType="choice", allowedVals=['ELLIPSE_FIT', 'CENTROID_FIT'], hint=_translate("Algorithm used to detect the pupil center."), label=_translate("Pupil center algorithm"), categ="Eyetracking" ) self.params['elPupilMeasure'] = Param( elPupilMeasure, valType='str', inputType="choice", allowedVals=['PUPIL_AREA', 'PUPIL_DIAMETER', 'NEITHER'], hint=_translate("Type of pupil data to record."), label=_translate("Pupil data type"), categ="Eyetracking" ) self.params['elAddress'] = Param( elAddress, valType='str', inputType="single", hint=_translate("IP Address of the EyeLink *Host* computer."), label=_translate("EyeLink IP address"), categ="Eyetracking" ) # tobii self.params['tbModel'] = Param( tbModel, valType='str', inputType="single", hint=_translate("Eye tracker model."), label=_translate("Model name"), categ="Eyetracking" ) self.params['tbLicenseFile'] = Param( tbLicenseFile, valType='str', inputType="file", hint=_translate("Eye tracker license file (optional)."), label=_translate("License file"), categ="Eyetracking" ) self.params['tbSerialNo'] = Param( tbSerialNo, valType='str', inputType="single", hint=_translate("Eye tracker serial number (optional)."), label=_translate("Serial number"), categ="Eyetracking" ) self.params['tbSampleRate'] = Param( tbSampleRate, valType='num', inputType="single", hint=_translate("Eye tracker sampling rate."), label=_translate("Sampling rate"), categ="Eyetracking" ) # pupil labs self.params['plPupillometryOnly'] = Param( plPupillometryOnly, valType='bool', inputType="bool", hint=_translate("Subscribe to pupil data only, does not require calibration or surface setup"), label=_translate("Pupillometry only"), categ="Eyetracking" ) self.params['plSurfaceName'] = Param( plSurfaceName, valType='str', inputType="single", hint=_translate("Name of the Pupil Capture surface"), label=_translate("Surface name"), categ="Eyetracking" ) self.params['plConfidenceThreshold'] = Param( plConfidenceThreshold, valType='num', inputType="single", hint=_translate("Gaze confidence threshold"), label=_translate("Gaze confidence threshold"), categ="Eyetracking" ) self.params['plPupilRemoteAddress'] = Param( plPupilRemoteAddress, valType='str', inputType="single", hint=_translate("Pupil remote address"), label=_translate("Pupil remote address"), categ="Eyetracking" ) self.params['plPupilRemotePort'] = Param( plPupilRemotePort, valType='num', inputType="single", hint=_translate("Pupil remote port"), label=_translate("Pupil remote port"), categ="Eyetracking" ) self.params['plPupilRemoteTimeoutMs'] = Param( plPupilRemoteTimeoutMs, valType='num', inputType="single", hint=_translate("Pupil remote timeout (ms)"), label=_translate("Pupil remote timeout (ms)"), categ="Eyetracking" ) self.params['plPupilCaptureRecordingLocation'] = Param( plPupilCaptureRecordingLocation, valType='str', inputType="single", hint=_translate("Pupil capture recording location"), label=_translate("Pupil capture recording location"), categ="Eyetracking" ) self.params['plCompanionAddress'] = Param( plCompanionAddress, valType='str', inputType="single", hint=_translate("Companion address"), label=_translate("Companion address"), categ="Eyetracking" ) self.params['plCompanionPort'] = Param( plCompanionPort, valType='num', inputType="single", hint=_translate("Companion port"), label=_translate("Companion port"), categ="Eyetracking" ) # EyeLogic self.params['ecSampleRate'] = Param( ecSampleRate, valType='str', inputType="single", hint=_translate("Eyetracker sampling rate: 'default' or <integer>[Hz]. Defaults to tracking mode '0'."), label=_translate("Sampling rate"), categ="Eyetracking" ) # Input self.params['keyboardBackend'] = Param( keyboardBackend, valType='str', inputType="choice", allowedVals=list(keyboardBackendMap), hint=_translate("What Python package should PsychoPy use to get keyboard input?"), label=_translate("Keyboard backend"), categ="Input" ) @property def _xml(self): # Make root element element = Element("Settings") # Add an element for each parameter for key, param in sorted(self.params.items()): if key == 'name': continue # Create node paramNode = param._xml paramNode.set("name", key) # Add node element.append(paramNode) return element def getInfo(self, removePipeSyntax=False): """ Rather than converting the value of params['Experiment Info'] into a dict from a string (which can lead to errors) use this function :return: Parameters ---------- removePipeSyntax : bool If True, then keys in expInfo dict are returned with pipe syntax (e.g. |req, |cfg, etc.) removed. Returns ------- dict expInfo as a dict """ infoStr = str(self.params['Experiment info'].val).strip() if len(infoStr) == 0: return {} try: infoDict = ast.literal_eval(infoStr) newDict = {} # check for strings of lists: "['male','female']" for key in infoDict: val = infoDict[key] # sanitize key if requested if removePipeSyntax: key, _ = parsePipeSyntax(key) if exputils.list_like_re.search(str(val)): # Try to call it with ast, if it produces a list/tuple, treat val type as list try: isList = ast.literal_eval(str(val)) except ValueError: # If ast errors, treat as code newDict[key] = Param(val=val, valType='code') else: if isinstance(isList, (list, tuple)): # If ast produces a list, treat as list newDict[key] = Param(val=val, valType='list') else: # If ast produces anything else, treat as code newDict[key] = Param(val=val, valType='code') elif val in ['True', 'False']: newDict[key] = Param(val=val, valType='bool') elif isinstance(val, str): newDict[key] = Param(val=val, valType='str') except (ValueError, SyntaxError): """under Python3 {'participant':'', 'session':02} raises an error because ints can't have leading zeros. We will check for those and correct them tests = ["{'participant':'', 'session':02}", "{'participant':'', 'session':02}", "{'participant':'', 'session': 0043}", "{'participant':'', 'session':02, 'id':009}", ] """ def entryToString(match): entry = match.group(0) digits = re.split(r": *", entry)[1] return ':{}'.format(repr(digits)) # 0 or more spaces, 1-5 zeros, 0 or more digits: pattern = re.compile(r": *0{1,5}\d*") try: newDict = eval(re.sub(pattern, entryToString, infoStr)) except SyntaxError: # still a syntax error, possibly caused by user msg = ('Builder Expt: syntax error in ' '"Experiment info" settings (expected a dict)') logging.error(msg) raise AttributeError(msg) return newDict def getType(self): return self.__class__.__name__ def getShortType(self): return self.getType().replace('Component', '') def writeUseVersion(self, buff): if self.params['Use version'].val: code = ('\nimport psychopy\n' 'psychopy.useVersion({})\n\n') val = repr(self.params['Use version'].val) buff.writeIndentedLines(code.format(val)) def writeInitCode(self, buff, version, localDateTime): buff.write( '#!/usr/bin/env python\n' '# -*- coding: utf-8 -*-\n' '"""\nThis experiment was created using PsychoPy3 Experiment ' 'Builder (v%s),\n' ' on %s\n' % (version, localDateTime) + 'If you publish work using this script the most relevant ' 'publication is:\n\n' u' Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, ' u'Kastman E, Lindeløv JK. (2019) \n' ' PsychoPy2: Experiments in behavior made easy Behav Res 51: 195. \n' ' https://doi.org/10.3758/s13428-018-01193-y\n' '\n"""\n') self.writeUseVersion(buff) psychopyImports = [] customImports = [] for import_ in self.exp.requiredImports: if import_.importFrom == 'psychopy': psychopyImports.append(import_.importName) else: customImports.append(import_) buff.writelines( "\n" "# --- Import packages ---" "\n" "from psychopy import locale_setup\n" "from psychopy import prefs\n" "from psychopy import plugins\n" "plugins.activatePlugins()\n" # activates plugins ) # adjust the prefs for this study if needed if self.params['Audio lib'].val.lower() != 'use prefs': buff.writelines( "prefs.hardware['audioLib'] = {}\n".format(self.params['Audio lib']) ) if self.params['Audio latency priority'].val.lower() != 'use prefs': buff.writelines( "prefs.hardware['audioLatencyMode'] = {}\n".format(self.params['Audio latency priority']) ) buff.write( "from psychopy import %s\n" % ', '.join(psychopyImports) + "from psychopy.tools import environmenttools\n" "from psychopy.constants import (\n" " NOT_STARTED, STARTED, PLAYING, PAUSED, STOPPED, STOPPING, FINISHED, PRESSED, \n" " RELEASED, FOREVER, priority\n" ")\n\n" "import numpy as np # whole numpy lib is available, " "prepend 'np.'\n" "from numpy import (%s,\n" % ', '.join(_numpyImports[:7]) + " %s)\n" % ', '.join(_numpyImports[7:]) + "from numpy.random import %s\n" % ', '.join(_numpyRandomImports) + "import os # handy system and path functions\n" + "import sys # to get file system encoding\n" "\n") if not self.params['eyetracker'] == "None" or self.params['keyboardBackend'] == "ioHub": code = ( "import psychopy.iohub as io\n" ) buff.writeIndentedLines(code) # Write custom import statements, line by line. for import_ in customImports: importName = import_.importName importFrom = import_.importFrom importAs = import_.importAs statement = '' if importFrom: statement += "from %s " % importFrom statement += "import %s" % importName if importAs: statement += " as %s" % importAs statement += "\n" buff.write(statement) buff.write("\n") def writeGlobals(self, buff, version): """ Create some global variables which functions will need """ # Substitute params params = self.params.copy() params['version'] = version if self.params['expName'].val in [None, '']: params['expName'].val = "untitled.py" code = ( "# --- Setup global variables (available in all functions) ---\n" "# create a device manager to handle hardware (keyboards, mice, mirophones, speakers, etc.)\n" "deviceManager = hardware.DeviceManager()\n" "# ensure that relative paths start from the same directory as this script\n" "_thisDir = os.path.dirname(os.path.abspath(__file__))\n" "# store info about the experiment session\n" "psychopyVersion = '%(version)s'\n" "expName = %(expName)s # from the Builder filename that created this script\n" "expVersion = %(expVersion)s\n" "# a list of functions to run when the experiment ends (starts off blank)\n" "runAtExit = []\n" ) buff.writeIndentedLines(code % params) # get info for this experiment expInfo = self.getInfo(removePipeSyntax=False) # add internal expInfo keys expInfo['date|hid'] = "data.getDateStr()" expInfo['expName|hid'] = "expName" expInfo['expVersion|hid'] = "expVersion" expInfo['psychopyVersion|hid'] = "psychopyVersion" # construct exp info dict code = ( "# information about this experiment\n" "expInfo = {\n" ) for key, value in expInfo.items(): code += ( f" '{key}': {value},\n" ) code += ( "}\n" "\n" ) buff.writeIndented(code) # write code for pilot mode code = ( "# --- Define some variables which will change depending on pilot mode ---\n" "'''\n" "To run in pilot mode, either use the run/pilot toggle in Builder, Coder and Runner, \n" "or run the experiment with `--pilot` as an argument. To change what pilot \n#" "mode does, check out the 'Pilot mode' tab in preferences.\n" "'''\n" "# work out from system args whether we are running in pilot mode\n" "PILOTING = core.setPilotModeFromArgs()\n" "# start off with values from experiment settings\n" "_fullScr = %(Full-screen window)s\n" "_winSize = %(Window size (pixels))s\n" "# if in pilot mode, apply overrides according to preferences\n" "if PILOTING:\n" " # force windowed mode\n" " if prefs.piloting['forceWindowed']:\n" " _fullScr = False\n" " # set window size\n" " _winSize = prefs.piloting['forcedWindowSize']\n" ) buff.writeIndented(code % self.params) def prepareResourcesJS(self): """Sets up the resources folder and writes the info.php file for PsychoJS """ join = os.path.join def copyTreeWithMD5(src, dst): """Copies the tree but checks SHA for each file first """ # despite time to check the md5 hashes this func gives speed-up # over about 20% over using shutil.rmtree() and copytree() for root, subDirs, files in os.walk(src): relPath = os.path.relpath(root, src) for thisDir in subDirs: if not os.path.isdir(join(root, thisDir)): os.makedirs(join(root, thisDir)) for thisFile in files: copyFileWithMD5(join(root, thisFile), join(dst, relPath, thisFile)) def copyFileWithMD5(src, dst): """Copies a file but only if doesn't exist or SHA is diff """ if os.path.isfile(dst): with open(dst, 'rb') as f: dstMD5 = hashlib.md5(f.read()).hexdigest() with open(src, 'rb') as f: srcMD5 = hashlib.md5(f.read()).hexdigest() if srcMD5 == dstMD5: return # already matches - do nothing # if we got here then the file exists but not the same # delete and replace. TODO: In future this should check date os.remove(dst) # either didn't exist or has been deleted folder = os.path.split(dst)[0] if not os.path.isdir(folder): os.makedirs(folder) shutil.copy2(src, dst) # write info.php file folder = os.path.dirname(self.exp.expPath) if not os.path.isdir(folder): os.mkdir(folder) # is email a defined parameter for this version if 'email' in self.params: email = repr(self.params['email'].val) else: email = "''" # populate resources folder resFolder = join(folder, 'resources') if not os.path.isdir(resFolder): os.mkdir(resFolder) resourceFiles = self.exp.getResourceFiles() for srcFile in resourceFiles: if "https://" in srcFile.get('abs', "") or srcFile.get('name', "") == "surveyId": # URLs and survey IDs don't need copying continue dstAbs = os.path.normpath(join(resFolder, srcFile['rel'])) dstFolder = os.path.split(dstAbs)[0] if not os.path.isdir(dstFolder): os.makedirs(dstFolder) copyFileWithMD5(srcFile['abs'], dstAbs) def writeInitCodeJS(self, buff, version, localDateTime, modular=True): from psychopy.tools import versionchooser as versions # create resources folder if self.exp.htmlFolder: self.prepareResourcesJS() jsFilename = self.params['expName'].val # configure the PsychoJS version number from current/requested versions useVer = self.params['Use version'].val useVer = versions.getPsychoJSVersionStr(version, useVer) # html header if self.exp.expPath: template = readTextFile("JS_htmlHeader.tmpl") header = template.format( name=jsFilename, version=useVer, params=self.params) jsFile = self.exp.expPath folder = os.path.dirname(jsFile) if not os.path.isdir(folder): os.makedirs(folder) with open(os.path.join(folder, "index.html"), 'wb') as html: html.write(header.encode()) html.close() # Write header comment starLen = "*"*(len(jsFilename) + 9) code = ("/%s \n" " * %s *\n" " %s/\n\n") buff.writeIndentedLines(code % (starLen, jsFilename.title(), starLen)) # Write imports if modular if modular: code = ( "import {{ core, data, sound, util, visual, hardware }} from './lib/psychojs-{version}.js';\n" "const {{ PsychoJS }} = core;\n" "const {{ TrialHandler, MultiStairHandler }} = data;\n" "const {{ Scheduler }} = util;\n" "//some handy aliases as in the psychopy scripts;\n" "const {{ abs, sin, cos, PI: pi, sqrt }} = Math;\n" "const {{ round }} = util;\n" "\n").format(version=useVer) buff.writeIndentedLines(code) # Get expInfo as a dict expInfoDict = self.getInfo().items() # Convert each item to str expInfoStr = "{" if len(expInfoDict): # Only make the dict multiline if it actually has contents expInfoStr += "\n" for key, value in self.getInfo().items(): expInfoStr += f" '{key}': {value},\n" expInfoStr += "}" code = ("\n// store info about the experiment session:\n" "let expName = '%s'; // from the Builder filename that created this script\n" "let expInfo = %s;\n" "\n" % (jsFilename, expInfoStr)) buff.writeIndentedLines(code) def writeExpSetupCodeJS(self, buff, version): # write the code to set up experiment buff.setIndentLevel(0, relative=False) template = readTextFile("JS_setupExp.tmpl") # Get file delimiter character delim_options = { 'comma': ",", 'semicolon': ";", 'tab': r"\t" } delim = delim_options.get( self.params['Data file delimiter'].val, genDelimiter(self.params['Data filename'].val) ) setRedirectURL = '' if len(self.params['Completed URL'].val) or len(self.params['Incomplete URL'].val): setRedirectURL = ("psychoJS.setRedirectUrls({completedURL}, {incompleteURL});\n" .format(completedURL=self.params['Completed URL'], incompleteURL=self.params['Incomplete URL'])) # check where to save data variables # if self.params['OSF Project ID'].val: # saveType = "OSF_VIA_EXPERIMENT_SERVER" # projID = "'{}'".format(self.params['OSF Project ID'].val) # else: # saveType = "EXPERIMENT_SERVER" # projID = 'undefined' code = template.format( params=self.params, filename=str(self.params['Data filename']), name=self.params['expName'].val, loggingLevel=self.params['logging level'].val.upper(), setRedirectURL=setRedirectURL, version=version, field_separator=repr(delim) ) buff.writeIndentedLines(code) def writeDataCode(self, buff): """ Write code to handle data and saving (create ExperimentHandler, pick filename, etc.) """ params = self.params.copy() # Enter function def code = ( '\n' 'def setupData(expInfo, dataDir=None):\n' ' """\n' ' Make an ExperimentHandler to handle trials and saving.\n' ' \n' ' Parameters\n' ' ==========\n' ' expInfo : dict\n' ' Information about this experiment, created by the `setupExpInfo` function.\n' ' dataDir : Path, str or None\n' ' Folder to save the data to, leave as None to create a folder in the current directory.' ' \n' ' Returns\n' ' ==========\n' ' psychopy.data.ExperimentHandler\n' ' Handler object for this experiment, contains the data to save and information about \n' ' where to save it to.\n' ' """\n' ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) # remove pipe syntax from expInfo code = ( "# remove dialog-specific syntax from expInfo\n" "for key, val in expInfo.copy().items():\n" " newKey, _ = data.utils.parsePipeSyntax(key)\n" " expInfo[newKey] = expInfo.pop(key)\n" ) buff.writeIndentedLines(code % self.params) # figure out participant id field (if any) participantVal = '' for target in ('participant', 'Participant', 'Subject', 'Observer'): if target in self.getInfo(removePipeSyntax=True): participantVal = " + expInfo['%s']" % target break # make sure we have a filename if not params['Data filename'].val: # i.e., the user deleted it params['Data filename'].val = ( "'data' + os.sep%s + data.getDateStr()" ) % participantVal # get origin path params['originPath'] = repr(self.exp.expPath) # get fallback data dir value params['dataDir'] = "_thisDir" # deprecated code: before v1.80.00 we had 'Saved data folder' param if 'Saved data folder' in params: if params['Saved data folder'].val.strip(): params['dataDir'] = params['Saved data folder'] else: params['dataDir'] = repr(self.exp.prefsBuilder['savedDataFolder'].strip()) code = ( "\n" "# data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc\n" f"if dataDir is None:\n" f" dataDir = %(dataDir)s\n" f"filename = %(Data filename)s\n" f"# make sure filename is relative to dataDir\n" f"if os.path.isabs(filename):\n" f" dataDir = os.path.commonprefix([dataDir, filename])\n" f" filename = os.path.relpath(filename, dataDir)\n" ) buff.writeIndentedLines(code % params) # set up the ExperimentHandler code = ("\n# an ExperimentHandler isn't essential but helps with data saving\n" "thisExp = data.ExperimentHandler(\n" " name=expName, version=expVersion,\n" " extraInfo=expInfo, runtimeInfo=None,\n" " originPath=%(originPath)s,\n" " savePickle=%(Save psydat file)s, saveWideText=%(Save wide csv file)s,\n" " dataFileName=dataDir + os.sep + filename, sortColumns=%(sortColumns)s\n" ")\n") buff.writeIndentedLines(code % params) # enforce dict on column priority param colPriority = params['colPriority'].val if isinstance(colPriority, str): try: colPriority = ast.literal_eval(colPriority) except: raise ValueError(_translate( "Could not interpret value as dict: {}" ).format(colPriority)) # setup column priority for key, val in colPriority.items(): code = ( f"thisExp.setPriority('{key}', {val})\n" ) buff.writeIndentedLines(code) code = ( "# return experiment handler\n" "return thisExp\n" ) buff.writeIndentedLines(code) # Exit function def buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("\n") def writeLoggingCode(self, buff): # Enter function def code = ( '\n' 'def setupLogging(filename):\n' ' """\n' ' Setup a log file and tell it what level to log at.\n' ' \n' ' Parameters\n' ' ==========\n' ' filename : str or pathlib.Path\n' ' Filename to save log file and data files as, doesn\'t need an extension.\n' ' \n' ' Returns\n' ' ==========\n' ' psychopy.logging.LogFile\n' ' Text stream to receive inputs from the logging system.\n' ' """\n' ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) # set app logging level code = ( "# set how much information should be printed to the console / app\n" "if PILOTING:\n" " logging.console.setLevel(\n" " prefs.piloting['pilotConsoleLoggingLevel']\n" " )\n" "else:\n" " logging.console.setLevel('%(consoleLoggingLevel)s')\n" ) buff.writeIndentedLines(code % self.params) # create log file if self.params['Save log file'].val: code = ( "# save a log file for detail verbose info\n" "logFile = logging.LogFile(filename+'.log')\n" "if PILOTING:\n" " logFile.setLevel(\n" " prefs.piloting['pilotLoggingLevel']\n" " )\n" "else:\n" " logFile.setLevel(\n" " logging.getLevel('%(logging level)s')\n" " )\n" "\n" "return logFile\n" ) buff.writeIndentedLines(code % self.params) # Exit function def buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("\n") def writeExpInfoDlgCode(self, buff): # Enter function def code = ( '\n' 'def showExpInfoDlg(expInfo):\n' ' """\n' ' Show participant info dialog.\n' ' Parameters\n' ' ==========\n' ' expInfo : dict\n' ' Information about this experiment.\n' ' \n' ' Returns\n' ' ==========\n' ' dict\n' ' Information about this experiment.\n' ' """\n' ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) sorting = "False" # in Py3 dicts are chrono-sorted so default no sort code = ( f"# show participant info dialog\n" f"dlg = gui.DlgFromDict(\n" f" dictionary=expInfo, sortKeys={sorting}, title=expName, alwaysOnTop=True\n" f")\n" f"if dlg.OK == False:\n" f" core.quit() # user pressed cancel\n" f"# return expInfo\n" f"return expInfo\n" ) buff.writeIndentedLines(code) # Exit function def buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("\n") def writeDevicesCode(self, buff): # Open function def code = ( '\n' 'def setupDevices(expInfo, thisExp, win):\n' ' """\n' ' Setup whatever devices are available (mouse, keyboard, speaker, eyetracker, etc.) and add them to \n' ' the device manager (deviceManager)\n' ' \n' ' Parameters\n' ' ==========\n' ' expInfo : dict\n' ' Information about this experiment, created by the `setupExpInfo` function.\n' ' thisExp : psychopy.data.ExperimentHandler\n' ' Handler object for this experiment, contains the data to save and information about \n' ' where to save it to.\n' ' win : psychopy.visual.Window\n' ' Window in which to run this experiment.\n' ' Returns\n' ' ==========\n' ' bool\n' ' True if completed successfully.\n' ' """\n' ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) # Substitute inits inits = deepcopy(self.params) if inits['mgMove'].val == "CONTINUOUS": inits['mgMove'].val = "$" inits['keyboardBackend'].val = keyboardBackendMap[inits['keyboardBackend'].val] # Make ioConfig dict code = ( "# --- Setup input devices ---\n" "ioConfig = {}\n" ) buff.writeIndentedLines(code % inits) # add eyetracker config if self.params['eyetracker'] != "None": # alert user if there's no monitor config if self.params['Monitor'].val in ["", None, "None"]: alert(code=4545) # write opening comment code = ( "# setup eyetracking\n" ) buff.writeIndentedLines(code) # if backend is known and has an associated class, use its methods if self.params['eyetracker'].val in knownEyetrackerBackends: # get backend class backend = knownEyetrackerBackends[self.params['eyetracker'].val] # alert user if they need fullscreen and don't have it if backend.needsFullscreen and not self.params['Full-screen window'].val: alert(code=4540) # alert user if they need calibration and don't have it if backend.needsCalibration and not any( isinstance(rt, EyetrackerCalibrationRoutine) for rt in self.exp.flow ): alert(code=4510, strFields={'eyetracker': self.params['eyetracker'].val}) # write code backend.writeDeviceCode(inits, buff) # otherwise, do it the old fashioned way else: code = ( "ioConfig[%(eyetracker)s] = {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "'name': 'tracker',\n" ) buff.writeIndentedLines(code % inits) # Initialise for MouseGaze if self.params['eyetracker'] == "GazePoint": code = ( "'network_settings': {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "'ip_address': %(gpAddress)s,\n" "'port': %(gpPort)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) elif self.params['eyetracker'] == "Tobii Technology": code = ( "'model_name': %(tbModel)s,\n" "'serial_number': %(tbSerialNo)s,\n" "'runtime_settings': {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "'sampling_rate': %(tbSampleRate)s,\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) elif self.params['eyetracker'] == "SR Research Ltd": code = ( "'model_name': %(elModel)s,\n" "'simulation_mode': %(elSimMode)s,\n" "'network_settings': %(elAddress)s,\n" "'default_native_data_file_name': 'EXPFILE',\n" "'runtime_settings': {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "'sampling_rate': %(elSampleRate)s,\n" "'track_eyes': %(elTrackEyes)s,\n" "'sample_filtering': {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "'FILTER_FILE': %(elDataFiltering)s,\n" "'FILTER_ONLINE': %(elLiveFiltering)s,\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "},\n" "'vog_settings': {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "'pupil_measure_types': %(elPupilMeasure)s,\n" "'tracking_mode': %(elTrackingMode)s,\n" "'pupil_center_algorithm': %(elPupilAlgorithm)s,\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) elif self.params['eyetracker'] == "Pupil Labs": # Open runtime_settings dict code = ( "'runtime_settings': {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) # Define runtime_settings dict code = ( "'pupillometry_only': %(plPupillometryOnly)s,\n" "'surface_name': %(plSurfaceName)s,\n" "'confidence_threshold': %(plConfidenceThreshold)s,\n" ) buff.writeIndentedLines(code % inits) # Open runtime_settings > pupil_remote dict code = ( "'pupil_remote': {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) # Define runtime_settings > pupil_remote dict code = ( "'ip_address': %(plPupilRemoteAddress)s,\n" "'port': %(plPupilRemotePort)s,\n" "'timeout_ms': %(plPupilRemoteTimeoutMs)s,\n" ) buff.writeIndentedLines(code % inits) # Close runtime_settings > pupil_remote dict buff.setIndentLevel(-1, relative=True) code = ( "},\n" ) buff.writeIndentedLines(code % inits) # Open runtime_settings > pupil_capture_recording dict code = ( "'pupil_capture_recording': {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) # Define runtime_settings > pupil_capture_recording dict code = ( "'enabled': %(plPupilCaptureRecordingEnabled)s,\n" "'location': %(plPupilCaptureRecordingLocation)s,\n" ) buff.writeIndentedLines(code % inits) # Close runtime_settings > pupil_capture_recording dict buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) # Close runtime_settings dict buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) elif self.params['eyetracker'] == "Pupil Labs (Neon)": # Open runtime_settings dict code = ( "'runtime_settings': {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) # Define runtime_settings dict code = ( "'companion_address': %(plCompanionAddress)s,\n" "'companion_port': %(plCompanionPort)s,\n" "'recording_enabled': %(plCompanionRecordingEnabled)s,\n" ) buff.writeIndentedLines(code % inits) # Close runtime_settings dict buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) elif self.params['eyetracker'] == "EyeLogic": code = ( "'runtime_settings': {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "'sampling_rate': %(ecSampleRate)s,\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) # Close ioDevice dict buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) # Add keyboard to ioConfig if self.params['keyboardBackend'] == 'ioHub': code = ( "\n" "# Setup iohub keyboard\n" "ioConfig['Keyboard'] = dict(use_keymap='psychopy')\n" ) buff.writeIndentedLines(code % inits) if self.needIoHub and self.params['keyboardBackend'] == 'PsychToolbox': alert(code=4550) # Add experiment handler filename to ioConfig if self.needIoHub: code = ( "\n" "# Setup iohub experiment\n" "ioConfig['Experiment'] = dict(filename=thisExp.dataFileName)\n" ) buff.writeIndentedLines(code % inits) # Make ioDataStoreConfig dict if self.params['Save hdf5 file'].val: code = ( "\n" "# --- Setup iohub hdf5 datastore ---\n" ) buff.writeIndentedLines(code % inits) # Specify session code = ( "ioSession = str(expInfo.get('session', '1'))\n" ) buff.writeIndentedLines(code % inits) # Create ioDataStoreConfig dict code = ( "ioDataStoreConfig = {" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( f"'experiment_code': %(expName)s,\n" # noqa: F541 "'session_code': ioSession,\n" "'datastore_name': thisExp.dataFileName,\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) # Start ioHub server if self.needIoHub: code = ( "\n" "# Start ioHub server\n" ) buff.writeIndentedLines(code % inits) if self.params['Save hdf5 file'].val: code = ( "ioServer = io.launchHubServer(window=win, **ioDataStoreConfig, **ioConfig)\n" ) else: code = ( "ioServer = io.launchHubServer(window=win, **ioConfig)\n" ) buff.writeIndentedLines(code % inits) else: code = ( "ioSession = ioServer = eyetracker = None" ) buff.writeIndentedLines(code % inits) # store ioServer code = ( "\n" "# store ioServer object in the device manager\n" "deviceManager.ioServer = ioServer\n" ) buff.writeIndentedLines(code % inits) # add eyetracker to DeviceManager if self.params['eyetracker'] != "None": code = ( "deviceManager.devices['eyetracker'] = ioServer.getDevice('tracker')\n" ) buff.writeIndentedLines(code % inits) # make default keyboard code = ( "\n" "# create a default keyboard (e.g. to check for escape)\n" "if deviceManager.getDevice('defaultKeyboard') is None:\n" " deviceManager.addDevice(\n" " deviceClass='keyboard', deviceName='defaultKeyboard', backend=%(keyboardBackend)s\n" " )\n" ) buff.writeIndentedLines(code % inits) # write any device setup code required by a component for rt in self.exp.flow: if isinstance(rt, Routine): for comp in rt: if hasattr(comp, "writeDeviceCode"): comp.writeDeviceCode(buff) elif isinstance(rt, BaseStandaloneRoutine): rt.writeDeviceCode(buff) code = ( "# return True if completed successfully\n" "return True\n" ) buff.writeIndentedLines(code) # Exit function def buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("\n") def writeWindowCode(self, buff): """Setup the window code. """ # Open function def code = ( '\n' 'def setupWindow(expInfo=None, win=None):\n' ' """\n' ' Setup the Window\n' ' \n' ' Parameters\n' ' ==========\n' ' expInfo : dict\n' ' Information about this experiment, created by the `setupExpInfo` function.\n' ' win : psychopy.visual.Window\n' ' Window to setup - leave as None to create a new window.\n' ' \n' ' Returns\n' ' ==========\n' ' psychopy.visual.Window\n' ' Window in which to run this experiment.\n' ' """\n' ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) params = self.params.copy() # get parameters for the Window params['fullScr'] = self.params['Full-screen window'].val # if fullscreen then hide the mouse, unless its requested explicitly allowGUI = (not bool(params['fullScr'])) or bool(self.params['Show mouse'].val) allowStencil = False # NB routines is a dict: for thisRoutine in list(self.exp.routines.values()): # a single routine is a list of components: for thisComp in thisRoutine: if thisComp.type in ('Aperture', 'Textbox'): allowStencil = True if thisComp.type == 'RatingScale': allowGUI = True # to have a mouse params['allowGUI'] = allowGUI params['allowStencil'] = allowStencil # use fbo? params['useFBO'] = "True" if params['blendMode'].val in ("nofbo",): params['blendMode'].val = 'avg' params['useFBO'] = "False" # Substitute units if self.params['Units'].val == 'use prefs': params['Units'] = "None" requestedScreenNumber = int(self.params['Screen'].val) nScreens = 10 # try: # nScreens = wx.Display.GetCount() # NO, don't rely on wx being present # except Exception: # # will fail if application hasn't been created (e.g. in test # # environments) # nScreens = 10 if requestedScreenNumber > nScreens: logging.warn("Requested screen can't be found. Writing script " "using first available screen.") params['screenNumber'] = 0 else: # computer has 1 as first screen params['screenNumber'] = requestedScreenNumber - 1 params['size'] = self.params['Window size (pixels)'] params['winType'] = self.params['winBackend'] # force windowed according to prefs/pilot mode if params['fullScr']: msg = _translate("Fullscreen settings ignored as running in pilot mode.") code = ( f"if PILOTING:\n" f" logging.debug('{msg}')\n" f"\n" ) buff.writeIndentedLines(code % params) # Do we need to make a new window? code = ( "if win is None:\n" " # if not given a window to setup, make one\n" " win = visual.Window(\n" " size=_winSize, fullscr=_fullScr, screen=%(screenNumber)s,\n" " winType=%(winType)s, allowGUI=%(allowGUI)s, allowStencil=%(allowStencil)s,\n" " monitor=%(Monitor)s, color=%(color)s, colorSpace=%(colorSpace)s,\n" " backgroundImage=%(backgroundImg)s, backgroundFit=%(backgroundFit)s,\n" " blendMode=%(blendMode)s, useFBO=%(useFBO)s,\n" " units=%(Units)s,\n" " checkTiming=False # we're going to do this ourselves in a moment\n" " )\n" "else:\n" " # if we have a window, just set the attributes which are safe to set\n" " win.color = %(color)s\n" " win.colorSpace = %(colorSpace)s\n" " win.backgroundImage = %(backgroundImg)s\n" " win.backgroundFit = %(backgroundFit)s\n" " win.units = %(Units)s\n" ) buff.writeIndentedLines(code % params) # do/skip frame rate measurement according to params if self.params['measureFrameRate']: code = ( "if expInfo is not None:\n" " # get/measure frame rate if not already in expInfo\n" " if win._monitorFrameRate is None:\n" " win._monitorFrameRate = win.getActualFrameRate(infoMsg=%(frameRateMsg)s)\n" " expInfo['frameRate'] = win._monitorFrameRate\n" ) buff.writeIndentedLines(code % params) elif self.params['frameRate']: code = ( "if expInfo is not None:\n" " expInfo['frameRate'] = %(frameRate)s\n" ) buff.writeIndentedLines(code % params) # Reset splash message code = ( "win.hideMessage()\n" ) buff.writeIndentedLines(code) # show/hide pilot indicator code = ( "# show a visual indicator if we're in piloting mode\n" "if PILOTING and prefs.piloting['showPilotingIndicator']:\n" " win.showPilotingIndicator()\n" ) buff.writeIndentedLines(code) # Import here to avoid circular dependency! from psychopy.experiment._experiment import RequiredImport microphoneImport = RequiredImport(importName='microphone', importFrom='psychopy', importAs='') if microphoneImport in self.exp.requiredImports: # need a pyo Server buff.writeIndentedLines("\n# Enable sound input/output:\n" "microphone.switchOn()\n") # Exit function def code = ( "\n" "return win\n" ) buff.writeIndentedLines(code) buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("\n") def writeSaveDataCode(self, buff): # Open function def code = ( '\n' 'def saveData(thisExp):\n' ' """\n' ' Save data from this experiment\n' ' \n' ' Parameters\n' ' ==========\n' ' thisExp : psychopy.data.ExperimentHandler\n' ' Handler object for this experiment, contains the data to save and information about \n' ' where to save it to.\n' ' """\n' ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) # Get filename from thisExp code = ( "filename = thisExp.dataFileName\n" "# these shouldn't be strictly necessary (should auto-save)\n" ) if self.params['Save wide csv file'].val: code += ( "thisExp.saveAsWideText(filename + '.csv', delim=%(Data file delimiter)s)\n" ) if self.params['Save psydat file'].val: code += ( "thisExp.saveAsPickle(filename)\n" ) buff.writeIndentedLines(code % self.params) # Exit function def buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("\n") def writeWindowCodeJS(self, buff): """Setup the JS window code. """ # Replace instances of 'use prefs' units = self.params['Units'].val if units == 'use prefs': units = 'height' code = ("// init psychoJS:\n" "const psychoJS = new PsychoJS({{\n" " debug: true\n" "}});\n\n" "// open window:\n" "psychoJS.openWindow({{\n" " fullscr: {fullScr},\n" " color: new util.Color({params[color]}),\n" " units: '{units}',\n" " waitBlanking: true,\n" " backgroundImage: {params[backgroundImg]},\n" " backgroundFit: {params[backgroundFit]},\n" "}});\n").format( fullScr=str(self.params['Full-screen window']).lower(), params=self.params, units=units ) buff.writeIndentedLines(code) def writePauseCode(self, buff): # Open function def code = ( 'def pauseExperiment(thisExp, win=None, timers=[], playbackComponents=[]):\n' ' """\n' ' Pause this experiment, preventing the flow from advancing to the next routine until resumed.\n' ' \n' ' Parameters\n' ' ==========\n' ' thisExp : psychopy.data.ExperimentHandler\n' ' Handler object for this experiment, contains the data to save and information about \n' ' where to save it to.\n' ' win : psychopy.visual.Window\n' ' Window for this experiment.\n' ' timers : list, tuple\n' ' List of timers to reset once pausing is finished.\n' ' playbackComponents : list, tuple\n' ' List of any components with a `pause` method which need to be paused.\n' ' """' ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) # handle pausing code = ( "# if we are not paused, do nothing\n" "if thisExp.status != PAUSED:\n" " return\n" "\n" "# start a timer to figure out how long we're paused for\n" "pauseTimer = core.Clock()\n" "# pause any playback components\n" "for comp in playbackComponents:\n" " comp.pause()\n" "# make sure we have a keyboard\n" "defaultKeyboard = deviceManager.getDevice('defaultKeyboard')\n" "if defaultKeyboard is None:\n" " defaultKeyboard = deviceManager.addKeyboard(\n" " deviceClass='keyboard',\n" " deviceName='defaultKeyboard',\n" " backend=%(keyboardBackend)s,\n" " )\n" "# run a while loop while we wait to unpause\n" "while thisExp.status == PAUSED:\n" ) if self.params['Enable Escape'].val: code += ( " # check for quit (typically the Esc key)\n" " if defaultKeyboard.getKeys(keyList=['escape']):\n" " endExperiment(thisExp, win=win)\n" ) code += ( " # sleep 1ms so other threads can execute\n" " clock.time.sleep(0.001)\n" "# if stop was requested while paused, quit\n" "if thisExp.status == FINISHED:\n" " endExperiment(thisExp, win=win)\n" "# resume any playback components\n" "for comp in playbackComponents:\n" " comp.play()\n" "# reset any timers\n" "for timer in timers:\n" " timer.addTime(-pauseTimer.getTime())\n" ) buff.writeIndentedLines(code % self.params) # Exit function def buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("\n") def writeEndCode(self, buff): """Write code for end of experiment (e.g. close log file). """ # Open function def code = ( '\n' 'def endExperiment(thisExp, win=None):\n' ' """\n' ' End this experiment, performing final shut down operations.\n' ' \n' ' This function does NOT close the window or end the Python process - use `quit` for this.\n' ' \n' ' Parameters\n' ' ==========\n' ' thisExp : psychopy.data.ExperimentHandler\n' ' Handler object for this experiment, contains the data to save and information about \n' ' where to save it to.\n' ' win : psychopy.visual.Window\n' ' Window for this experiment.\n' ' """\n' ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) # Write code to end experiment code = ( "if win is not None:\n" " # remove autodraw from all current components\n" " win.clearAutoDraw()\n" " # Flip one final time so any remaining win.callOnFlip() \n" " # and win.timeOnFlip() tasks get executed\n" " win.flip()\n" "# return console logger level to WARNING\n" "logging.console.setLevel(logging.WARNING)\n" "# mark experiment handler as finished\n" "thisExp.status = FINISHED\n" "# run any 'at exit' functions\n" "for fcn in runAtExit:\n" " fcn()\n" ) if self.params['Save log file'].val: code += ( "logging.flush()\n" ) buff.writeIndentedLines(code) # Exit function def buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("\n") # Open function def code = ( '\n' 'def quit(thisExp, win=None, thisSession=None):\n' ' """\n' ' Fully quit, closing the window and ending the Python process.\n' ' \n' ' Parameters\n' ' ==========\n' ' win : psychopy.visual.Window\n' ' Window to close.\n' ' thisSession : psychopy.session.Session or None\n' ' Handle of the Session object this experiment is being run from, if any.\n' ' """\n' ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) # Write code to end session code = ( "thisExp.abort() # or data files will save again on exit\n" "# make sure everything is closed down\n" "if win is not None:\n" " # Flip one final time so any remaining win.callOnFlip() \n" " # and win.timeOnFlip() tasks get executed before quitting\n" " win.flip()\n" " win.close()\n" ) if self.params['Save log file'].val: code += ( "logging.flush()\n" ) code += ( "if thisSession is not None:\n" " thisSession.stop()\n" "# terminate Python process\n" "core.quit()\n" ) buff.writeIndentedLines(code) # Exit function def buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("\n") def writeEndCodeJS(self, buff): """Write some general functions that might be used by any Scheduler/object""" recordLoopIterationFunc = ("\nfunction importConditions(currentLoop) {\n" " return async function () {\n" " psychoJS.importAttributes(currentLoop.getCurrentTrial());\n" " return Scheduler.Event.NEXT;\n" " };\n" "}\n") buff.writeIndentedLines(recordLoopIterationFunc) code = ( "\n" "async function quitPsychoJS(message, isCompleted) {\n" ) buff.writeIndented(code) buff.setIndentLevel(1, relative=True) code = ("// Check for and save orphaned data\n" "if (psychoJS.experiment.isEntryEmpty()) {\n" " psychoJS.experiment.nextEntry();\n" "}\n") buff.writeIndentedLines(code) # Write End Experiment code component for thisRoutine in self.exp.flow: # write for regular Routines if isinstance(thisRoutine, Routine): for thisComp in thisRoutine: if hasattr(thisComp, "writeExperimentEndCodeJS"): thisComp.writeExperimentEndCodeJS(buff) # write for standalone Routines if isinstance(thisRoutine, BaseStandaloneRoutine): if hasattr(thisRoutine, "writeExperimentEndCodeJS"): thisRoutine.writeExperimentEndCodeJS(buff) code = ("psychoJS.window.close();\n" "psychoJS.quit({message: message, isCompleted: isCompleted});\n\n" "return Scheduler.Event.QUIT;\n") buff.writeIndentedLines(code) buff.setIndentLevel(-1, relative=True) buff.writeIndented("}\n") buff.setIndentLevel(-1) @property 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 @monitor.setter def monitor(self, monitor): self._monitor = monitor @property def needIoHub(self): # Needed for keyboard kb = self.params['keyboardBackend'] == 'ioHub' # Needed for eyetracking et = self.params['eyetracker'] != 'None' return any((kb, et))
96,405
Python
.py
2,079
33.082251
155
0.535076
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,608
eyetracking.py
psychopy_psychopy/psychopy/experiment/components/settings/eyetracking.py
from psychopy.localization import _translate from psychopy.experiment import Param knownEyetrackerBackends = {} class EyetrackerBackend: # label to display in Builder label = None # key to index this backend by key = None # information about this backend's needs (for raising alerts and etc.) needsFullscreen = True needsCalibration = True def __init_subclass__(cls): # skip any classes with no key if cls.key is None: return # append to global variable global knownEyetrackerBackends knownEyetrackerBackends[cls.key] = cls @classmethod def getParams(cls): """ Method to get the params to be added to SettingsComponent by this backend. Returns ------- dict[str: Param] Dict of params to add, by name list[str] List determining order of params (by name) """ params = {} order = [] return params, order @classmethod def writeDeviceCode(cls, inits, buff): """ Overload this method in a subclass to control the code that's written in the `setupDevices` function of Builder experiments when using this backend. Parameters ---------- comp : dict[str: psychopy.experiment.Param] Dict of params from the Settings Component buff : io.StringIO String buffer to write to (i.e. the experiment-in-progress) """ raise NotImplementedError() class MouseGazeEyetrackerBackend(EyetrackerBackend): label = "MouseGaze" key = "eyetracker.hw.mouse.EyeTracker" needsFullscreen = False needsCalibration = False @classmethod def getParams(cls): # define order order = [ "mgMove", "mgBlink", "mgSaccade", ] # define params params = {} params['mgMove'] = Param( "CONTINUOUS", valType='str', inputType="choice", allowedVals=['CONTINUOUS', 'LEFT_BUTTON', 'MIDDLE_BUTTON', 'RIGHT_BUTTON'], hint=_translate("Mouse button to press for eye movement."), label=_translate("Move button"), categ="Eyetracking" ) params['mgBlink'] = Param( "MIDDLE_BUTTON", valType='list', inputType="multiChoice", allowedVals=['LEFT_BUTTON', 'MIDDLE_BUTTON', 'RIGHT_BUTTON'], hint=_translate("Mouse button to press for a blink."), label=_translate("Blink button"), categ="Eyetracking" ) params['mgSaccade'] = Param( 0.5, valType='num', inputType="single", hint=_translate("Visual degree threshold for Saccade event creation."), label=_translate("Saccade threshold"), categ="Eyetracking" ) return params, order @classmethod def writeDeviceCode(cls, inits, buff): code = ( "ioConfig[%(eyetracker)s] = {\n" " 'name': 'tracker',\n" " 'controls': {\n" " 'move': [%(mgMove)s],\n" " 'blink':%(mgBlink)s,\n" " 'saccade_threshold': %(mgSaccade)s,\n" " },\n" "}\n" ) buff.writeIndentedLines(code % inits)
3,325
Python
.py
91
27.252747
100
0.585862
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,609
__init__.py
psychopy_psychopy/psychopy/experiment/components/code/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy import prefs from psychopy.experiment.components import BaseComponent, Param, _translate from psychopy.alerts import alerttools class CodeComponent(BaseComponent): """ This Component can be used to insert short pieces of python code into your experiments. This might be create a variable that you want for another :ref:`Component <components>`, to manipulate images before displaying them, to interact with hardware for which there isn't yet a pre-packaged component in |PsychoPy| (e.g. writing code to interact with the serial/parallel ports). See `code uses`_ below. Be aware that the code for each of the components in your :ref:`Routine <routines>` are executed in the order they appear on the :ref:`Routine <routines>` display (from top to bottom). If you want your `Code Component` to alter a variable to be used by another component immediately, then it needs to be above that component in the view. You may want the code not to take effect until next frame however, in which case put it at the bottom of the :ref:`Routine <routines>`. You can move `Components` up and down the :ref:`Routine <routines>` by right-clicking on their icons. Within your code you can use other variables and modules from the script. For example, all routines have a stopwatch-style :class:`~psychopy.core.Clock` associated with them, which gets reset at the beginning of that repeat of the routine. So if you have a :ref:`Routine <routines>` called trial, there will be a :class:`~psychopy.core.Clock` called trialClock and so you can get the time (in sec) from the beginning of the trial by using:: currentT = trialClock.getTime() To see what other variables you might want to use, and also what terms you need to avoid in your chunks of code, :ref:`compile your script <compileScript>` before inserting the code object and take a look at the contents of that script. Note that this page is concerned with `Code Components` specifically, and not all cases in which you might use python syntax within the Builder. It is also possible to put code into a non-code input field (such as the duration or text of a `Text Component`). The syntax there is slightly different (requiring a `$` to trigger the special handling, or `\\$` to avoid triggering special handling). The syntax to use within a Code Component is always regular python syntax. """ categories = ['Custom'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'code.png' tooltip = _translate('Code: insert python commands into an experiment') def __init__(self, exp, parentName, name='code', beforeExp="", beginExp="", beginRoutine="", eachFrame="", endRoutine="", endExperiment="", codeType=None, translator="manual"): super(CodeComponent, self).__init__(exp, parentName, name) self.type = 'Code' self.url = "https://www.psychopy.org/builder/components/code.html" # params # want a copy, else codeParamNames list gets mutated self.order = ['name', 'Code Type', 'disabled', 'Before Experiment', 'Begin Experiment', 'Begin Routine', 'Each Frame', 'End Routine', 'End Experiment', 'Before JS Experiment', 'Begin JS Experiment', 'Begin JS Routine', 'Each JS Frame', 'End JS Routine', 'End JS Experiment', ] if not codeType: codeType = prefs.builder['codeComponentLanguage'] msg = _translate("Display Python or JS Code") self.params['Code Type'] = Param( codeType, valType='str', inputType="choice", allowedTypes=[], allowedVals=['Py', 'JS', 'Both', 'Auto->JS'], hint=msg, direct=False, label=_translate("Code type")) msg = _translate("Code to run before the experiment starts " "(initialization); right-click checks syntax") self.params['Before Experiment'] = Param( beforeExp, valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("Before experiment")) msg = _translate("Code at the start of the experiment ; right-click " "checks syntax") self.params['Begin Experiment'] = Param( beginExp, valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("Begin experiment")) msg = _translate("Code to be run at the start of each repeat of the " "Routine (e.g. each trial); " "right-click checks syntax") self.params['Begin Routine'] = Param( beginRoutine, valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("Begin Routine")) msg = _translate("Code to be run on every video frame during for the" " duration of this Routine; " "right-click checks syntax") self.params['Each Frame'] = Param( eachFrame, valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("Each frame")) msg = _translate("Code at the end of this repeat of the Routine (e.g." " getting/storing responses); " "right-click checks syntax") self.params['End Routine'] = Param( endRoutine, valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("End Routine")) msg = _translate("Code at the end of the entire experiment (e.g. " "saving files, resetting computer); " "right-click checks syntax") self.params['End Experiment'] = Param( endExperiment, valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("End experiment")) # todo: copy initial vals once javscript interp can do comments msg = _translate("Code before the start of the experiment (initialization" "); right-click checks syntax") self.params['Before JS Experiment'] = Param( '', valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("Before JS experiment")) msg = _translate("Code at the start of the experiment (initialization" "); right-click checks syntax") self.params['Begin JS Experiment'] = Param( '', valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("Begin JS experiment")) msg = _translate("Code to be run at the start of each repeat of the " "Routine (e.g. each trial); " "right-click checks syntax") self.params['Begin JS Routine'] = Param( '', valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("Begin JS Routine")) msg = _translate("Code to be run on every video frame during for the" " duration of this Routine; " "right-click checks syntax") self.params['Each JS Frame'] = Param( '', valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("Each JS frame")) msg = _translate("Code at the end of this repeat of the Routine (e.g." " getting/storing responses); " "right-click checks syntax") self.params['End JS Routine'] = Param( '', valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("End JS Routine")) msg = _translate("Code at the end of the entire experiment (e.g. " "saving files, resetting computer); " "right-click checks syntax") self.params['End JS Experiment'] = Param( '', valType='extendedCode', inputType="multi", allowedTypes=[], updates='constant', allowedUpdates=[], hint=msg, label=_translate("End JS experiment")) # these inherited params are harmless but might as well trim: for p in ('startType', 'startVal', 'startEstim', 'stopVal', 'stopType', 'durationEstim', 'saveStartStop', 'syncScreenRefresh'): if p in self.params: del self.params[p] def integrityCheck(self): python_parts = { 'Before Experiment', 'Begin Experiment', 'Begin Routine', 'Each Frame', 'End Routine', 'End Experiment'} js_parts = { 'Before JS Experiment', 'Begin JS Experiment', 'Begin JS Routine', 'Each JS Frame', 'End JS Routine', 'End JS Experiment'} for part in python_parts: if len(str(self.params[part])): alerttools.checkPythonSyntax(self, part) for part in js_parts: if len(str(self.params[part])): alerttools.checkJavaScriptSyntax(self, part) def writePreCode(self, buff): if len(str(self.params['Before Experiment'])) and not self.params['disabled']: alerttools.checkPythonSyntax(self, 'Before Experiment') if self.params['Before Experiment']: buff.writeIndentedLines("# Run 'Before Experiment' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['Before Experiment']) + '\n') def writePreCodeJS(self, buff): if len(str(self.params['Before JS Experiment'])) and not self.params['disabled']: alerttools.checkJavaScriptSyntax(self, 'Before JS Experiment') if self.params['Before Experiment']: buff.writeIndentedLines("// Run 'Before Experiment' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['Before JS Experiment']) + '\n') def writeInitCode(self, buff): if len(str(self.params['Begin Experiment'])) and not self.params['disabled']: alerttools.checkPythonSyntax(self, 'Begin Experiment') if self.params['Begin Experiment']: buff.writeIndentedLines("# Run 'Begin Experiment' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['Begin Experiment']) + '\n') def writeInitCodeJS(self, buff): if len(str(self.params['Begin JS Experiment'])) and not self.params['disabled']: alerttools.checkJavaScriptSyntax(self, 'Begin JS Experiment') if self.params['Begin Experiment']: buff.writeIndentedLines("// Run 'Begin Experiment' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['Begin JS Experiment']) + '\n') def writeRoutineStartCode(self, buff): if len(str(self.params['Begin Routine'])) and not self.params['disabled']: alerttools.checkPythonSyntax(self, 'Begin Routine') if self.params['Begin Routine']: buff.writeIndentedLines("# Run 'Begin Routine' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['Begin Routine']) + '\n') def writeRoutineStartCodeJS(self, buff): if len(str(self.params['Begin JS Routine'])) and not self.params['disabled']: alerttools.checkJavaScriptSyntax(self, 'Begin JS Routine') if self.params['Begin Routine']: buff.writeIndentedLines("// Run 'Begin Routine' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['Begin JS Routine']) + '\n') def writeFrameCode(self, buff): if len(str(self.params['Each Frame'])) and not self.params['disabled']: alerttools.checkPythonSyntax(self, 'Each Frame') if self.params['Each Frame']: buff.writeIndentedLines("# Run 'Each Frame' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['Each Frame']) + '\n') def writeFrameCodeJS(self, buff): if len(str(self.params['Each JS Frame'])) and not self.params['disabled']: alerttools.checkJavaScriptSyntax(self, 'Each JS Frame') if self.params['Each Frame']: buff.writeIndentedLines("// Run 'Each Frame' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['Each JS Frame']) + '\n') def writeRoutineEndCode(self, buff): if len(str(self.params['End Routine'])) and not self.params['disabled']: alerttools.checkPythonSyntax(self, 'End Routine') if self.params['End Routine']: buff.writeIndentedLines("# Run 'End Routine' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['End Routine']) + '\n') def writeRoutineEndCodeJS(self, buff): if len(str(self.params['End JS Routine'])) and not self.params['disabled']: alerttools.checkJavaScriptSyntax(self, 'End JS Routine') if self.params['End Routine']: buff.writeIndentedLines("// Run 'End Routine' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['End JS Routine']) + '\n') def writeExperimentEndCode(self, buff): if len(str(self.params['End Experiment'])) and not self.params['disabled']: alerttools.checkPythonSyntax(self, 'End Experiment') if self.params['End Experiment']: buff.writeIndentedLines("# Run 'End Experiment' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['End Experiment']) + '\n') def writeExperimentEndCodeJS(self, buff): if len(str(self.params['End JS Experiment'])) and not self.params['disabled']: alerttools.checkJavaScriptSyntax(self, 'End JS Experiment') if self.params['End Experiment']: buff.writeIndentedLines("// Run 'End Experiment' code from %(name)s" % self.params) buff.writeIndentedLines(str(self.params['End JS Experiment']) + '\n')
15,441
Python
.py
262
46.874046
102
0.617356
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,610
__init__.py
psychopy_psychopy/psychopy/experiment/components/form/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy.experiment.components import Param, getInitVals, _translate, BaseVisualComponent from psychopy.tools.stimulustools import formStyles __author__ = 'Jon Peirce, David Bridges, Anthony Haffey' knownStyles = list(formStyles) class FormComponent(BaseVisualComponent): """A class for presenting a survey as a Builder component""" categories = ['Responses'] targets = ['PsychoPy', 'PsychoJS'] version = "2020.2.0" iconFile = Path(__file__).parent / 'form.png' tooltip = _translate('Form: a Psychopy survey tool') beta = True def __init__(self, exp, parentName, name='form', items='', textHeight=0.03, font="Open Sans", randomize=False, fillColor='', borderColor='', itemColor='white', responseColor='white', markerColor='red', size=(1, .7), pos=(0, 0), style='dark', itemPadding=0.05, startType='time (s)', startVal='0.0', stopType='duration (s)', stopVal='', startEstim='', durationEstim='', # legacy color='white'): super(FormComponent, self).__init__( exp, parentName, name=name, pos=pos, size=size, color=color, fillColor=fillColor, borderColor=borderColor, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) # these are defined by the BaseVisual but we don't want them del self.params['ori'] del self.params['units'] # we only support height units right now del self.params['color'] self.type = 'Form' self.url = "https://www.psychopy.org/builder/components/form.html" self.exp.requirePsychopyLibs(['visual', 'event', 'logging']) # params self.order += ['Items', 'Randomize', # Basic tab 'Data Format', # Data tab ] self.order.insert(self.order.index("units"), "Item Padding") # normal params: # = the usual as inherited from BaseComponent plus: self.params['Items'] = Param( items, valType='file', inputType="table", allowedTypes=[], categ='Basic', updates='constant', hint=_translate("The csv filename containing the items for your survey."), label=_translate("Items"), ctrlParams={ 'template': Path(__file__).parent / "formItems.xltx" } ) self.params['Text Height'] = Param( textHeight, valType='num', inputType="single", allowedTypes=[], categ='Formatting', updates='constant', hint=_translate("The size of the item text for Form"), label=_translate("Text height")) self.params['Font'] = Param( font, valType='str', inputType="single", allowedTypes=[], categ='Formatting', updates='constant', allowedUpdates=["constant"], hint=_translate("The font name (e.g. Comic Sans)"), label=_translate("Font")) self.params['Randomize'] = Param( randomize, valType='bool', inputType="bool", allowedTypes=[], categ='Basic', updates='constant', hint=_translate("Do you want to randomize the order of your questions?"), label=_translate("Randomize")) self.params['Item Padding'] = Param( itemPadding, valType='num', inputType="single", allowedTypes=[], categ='Layout', updates='constant', hint=_translate("The padding or space between items."), label=_translate("Item padding")) self.params['Data Format'] = Param( 'rows', valType='str', inputType="choice", allowedTypes=[], categ='Basic', allowedVals=['columns', 'rows'], updates='constant', hint=_translate("Store item data by columns, or rows"), label=_translate("Data format")) # Appearance for param in ['fillColor', 'borderColor', 'itemColor', 'responseColor', 'markerColor', 'Style']: if param in self.order: self.order.remove(param) self.order.insert( self.order.index("colorSpace"), param ) self.params['Style'] = Param( style, valType='str', inputType="choice", categ="Appearance", updates='constant', allowedVals=knownStyles + ["custom..."], hint=_translate( "Styles determine the appearance of the form"), label=_translate("Styles")) for param in ['fillColor', 'borderColor', 'itemColor', 'responseColor', 'markerColor']: self.depends += [{ "dependsOn": "Style", # must be param name "condition": "=='custom...'", # val to check for "param": param, # param property to alter "true": "enable", # what to do with param if condition is True "false": "disable", # permitted: hide, show, enable, disable }] self.params['fillColor'].hint = _translate("Color of the form's background") self.params['borderColor'].hint = _translate("Color of the outline around the form") self.params['itemColor'] = Param(itemColor, valType='color', inputType="color", categ='Appearance', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=_translate("Base text color for questions"), label=_translate("Item color")) self.params['responseColor'] = Param(responseColor, valType='color', inputType="color", categ='Appearance', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=_translate("Base text color for responses, also sets color of lines in sliders and borders of textboxes"), label=_translate("Response color")) self.params['markerColor'] = Param(markerColor, valType='color', inputType="color", categ='Appearance', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=_translate("Color of markers and the scrollbar"), label=_translate("Marker color")) self.params['pos'].allowedUpdates = [] self.params['size'].allowedUpdates = [] def writeInitCode(self, buff): inits = getInitVals(self.params) inits['depth'] = -self.getPosInRoutine() # build up an initialization string for Form(): code = ( "win.allowStencil = True\n" "%(name)s = visual.Form(win=win, name='%(name)s',\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "items=%(Items)s,\n" "textHeight=%(Text Height)s,\n" "font=%(Font)s,\n" "randomize=%(Randomize)s,\n" "style=%(Style)s,\n" "fillColor=%(fillColor)s, borderColor=%(borderColor)s, itemColor=%(itemColor)s, \n" "responseColor=%(responseColor)s, markerColor=%(markerColor)s, colorSpace=%(colorSpace)s, \n" "size=%(size)s,\n" "pos=%(pos)s,\n" "itemPadding=%(Item Padding)s,\n" "depth=%(depth)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( ")\n" ) buff.writeIndentedLines(code % inits) def writeInitCodeJS(self, buff): inits = getInitVals(self.params) inits['depth'] = -self.getPosInRoutine() # build up an initialization string for Form(): initStr = ("{name} = new visual.Form({{\n" " win : psychoJS.window, name:'{name}',\n" " items : {Items},\n" " textHeight : {Text Height},\n" " font : {Font},\n" " randomize : {Randomize},\n" " size : {size},\n" " pos : {pos},\n" " style : {Style},\n" " itemPadding : {Item Padding},\n" " depth : {depth}\n" "}});\n".format(**inits)) buff.writeIndentedLines(initStr) def writeRoutineEndCode(self, buff): # save data, according to row/col format buff.writeIndented("{name}.addDataToExp(thisExp, {Data Format})\n" .format(**self.params)) buff.writeIndented("{name}.autodraw = False\n" .format(**self.params)) def writeRoutineEndCodeJS(self, buff): # save data, according to row/col format buff.writeIndented("{name}.addDataToExp(psychoJS.experiment, {Data Format});\n" .format(**self.params))
9,443
Python
.py
194
36.360825
123
0.564236
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,611
__init__.py
psychopy_psychopy/psychopy/experiment/components/joystick/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy.experiment.components import BaseComponent, Param, _translate from psychopy.experiment import valid_var_re from psychopy.experiment import CodeGenerationException, valid_var_re import re class JoystickComponent(BaseComponent): """An event class for checking the joystick location and buttons at given timepoints """ categories = ['Responses'] targets = ['PsychoPy'] iconFile = Path(__file__).parent / 'joystick.png' tooltip = _translate('Joystick: query joystick position and buttons') def __init__(self, exp, parentName, name='joystick', startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal='', startEstim='', durationEstim='', save='final', forceEndRoutineOnPress="any click", timeRelativeTo='joystick onset', deviceNumber='0', allowedButtons=''): super(JoystickComponent, self).__init__( exp, parentName, name=name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Joystick' self.url = "https://www.psychopy.org/builder/components/joystick.html" self.exp.requirePsychopyLibs(['event']) self.categories = ['Inputs'] self.order += ['forceEndRoutine', # Basic tab 'saveJoystickState', 'timeRelativeTo', 'clickable', 'saveParamsClickable', 'allowedButtons', # Data tab 'deviceNumber', # Hardware tab ] # params msg = _translate( "How often should the joystick state (x,y,buttons) be stored? " "On every video frame, every click or just at the end of the " "Routine?") self.params['saveJoystickState'] = Param( save, valType='str', inputType="choice", categ='Data', allowedVals=['final', 'on click', 'every frame', 'never'], hint=msg, direct=False, label=_translate("Save joystick state")) msg = _translate("Should a button press force the end of the Routine" " (e.g end the trial)?") if forceEndRoutineOnPress is True: forceEndRoutineOnPress = 'any click' elif forceEndRoutineOnPress is False: forceEndRoutineOnPress = 'never' self.params['forceEndRoutineOnPress'] = Param( forceEndRoutineOnPress, valType='str', inputType="choice", categ='Basic', allowedVals=['never', 'any click', 'valid click'], updates='constant', hint=msg, direct=False, label=_translate("End Routine on press")) msg = _translate("What should the values of joystick.time should be " "relative to?") self.params['timeRelativeTo'] = Param( timeRelativeTo, valType='str', inputType="choice", categ='Data', allowedVals=['joystick onset', 'experiment', 'routine'], updates='constant', direct=False, hint=msg, label=_translate("Time relative to")) msg = _translate('A comma-separated list of your stimulus names that ' 'can be "clicked" by the participant. ' 'e.g. target, foil' ) self.params['clickable'] = Param( '', valType='list', inputType="single", categ='Data', updates='constant', hint=msg, label=_translate("Clickable stimuli")) msg = _translate('The params (e.g. name, text), for which you want ' 'to store the current value, for the stimulus that was' '"clicked" by the joystick. Make sure that all the ' 'clickable objects have all these params.' ) self.params['saveParamsClickable'] = Param( 'name,', valType='list', inputType="single", categ='Data', updates='constant', allowedUpdates=[], hint=msg, direct=False, label=_translate("Store params for clicked")) msg = _translate('Device number, if you have multiple devices which' ' one do you want (0, 1, 2...)') self.params['deviceNumber'] = Param( deviceNumber, valType='int', inputType="single", allowedTypes=[], categ='Hardware', updates='constant', allowedUpdates=[], hint=msg, label=_translate("Device number")) msg = _translate('Buttons to be read (blank for any) numbers separated by ' 'commas') self.params['allowedButtons'] = Param( allowedButtons, valType='list', inputType="single", allowedTypes=[], categ='Data', updates='constant', allowedUpdates=[], hint=msg, label=_translate("Allowed buttons")) @property def _clickableParamsList(self): # convert clickableParams (str) to a list params = self.params['saveParamsClickable'].val paramsList = re.findall(r"[\w']+", params) return paramsList or ['name'] def _writeClickableObjectsCode(self, buff): # code to check if clickable objects were clicked code = ( "# check if the joystick was inside our 'clickable' objects\n" "gotValidClick = False;\n" "for obj in [%(clickable)s]:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("if obj.contains(%(name)s.getX(), %(name)s.getY()):\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("gotValidClick = True\n") buff.writeIndentedLines(code % self.params) code = '' for paramName in self._clickableParamsList: code += "%s.clicked_%s.append(obj.%s)\n" %(self.params['name'], paramName, paramName) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-2, relative=True) def writeStartCode(self, buff): code = ("from psychopy.hardware import joystick as joysticklib " "# joystick/gamepad accsss\n" "from psychopy.experiment.components.joystick import " "virtualJoystick as virtualjoysticklib\n") buff.writeIndentedLines(code % self.params) def writeInitCode(self, buff): code = ("x, y = [None, None]\n" "%(name)s = type('', (), {})() " "# Create an object to use as a name space\n" "%(name)s.device = None\n" "%(name)s.device_number = %(deviceNumber)s\n" "%(name)s.joystickClock = core.Clock()\n" "%(name)s.xFactor = 1\n" "%(name)s.yFactor = 1\n" "\n" "try:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("numJoysticks = joysticklib.getNumJoysticks()\n" "if numJoysticks > 0:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("try:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("joystickCache\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("except NameError:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("joystickCache={}\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("if not %(deviceNumber)s in joystickCache:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("joystickCache[%(deviceNumber)s] = joysticklib.Joystick(%(deviceNumber)s)\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("%(name)s.device = joystickCache[%(deviceNumber)s]\n") buff.writeIndentedLines(code % self.params) code = ("if win.units == 'height':\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(1, relative=True) code = ("%(name)s.xFactor = 0.5 * win.size[0]/win.size[1]\n" "%(name)s.yFactor = 0.5\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) buff.setIndentLevel(-1, relative=True) code = ("else:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("%(name)s.device = virtualjoysticklib.VirtualJoystick(%(deviceNumber)s)\n" "logging.warning(\"joystick_{}: " "Using keyboard+mouse emulation 'ctrl' " "+ 'Alt' + digit.\".format(%(name)s.device_number))\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) buff.setIndentLevel(-1, relative=True) code = ("except Exception:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("pass\n\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("if not %(name)s.device:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ("logging.error('No joystick/gamepad device found.')\n" "core.quit()\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ("\n" "%(name)s.status = None\n" "%(name)s.clock = core.Clock()\n" "%(name)s.numButtons = %(name)s.device.getNumButtons()\n" "%(name)s.getNumButtons = %(name)s.device.getNumButtons\n" "%(name)s.getAllButtons = %(name)s.device.getAllButtons\n" "%(name)s.getX = lambda: %(name)s.xFactor * %(name)s.device.getX()\n" "%(name)s.getY = lambda: %(name)s.yFactor * %(name)s.device.getY()\n" ) buff.writeIndentedLines(code % self.params) buff.writeIndented("\n") def writeRoutineStartCode(self, buff): """Write the code that will be called at the start of the routine """ code = ("{name}.oldButtonState = {name}.device.getAllButtons()[:]\n") buff.writeIndentedLines(code.format(**self.params)) allowedButtons = self.params['allowedButtons'].val.strip() allowedButtonsIsVar = (valid_var_re.match(str(allowedButtons)) and not allowedButtons == 'None') if allowedButtonsIsVar: # if it looks like a variable, check that the variable is suitable # to eval at run-time code = ("# AllowedKeys looks like a variable named `{0}`\n" #"print(\"{0}<{{}}> type:{{}}\".format({0}, type({0})))\n" "if not type({0}) in [list, tuple, np.ndarray]:\n") buff.writeIndentedLines(code.format(allowedButtons)) buff.setIndentLevel(1, relative=True) code = ("if type({0}) == int:\n") buff.writeIndentedLines(code.format(allowedButtons)) buff.setIndentLevel(1, relative=True) code = ("{0} = [{0}]\n") buff.writeIndentedLines(code.format(allowedButtons)) buff.setIndentLevel(-1, relative=True) code = ("elif not (isinstance({0}, str) " "or isinstance({0}, unicode)):\n") buff.writeIndentedLines(code.format(allowedButtons)) buff.setIndentLevel(1, relative=True) code = ("logging.error('AllowedKeys variable `{0}` is " "not string- or list-like.')\n" "core.quit()\n") buff.writeIndentedLines(code.format(allowedButtons)) buff.setIndentLevel(-1, relative=True) code = ("elif not ',' in {0}: {0} = eval(({0},))\n" "else: {0} = eval({0})\n") buff.writeIndentedLines(code.format(allowedButtons)) buff.setIndentLevel(-1, relative=True) # do we need a list of buttons? (variable case is already handled) if allowedButtons in [None, "none", "None", "", "[]", "()"]: buttonList=[] elif not allowedButtonsIsVar: try: buttonList = eval(allowedButtons) except Exception: raise CodeGenerationException( self.params["name"], "Allowed buttons list is invalid.") if type(buttonList) == tuple: buttonList = list(buttonList) elif isinstance(buttonList, int): # a single string/key buttonList = [buttonList] #print("buttonList={}".format(buttonList)) if allowedButtonsIsVar: code = ("{name}.activeButtons={0}\n") buff.writeIndentedLines(code.format(allowedButtons, **self.params)) else: if buttonList == []: code = ("{name}.activeButtons=[i for i in range({name}.numButtons)]") buff.writeIndentedLines(code.format(allowedButtons, **self.params)) else: code = ("{name}.activeButtons={0}") buff.writeIndentedLines(code.format(buttonList, **self.params)) # create some lists to store recorded values positions and events if # we need more than one code = ("# setup some python lists for storing info about the " "%(name)s\n") if self.params['saveJoystickState'].val in ['every frame', 'on click']: code += ("%(name)s.x = []\n" "%(name)s.y = []\n" "%(name)s.buttonLogs = [[] for i in range(%(name)s.numButtons)]\n" "%(name)s.time = []\n") if self.params['clickable'].val: for clickableObjParam in self._clickableParamsList: code += "%(name)s.clicked_{} = []\n".format(clickableObjParam) code += "gotValidClick = False # until a click is received\n" if self.params['timeRelativeTo'].val.lower() == 'routine': code += "%(name)s.joystickClock.reset()\n" buff.writeIndentedLines(code % self.params) def writeFrameCode(self, buff): """Write the code that will be called every frame""" # some shortcuts forceEnd = self.params['forceEndRoutineOnPress'].val #routineClockName = self.exp.flow._currentRoutine._clockName # get a clock for timing timeRelative = self.params['timeRelativeTo'].val.lower() if timeRelative == 'experiment': self.clockStr = 'globalClock' elif timeRelative in ['routine', 'joystick onset']: self.clockStr = '%s.joystickClock' % self.params['name'].val # only write code for cases where we are storing data as we go (each # frame or each click) # might not be saving clicks, but want it to force end of trial if (self.params['saveJoystickState'].val not in ['every frame', 'on click'] and forceEnd == 'never'): return buff.writeIndented("# *%s* updates\n" % self.params['name']) # writes an if statement to determine whether to draw etc indented = self.writeStartTestCode(buff) if indented: code = ("{name}.status = STARTED\n") if self.params['timeRelativeTo'].val.lower() == 'joystick onset': code += "{name}.joystickClock.reset()\n" buff.writeIndentedLines(code.format(**self.params)) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) # test for stop (only if there was some setting for duration or stop) indented = self.writeStopTestCode(buff) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) # if STARTED and not FINISHED! code = ("if %(name)s.status == STARTED: " "# only update if started and not finished!\n") % self.params buff.writeIndented(code) buff.setIndentLevel(1, relative=True) # to get out of if statement dedentAtEnd = 1 # keep track of how far to dedent later # write param checking code if (self.params['saveJoystickState'].val == 'on click' or forceEnd in ['any click', 'valid click']): code = ("{name}.newButtonState = {name}.getAllButtons()[:]\n" "if {name}.newButtonState != {name}.oldButtonState: " "# New button press\n") buff.writeIndentedLines(code.format(**self.params)) buff.setIndentLevel(1, relative=True) dedentAtEnd += 1 code = ("{name}.pressedButtons = [i for i in range({name}.numButtons) " "if {name}.newButtonState[i] and not {name}.oldButtonState[i]]\n" "{name}.releasedButtons = [i for i in range({name}.numButtons) " "if not {name}.newButtonState[i] and {name}.oldButtonState[i]]\n" "{name}.newPressedButtons = [i for i in {name}.activeButtons " "if i in {name}.pressedButtons]\n" "{name}.oldButtonState = {name}.newButtonState\n" "{name}.buttons = {name}.newPressedButtons\n" #"print({name}.pressedButtons)\n" #"print({name}.newPressedButtons)\n" "[logging.data(\"joystick_{{}}_button: {{}}, pos=({{:1.4f}},{{:1.4f}})\".format(" "{name}.device_number, i, {name}.getX(), {name}.getY())) for i in {name}.pressedButtons]\n" ) buff.writeIndentedLines(code.format(**self.params)) code = ("if len({name}.buttons) > 0: # state changed to a new click\n") buff.writeIndentedLines(code.format(**self.params)) buff.setIndentLevel(1, relative=True) dedentAtEnd += 1 elif self.params['saveJoystickState'].val == 'every frame': code = ("{name}.newButtonState = {name}.getAllButtons()[:]\n" "{name}.pressedButtons = [i for i in range({name}.numButtons) " "if {name}.newButtonState[i] and not {name}.oldButtonState[i]]\n" "{name}.releasedButtons = [i for i in range({name}.numButtons) " "if not {name}.newButtonState[i] and {name}.oldButtonState[i]]\n" "{name}.newPressedButtons = [i for i in {name}.activeButtons " "if i in {name}.pressedButtons]\n" "{name}.buttons = {name}.newPressedButtons\n" #"print({name}.pressedButtons)\n" #"print({name}.newPressedButtons)\n" "[logging.data(\"joystick_{{}}_button: {{}}, pos=({{:1.4f}},{{:1.4f}})\".format(" "{name}.device_number, i, {name}.getX(), {name}.getY())) for i in {name}.pressedButtons]\n" ) buff.writeIndentedLines(code.format(**self.params)) # only do this if buttons were pressed if self.params['saveJoystickState'].val in ['on click', 'every frame']: code = ("x, y = %(name)s.getX(), %(name)s.getY()\n" #"print(\"x:{} y:{}\".format(x,y))\n" "%(name)s.x.append(x)\n" "%(name)s.y.append(y)\n" "[%(name)s.buttonLogs[i].append(int(%(name)s.newButtonState[i])) " "for i in %(name)s.activeButtons]\n") buff.writeIndentedLines(code % self.params) code = ("{name}.time.append({clockStr}.getTime())\n") buff.writeIndentedLines( code.format(name=self.params['name'],clockStr=self.clockStr)) # also write code about clicked objects if needed. if self.params['clickable'].val: self._writeClickableObjectsCode(buff) # does the response end the trial? if forceEnd == 'any click': code = ("# abort routine on response\n" "continueRoutine = False\n") buff.writeIndentedLines(code) elif forceEnd == 'valid click': code = ("if gotValidClick: # abort routine on response\n") buff.writeIndentedLines(code) buff.setIndentLevel(1, relative=True) code = ("continueRoutine = False\n") buff.writeIndentedLines(code) buff.setIndentLevel(-1, relative=True) else: pass # forceEnd == 'never' # 'if' statement of the time test and button check buff.setIndentLevel(-dedentAtEnd, relative=True) def writeRoutineEndCode(self, buff): # some shortcuts name = self.params['name'] # do this because the param itself is not a string! store = self.params['saveJoystickState'].val if store == 'nothing': return forceEnd = self.params['forceEndRoutineOnPress'].val if len(self.exp.flow._loopList): currLoop = self.exp.flow._loopList[-1] # last (outer-most) loop else: currLoop = self.exp._expHandler if currLoop.type == 'StairHandler': code = ("# NB PsychoPy doesn't handle a 'correct answer' for " "joystick events so doesn't know how to handle joystick with " "StairHandler\n") else: code = ("# store data for %s (%s)\n" % (currLoop.params['name'], currLoop.type)) buff.writeIndentedLines(code) if store == 'final': # write code about clicked objects if needed. buff.writeIndentedLines(code) if self.params['clickable'].val: code = ("if len({name}.buttons) > 0:\n") buff.writeIndentedLines(code.format(**self.params)) buff.setIndentLevel(+1, relative=True) self._writeClickableObjectsCode(buff) buff.setIndentLevel(-1, relative=True) code = ("x, y = {name}.getX(), {name}.getY()\n" "{name}.newButtonState = {name}.getAllButtons()[:]\n" "{name}.pressedState = [{name}.newButtonState[i] " "for i in range({name}.numButtons)]\n" "{name}.time = {clock}.getTime()\n") buff.writeIndentedLines( code.format(name=self.params['name'], clock=self.clockStr)) if currLoop.type != 'StairHandler': code = ( "{loopName}.addData('{joystickName}.x', x)\n" "{loopName}.addData('{joystickName}.y', y)\n" "[{loopName}.addData('{joystickName}.button_{{0}}'.format(i), " "int({joystickName}.pressedState[i])) " "for i in {joystickName}.activeButtons]\n" "{loopName}.addData('{joystickName}.time', {joystickName}.time)\n" ) buff.writeIndentedLines( code.format(loopName=currLoop.params['name'], joystickName=name)) # then add `trials.addData('joystick.clicked_name',.....)` if self.params['clickable'].val: for paramName in self._clickableParamsList: code = ( "if len({joystickName}.clicked_{param}):\n" " {loopName}.addData('{joystickName}.clicked_{param}', " "{joystickName}.clicked_{param}[0])\n" ) buff.writeIndentedLines( code.format(loopName=currLoop.params['name'], joystickName=name, param=paramName)) elif store != 'never': joystickDataProps = ['x', 'y', 'time'] # possibly add clicked params if we have clickable objects if self.params['clickable'].val: for paramName in self._clickableParamsList: joystickDataProps.append("clicked_{}".format(paramName)) # use that set of properties to create set of addData commands for property in joystickDataProps: if store == 'every frame' or forceEnd == "never": code = ("%s.addData('%s.%s', %s.%s)\n" % (currLoop.params['name'], name, property, name, property)) buff.writeIndented(code) else: # we only had one click so don't return a list code = ("if len(%s.%s): %s.addData('%s.%s', %s.%s[0])\n" % (name, property, currLoop.params['name'], name, property, name, property)) buff.writeIndented(code) if store == 'every frame' or forceEnd == "never": code = ("[{0}.addData('{name}.button_{{0}}'.format(i), " "{name}.buttonLogs[i]) for i in {name}.activeButtons " "if len({name}.buttonLogs[i])]\n") else: code = ("[{0}.addData('{name}.button_{{0}}'.format(i), " "{name}.buttonLogs[i][0]) for i in {name}.activeButtons " "if len({name}.buttonLogs[i])]\n") buff.writeIndented(code.format(currLoop.params['name'], **self.params)) # get parent to write code too (e.g. store onset/offset times) super().writeRoutineEndCode(buff)
26,414
Python
.py
486
40.5
127
0.562611
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,612
virtualJoystick.py
psychopy_psychopy/psychopy/experiment/components/joystick/virtualJoystick.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). # Support for fake joystick/gamepad during development # if no 'real' joystick/gamepad is available use keyboard emulation # 'ctrl' + 'alt' + numberKey from psychopy import event class VirtualJoystick: def __init__(self, device_number): self.device_number = device_number self.numberKeys = ['0','1','2','3','4','5','6','7','8','9'] self.modifierKeys = ['ctrl','alt'] self.mouse = event.Mouse() event.Mouse(visible=False) def getNumButtons(self): return len(self.numberKeys) def getAllButtons(self): keys = event.getKeys(keyList=self.numberKeys, modifiers=True) values = [key for key, modifiers in keys if all([modifiers[modKey] for modKey in self.modifierKeys])] self.state = [key in values for key in self.numberKeys] mouseButtons = self.mouse.getPressed() self.state[:len(mouseButtons)] = [a or b != 0 for (a,b) in zip(self.state, mouseButtons)] return self.state def getX(self): (x, y) = self.mouse.getPos() return x def getY(self): (x, y) = self.mouse.getPos() return y
1,359
Python
.py
31
37.774194
109
0.659591
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,613
__init__.py
psychopy_psychopy/psychopy/experiment/components/panorama/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path from psychopy.experiment.components import Param, _translate, getInitVals, BaseVisualComponent class PanoramaComponent(BaseVisualComponent): """This is used by Builder to represent a component that was not known by the current installed version of PsychoPy (most likely from the future). We want this to be loaded, represented and saved but not used in any script-outputs. It should have nothing but a name - other params will be added by the loader """ categories = ['Stimuli'] targets = ['PsychoPy'] version = "2023.1.0" iconFile = Path(__file__).parent / 'panorama.png' tooltip = _translate('Panorama: Present a panoramic image (such as from a phone camera in Panorama mode) on ' 'screen.') beta = True def __init__(self, exp, parentName, name='pan', startType='time (s)', startVal=0, stopType='duration (s)', stopVal='', startEstim='', durationEstim='', saveStartStop=True, syncScreenRefresh=True, image="", interpolate='linear', posCtrl="mouse", smooth=True, posSensitivity=1, elevation="", azimuth="", zoomCtrl="wheel", zoom=1, zoomSensitivity=1, inKey="up", outKey="down", upKey="w", leftKey="a", downKey="s", rightKey="d", stopKey="space"): self.exp = exp # so we can access the experiment if necess self.parentName = parentName # to access the routine too if needed self.params = {} self.depends = [] super(PanoramaComponent, self).__init__( exp, parentName, name=name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim, saveStartStop=saveStartStop, syncScreenRefresh=syncScreenRefresh, ) self.type = 'Panorama' self.order += [ "image", "posCtrl", "azimuth", "elevation", "upKey", "leftKey", "downKey", "rightKey", "stopKey", "posSensitivity", "smooth", "zoomCtrl", "zoom", "inKey", "outKey", "zoomSensitivity" ] msg = _translate( "The image to be displayed - a filename, including path" ) self.params['image'] = Param( image, valType='file', inputType="file", allowedTypes=[], categ='Basic', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Image")) msg = _translate( "How should the image be interpolated if/when rescaled") self.params['interpolate'] = Param( interpolate, valType='str', inputType="choice", allowedVals=['linear', 'nearest'], categ='Basic', updates='constant', allowedUpdates=[], hint=msg, direct=False, label=_translate("Interpolate")) # Position controls msg = _translate( "How to control looking around the panorama scene" ) self.params['posCtrl'] = Param( posCtrl, valType='str', inputType="choice", categ="Basic", allowedVals=[ "mouse", "drag", "arrows", "wasd", "keymap", "custom"], allowedLabels=[ "Mouse", "Drag", "Keyboard (Arrow Keys)", "Keyboard (WASD)", "Keyboard (Custom keys)", "Custom"], updates="constant", hint=msg, label=_translate("Position control") ) self.depends.append( { "dependsOn": "posCtrl", # if... "condition": "=='custom'", # meets... "param": "azimuth", # then... "true": "show", # should... "false": "hide", # otherwise... } ) msg = _translate( "Horizontal look position, ranging from -1 (fully left) to 1 (fully right)" ) self.params['azimuth'] = Param( azimuth, valType='code', inputType='single', categ='Basic', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Azimuth") ) self.depends.append( { "dependsOn": "posCtrl", # if... "condition": "=='custom'", # meets... "param": "elevation", # then... "true": "show", # should... "false": "hide", # otherwise... } ) msg = _translate( "Vertical look position, ranging from -1 (fully down) to 1 (fully up)" ) self.params['elevation'] = Param( elevation, valType='code', inputType='single', categ='Basic', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Elevation") ) keys = {'upKey': upKey, 'leftKey': leftKey, 'downKey': downKey, 'rightKey': rightKey, 'stopKey': stopKey} labels = {'upKey': _translate("Up"), 'leftKey': _translate("Left"), 'downKey': _translate("Down"), 'rightKey': _translate("Right"), 'stopKey': _translate("Stop")} for key, val in keys.items(): # Only show key controls if control type is custom keys self.depends.append( { "dependsOn": "posCtrl", # if... "condition": "=='keymap'", # meets... "param": key, # then... "true": "show", # should... "false": "hide", # otherwise... } ) # Add a ctrl for each key msg = _translate("What key corresponds to the view action '{}'?") self.params[key] = Param( val, valType='str', inputType='single', categ='Basic', updates='constant', hint=msg.format(labels[key]), label=labels[key] ) self.depends.append( { "dependsOn": "posCtrl", # if... "condition": "in ('custom', 'mouse')", # meets... "param": "smooth", # then... "true": "hide", # should... "false": "show", # otherwise... } ) msg = _translate( "Should movement be smoothed, so the view keeps moving a little after a change?" ) self.params['smooth'] = Param( smooth, valType='bool', inputType="bool", categ="Basic", updates="constant", hint=msg, label=_translate("Smooth?") ) self.depends.append( { "dependsOn": "posCtrl", # if... "condition": "=='custom'", # meets... "param": "posSensitivity", # then... "true": "hide", # should... "false": "show", # otherwise... } ) msg = _translate( "Multiplier to apply to view changes. 1 means that moving the mouse from the center of the screen to the " "edge or holding down a key for 2s will rotate 180°." ) self.params['posSensitivity'] = Param( posSensitivity, valType='code', inputType="single", categ="Basic", hint=msg, label=_translate("Movement sensitivity") ) # Zoom controls msg = _translate( "How to control zooming in and out of the panorama scene" ) self.params['zoomCtrl'] = Param( zoomCtrl, valType='str', inputType="choice", categ="Basic", allowedVals=[ "wheel", "invwheel", "arrows", "plusmin", "keymap", "custom"], allowedLabels=[ "Mouse Wheel", "Mouse Wheel (Inverted)", "Keyboard (Arrow Keys)", "Keyboard (+-)", "Keyboard (Custom keys)", "Custom"], updates="constant", hint=msg, label=_translate("Zoom control") ) keys = {'inKey': inKey, 'outKey': outKey} labels = {'inKey': _translate("Zoom in"), 'outKey': _translate("Zoom out")} for key, val in keys.items(): # Only show key controls if zoom type is custom keys self.depends.append( { "dependsOn": "zoomCtrl", # if... "condition": "=='keymap'", # meets... "param": key, # then... "true": "show", # should... "false": "hide", # otherwise... }, ) # Add a ctrl for each key msg = _translate("What key corresponds to the view action '{}'?") self.params[key] = Param( val, valType='str', inputType='single', categ='Basic', updates='constant', hint=msg.format(labels[key]), label=labels[key] ) self.depends.append( { "dependsOn": "zoomCtrl", # if... "condition": "=='custom'", # meets... "param": "zoom", # then... "true": "show", # should... "false": "hide", # otherwise... } ) msg = _translate( "How zoomed in the scene is, with 1 being no adjustment." ) self.params['zoom'] = Param( zoom, valType='code', inputType='single', categ='Basic', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Zoom") ) self.depends.append( { "dependsOn": "zoomCtrl", # if... "condition": "=='custom'", # meets... "param": "zoomSensitivity", # then... "true": "hide", # should... "false": "show", # otherwise... } ) msg = _translate( "Multiplier to apply to zoom changes. 1 means that pressing the zoom in key for 1s or scrolling the mouse " "wheel 100% zooms in 100%." ) self.params['zoomSensitivity'] = Param( zoomSensitivity, valType='code', inputType="single", categ="Basic", hint=msg, label=_translate("Zoom sensitivity") ) # Most params don't apply to 3d stim, so delete them for key in ["color", "fillColor", "borderColor", "colorSpace", "opacity", "contrast", "size", "pos", "units", "ori"]: del self.params[key] def writeStartCode(self, buff): pass def writeInitCode(self, buff): inits = getInitVals(self.params, target="PsychoPy") code = ( "\n" "# create panorama stimulus for %(name)s\n" "%(name)s = visual.PanoramicImageStim(\n" " win,\n" " image=%(image)s,\n" " elevation=%(elevation)s, azimuth=%(azimuth)s,\n" " interpolate=%(interpolate)s\n" ")\n" "# add attribute to keep track of last movement\n" "%(name)s.momentum = np.asarray([0.0, 0.0])\n" ) buff.writeIndentedLines(code % inits) # Add control handlers code = ( "# add control handlers for %(name)s\n" "%(name)s.mouse = event.Mouse()\n" "%(name)s.kb = keyboard.Keyboard()\n" ) buff.writeIndentedLines(code % inits) if self.params['posCtrl'].val in ("arrows", "wasd", "keymap"): # If keyboard, add mapping of keys to deltas code = ( "# store a dictionary to map keys to the amount to change by per frame\n" "%(name)s.kb.deltas = {{\n" " {u}: np.array([0, +win.monitorFramePeriod]),\n" " {l}: np.array([-win.monitorFramePeriod, 0]),\n" " {d}: np.array([0, -win.monitorFramePeriod]),\n" " {r}: np.array([+win.monitorFramePeriod, 0]),\n" " {x}: np.array([0, 0]),\n" "}}\n" ) if self.params['posCtrl'].val == "wasd": # If WASD, sub in w, a, s and d code = code.format(u="'w'", l="'a'", d="'s'", r="'d'", x="'space'") elif self.params['posCtrl'].val == "arrows": # If arrows, sub in left, right, up and down code = code.format(l="'left'", r="'right'", u="'up'", d="'down'", x="'space'") else: # Otherwise, use custom keys code = code.format( l=self.params['leftKey'], r=self.params['rightKey'], u=self.params['upKey'], d=self.params['downKey'], x=self.params['stopKey']) buff.writeIndentedLines(code % inits) def writeFrameCode(self, buff): # If control style isn't custom, make sure elevation, azimuth and zoom aren't updated each frame if self.params['posCtrl'].val != "custom": self.params['azimuth'].updates = "constant" self.params['elevation'].updates = "constant" if self.params['zoomCtrl'].val != "custom": self.params['zoom'].updates = "constant" # Start code indented = self.writeStartTestCode(buff) if indented: code = ( "# start drawing %(name)s\n" "%(name)s.setAutoDraw(True)\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-indented, relative=True) # Active code indented = self.writeActiveTestCode(buff) if indented: # Pos control code if self.params['posCtrl'].val == "mouse": # If control style is mouse, set azimuth and elevation according to mouse pos code = ( "# update panorama view from mouse pos\n" "pos = layout.Position(%(name)s.mouse.getPos(), win.units, win)\n" "%(name)s.azimuth = -pos.norm[0] * %(posSensitivity)s\n" "%(name)s.elevation = -pos.norm[1] * %(posSensitivity)s\n" ) buff.writeIndentedLines(code % self.params) elif self.params['posCtrl'].val == "drag": # If control style is drag, set azimuth and elevation according to change in mouse pos code = ( "# update panorama view from mouse change if clicked\n" "rel = layout.Position(%(name)s.mouse.getRel(), win.units, win)\n" "if %(name)s.mouse.getPressed()[0]:\n" " %(name)s.momentum = rel.norm * %(posSensitivity)s\n" " %(name)s.azimuth -= %(name)s.momentum[0]\n" " %(name)s.elevation -= %(name)s.momentum[1]\n" ) buff.writeIndentedLines(code % self.params) if self.params['smooth']: # If smoothing requested, let momentum decay sinusoidally code = ( "else:\n" " # after click, keep moving a little\n" " %(name)s.azimuth -= %(name)s.momentum[0]\n" " %(name)s.elevation -= %(name)s.momentum[1]\n" " # decrease momentum every frame so that it approaches 0\n" " %(name)s.momentum = %(name)s.momentum * (1 - win.monitorFramePeriod * 2)\n" ) buff.writeIndentedLines(code % self.params) elif self.params['posCtrl'].val in ("arrows", "wasd", "keymap"): # If control is keyboard, set azimuth and elevation according to keypresses code = ( "# update panorama view from key presses\n" "keys = %(name)s.kb.getKeys(list(%(name)s.kb.deltas), waitRelease=False, clear=False)\n" "if len(keys):\n" " # work out momentum of movement from keys pressed\n" " %(name)s.momentum = np.asarray([0.0, 0.0])\n" " for key in keys:\n" " %(name)s.momentum += %(name)s.kb.deltas[key.name] * %(posSensitivity)s\n" " # apply momentum to panorama view\n" " %(name)s.azimuth += %(name)s.momentum[0]\n" " %(name)s.elevation += %(name)s.momentum[1]\n" " # get keys which have been released and clear them from the buffer before next frame\n" " %(name)s.kb.getKeys(list(%(name)s.kb.deltas), waitRelease=True, clear=True)\n" ) buff.writeIndentedLines(code % self.params) if self.params['smooth']: # If smoothing requested, let momentum decay sinusoidally code = ( "else:\n" " # after pressing, keep moving a little\n" " %(name)s.azimuth += %(name)s.momentum[0]\n" " %(name)s.elevation += %(name)s.momentum[1]\n" " # decrease momentum every frame so that it approaches 0\n" " %(name)s.momentum = %(name)s.momentum * (1 - win.monitorFramePeriod * 4)\n" ) buff.writeIndentedLines(code % self.params) # Zoom control code if self.params['zoomCtrl'].val in ("wheel", "invwheel"): # If control style is wheel, set zoom from mouse wheel if self.params['zoomCtrl'].val == "invwheel": _op = "-=" else: _op = "+=" code = ( f"# update panorama zoom from mouse wheel\n" f"%(name)s.zoom {_op} %(name)s.mouse.getWheelRel()[1] * %(zoomSensitivity)s * win.monitorFramePeriod * 4\n" ) buff.writeIndentedLines(code % self.params) elif self.params['zoomCtrl'].val in ("arrows", "plusmin", "keymap"): # If control style is key based, get keys from params/presets and set from pressed if self.params['zoomCtrl'].val == "arrows": inKey, outKey = ("'up'", "'down'") elif self.params['zoomCtrl'].val == "plusmin": inKey, outKey = ("'equal'", "'minus'") else: inKey, outKey = (self.params['inKey'], self.params['outKey']) code = ( f"# update panorama zoom from key presses\n" f"keys = %(name)s.kb.getKeys([{inKey}, {outKey}], waitRelease=False, clear=False)\n" f"# work out zoom change from keys pressed\n" f"for key in keys:\n" f" if key.name == {inKey}:\n" f" %(name)s.zoom += %(zoomSensitivity)s * win.monitorFramePeriod * 4\n" f" if key.name == {outKey}:\n" f" %(name)s.zoom -= %(zoomSensitivity)s * win.monitorFramePeriod * 4\n" f"# get keys which have been released and clear them from the buffer before next frame\n" f"%(name)s.kb.getKeys([{inKey}, {outKey}], waitRelease=True, clear=True)\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-indented, relative=True) # Stop code indented = self.writeStopTestCode(buff) if indented: code = ( "# Stop drawing %(name)s\n" "%(name)s.setAutoDraw(False)\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-indented, relative=True)
20,347
Python
.py
427
33.470726
135
0.501938
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,614
__init__.py
psychopy_psychopy/psychopy/experiment/components/keyboard/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy.experiment.components import BaseDeviceComponent, Param, _translate, getInitVals from psychopy.experiment import CodeGenerationException, valid_var_re from pkgutil import find_loader # Check for psychtoolbox havePTB = find_loader('psychtoolbox') is not None class KeyboardComponent(BaseDeviceComponent): """An event class for checking the keyboard at given timepoints""" # an attribute of the class, determines the section in components panel categories = ['Responses'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'keyboard.png' tooltip = _translate('Keyboard: check and record keypresses') deviceClasses = ["psychopy.hardware.keyboard.KeyboardDevice"] def __init__(self, exp, parentName, name='key_resp', deviceLabel="", allowedKeys="'y','n','left','right','space'", registerOn="press", store='last key', forceEndRoutine=True, storeCorrect=False, correctAns="", discardPrev=True, startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal='', startEstim='', durationEstim='', syncScreenRefresh=True, disabled=False): BaseDeviceComponent.__init__( self, exp, parentName, name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim, deviceLabel=deviceLabel, disabled=disabled ) self.type = 'Keyboard' self.url = "https://www.psychopy.org/builder/components/keyboard.html" self.exp.requirePsychopyLibs(['gui']) # params # NB name and timing params always come 1st self.order += ['forceEndRoutine', 'registerOn', 'allowedKeys', # Basic tab 'store', 'storeCorrect', 'correctAns' # Data tab ] # --- Basic --- self.order += [ "registerOn", "allowedKeys", "forceEndRoutine" ] msg = _translate( "When should the keypress be registered? As soon as pressed, or when released?") self.params['registerOn'] = Param( registerOn, valType='str', inputType='choice', categ='Basic', updates='constant', allowedVals=["press", "release"], hint=msg, label=_translate("Register keypress on...") ) msg = _translate( "A comma-separated list of keys (with quotes), such as " "'q','right','space','left'") self.params['allowedKeys'] = Param( allowedKeys, valType='list', inputType="single", categ='Basic', updates='constant', allowedUpdates=['constant', 'set every repeat'], hint=(msg), label=_translate("Allowed keys")) msg = _translate("Should a response force the end of the Routine " "(e.g end the trial)?") self.params['forceEndRoutine'] = Param( forceEndRoutine, valType='bool', inputType="bool", allowedTypes=[], categ='Basic', updates='constant', hint=msg, label=_translate("Force end of Routine")) # hints say 'responses' not 'key presses' because the same hint is # also used with button boxes msg = _translate("Do you want to discard all responses occurring " "before the onset of this Component?") self.params['discard previous'] = Param( discardPrev, valType='bool', inputType="bool", allowedTypes=[], categ='Data', updates='constant', hint=msg, label=_translate("Discard previous")) msg = _translate("Choose which (if any) responses to store at the " "end of a trial") self.params['store'] = Param( store, valType='str', inputType="choice", allowedTypes=[], categ='Data', allowedVals=['last key', 'first key', 'all keys', 'nothing'], updates='constant', direct=False, hint=msg, label=_translate("Store")) msg = _translate("Do you want to save the response as " "correct/incorrect?") self.params['storeCorrect'] = Param( storeCorrect, valType='bool', inputType="bool", allowedTypes=[], categ='Data', updates='constant', hint=msg, label=_translate("Store correct")) self.depends += [ # allows params to turn each other off/on {"dependsOn": "storeCorrect", # must be param name "condition": "== True", # val to check for "param": "correctAns", # param property to alter "true": "enable", # what to do with param if condition is True "false": "disable", # permitted: hide, show, enable, disable } ] msg = _translate( "What is the 'correct' key? Might be helpful to add a " "correctAns column and use $correctAns to compare to the key " "press.") self.params['correctAns'] = Param( correctAns, valType='str', inputType="single", allowedTypes=[], categ='Data', updates='constant', hint=msg, direct=False, label=_translate("Correct answer")) msg = _translate( "A reaction time to a visual stimulus should be based on when " "the screen flipped") self.params['syncScreenRefresh'] = Param( syncScreenRefresh, valType='bool', inputType="bool", categ='Data', updates='constant', hint=msg, label=_translate("Sync timing with screen")) def writeDeviceCode(self, buff): # get inits inits = getInitVals(self.params) # write device creation code code = ( "if deviceManager.getDevice(%(deviceLabel)s) is None:\n" " # initialise %(deviceLabelCode)s\n" " %(deviceLabelCode)s = deviceManager.addDevice(\n" " deviceClass='keyboard',\n" " deviceName=%(deviceLabel)s,\n" " )\n" ) buff.writeOnceIndentedLines(code % inits) def writeInitCode(self, buff): # get inits inits = getInitVals(self.params) # make Keyboard object code = ( "%(name)s = keyboard.Keyboard(deviceName=%(deviceLabel)s)\n" ) buff.writeIndentedLines(code % inits) def writeInitCodeJS(self, buff): code = "%(name)s = new core.Keyboard({psychoJS: psychoJS, clock: new util.Clock(), waitForStart: true});\n\n" buff.writeIndentedLines(code % self.params) def writeRoutineStartCode(self, buff): code = ( "# create starting attributes for %(name)s\n" "%(name)s.keys = []\n" "%(name)s.rt = []\n" "_%(name)s_allKeys = []\n" ) buff.writeIndentedLines(code % self.params) # if allowedKeys looks like a variable, load it from global allowedKeys = str(self.params['allowedKeys']) allowedKeysIsVar = valid_var_re.match(str(allowedKeys)) and not allowedKeys == 'None' if allowedKeysIsVar: code = ( "# allowedKeys looks like a variable, so make sure it exists locally\n" "if '%(allowedKeys)s' in globals():\n" " %(allowedKeys)s = globals()['%(allowedKeys)s']\n" ) buff.writeIndentedLines(code % self.params) def writeRoutineStartCodeJS(self, buff): code = ("%(name)s.keys = undefined;\n" "%(name)s.rt = undefined;\n" "_%(name)s_allKeys = [];\n") buff.writeIndentedLines(code % self.params) def writeFrameCode(self, buff): """Write the code that will be called every frame """ # some shortcuts store = self.params['store'].val storeCorr = self.params['storeCorrect'].val forceEnd = self.params['forceEndRoutine'].val allowedKeys = str(self.params['allowedKeys']) visualSync = self.params['syncScreenRefresh'].val buff.writeIndented("\n") buff.writeIndented("# *%s* updates\n" % self.params['name']) if visualSync: buff.writeIndented("waitOnFlip = False\n") allowedKeysIsVar = (valid_var_re.match(str(allowedKeys)) and not allowedKeys == 'None') # writes an if statement to determine whether to draw etc indented = self.writeStartTestCode(buff) if indented: if allowedKeysIsVar: # if it looks like a variable, check that the variable is suitable # to eval at run-time stringType = 'str' code = ( "# allowed keys looks like a variable named `{0}`\n" "if not type({0}) in [list, tuple, np.ndarray]:\n" " if not isinstance({0}, {1}):\n" " {0} = str({0})\n" ).format(allowedKeys, stringType) code += ( " elif not ',' in {0}:\n" " {0} = ({0},)\n" " else:\n" " {0} = eval({0})\n" .format(allowedKeys)) buff.writeIndentedLines(code) keyListStr = "list(%s)" % allowedKeys # eval at run time buff.writeIndented("# keyboard checking is just starting\n") if visualSync: code = ("waitOnFlip = True\n" "win.callOnFlip(%(name)s.clock.reset) " "# t=0 on next screen flip\n") % self.params else: code = "%(name)s.clock.reset() # now t=0\n" % self.params buff.writeIndentedLines(code) if self.params['discard previous'].val: if visualSync: code = ("win.callOnFlip(%(name)s.clearEvents, eventType='keyboard') " "# clear events on next screen flip\n") % self.params else: code = "%(name)s.clearEvents(eventType='keyboard')\n" % self.params buff.writeIndented(code) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) # test for stop (only if there was some setting for duration or stop) indented = self.writeStopTestCode(buff) if indented: buff.writeIndented("%(name)s.status = FINISHED\n" % self.params) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) buff.writeIndented("if %s.status == STARTED%s:\n" % (self.params['name'], ['', ' and not waitOnFlip'][visualSync])) buff.setIndentLevel(1, relative=True) # to get out of if statement dedentAtEnd = 1 # keep track of how far to dedent later # do we need a list of keys? (variable case is already handled) if allowedKeys in [None, "none", "None", "", "[]", "()"]: keyListStr = "" elif not allowedKeysIsVar: keyListStr = self.params['allowedKeys'] # check for keypresses expEscape = "None" if self.exp.settings.params['Enable Escape']: expEscape = '["escape"]' code = ("theseKeys = {name}.getKeys(keyList={keyStr}, ignoreKeys={expEscape}, waitRelease={waitRelease})\n" "_{name}_allKeys.extend(theseKeys)\n" "if len(_{name}_allKeys):\n") buff.writeIndentedLines( code.format( name=self.params['name'], waitRelease=self.params['registerOn'] == "release", keyStr=(keyListStr or None), expEscape=expEscape ) ) buff.setIndentLevel(1, True) dedentAtEnd += 1 if store == 'first key': # then see if a key has already been pressed code = ("{name}.keys = _{name}_allKeys[0].name # just the first key pressed\n" "{name}.rt = _{name}_allKeys[0].rt\n" "{name}.duration = _{name}_allKeys[0].duration\n") buff.writeIndentedLines(code.format(name=self.params['name'])) elif store == 'last key' or store == "nothing": # If store nothing, save last key for correct answer test code = ("{name}.keys = _{name}_allKeys[-1].name # just the last key pressed\n" "{name}.rt = _{name}_allKeys[-1].rt\n" "{name}.duration = _{name}_allKeys[-1].duration\n") buff.writeIndentedLines(code.format(name=self.params['name'])) elif store == 'all keys': code = ("{name}.keys = [key.name for key in _{name}_allKeys] # storing all keys\n" "{name}.rt = [key.rt for key in _{name}_allKeys]\n" "{name}.duration = [key.duration for key in _{name}_allKeys]\n") buff.writeIndentedLines(code.format(name=self.params['name'])) if storeCorr: code = ("# was this correct?\n" "if ({name}.keys == str({correctAns})) or ({name}.keys == {correctAns}):\n" " {name}.corr = 1\n" "else:\n" " {name}.corr = 0\n") buff.writeIndentedLines( code.format( name=self.params['name'], correctAns=self.params['correctAns'] ) ) if forceEnd == True: code = ("# a response ends the routine\n" "continueRoutine = False\n") buff.writeIndentedLines(code) buff.setIndentLevel(-(dedentAtEnd), relative=True) def writeFrameCodeJS(self, buff): # some shortcuts store = self.params['store'].val storeCorr = self.params['storeCorrect'].val forceEnd = self.params['forceEndRoutine'].val allowedKeys = self.params['allowedKeys'].val.strip() buff.writeIndented("\n") buff.writeIndented("// *%s* updates\n" % self.params['name']) allowedKeysIsVar = (valid_var_re.match(str(allowedKeys)) and not allowedKeys == 'None') if allowedKeysIsVar: # if it looks like a variable, check that the variable is suitable # to eval at run-time raise CodeGenerationException( "Variables for allowKeys aren't supported for JS yet") #code = ("# AllowedKeys looks like a variable named `%s`\n" # "if not '%s' in locals():\n" # " logging.error('AllowedKeys variable `%s` is not defined.')\n" # " core.quit()\n" # "if not type(%s) in [list, tuple, np.ndarray]:\n" # " if not isinstance(%s, str):\n" # " logging.error('AllowedKeys variable `%s` is " # "not string- or list-like.')\n" # " core.quit()\n" % # allowedKeys) # #vals = (allowedKeys, allowedKeys, allowedKeys) #code += ( # " elif not ',' in %s: %s = (%s,)\n" % vals + # " else: %s = eval(%s)\n" % (allowedKeys, allowedKeys)) #buff.writeIndentedLines(code) # #keyListStr = "keyList=list(%s)" % allowedKeys # eval at run time # write code to run on first frame once started indented = self.writeStartTestCodeJS(buff) if indented: buff.writeIndented("// keyboard checking is just starting\n") if self.params['syncScreenRefresh'].val: code = ("psychoJS.window.callOnFlip(function() { %(name)s.clock.reset(); }); " "// t=0 on next screen flip\n" "psychoJS.window.callOnFlip(function() { %(name)s.start(); }); " "// start on screen flip\n") % self.params else: code = ("%(name)s.clock.reset();\n" "%(name)s.start();\n") % self.params buff.writeIndentedLines(code) if self.params['discard previous'].val: if self.params['syncScreenRefresh'].val: buff.writeIndented("psychoJS.window.callOnFlip(function() { %(name)s.clearEvents(); });\n" % self.params) else: buff.writeIndented("%(name)s.clearEvents();\n" % self.params) # to get out of the if statement for n in range(indented): buff.setIndentLevel(-1, relative=True) buff.writeIndented("}\n") # write code to run on last frame when stopping indented = self.writeStopTestCodeJS(buff) if indented: # writes an if statement to determine whether to draw etc self.writeStopTestCodeJS(buff) buff.writeIndented("%(name)s.status = PsychoJS.Status.FINISHED;\n" " }\n" "\n" % self.params) # to get out of the if statement for n in range(indented): buff.setIndentLevel(-1, relative=True) buff.writeIndented("}\n") # write code to run each frame while active indented = self.writeActiveTestCodeJS(buff) if indented: # do we need a list of keys? (variable case is already handled) if allowedKeys in [None, "none", "None", "", "[]", "()"]: keyListStr = "[]" elif not allowedKeysIsVar: try: keyList = eval(allowedKeys) except Exception: raise CodeGenerationException( self.params["name"], "Allowed keys list is invalid.") # this means the user typed "left","right" not ["left","right"] if type(keyList) == tuple: keyList = list(keyList) elif isinstance(keyList, str): # a single string/key keyList = [keyList] keyListStr = "%s" % repr(keyList) # check for keypresses waitRelease = "false" if self.params['registerOn'] == "release": waitRelease = "true" code = ("let theseKeys = {name}.getKeys({{keyList: {keyStr}, waitRelease: {waitRelease}}});\n" "_{name}_allKeys = _{name}_allKeys.concat(theseKeys);\n" "if (_{name}_allKeys.length > 0) {{\n") buff.writeIndentedLines( code.format( name=self.params['name'], waitRelease=waitRelease, keyStr=keyListStr ) ) buff.setIndentLevel(1, True) indented += 1 # how do we store it? if store == 'first key': # then see if a key has already been pressed code = ("{name}.keys = _{name}_allKeys[0].name; // just the first key pressed\n" "{name}.rt = _{name}_allKeys[0].rt;\n" "{name}.duration = _{name}_allKeys[0].duration;\n") buff.writeIndentedLines(code.format(name=self.params['name'])) elif store == 'last key' or store =='nothing': code = ("{name}.keys = _{name}_allKeys[_{name}_allKeys.length - 1].name; // just the last key pressed\n" "{name}.rt = _{name}_allKeys[_{name}_allKeys.length - 1].rt;\n" "{name}.duration = _{name}_allKeys[_{name}_allKeys.length - 1].duration;\n") buff.writeIndentedLines(code.format(name=self.params['name'])) elif store == 'all keys': code = ("{name}.keys = _{name}_allKeys.map((key) => key.name); // storing all keys\n" "{name}.rt = _{name}_allKeys.map((key) => key.rt);\n" \ "{name}.duration = _{name}_allKeys.map((key) => key.duration);\n") buff.writeIndentedLines(code.format(name=self.params['name'])) if storeCorr: code = ("// was this correct?\n" "if ({name}.keys == {correctAns}) {{\n" " {name}.corr = 1;\n" "}} else {{\n" " {name}.corr = 0;\n" "}}\n") buff.writeIndentedLines( code.format( name=self.params['name'], correctAns=self.params['correctAns'] ) ) if forceEnd == True: code = ("// a response ends the routine\n" "continueRoutine = false;\n") buff.writeIndentedLines(code) # to get out of the if statement for n in range(indented): buff.setIndentLevel(-1, relative=True) buff.writeIndented("}\n") buff.writeIndented("\n") def writeRoutineEndCode(self, buff): # some shortcuts name = self.params['name'] store = self.params['store'].val if store == 'nothing': return if len(self.exp.flow._loopList): currLoop = self.exp.flow._loopList[-1] # last (outer-most) loop else: currLoop = self.exp._expHandler # write the actual code code = ("# check responses\n" "if %(name)s.keys in ['', [], None]: # No response was made\n" " %(name)s.keys = None\n") buff.writeIndentedLines(code % self.params) if self.params['storeCorrect'].val: # check for correct NON-response code = (" # was no response the correct answer?!\n" " if str(%(correctAns)s).lower() == 'none':\n" " %(name)s.corr = 1; # correct non-response\n" " else:\n" " %(name)s.corr = 0; # failed to respond (incorrectly)\n" % self.params) code += ("# store data for %s (%s)\n" % (currLoop.params['name'], currLoop.type)) buff.writeIndentedLines(code % self.params) if currLoop.type in ['StairHandler', 'MultiStairHandler']: # data belongs to a Staircase-type of object if self.params['storeCorrect'].val is True: code = ("%s.addResponse(%s.corr, level)\n" % (currLoop.params['name'], name) + "%s.addOtherData('%s.rt', %s.rt)\n" % (currLoop.params['name'], name, name)) buff.writeIndentedLines(code) else: # always add keys buff.writeIndented("%s.addData('%s.keys',%s.keys)\n" % (currLoop.params['name'], name, name)) if self.params['storeCorrect'].val == True: buff.writeIndented("%s.addData('%s.corr', %s.corr)\n" % (currLoop.params['name'], name, name)) # only add an RT if we had a response code = ( "if %(name)s.keys != None: # we had a response\n" % self.params + " %s.addData('%s.rt', %s.rt)\n" % (currLoop.params['name'], name, name) + " %s.addData('%s.duration', %s.duration)\n" % (currLoop.params['name'], name, name) ) buff.writeIndentedLines(code) # get parent to write code too (e.g. store onset/offset times) super().writeRoutineEndCode(buff) def writeRoutineEndCodeJS(self, buff): # some shortcuts name = self.params['name'] store = self.params['store'].val forceEnd = self.params['forceEndRoutine'].val if store == 'nothing': # Still stop keyboard to prevent textbox from not working on single keypresses due to buffer buff.writeIndentedLines("%(name)s.stop();\n" % self.params) return if len(self.exp.flow._loopList): currLoop = self.exp.flow._loopList[-1] # last (outer-most) loop else: currLoop = self.exp._expHandler if self.params['storeCorrect'].val: # check for correct NON-repsonse code = ("// was no response the correct answer?!\n" "if (%(name)s.keys === undefined) {\n" " if (['None','none',undefined].includes(%(correctAns)s)) {\n" " %(name)s.corr = 1; // correct non-response\n" " } else {\n" " %(name)s.corr = 0; // failed to respond (incorrectly)\n" " }\n" "}\n" % self.params) code += "// store data for current loop\n" buff.writeIndentedLines(code % self.params) code = ( "// update the trial handler\n" "if (currentLoop instanceof MultiStairHandler) {\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(1, relative=True) code = ( "currentLoop.addResponse(%(name)s.corr, level);\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % self.params) # always add keys buff.writeIndented("psychoJS.experiment.addData('%(name)s.keys', %(name)s.keys);\n" % self.params) if self.params['storeCorrect'].val == True: buff.writeIndented("psychoJS.experiment.addData('%(name)s.corr', %(name)s.corr);\n" % self.params) # only add an RT if we had a response code = ("if (typeof {name}.keys !== 'undefined') {{ // we had a response\n" " psychoJS.experiment.addData('{name}.rt', {name}.rt);\n" " psychoJS.experiment.addData('{name}.duration', {name}.duration);\n") if forceEnd: code += (" routineTimer.reset();\n" " }}\n\n") else: code += " }}\n\n" buff.writeIndentedLines(code.format(name=name)) # Stop keyboard buff.writeIndentedLines("%(name)s.stop();\n" % self.params)
26,961
Python
.py
531
36.951036
121
0.532974
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,615
__init__.py
psychopy_psychopy/psychopy/experiment/components/camera/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import copy import functools from pathlib import Path from psychopy.alerts import alert from psychopy import logging from psychopy.experiment.components import ( BaseComponent, BaseDeviceComponent, Param, _translate, getInitVals ) from psychopy.sound.audiodevice import sampleRateQualityLevels from psychopy.tools import stringtools as st, systemtools as syst, audiotools as at _hasPTB = True try: import psychtoolbox.audio as audio except (ImportError, ModuleNotFoundError): logging.warning( "The 'psychtoolbox' library cannot be loaded but is required for audio " "capture (use `pip install psychtoolbox` to get it). Microphone " "recording will be unavailable this session. Note that opening a " "microphone stream will raise an error.") _hasPTB = False # Get list of sample rates micSampleRates = {r[1]: r[0] for r in sampleRateQualityLevels.values()} class CameraComponent(BaseDeviceComponent): """ This component provides a way to use the webcam to record participants during an experiment. **Note: For online experiments, the browser will notify participants to allow use of webcam before the start of the task.** When recording via webcam, specify the starting time relative to the start of the routine (see `start` below) and a stop time (= duration in seconds). A blank duration evaluates to recording for 0.000s. The resulting video files are saved in .mp4 format if recorded locally and saved in .webm if recorded online. There will be one file per recording. The files appear in a new folder within the data directory in a folder called data_cam_recorded. The file names include the unix (epoch) time of the onset of the recording with milliseconds, e.g., `recording_cam_2022-06-16_14h32.42.064.mp4`. **Note: For online experiments, the recordings can only be downloaded from the "Download results" button from the study's Pavlovia page.** """ categories = ['Responses'] targets = ["PsychoPy", "PsychoJS"] version = "2022.2.0" iconFile = Path(__file__).parent / 'webcam.png' tooltip = _translate('Webcam: Record video from a webcam.') beta = True deviceClasses = ["psychopy.hardware.camera.Camera"] def __init__( # Basic self, exp, parentName, name='cam', startType='time (s)', startVal='0', startEstim='', stopType='duration (s)', stopVal='', durationEstim='', # Device deviceLabel="", cameraLib="ffpyplayer", device="default", resolution="", frameRate="", deviceManual="", resolutionManual="", frameRateManual="", # audio micDeviceLabel="", mic=None, channels='auto', sampleRate='DVD Audio (48kHz)', maxSize=24000, # Data saveFile=True, outputFileType="mp4", codec="h263", saveStartStop=True, syncScreenRefresh=False, # Testing disabled=False, ): # Initialise superclass super(CameraComponent, self).__init__( exp, parentName, name=name, startType=startType, startVal=startVal, startEstim=startEstim, stopType=stopType, stopVal=stopVal, durationEstim=durationEstim, # Device deviceLabel=deviceLabel, # Data saveStartStop=saveStartStop, syncScreenRefresh=syncScreenRefresh, # Testing disabled=disabled, ) # Mark as type self.type = 'Camera' # Store exp references self.exp = exp self.parentName = parentName # Add requirement self.exp.requireImport(importName="camera", importFrom="psychopy.hardware") self.exp.requireImport(importName="microphone", importFrom="psychopy.sound") # Define some functions for live populating listCtrls def getResolutionsForDevice(cameraLib, deviceName): """ Get a list of resolutions available for the given device. Parameters ---------- cameraLib : Param Param object containing name of backend library deviceName : Param Param object containing device name/index Returns ------- list List of resolutions, specified as strings in the format `(width, height)` """ if cameraLib == "opencv": return [""] try: from psychopy.hardware.camera import Camera # get all devices if isinstance(cameraLib, Param): cameraLib = cameraLib.val connectedCameras = Camera.getCameras(cameraLib=cameraLib) # if device is a param, get its val if isinstance(deviceName, Param): deviceName = deviceName.val # get first device if default if deviceName in (None, "", "default") and len(connectedCameras): deviceName = list(connectedCameras)[0] # get formats for this device formats = connectedCameras.get(deviceName, []) # extract resolutions formats = [_format.frameSize for _format in formats] # remove duplicates and sort formats = list(set(formats)) formats.sort(key=lambda res: res[0], reverse=True) return [""] + formats except: return [""] def getFrameRatesForDevice(cameraLib, deviceName, resolution=None): """ Get a list of frame rates available for the given device. Parameters ---------- cameraLib : Param Param object containing name of backend library deviceName : Param Param object containing device name/index Returns ------- list List of frame rates """ if cameraLib == "opencv": return [""] try: from psychopy.hardware.camera import Camera # get all devices if isinstance(cameraLib, Param): cameraLib = cameraLib.val connectedCameras = Camera.getCameras(cameraLib=cameraLib) # if device is a param, get its val if isinstance(deviceName, Param): deviceName = deviceName.val # get first device if default if deviceName in (None, "", "default") and len(connectedCameras): deviceName = list(connectedCameras)[0] # get formats for this device formats = connectedCameras.get(deviceName, []) # if frameRate is a param, get its val if isinstance(resolution, Param): resolution = resolution.val # filter for current frame rate if resolution not in (None, "", "default"): formats = [f for f in formats if f.frameSize == resolution] # extract resolutions formats = [_format.frameRate for _format in formats] # remove duplicates and sort formats = list(set(formats)) formats.sort(reverse=True) return [""] + formats except: return [""] # --- Device params --- self.order += [ "cameraLib", "device", "deviceManual", "resolution", "resolutionManual", "frameRate", "frameRateManual", ] self.params['cameraLib'] = Param( cameraLib, valType='str', inputType="choice", categ="Device", allowedVals=["ffpyplayer", "opencv"], allowedLabels=["FFPyPlayer", "OpenCV"], hint=_translate("Python package to use behind the scenes."), label=_translate("Backend") ) msg = _translate( "What device would you like to use to record video? This will only affect local " "experiments - online experiments ask the participant which device to use." ) def getCameraNames(): """ Similar to getCameraDescriptions, only returns camera names as a list of strings. Returns ------- list Array of camera device names, preceeded by "default" """ if self.params['cameraLib'] == "opencv": return ["default"] # enter a try statement in case ffpyplayer isn't installed try: # import from psychopy.hardware.camera import Camera connectedCameras = Camera.getCameras(cameraLib=self.params['cameraLib'].val) return ["default"] + list(connectedCameras) except: return ["default"] self.params['device'] = Param( device, valType='str', inputType="choice", categ="Device", allowedVals=getCameraNames, allowedLabels=getCameraNames, hint=msg, label=_translate("Video device") ) self.depends.append({ "dependsOn": 'cameraLib', # if... "condition": "", # meets... "param": 'device', # then... "true": "populate", # should... "false": "populate", # otherwise... }) self.params['deviceManual'] = Param( deviceManual, valType='code', inputType="single", categ="Device", hint=msg, label=_translate("Video device") ) msg = _translate("Resolution (w x h) to record to, leave blank to use device default.") conf = functools.partial(getResolutionsForDevice, self.params['cameraLib'], self.params['device']) self.params['resolution'] = Param( resolution, valType='list', inputType="choice", categ="Device", allowedVals=conf, allowedLabels=conf, hint=msg, label=_translate("Resolution") ) self.depends.append({ "dependsOn": 'device', # if... "condition": "", # meets... "param": 'resolution', # then... "true": "populate", # should... "false": "populate", # otherwise... }) self.params['resolutionManual'] = Param( resolutionManual, valType='list', inputType="single", categ="Device", hint=msg, label=_translate("Resolution") ) msg = _translate("Frame rate (frames per second) to record at, leave " "blank to use device default.") conf = functools.partial( getFrameRatesForDevice, self.params['cameraLib'], self.params['device'], self.params['resolution']) self.params['frameRate'] = Param( frameRate, valType='int', inputType="choice", categ="Device", allowedVals=conf, allowedLabels=conf, hint=msg, label=_translate("Frame rate") ) self.depends.append({ "dependsOn": 'device', # if... "condition": "", # meets... "param": 'frameRate', # then... "true": "populate", # should... "false": "populate", # otherwise... }) msg += _translate( " For some cameras, you may need to use " "`camera.CAMERA_FRAMERATE_NTSC` or " "`camera.CAMERA_FRAMERATE_NTSC / 2`.") self.params['frameRateManual'] = Param( frameRateManual, valType='int', inputType="single", categ="Device", hint=msg, label=_translate("Frame rate") ) # add dependencies for manual spec under open cv for param in ("device", "resolution", "frameRate"): # hide the choice ctrl self.depends.append({ "dependsOn": 'cameraLib', # if... "condition": "=='opencv'", # meets... "param": param, # then... "true": "hide", # should... "false": "show", # otherwise... }) # show to manual ctrl self.depends.append({ "dependsOn": 'cameraLib', # if... "condition": "=='opencv'", # meets... "param": param + "Manual", # then... "true": "show", # should... "false": "hide", # otherwise... }) # --- Audio params --- self.order += [ "micDeviceLabel", "mic", "micChannels", "micSampleRate", "micMaxRecSize" ] self.params['micDeviceLabel'] = Param( micDeviceLabel, valType="str", inputType="single", categ="Audio", label=_translate("Microphone device label"), hint=_translate( "A label to refer to this Component's associated microphone device by. If using " "the same device for multiple components, be sure to use the same label here." ) ) def getMicDeviceIndices(): from psychopy.hardware.microphone import MicrophoneDevice profiles = MicrophoneDevice.getAvailableDevices() return [None] + [profile['index'] for profile in profiles] def getMicDeviceNames(): from psychopy.hardware.microphone import MicrophoneDevice profiles = MicrophoneDevice.getAvailableDevices() return ["default"] + [profile['deviceName'] for profile in profiles] msg = _translate( "What microphone device would you like the use to record? This " "will only affect local experiments - online experiments ask the " "participant which mic to use.") self.params['mic'] = Param( mic, valType='str', inputType="choice", categ="Audio", allowedVals=getMicDeviceIndices, allowedLabels=getMicDeviceNames, hint=msg, label=_translate("Microphone") ) msg = _translate( "Record two channels (stereo) or one (mono, smaller file). Select " "'auto' to use as many channels as the selected device allows.") self.params['micChannels'] = Param( channels, valType='str', inputType="choice", categ='Audio', allowedVals=['auto', 'mono', 'stereo'], hint=msg, label=_translate("Channels")) msg = _translate( "How many samples per second (Hz) to record at") self.params['micSampleRate'] = Param( sampleRate, valType='num', inputType="choice", categ='Audio', allowedVals=list(micSampleRates), hint=msg, direct=False, label=_translate("Sample rate (hz)")) msg = _translate( "To avoid excessively large output files, what is the biggest file " "size you are likely to expect?") self.params['micMaxRecSize'] = Param( maxSize, valType='num', inputType="single", categ='Audio', hint=msg, label=_translate("Max recording size (kb)")) # --- Data params --- msg = _translate("Save webcam output to a file?") self.params['saveFile'] = Param( saveFile, valType='bool', inputType="bool", categ="Data", hint=msg, label=_translate("Save file?") ) @staticmethod def setupMicNameInInits(inits): # substitute component name + "Microphone" for mic device name if blank if not inits['micDeviceLabel']: # if deviceName exists but is blank, use component name inits['micDeviceLabel'].val = inits['name'].val + "Microphone" inits['micDeviceLabel'].valType = 'str' # make a code version of mic device name inits['micDeviceLabelCode'] = copy.copy(inits['micDeviceLabel']) inits['micDeviceLabelCode'].valType = "code" def writeDeviceCode(self, buff): """ Code to setup the CameraDevice for this component. Parameters ---------- buff : io.StringIO Text buffer to write code to. """ inits = getInitVals(self.params) self.setupMicNameInInits(inits) # --- setup mic --- # substitute sample rate value for numeric equivalent inits['micSampleRate'] = micSampleRates[inits['micSampleRate'].val] # substitute channel value for numeric equivalent inits['micChannels'] = {'mono': 1, 'stereo': 2, 'auto': None}[self.params['micChannels'].val] # initialise mic device code = ( "# initialise microphone\n" "deviceManager.addDevice(\n" " deviceClass='psychopy.hardware.microphone.MicrophoneDevice',\n" " deviceName=%(micDeviceLabel)s,\n" " index=%(mic)s,\n" " channels=%(micChannels)s, \n" " sampleRateHz=%(micSampleRate)s, \n" " maxRecordingSize=%(micMaxRecSize)s\n" ")\n" ) buff.writeOnceIndentedLines(code % inits) # --- setup camera --- # initialise camera device code = ( "# initialise camera\n" "cam = deviceManager.addDevice(\n" " deviceClass='psychopy.hardware.camera.Camera',\n" " deviceName=%(deviceLabel)s,\n" " cameraLib=%(cameraLib)s, \n" " device=%(device)s, \n" " mic=%(micDeviceLabel)s, \n" " frameRate=%(frameRate)s, \n" " frameSize=%(resolution)s\n" ")\n" "cam.open()\n" "\n" ) buff.writeOnceIndentedLines(code % inits) def writeRoutineStartCode(self, buff): pass def writeStartCode(self, buff): inits = getInitVals(self.params) # Use filename with a suffix to store recordings code = ( "# Make folder to store recordings from %(name)s\n" "%(name)sRecFolder = filename + '_%(name)s_recorded'\n" "if not os.path.isdir(%(name)sRecFolder):\n" " os.mkdir(%(name)sRecFolder)\n" ) buff.writeIndentedLines(code % inits) def writeInitCode(self, buff): inits = getInitVals(self.params, "PsychoPy") # Create Microphone object code = ( "# get camera object\n" "%(name)s = deviceManager.getDevice(%(deviceLabel)s)\n" "# connect camera save method to experiment handler so it's called when data saves\n" "thisExp.connectSaveMethod(%(name)s.save)\n" ) buff.writeIndentedLines(code % inits) def writeInitCodeJS(self, buff): inits = getInitVals(self.params, target="PsychoJS") # Write code code = ( "%(name)s = new hardware.Camera({\n" " name:'%(name)s',\n" " win: psychoJS.window," "});\n" "// Get permission from participant to access their camera\n" "await %(name)s.authorize()\n" "// Switch on %(name)s\n" "await %(name)s.open()\n" "\n" ) buff.writeIndentedLines(code % inits) def writeFrameCode(self, buff): # Start webcam at component start indented = self.writeStartTestCode(buff) if indented: code = ( "# Start %(name)s recording\n" "%(name)s.record()\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-indented, relative=True) # Update any params while active indented = self.writeActiveTestCode(buff) buff.setIndentLevel(-indented, relative=True) # Stop webcam at component stop indented = self.writeStopTestCode(buff) if indented: code = ( "# Stop %(name)s recording\n" "%(name)s.stop()\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-indented, relative=True) def writeFrameCodeJS(self, buff): # Start webcam at component start self.writeStartTestCodeJS(buff) code = ( "await %(name)s.record()\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ( "};\n" ) buff.writeIndentedLines(code) # Stop webcam at component stop self.writeStopTestCodeJS(buff) code = ( "await %(name)s.stop()\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ( "};\n" ) buff.writeIndentedLines(code) def writeRoutineEndCode(self, buff): code = ( "# Make sure %(name)s has stopped recording\n" "if %(name)s.status == STARTED:\n" " %(name)s.stop()\n" ) buff.writeIndentedLines(code % self.params) if self.params['saveFile']: code = ( "# Save %(name)s recording\n" "%(name)sFilename = os.path.join(\n" " %(name)sRecFolder, \n" " 'recording_%(name)s_%%s.mp4' %% data.utils.getDateStr()\n" ")\n" "%(name)s.save(%(name)sFilename, encoderLib='ffpyplayer')\n" "thisExp.currentLoop.addData('%(name)s.clip', %(name)sFilename)\n" ) buff.writeIndentedLines(code % self.params) def writeRoutineEndCodeJS(self, buff): code = ( "// Ensure that %(name)s is stopped\n" "if (%(name)s.status === PsychoJS.Status.STARTED) {\n" " await %(name)s.stop()\n" "}\n" ) buff.writeIndentedLines(code % self.params) if self.params['saveFile']: code = ( "// Save %(name)s recording\n" "let %(name)sFilename = `recording_%(name)s_${util.MonotonicClock.getDateStr()}`;\n" "await %(name)s.save({\n" " tag: %(name)sFilename,\n" " waitForCompletion: true,\n" " showDialog: true,\n" " dialogMsg: \"Please wait a few moments while the video is uploading to the server...\"\n" "});\n" "psychoJS.experiment.addData('%(name)s.clip', %(name)sFilename);\n" ) buff.writeIndentedLines(code % self.params) def writeExperimentEndCode(self, buff): code = ( "# Switch off %(name)s\n" "%(name)s.close()\n" ) buff.writeIndentedLines(code % self.params) def writeExperimentEndCodeJS(self, buff): code = ( "// Switch off %(name)s\n" "%(name)s.close()\n" ) buff.writeIndentedLines(code % self.params) if __name__ == "__main__": pass
23,557
Python
.py
550
30.901818
393
0.556597
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,616
__init__.py
psychopy_psychopy/psychopy/experiment/components/polygon/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy.experiment.components import BaseVisualComponent, Param, getInitVals, _translate from psychopy import logging class PolygonComponent(BaseVisualComponent): """A class for presenting grating stimuli""" categories = ['Stimuli'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'polygon.png' tooltip = _translate('Polygon: any regular polygon (line, triangle, square' '...circle)') def __init__(self, exp, parentName, name='polygon', interpolate='linear', units='from exp settings', anchor='center', lineColor='white', lineColorSpace='rgb', lineWidth=1, fillColor='white', fillColorSpace='rgb', shape='triangle', nVertices=4, vertices="", pos=(0, 0), size=(0.5, 0.5), ori=0, draggable=False, startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim=''): super(PolygonComponent, self).__init__( exp, parentName, name=name, units=units, fillColor=fillColor, borderColor=lineColor, pos=pos, size=size, ori=ori, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Polygon' self.url = "https://www.psychopy.org/builder/components/polygon.html" self.exp.requirePsychopyLibs(['visual']) self.order += ['shape', 'nVertices', # Basic tab ] self.order.insert(self.order.index("borderColor"), "lineColor") self.depends = [ # allows params to turn each other off/on {"dependsOn": "shape", # must be param name "condition": "=='regular polygon...'", # val to check for "param": "nVertices", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }, {"dependsOn": "shape", # must be param name "condition": "=='custom polygon...'", # val to check for "param": "vertices", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }, ] # params msg = _translate("How many vertices in your regular polygon?") self.params['nVertices'] = Param( nVertices, valType='int', inputType="single", categ='Basic', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Num. vertices")) msg = _translate("What are the vertices of your polygon? Should be an nx2 array or a list of [x, y] lists") self.params['vertices'] = Param( vertices, valType='list', inputType='single', categ='Basic', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Vertices") ) self.params['anchor'] = Param( anchor, valType='str', inputType="choice", categ='Layout', allowedVals=['center', 'top-center', 'bottom-center', 'center-left', 'center-right', 'top-left', 'top-right', 'bottom-left', 'bottom-right', ], updates='constant', hint=_translate("Which point on the stimulus should be anchored to its exact position?"), label=_translate("Anchor")) self.params['draggable'] = Param( draggable, valType="code", inputType="bool", categ="Layout", updates="constant", label=_translate("Draggable?"), hint=_translate( "Should this stimulus be moveble by clicking and dragging?" ) ) msg = _translate("What shape is this? With 'regular polygon...' you " "can set number of vertices and with 'custom " "polygon...' you can set vertices") self.params['shape'] = Param( shape, valType='str', inputType="choice", categ='Basic', allowedVals=["line", "triangle", "rectangle", "circle", "cross", "star7", "arrow", "regular polygon...", "custom polygon..."], allowedLabels=["Line", "Triangle", "Rectangle", "Circle", "Cross", "Star", "Arrow", "Regular polygon...", "Custom polygon..."], hint=msg, direct=False, label=_translate("Shape")) self.params['lineColor'] = self.params['borderColor'] del self.params['borderColor'] msg = _translate("Width of the shape's line (always in pixels - this" " does NOT use 'units')") self.params['lineWidth'] = Param( lineWidth, valType='num', inputType="single", allowedTypes=[], categ='Appearance', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Line width")) msg = _translate( "How should the image be interpolated if/when rescaled") self.params['interpolate'] = Param( interpolate, valType='str', inputType="choice", allowedVals=['linear', 'nearest'], categ='Texture', updates='constant', allowedUpdates=[], direct=False, hint=msg, label=_translate("Interpolate")) self.params['size'].hint = _translate( "Size of this stimulus [w,h]. Note that for a line only the " "first value is used, for triangle and rect the [w,h] is as " "expected,\n but for higher-order polygons it represents the " "[w,h] of the ellipse that the polygon sits on!! ") self.depends.append({ 'dependsOn': "shape", # if... 'condition': "=='line'", # is... 'param': "anchor", # then... 'true': "hide", # should... 'false': "show", # otherwise... }) del self.params['color'] def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # handle dependent params params = self.params.copy() if params['shape'] == 'regular polygon...': params['shape'] = params['nVertices'] elif params['shape'] == 'custom polygon...': params['shape'] = params['vertices'] # replace variable params with defaults inits = getInitVals(params) if inits['size'].val in ['1.0', '1']: inits['size'].val = '[1.0, 1.0]' vertices = inits['shape'] if vertices in ['line', '2']: code = ("%s = visual.Line(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " size=%(size)s,\n" % inits) elif vertices in ['triangle', '3']: code = ("%s = visual.ShapeStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " size=%(size)s, vertices='triangle',\n" % inits) elif vertices in ['rectangle', '4']: code = ("%s = visual.Rect(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " width=%(size)s[0], height=%(size)s[1],\n" % inits) elif vertices in ['circle', '100']: code = ("%s = visual.ShapeStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " size=%(size)s, vertices='circle',\n" % inits) elif vertices in ['star', 'star7']: code = ("%s = visual.ShapeStim(\n" % inits['name'] + " win=win, name='%s', vertices='star7',%s\n" % (inits['name'], unitsStr) + " size=%(size)s,\n" % inits) elif vertices in ['cross']: code = ("%s = visual.ShapeStim(\n" % inits['name'] + " win=win, name='%s', vertices='cross',%s\n" % (inits['name'], unitsStr) + " size=%(size)s,\n" % inits) elif self.params['shape'] == 'regular polygon...': code = ("%s = visual.Polygon(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " edges=%s," % str(inits['nVertices'].val) + " size=%(size)s,\n" % inits) else: code = ("%s = visual.ShapeStim(\n" % inits['name'] + " win=win, name='%s', vertices=%s,%s\n" % (inits['name'], vertices, unitsStr) + " size=%(size)s,\n" % inits) code += (" ori=%(ori)s, pos=%(pos)s, draggable=%(draggable)s, anchor=%(anchor)s,\n" " lineWidth=%(lineWidth)s,\n" " colorSpace=%(colorSpace)s, lineColor=%(lineColor)s, fillColor=%(fillColor)s,\n" " opacity=%(opacity)s, " % inits) depth = -self.getPosInRoutine() code += "depth=%.1f, " % depth if self.params['interpolate'].val == 'linear': code += "interpolate=True)\n" else: code += "interpolate=False)\n" buff.writeIndentedLines(code) def writeInitCodeJS(self, buff): inits = getInitVals(self.params) # Check for unsupported units if self.params['units'].val == 'from exp settings': unitsStr = "" elif inits['units'].val in ['cm', 'deg', 'degFlatPos', 'degFlat']: msg = "'{units}' units for your '{name}' shape is not currently supported for PsychoJS: " \ "switching units to 'height'." logging.warning(msg.format(units=inits['units'].val, name=self.params['name'].val,)) unitsStr = "units : 'height', " else: unitsStr = "units : %(units)s, " % self.params # replace variable params with defaults inits = getInitVals(self.params) # check for NoneTypes for param in inits: if inits[param] in [None, 'None', 'none', '']: inits[param].val = 'undefined' if inits['size'].val in ['1.0', '1']: inits['size'].val = '[1.0, 1.0]' if self.params['shape'] == 'regular polygon...': vertices = self.params['nVertices'] else: vertices = self.params['shape'] if vertices in ['line', '2']: code = ("{name} = new visual.ShapeStim ({{\n" " win: psychoJS.window, name: '{name}', {unitsStr}\n" " vertices: [[-{size}[0]/2.0, 0], [+{size}[0]/2.0, 0]],\n") elif vertices in ['triangle', '3']: code = ("{name} = new visual.ShapeStim ({{\n" " win: psychoJS.window, name: '{name}', {unitsStr}\n" " vertices: [[-{size}[0]/2.0, -{size}[1]/2.0], [+{size}[0]/2.0, -{size}[1]/2.0], [0, {size}[1]/2.0]],\n") elif vertices in ['rectangle', '4']: code = ("{name} = new visual.Rect ({{\n" " win: psychoJS.window, name: '{name}', {unitsStr}\n" " width: {size}[0], height: {size}[1],\n") elif vertices in ['circle', '100']: code = ("{name} = new visual.Polygon({{\n" " win: psychoJS.window, name: '{name}', {unitsStr}\n" " edges: 100, size:{size},\n") elif vertices in ['star']: code = ("{name} = new visual.ShapeStim ({{\n" " win: psychoJS.window, name: '{name}', {unitsStr}\n" " vertices: 'star7', size: {size},\n") elif vertices in ['cross']: code = ("{name} = new visual.ShapeStim ({{\n" " win: psychoJS.window, name: '{name}', {unitsStr}\n" " vertices: 'cross', size:{size},\n") elif vertices in ['arrow']: code = ("{name} = new visual.ShapeStim ({{\n" " win: psychoJS.window, name: '{name}', {unitsStr}\n" " vertices: 'arrow', size:{size},\n") elif self.params['shape'] == 'regular polygon...': code = ("{name} = new visual.Polygon ({{\n" " win: psychoJS.window, name: '{name}', {unitsStr}\n" " edges: {nVertices}, size:{size},\n") else: code = ("{name} = new visual.ShapeStim({{\n" + " win: psychoJS.window, name: '{name}', {unitsStr}\n" " vertices: {vertices}, size: {size},\n") depth = -self.getPosInRoutine() interpolate = 'true' if self.params['interpolate'].val != 'linear': interpolate = 'false' # make a util.Color object for non-transparent for key in ("fillColor", "lineColor"): if inits[key].val != "undefined": inits[key].val = "new util.Color(%s)" % inits[key] inits[key].valType = "code" # add other params code += ( " ori: {ori}, \n" " pos: {pos}, \n" " draggable: {draggable}, \n" " anchor: {anchor}, \n" " lineWidth: {lineWidth}, \n" " lineColor: {lineColor}, \n" " fillColor: {fillColor}, \n" " colorSpace: {colorSpace}, \n" " opacity: {opacity}, \n" " depth: {depth}, \n" " interpolate: {interpolate}, \n" "}});\n" "\n" ) buff.writeIndentedLines(code.format(name=inits['name'], unitsStr=unitsStr, anchor=inits['anchor'], lineWidth=inits['lineWidth'], size=inits['size'], ori=inits['ori'], pos=inits['pos'], colorSpace=inits['colorSpace'], lineColor=inits['lineColor'], fillColor=inits['fillColor'], opacity=inits['opacity'], depth=depth, interpolate=interpolate, nVertices=inits['nVertices'], vertices=inits['vertices'], draggable=inits['draggable'] ))
15,649
Python
.py
296
37.655405
126
0.4919
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,617
__init__.py
psychopy_psychopy/psychopy/experiment/components/microphone/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). # Author: Jeremy R. Gray, 2012 from pathlib import Path from psychopy import logging from psychopy.alerts import alert from psychopy.tools import stringtools as st, systemtools as syst, audiotools as at from psychopy.experiment.components import ( BaseComponent, BaseDeviceComponent, Param, getInitVals, _translate ) from psychopy.tools.audiotools import sampleRateQualityLevels _hasPTB = True try: import psychtoolbox.audio as audio except (ImportError, ModuleNotFoundError): logging.warning( "The 'psychtoolbox' library cannot be loaded but is required for audio " "capture (use `pip install psychtoolbox` to get it). Microphone " "recording will be unavailable this session. Note that opening a " "microphone stream will raise an error.") _hasPTB = False # Get list of sample rates sampleRates = {r[1]: r[0] for r in sampleRateQualityLevels.values()} class MicrophoneComponent(BaseDeviceComponent): """An event class for capturing short sound stimuli""" categories = ['Responses'] targets = ['PsychoPy', 'PsychoJS'] version = "2021.2.0" iconFile = Path(__file__).parent / 'microphone.png' tooltip = _translate('Microphone: basic sound capture (fixed onset & ' 'duration), okay for spoken words') deviceClasses = ['psychopy.hardware.microphone.MicrophoneDevice'] # dict of available transcribers (plugins can add entries to this) localTranscribers = { "Google": "google", } onlineTranscribers = { "Google": "google", } # dict mapping transcriber names to importable paths transcriberPaths = { 'google': "psychopy.sound.transcribe:GoogleCloudTranscriber" } def __init__(self, exp, parentName, name='mic', startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=2.0, startEstim='', durationEstim='', channels='auto', device=None, sampleRate='DVD Audio (48kHz)', maxSize=24000, outputType='default', speakTimes=False, trimSilent=False, policyWhenFull='warn', transcribe=False, transcribeBackend="none", transcribeLang="en-US", transcribeWords="", transcribeWhisperModel="base", transcribeWhisperDevice="auto", #legacy stereo=None, channel=None): super(MicrophoneComponent, self).__init__( exp, parentName, name=name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Microphone' self.url = "https://www.psychopy.org/builder/components/microphone.html" self.exp.requirePsychopyLibs(['sound']) self.order += [] self.params['stopType'].allowedVals = ['duration (s)'] msg = _translate( 'The duration of the recording in seconds; blank = 0 sec') self.params['stopType'].hint = msg # --- Device params --- self.order += [ "device", "channels", "sampleRate", "maxSize", ] def getDeviceIndices(): from psychopy.hardware.microphone import MicrophoneDevice profiles = MicrophoneDevice.getAvailableDevices() return [None] + [profile['index'] for profile in profiles] def getDeviceNames(): from psychopy.hardware.microphone import MicrophoneDevice profiles = MicrophoneDevice.getAvailableDevices() return ["default"] + [profile['deviceName'] for profile in profiles] self.params['device'] = Param( device, valType='code', inputType="choice", categ="Device", allowedVals=getDeviceIndices, allowedLabels=getDeviceNames, label=_translate("Device"), hint=_translate( "What microphone device would you like the use to record? This will only affect " "local experiments - online experiments ask the participant which mic to use." ) ) # grey out device settings when device is default for depParam in ("channels", "sampleRate"): self.depends.append({ "dependsOn": "device", # if... "condition": "== 'None'", # is... "param": depParam, # then... "true": "hide", # should... "false": "show", # otherwise... }) if stereo is not None: # If using a legacy mic component, work out channels from old bool value of stereo channels = ['mono', 'stereo'][stereo] self.params['channels'] = Param( channels, valType='str', inputType="choice", categ='Device', allowedVals=['auto', 'mono', 'stereo'], allowedLabels=[_translate("Auto"), _translate("Mono"), _translate("Stereo")], label=_translate("Channels"), hint=_translate( "Record two channels (stereo) or one (mono, smaller file). Select 'auto' to use as " "many channels as the selected device allows." ) ) self.params['sampleRate'] = Param( sampleRate, valType='num', inputType="choice", categ='Device', allowedVals=list(sampleRates), label=_translate("Sample rate (hz)"), hint=_translate( "How many samples per second (Hz) to record at" ), direct=False ) self.params['maxSize'] = Param( maxSize, valType='num', inputType="single", categ='Device', updates="set every repeat", label=_translate("Max recording size (kb)"), hint=_translate( "To avoid excessively large output files, what is the biggest file size you are " "likely to expect?" ) ) # --- Data params --- msg = _translate( "What file type should output audio files be saved as?") self.params['outputType'] = Param( outputType, valType='code', inputType='choice', categ='Data', allowedVals=["default"] + at.AUDIO_SUPPORTED_CODECS, hint=msg, label=_translate("Output file type") ) self.params['policyWhenFull'] = Param( policyWhenFull, valType="str", inputType="choice", categ="Data", updates="set every repeat", allowedVals=["warn", "roll", "error"], allowedLabels=[ _translate("Discard incoming data"), _translate("Clear oldest data"), _translate("Raise error"), ], label=_translate("Full buffer policy"), hint=_translate( "What to do when we reach the max amount of audio data which can be safely stored " "in memory?" ) ) msg = _translate( "Tick this to save times when the participant starts and stops speaking") self.params['speakTimes'] = Param( speakTimes, valType='bool', inputType='bool', categ='Transcription', hint=msg, label=_translate("Speaking start / stop times") ) msg = _translate( "Trim periods of silence from the output file") self.params['trimSilent'] = Param( trimSilent, valType='bool', inputType='bool', categ='Data', hint=msg, label=_translate("Trim silent") ) # Transcription params self.order += [ 'transcribe', 'transcribeBackend', 'transcribeLang', 'transcribeWords', ] self.params['transcribe'] = Param( transcribe, valType='bool', inputType='bool', categ='Transcription', hint=_translate("Whether to transcribe the audio recording and store the transcription"), label=_translate("Transcribe audio") ) # whisper specific params whisperParams = [ 'transcribeBackend', 'transcribeLang', 'transcribeWords', 'transcribeWhisperModel', 'transcribeWhisperDevice', 'speakTimes' ] for depParam in whisperParams: self.depends.append({ "dependsOn": "transcribe", "condition": "==True", "param": depParam, "true": "enable", # what to do with param if condition is True "false": "disable", # permitted: hide, show, enable, disable }) self.params['transcribeBackend'] = Param( transcribeBackend, valType='code', inputType='choice', categ='Transcription', allowedVals=list(self.allTranscribers.values()), allowedLabels=list(self.allTranscribers), direct=False, hint=_translate("What transcription service to use to transcribe audio?"), label=_translate("Transcription backend") ) self.params['transcribeLang'] = Param( transcribeLang, valType='str', inputType='single', categ='Transcription', hint=_translate("What language you expect the recording to be spoken in, e.g. en-US for English"), label=_translate("Transcription language") ) self.depends.append({ "dependsOn": "transcribeBackend", "condition": "=='Google'", "param": "transcribeLang", "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }) self.params['transcribeWords'] = Param( transcribeWords, valType='list', inputType='single', categ='Transcription', hint=_translate("Set list of words to listen for - if blank will listen for all words in chosen language. \n\n" "If using the built-in transcriber, you can set a minimum % confidence level using a colon " "after the word, e.g. 'red:100', 'green:80'. Otherwise, default confidence level is 80%."), label=_translate("Expected words") ) self.depends.append({ "dependsOn": "transcribeBackend", "condition": "=='Google'", "param": "transcribeWords", "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }) self.params['transcribeWhisperModel'] = Param( transcribeWhisperModel, valType='code', inputType='choice', categ='Transcription', allowedVals=["tiny", "base", "small", "medium", "large", "tiny.en", "base.en", "small.en", "medium.en"], hint=_translate( "Which model of Whisper AI should be used for transcription? Details of each model are available here at github.com/openai/whisper"), label=_translate("Whisper model") ) self.depends.append({ "dependsOn": "transcribeBackend", "condition": "=='Whisper'", "param": "transcribeWhisperModel", "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }) self.depends.append({ "dependsOn": "transcribeBackend", "condition": "=='Whisper'", "param": "speakTimes", "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }) # settings for whisper we might want, we'll need to get these from the # plugin itself at some point self.params['transcribeWhisperDevice'] = Param( transcribeWhisperDevice, valType='code', inputType='choice', categ='Transcription', allowedVals=["auto", "gpu", "cpu"], hint=_translate( "Which device to use for transcription?"), label=_translate("Whisper device") ) self.depends.append({ "dependsOn": "transcribeBackend", "condition": "=='Whisper'", "param": "transcribeWhisperDevice", "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }) @property def allTranscribers(self): """ Dict of all available transcribers (combines MicrophoneComponent.localTranscribers and MicrophoneComponent.onlineTranscribers) """ return {'None': "none", **self.localTranscribers, **self.onlineTranscribers} def writeDeviceCode(self, buff): """ Code to setup the CameraDevice for this component. Parameters ---------- buff : io.StringIO Text buffer to write code to. """ inits = getInitVals(self.params) # --- setup mic --- # Substitute sample rate value for numeric equivalent inits['sampleRate'] = sampleRates[inits['sampleRate'].val] # Substitute channel value for numeric equivalent inits['channels'] = {'mono': 1, 'stereo': 2, 'auto': None}[self.params['channels'].val] # initialise mic device code = ( "# initialise microphone\n" "deviceManager.addDevice(\n" " deviceClass='psychopy.hardware.microphone.MicrophoneDevice',\n" " deviceName=%(deviceLabel)s,\n" " index=%(device)s,\n" " maxRecordingSize=%(maxSize)s,\n" ) if self.params['device'].val not in ("None", "", None): code += ( " channels=%(channels)s, \n" " sampleRateHz=%(sampleRate)s, \n" ) code += ( ")\n" ) buff.writeOnceIndentedLines(code % inits) def writeStartCode(self, buff): inits = getInitVals(self.params) # Use filename with a suffix to store recordings code = ( "# Make folder to store recordings from %(name)s\n" "%(name)sRecFolder = filename + '_%(name)s_recorded'\n" "if not os.path.isdir(%(name)sRecFolder):\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "os.mkdir(%(name)sRecFolder)\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) def writeStartCodeJS(self, buff): inits = getInitVals(self.params) code = ( "// Define folder to store recordings from %(name)s" "%(name)sRecFolder = filename + '_%(name)s_recorded" ) buff.writeIndentedLines(code % inits) def writeRunOnceInitCode(self, buff): inits = getInitVals(self.params) # get transcriber path if inits['transcribeBackend'].val in MicrophoneComponent.transcriberPaths: inits['transcriberPath'] = MicrophoneComponent.transcriberPaths[inits['transcribeBackend'].val] else: inits['transcriberPath'] = inits['transcribeBackend'].val # check if the user wants to do transcription if inits['transcribe'].val: code = ( "# Setup speech-to-text transcriber for audio recordings\n" "from psychopy.sound.transcribe import setupTranscriber\n" "setupTranscriber(\n" " '%(transcriberPath)s'") # handle advanced config options if inits['transcribeBackend'].val == 'Whisper': code += ( ",\n config={'device': '%(transcribeWhisperDevice)s'})\n") else: code += (")\n") buff.writeOnceIndentedLines(code % inits) def writeInitCode(self, buff): inits = getInitVals(self.params) if inits['outputType'].val == 'default': inits['outputType'].val = 'wav' # Assign name to device var name code = ( "# make microphone object for %(name)s\n" "%(name)s = sound.microphone.Microphone(\n" " device=%(deviceLabel)s,\n" " name='%(name)s',\n" " recordingFolder=%(name)sRecFolder,\n" " recordingExt='%(outputType)s'\n" ")\n" "# tell the experiment handler to save this Microphone's clips if the experiment is " "force ended\n" "runAtExit.append(%(name)s.saveClips)\n" "# connect camera save method to experiment handler so it's called when data saves\n" "thisExp.connectSaveMethod(%(name)s.saveClips)\n" ) buff.writeIndentedLines(code % inits) def writeInitCodeJS(self, buff): inits = getInitVals(self.params) inits['sampleRate'] = sampleRates[inits['sampleRate'].val] # Alert user if non-default value is selected for device if inits['device'].val != 'default': alert(5055, strFields={'name': inits['name'].val}) # Write code code = ( "%(name)s = new sound.Microphone({\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "win : psychoJS.window, \n" "name:'%(name)s',\n" "sampleRateHz : %(sampleRate)s,\n" "channels : %(channels)s,\n" "maxRecordingSize : %(maxSize)s,\n" "loopback : true,\n" "policyWhenFull : 'ignore',\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "});\n" ) buff.writeIndentedLines(code % inits) def writeFrameCode(self, buff): """Write the code that will be called every frame""" inits = getInitVals(self.params) inits['routine'] = self.parentName # Start the recording indented = self.writeStartTestCode(buff) if indented: code = ( "# start recording with %(name)s\n" "%(name)s.start()\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-indented, relative=True) # Get clip each frame indented = self.writeActiveTestCode(buff) code = ( "# update recorded clip for %(name)s\n" "%(name)s.poll()\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-indented, relative=True) # Stop recording indented = self.writeStopTestCode(buff) if indented: code = ( "# stop recording with %(name)s\n" "%(name)s.stop()\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-indented, relative=True) def writeFrameCodeJS(self, buff): inits = getInitVals(self.params) inits['routine'] = self.parentName # Start the recording self.writeStartTestCodeJS(buff) code = ( "await %(name)s.start();\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}" ) buff.writeIndentedLines(code % inits) if self.params['stopVal'].val not in ['', None, -1, 'None']: # Stop the recording self.writeStopTestCodeJS(buff) code = ( "%(name)s.pause();\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}" ) buff.writeIndentedLines(code % inits) def writeRoutineEndCode(self, buff): inits = getInitVals(self.params) # Alter inits if len(self.exp.flow._loopList): inits['loop'] = self.exp.flow._loopList[-1].params['name'] inits['filename'] = f"'recording_{inits['name']}_{inits['loop']}_%s.{inits['outputType']}' % {inits['loop']}.thisTrialN" else: inits['loop'] = "thisExp" inits['filename'] = f"'recording_{inits['name']}'" transcribe = inits['transcribe'].val if inits['transcribe'].val == False: inits['transcribeBackend'].val = None # Warn user if their transcriber won't work locally if inits['transcribe'].val: if self.params['transcribeBackend'].val in self.localTranscribers: inits['transcribeBackend'].val = self.localTranscribers[self.params['transcribeBackend'].val] else: default = list(self.localTranscribers.values())[0] alert(4610, strFields={"transcriber": inits['transcribeBackend'].val, "default": default}) # Store recordings from this routine code = ( "# tell mic to keep hold of current recording in %(name)s.clips and transcript (if applicable) in %(name)s.scripts\n" "# this will also update %(name)s.lastClip and %(name)s.lastScript\n" "%(name)s.stop()\n" ) buff.writeIndentedLines(code % inits) if inits['transcribeBackend'].val: code = ( "tag = data.utils.getDateStr()\n" "%(name)sClip, %(name)sScript = %(name)s.bank(\n" ) else: code = ( "tag = data.utils.getDateStr()\n" "%(name)sClip = %(name)s.bank(\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "tag=tag, transcribe='%(transcribeBackend)s',\n" ) buff.writeIndentedLines(code % inits) if transcribe: code = ( "language=%(transcribeLang)s, expectedWords=%(transcribeWords)s\n" ) else: code = ( "config=None\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( ")\n" "%(loop)s.addData(\n" " '%(name)s.clip', %(name)s.recordingFolder / %(name)s.getClipFilename(tag)\n" ")" ) buff.writeIndentedLines(code % inits) if transcribe: code = ( "%(loop)s.addData('%(name)s.script', %(name)sScript)\n" ) buff.writeIndentedLines(code % inits) if inits['speakTimes'] and inits['transcribeBackend'].val == "Whisper": code = ( "# save transcription data\n" "with open(os.path.join(%(name)sRecFolder, 'recording_%(name)s_%%s.json' %% tag), 'w') as fp:\n" " fp.write(%(name)sScript.response)\n" "# save speaking start/stop times\n" "%(name)sSpeechInterval = %(name)s.lastScript.getSpeechInterval()\n" "%(name)sSpeechOnset = %(name)sSpeechInterval[0]\n" "%(name)sSpeechOffset = %(name)sSpeechInterval[1]\n" "thisExp.addData('%(name)s.speechStart', %(name)sSpeechOnset)\n" "thisExp.addData('%(name)s.speechEnd', %(name)sSpeechOffset)\n" ) buff.writeIndentedLines(code % inits) # Write base end routine code BaseComponent.writeRoutineEndCode(self, buff) def writeRoutineEndCodeJS(self, buff): inits = getInitVals(self.params) inits['routine'] = self.parentName if self.params['transcribeBackend'].val in self.allTranscribers: inits['transcribeBackend'].val = self.allTranscribers[self.params['transcribeBackend'].val] # Warn user if their transcriber won't work online if inits['transcribe'].val and inits['transcribeBackend'].val not in self.onlineTranscribers.values(): default = list(self.onlineTranscribers.values())[0] alert(4605, strFields={"transcriber": inits['transcribeBackend'].val, "default": default}) # Write base end routine code BaseComponent.writeRoutineEndCodeJS(self, buff) # Store recordings from this routine code = ( "// stop the microphone (make the audio data ready for upload)\n" "await %(name)s.stop();\n" "// construct a filename for this recording\n" "thisFilename = 'recording_%(name)s_' + currentLoop.name + '_' + currentLoop.thisN\n" "// get the recording\n" "%(name)s.lastClip = await %(name)s.getRecording({\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "tag: thisFilename + '_' + util.MonotonicClock.getDateStr(),\n" "flush: false\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "});\n" "psychoJS.experiment.addData('%(name)s.clip', thisFilename);\n" "// start the asynchronous upload to the server\n" "%(name)s.lastClip.upload();\n" ) buff.writeIndentedLines(code % inits) if self.params['transcribe'].val: code = ( "// transcribe the recording\n" "const transcription = await %(name)s.lastClip.transcribe({\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "languageCode: %(transcribeLang)s,\n" "engine: sound.AudioClip.Engine.%(transcribeBackend)s,\n" "wordList: %(transcribeWords)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "});\n" "%(name)s.lastScript = transcription.transcript;\n" "%(name)s.lastConf = transcription.confidence;\n" "psychoJS.experiment.addData('%(name)s.transcript', %(name)s.lastScript);\n" "psychoJS.experiment.addData('%(name)s.confidence', %(name)s.lastConf);\n" ) buff.writeIndentedLines(code % inits) def writeExperimentEndCode(self, buff): """Write the code that will be called at the end of an experiment (e.g. save log files or reset hardware) """ inits = getInitVals(self.params) if len(self.exp.flow._loopList): currLoop = self.exp.flow._loopList[-1] # last (outer-most) loop else: currLoop = self.exp._expHandler inits['loop'] = currLoop.params['name'] if inits['outputType'].val == 'default': inits['outputType'].val = 'wav' # Save recording code = ( "# save %(name)s recordings\n" "%(name)s.saveClips()\n" ) buff.writeIndentedLines(code % inits) def getDeviceName(index): """ Get device name from a given index Parameters ---------- index : int or None Index of the device to use """ name = "defaultMicrophone" if isinstance(index, str) and index.isnumeric(): index = int(index) for dev in syst.getAudioCaptureDevices(): if dev['index'] == index: name = dev['name'] return name def getDeviceVarName(index, case="camel"): """ Get device name from a given index and convert it to a valid variable name. Parameters ---------- index : int or None Index of the device to use case : str Format of the variable name (see stringtools.makeValidVarName for info on accepted formats) """ # Get device name name = getDeviceName(index) # If device name is just default, add "microphone" for clarity if name == "default": name += "_microphone" # Make valid varName = st.makeValidVarName(name, case=case) return varName
28,597
Python
.py
649
32.812018
149
0.574677
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,618
__init__.py
psychopy_psychopy/psychopy/experiment/components/resourceManager/__init__.py
from pathlib import Path from psychopy.alerts import alert from .._base import BaseComponent from psychopy.localization import _translate from ... import getInitVals from ...params import Param class ResourceManagerComponent(BaseComponent): categories = ['Custom'] targets = ['PsychoJS'] iconFile = Path(__file__).parent / "resource_manager.png" tooltip = _translate("Pre-load some resources into memory so that components using them can start without having " "to load first") beta = True def __init__(self, exp, parentName, name='resources', startType='time (s)', startVal=0, stopType='duration (s)', stopVal='', startEstim='', durationEstim='', resources=None, actionType='Start and Check', saveStartStop=True, syncScreenRefresh=False, forceEndRoutine=False, disabled=False): BaseComponent.__init__(self, exp, parentName, name=name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim, saveStartStop=saveStartStop, syncScreenRefresh=syncScreenRefresh, disabled=disabled) self.type = 'ResourceManager' self.url = "https://www.psychopy.org/builder/components/resourcemanager" if not resources: resources = [] self.params['resources'] = Param(resources, valType='list', inputType="fileList", categ='Basic', updates='constant', hint=_translate("Resources to download/check"), direct=False, label=_translate("Resources")) self.params['checkAll'] = Param(resources, valType='bool', inputType="bool", categ='Basic', hint=_translate("When checking these resources, also check for all currently downloading?"), label=_translate("Check all")) self.params['actionType'] = Param(actionType, valType='str', inputType='choice', categ='Basic', allowedVals=["Start and Check", "Start Only", "Check Only"], hint=_translate("Should this Component start an / or check resource preloading?"), label=_translate("Preload actions") ) msg = _translate("Should we end the Routine when the resource download is complete?") self.params['forceEndRoutine'] = Param( forceEndRoutine, valType='bool', inputType="bool", allowedTypes=[], categ='Basic', updates='constant', hint=msg, label=_translate("Force end Routine")) self.params['stopVal'].label = _translate("Check") self.depends.append( {"dependsOn": "actionType", # must be param name "condition": "=='Start Only'", # val to check for "param": "stop", # param property to alter "true": "hide", # what to do with param if condition is True "false": "show", # permitted: hide, show, enable, disable } ) self.depends.append( {"dependsOn": "actionType", # must be param name "condition": "=='Check Only'", # val to check for "param": "start", # param property to alter "true": "hide", # what to do with param if condition is True "false": "show", # permitted: hide, show, enable, disable } ) self.depends.append( {"dependsOn": "actionType", # must be param name "condition": "=='Check Only'", # val to check for "param": "start", # param property to alter "true": "hide", # what to do with param if condition is True "false": "show", # permitted: hide, show, enable, disable } ) del self.params['syncScreenRefresh'] del self.params['saveStartStop'] def writeInitCodeJS(self, buff): # Get initial values inits = getInitVals(self.params, 'PsychoJS') # Create object code = ( "%(name)s = {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "status: PsychoJS.Status.NOT_STARTED\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "};\n" ) buff.writeIndentedLines(code % inits) def writeFrameCodeJS(self, buff): # Get initial values inits = getInitVals(self.params, 'PsychoJS') # Sub in ALL_RESOURCES if checkAll is ticked if inits['checkAll']: inits['resources'] = "core.ServerManager.ALL_RESOURCES" # Write start code if mode includes start if "start" in self.params['actionType'].val.lower(): code = ( "// start downloading resources specified by component %(name)s\n" "if (t >= %(startVal)s && %(name)s.status === PsychoJS.Status.NOT_STARTED) {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "console.log('register and start downloading resources specified by component %(name)s');\n" "await psychoJS.serverManager.prepareResources(%(resources)s);\n" "%(name)s.status = PsychoJS.Status.STARTED;\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}" ) buff.writeIndentedLines(code % inits) # Write check code if mode includes check if "check" in self.params['actionType'].val.lower(): code = ( "// check on the resources specified by component %(name)s\n" "if (t >= %(stopVal)s && %(name)s.status === PsychoJS.Status.STARTED) {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "if (psychoJS.serverManager.getResourceStatus(%(resources)s) === core.ServerManager.ResourceStatus.DOWNLOADED) {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "console.log('finished downloading resources specified by component %(name)s');\n" "%(name)s.status = PsychoJS.Status.FINISHED;\n" ) if self.params['forceEndRoutine']: code += "continueRoutine = false;\n" buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "} else {" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "console.log('resource specified in %(name)s took longer than expected to download');\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}" ) buff.writeIndentedLines(code % inits)
7,621
Python
.py
161
34.391304
135
0.562794
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,619
__init__.py
psychopy_psychopy/psychopy/experiment/components/text/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy.alerts import alerttools from psychopy.experiment.components import BaseVisualComponent, Param, getInitVals, _translate class TextComponent(BaseVisualComponent): """An event class for presenting text-based stimuli """ categories = ['Stimuli'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'text.png' tooltip = _translate('Text: present text stimuli') def __init__(self, exp, parentName, name='text', # effectively just a display-value text=_translate('Any text\n\nincluding line breaks'), font='Arial', units='from exp settings', color='white', colorSpace='rgb', pos=(0, 0), letterHeight=0.05, ori=0, draggable=False, startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, flip='None', startEstim='', durationEstim='', wrapWidth='', languageStyle='LTR'): super(TextComponent, self).__init__(exp, parentName, name=name, units=units, color=color, colorSpace=colorSpace, pos=pos, ori=ori, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Text' self.url = "https://www.psychopy.org/builder/components/text.html" # params _allow3 = ['constant', 'set every repeat', 'set every frame'] # list self.params['text'] = Param( text, valType='str', inputType="multi", allowedTypes=[], categ='Basic', updates='constant', allowedUpdates=_allow3[:], # copy the list hint=_translate("The text to be displayed"), canBePath=False, label=_translate("Text")) self.params['font'] = Param( font, valType='str', inputType="single", allowedTypes=[], categ='Formatting', updates='constant', allowedUpdates=_allow3[:], # copy the list hint=_translate("The font name (e.g. Comic Sans)"), label=_translate("Font")) del self.params['size'] # because you can't specify width for text self.params['draggable'] = Param( draggable, valType="code", inputType="bool", categ="Layout", updates="constant", label=_translate("Draggable?"), hint=_translate( "Should this stimulus be moveble by clicking and dragging?" ) ) self.params['letterHeight'] = Param( letterHeight, valType='num', inputType="single", allowedTypes=[], categ='Formatting', updates='constant', allowedUpdates=_allow3[:], # copy the list hint=_translate("Specifies the height of the letter (the width" " is then determined by the font)"), label=_translate("Letter height")) self.params['wrapWidth'] = Param( wrapWidth, valType='num', inputType="single", allowedTypes=[], categ='Layout', updates='constant', allowedUpdates=['constant'], hint=_translate("How wide should the text get when it wraps? (in" " the specified units)"), label=_translate("Wrap width")) self.params['flip'] = Param( flip, valType='str', inputType="single", allowedTypes=[], categ='Layout', allowedVals=["horiz", "vert", "None"], updates='constant', allowedUpdates=_allow3[:], # copy the list hint=_translate("horiz = left-right reversed; vert = up-down" " reversed; $var = variable"), label=_translate("Flip (mirror)")) self.params['languageStyle'] = Param( languageStyle, valType='str', inputType="choice", categ='Formatting', allowedVals=['LTR', 'RTL', 'Arabic'], hint=_translate("Handle right-to-left (RTL) languages and Arabic reshaping"), label=_translate("Language style")) del self.params['fillColor'] del self.params['borderColor'] def _getParamCaps(self, paramName): """ TEMPORARY FIX TextStim in JS doesn't accept `letterHeight` as a param. Ideally this needs to be fixed in JS, but in the meantime overloading this function in Python to write `setHeight` rather than `setLetterHeight` means it stops biting users. """ # call base function paramName = BaseVisualComponent._getParamCaps(self, paramName) # replace letterHeight if paramName == "LetterHeight": paramName = "Height" return paramName def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # do writing of init # replaces variable params with sensible defaults inits = getInitVals(self.params, 'PsychoPy') if self.params['wrapWidth'].val in ['', 'None', 'none']: inits['wrapWidth'] = 'None' code = ("%(name)s = visual.TextStim(win=win, " "name='%(name)s',\n" " text=%(text)s,\n" " font=%(font)s,\n" " " + unitsStr + "pos=%(pos)s, draggable=%(draggable)s, height=%(letterHeight)s, " "wrapWidth=%(wrapWidth)s, ori=%(ori)s, \n" " color=%(color)s, colorSpace=%(colorSpace)s, " "opacity=%(opacity)s, \n" " languageStyle=%(languageStyle)s,") buff.writeIndentedLines(code % inits) flip = self.params['flip'].val.strip() if flip == 'horiz': flipStr = 'flipHoriz=True, ' elif flip == 'vert': flipStr = 'flipVert=True, ' else: flipStr = '' depth = -self.getPosInRoutine() buff.writeIndented(' ' + flipStr + 'depth=%.1f);\n' % depth) def writeInitCodeJS(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = " units: undefined, \n" else: unitsStr = " units: %(units)s, \n" % self.params # do writing of init # replaces variable params with sensible defaults inits = getInitVals(self.params, 'PsychoJS') # check for NoneTypes for param in inits: if inits[param] in [None, 'None', '']: inits[param].val = 'undefined' if param == 'text': inits[param].val = "" code = ("%(name)s = new visual.TextStim({\n" " win: psychoJS.window,\n" " name: '%(name)s',\n" " text: %(text)s,\n" " font: %(font)s,\n" + unitsStr + " pos: %(pos)s, draggable: %(draggable)s, height: %(letterHeight)s," " wrapWidth: %(wrapWidth)s, ori: %(ori)s,\n" " languageStyle: %(languageStyle)s,\n" " color: new util.Color(%(color)s)," " opacity: %(opacity)s,") buff.writeIndentedLines(code % inits) flip = self.params['flip'].val.strip() if flip == 'horiz': flipStr = 'flipHoriz : true, ' elif flip == 'vert': flipStr = 'flipVert : true, ' elif flip and not flip == "None": msg = ("flip value should be 'horiz' or 'vert' (no quotes)" " in component '%s'") raise ValueError(msg % self.params['name'].val) else: flipStr = '' depth = -self.getPosInRoutine() code = (" %sdepth: %.1f \n" "});\n\n" % (flipStr, depth)) buff.writeIndentedLines(code) def integrityCheck(self): super().integrityCheck() # run parent class checks first alerttools.testFont(self) # Test whether font is available locally
8,750
Python
.py
175
36.268571
114
0.537634
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,620
__init__.py
psychopy_psychopy/psychopy/experiment/components/aperture/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path from psychopy.experiment import Param from psychopy.experiment.components import getInitVals, _translate from psychopy.experiment.components.polygon import PolygonComponent __author__ = 'Jeremy Gray, Jon Peirce' # March 2011; builder-component for Yuri Spitsyn's visual.Aperture class # July 2011: jwp added the code for it to be enabled only when needed class ApertureComponent(PolygonComponent): """ This component can be used to filter the visual display, as if the subject is looking at it through an opening (i.e. add an image component, as the background image, then add an aperture to show part of the image). Only one aperture is enabled at a time; you can't "double up": a second aperture takes precedence. """ categories = ['Stimuli'] targets = ['PsychoPy'] iconFile = Path(__file__).parent / 'aperture.png' tooltip = _translate('Aperture: restrict the drawing of stimuli to a given ' 'region') def __init__(self, exp, parentName, name='aperture', units='norm', size=1, pos=(0, 0), anchor="center", ori=0, shape='triangle', nVertices=4, vertices="", startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim=''): # initialise main parameters super(ApertureComponent, self).__init__( exp, parentName, name=name, units=units, pos=pos, size=size, ori=ori, shape=shape, nVertices=nVertices, vertices=vertices, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Aperture' self.url = "https://www.psychopy.org/builder/components/aperture.html" self.order += [] msg = _translate( "How big is the aperture? (a single number for diameter)") self.params['size'].hint = msg self.params['anchor'] = Param( anchor, valType='str', inputType="choice", categ='Layout', allowedVals=['center', 'top-center', 'bottom-center', 'center-left', 'center-right', 'top-left', 'top-right', 'bottom-left', 'bottom-right', ], updates='constant', hint=_translate("Which point on the aperture should be anchored to its exact position?"), label=_translate("Anchor")) # only localize hints and labels self.params['size'].label = _translate("Size") self.params['pos'].hint = _translate("Where is the aperture centred?") # Remove Polygon params which are not needed del self.params['colorSpace'] del self.params['fillColor'] del self.params['lineColor'] del self.params['lineWidth'] del self.params['contrast'] del self.params['opacity'] del self.params['interpolate'] def writeInitCode(self, buff): # do writing of init inits = getInitVals(self.params) inits['depth'] = -self.getPosInRoutine() # additional substitutions if self.params['units'].val == 'from exp settings': inits['units'].val = None if self.params['shape'] == 'regular polygon...': inits['vertices'] = self.params['nVertices'] elif self.params['shape'] != 'custom polygon...': inits['vertices'] = self.params['shape'] code = ( "%(name)s = visual.Aperture(\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "win=win, name='%(name)s',\n" "units=%(units)s, size=%(size)s, pos=%(pos)s, ori=%(ori)s,\n" "shape=%(vertices)s, anchor=%(anchor)s\n," "depth=%(depth)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( ")\n" "%(name)s.disable() # disable until its actually used\n" ) buff.writeIndentedLines(code % inits) def writeFrameCode(self, buff): """Only activate the aperture for the required frames """ params = self.params code = (f"\n" f"# *{params['name']}* updates\n") buff.writeIndented(code) # writes an if statement to determine whether to draw etc indented = self.writeStartTestCode(buff) if indented: buff.writeIndented("%(name)s.enabled = True\n" % self.params) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) indented = self.writeStopTestCode(buff) if indented: buff.writeIndented("%(name)s.enabled = False\n" % self.params) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) # set parameters that need updating every frame # do any params need updating? (this method inherited from _base) if self.checkNeedToUpdate('set every frame'): code = ("if %(name)s.status == STARTED: # only update if being drawn\n") buff.writeIndented(code % self.params) buff.setIndentLevel(+1, relative=True) # to enter the if block self.writeParamUpdates(buff, 'set every frame') buff.setIndentLevel(-1, relative=True) # to exit the if block def writeRoutineEndCode(self, buff): msg = "%(name)s.enabled = False # just in case it was left enabled\n" buff.writeIndented(msg % self.params) # get parent to write code too (e.g. store onset/offset times) super().writeRoutineEndCode(buff)
6,214
Python
.py
130
37.061538
101
0.600726
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,621
__init__.py
psychopy_psychopy/psychopy/experiment/components/eyetracker_record/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from __future__ import absolute_import, print_function from builtins import super # provides Py3-style super() using python-future from os import path from pathlib import Path from psychopy.experiment.components import BaseComponent, Param, _translate from psychopy.alerts import alert class EyetrackerRecordComponent(BaseComponent): """A class for using one of several eyetrackers to follow gaze""" categories = ['Eyetracking'] targets = ['PsychoPy'] version = "2021.2.0" iconFile = Path(__file__).parent / 'eyetracker_record.png' tooltip = _translate('Start and / or Stop recording data from the eye tracker') beta = True def __init__(self, exp, parentName, name='etRecord', startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim='', actionType="Start and Stop", stopWithRoutine=False, # legacy save='final', configFile='myTracker.yaml'): BaseComponent.__init__(self, exp, parentName, name=name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'EyetrackerRecord' self.url = "https://www.psychopy.org/builder/components/eyetracker.html" self.exp.requirePsychopyLibs(['iohub', 'hardware']) self.params['actionType'] = Param( actionType, valType='str', inputType='choice', categ='Basic', allowedVals=["Start and Stop", "Start Only", "Stop Only"], hint=_translate("Should this Component start and / or stop eye tracker recording?"), label=_translate("Record actions") ) self.depends.append( {"dependsOn": "actionType", # must be param name "condition": "=='Start Only'", # val to check for "param": "stop", # param property to alter "true": "hide", # what to do with param if condition is True "false": "show", # permitted: hide, show, enable, disable } ) self.depends.append( {"dependsOn": "actionType", # must be param name "condition": "=='Stop Only'", # val to check for "param": "start", # param property to alter "true": "hide", # what to do with param if condition is True "false": "show", # permitted: hide, show, enable, disable } ) self.params['stopWithRoutine'] = Param( stopWithRoutine, valType='bool', inputType="bool", updates='constant', categ='Basic', hint=_translate( "Should eyetracking stop when the Routine ends? Tick to force stopping " "after the Routine has finished."), label=_translate('Stop with Routine?')) self.depends.append( { "dependsOn": "actionType", # must be param name "condition": "in ('Start and Stop', 'Stop Only')", # val to check for "param": "stopWithRoutine", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) # TODO: Display actionType control after component name. # Currently, adding params before start / stop time # in .order has no effect self.order = self.order[:1]+['actionType']+self.order[1:] def getStartAndDuration(self): """ Due to the different action types hiding either the start or stop field parameters, we need to force the start and stop criteria to correct types and values, make sure the component is displayed accurately on the timeline reflecting the status of EyetrackerRecordComponent instead of the eyetracker device, and ensure proper nonSlip timing determination """ # make a copy of params so we can change stuff harmlessly params = self.params.copy() # check if the actionType is 'Start Only' or 'Stop Only' if params['actionType'].val == 'Start Only': # if only starting, pretend stop is 0 params['stopType'].val = 'duration (s)' params['stopVal'].val = 0.0 elif params['actionType'].val == 'Stop Only': # if only stopping, pretend start was 0 params['startType'].val = 'time (s)' params['startVal'].val = 0.0 return super().getStartAndDuration(params) def writeInitCode(self, buff): inits = self.params # Make a controller object code = ( "%(name)s = hardware.eyetracker.EyetrackerControl(\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "tracker=eyetracker,\n" "actionType=%(actionType)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( ")" ) buff.writeIndentedLines(code % inits) def writeFrameCode(self, buff): """Write the code that will be called every frame """ # Alert user if eyetracking isn't setup if self.exp.eyetracking == "None": alert(code=4505) buff.writeIndented("\n") buff.writeIndentedLines("# *%s* updates\n" % self.params['name']) if "start" in self.params['actionType'].val.lower(): # if this Component can start recording, write start test code indented = self.writeStartTestCode(buff) # write code to start code = ( "%(name)s.start()\n" ) buff.writeIndentedLines(code % self.params) # dedent buff.setIndentLevel(-indented, relative=True) else: # if this Component can't start recording, make sure it reads as already started code = ( "if %(name)s.status == NOT_STARTED:\n" " %(name)s.frameNStart = frameN # exact frame index\n" " %(name)s.tStart = t # local t and not account for scr refresh\n" " %(name)s.tStartRefresh = tThisFlipGlobal # on global time\n" " win.timeOnFlip(%(name)s, 'tStartRefresh') # time at next scr refresh\n" " %(name)s.status = STARTED\n" ) buff.writeIndentedLines(code % self.params) if "stop" in self.params['actionType'].val.lower(): # if this Component can stop recording, write stop test code indented = self.writeStopTestCode(buff) # write code to stop code = ( "%(name)s.stop()\n" ) buff.writeIndentedLines(code % self.params) # dedent buff.setIndentLevel(-indented, relative=True) else: # if this Component can't stop recording, mark as finished as soon as recording has started code = ( "if %(name)s.status == STARTED:\n" " %(name)s.tStop = t # not accounting for scr refresh\n" " %(name)s.tStopRefresh = tThisFlipGlobal # on global time\n" " %(name)s.frameNStop = frameN # exact frame index\n" " %(name)s.status = FINISHED\n" ) buff.writeIndentedLines(code % self.params) def writeRoutineEndCode(self, buff): if self.params['stopWithRoutine']: # stop at the end of the Routine, if requested code = ( "%(name)s.stop() # ensure eyetracking has stopped at end of Routine\n" ) buff.writeIndentedLines(code % self.params)
8,278
Python
.py
170
37.011765
103
0.580861
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,622
__init__.py
psychopy_psychopy/psychopy/experiment/components/variable/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Part of the PsychoPy library Copyright (C) 2015 Jonathan Peirce Distributed under the terms of the GNU General Public License (GPL). """ from pathlib import Path from psychopy.experiment.components import BaseComponent, Param, _translate import numpy as np class VariableComponent(BaseComponent): """An class for creating variables in builder.""" categories = ['Custom'] targets = ['PsychoPy'] iconFile = Path(__file__).parent / 'variable.png' tooltip = _translate('Variable: create a new variable') def __init__(self, exp, parentName, name='var1', startExpValue = '', startRoutineValue='', startFrameValue=''): super().__init__(exp, parentName, name) categories = ['Custom'] self.type = 'Variable' self.url = "https://www.psychopy.org/builder/components/variable.html" self.order += ['startExpValue', 'saveStartExp', 'startRoutineValue', # Basic tab 'saveStartRoutine', 'startFrameValue', 'saveFrameValue', 'saveEndRoutine', 'saveEndExp', # Data tab ] # set parameters hnt = _translate("The start value. A variable can be set to any value.") self.params['startExpValue'] = Param( startExpValue, valType='code', inputType="single", allowedTypes=[], updates='constant', categ='Basic', hint=hnt, label=_translate("Experiment start value")) hnt = _translate("Set the value for the beginning of each Routine.") self.params['startRoutineValue'] = Param( startRoutineValue, valType='code', inputType="single", allowedTypes=[], updates='constant', categ='Basic', hint=hnt, label=_translate("Routine start value")) hnt = _translate("Set the value for the beginning of every screen refresh.") self.params['startFrameValue'] = Param( startFrameValue, valType='code', inputType="single", allowedTypes=[], categ='Basic', hint=hnt, label=_translate("Frame start value")) # Save options hnt = _translate("Save the experiment start value in data file.") self.params['saveStartExp'] = Param( False, valType='bool', inputType="bool", categ='Data', updates='constant', hint=hnt, label=_translate("Save exp start value")) hnt = _translate("Save the experiment end value in data file.") self.params['saveEndExp'] = Param( False, valType='bool', inputType="bool", categ='Data', updates='constant', hint=hnt, label=_translate("Save exp end value")) hnt = _translate("Save the Routine start value in data file.") self.params['saveStartRoutine'] = Param( False, valType='bool', inputType="bool", categ='Data', updates='constant', hint=hnt, label=_translate("Save Routine start value")) hnt = _translate("Save the Routine end value in data file.") self.params['saveEndRoutine'] = Param( True, valType='bool', inputType="bool", categ='Data', updates='constant', hint=hnt, label=_translate("Save Routine end value")) hnt = _translate("Save choice of frame value in data file.") self.params['saveFrameValue'] = Param( 'never', valType='str', inputType="choice", categ='Data', allowedVals=['first', 'last', 'all', 'never'], updates='constant', direct=False, hint=hnt, label=_translate("Save frame value")) def writeInitCode(self, buff): """Write variable initialisation code.""" code = ("# Set experiment start values for variable component %(name)s\n") if self.params['startExpValue'] == '': code += ("%(name)s = ''\n") else: code += ("%(name)s = %(startExpValue)s\n") # Create variable container code += ("%(name)sContainer = []\n") buff.writeIndented(code % self.params) # def writeRoutineStartCode(self, buff): """Write the code that will be called at the start of the Routine.""" if not self.params['startRoutineValue'] == '': code = ("%(name)s = %(startRoutineValue)s # Set Routine start values for %(name)s\n") if self.params['saveStartRoutine'] == True: code += ("thisExp.addData('%(name)s.routineStartVal', %(name)s) # Save exp start value\n") buff.writeIndentedLines(code % self.params) def writeFrameCode(self, buff): """Write the code that will be called at the start of the frame.""" if not self.params['startFrameValue'] == '': # Create dict for hold start and end types and converting them from types to variables timeTypeDict = {'time (s)': 't', 'frame N': 'frameN', 'condition': self.params['startVal'].val, 'duration (s)': 't','duration (frames)': 'frameN'} # Useful values for string creation startType = timeTypeDict[self.params['startType'].val] endType = timeTypeDict[self.params['stopType'].val] code = '' # Create default string frameCode = ("%(name)s = %(startFrameValue)s # Set frame start values for %(name)s\n" % self.params) if not self.params['saveFrameValue'] == 'Never': frameCode += ("%(name)sContainer.append(%(name)s) # Save frame values\n" % self.params) # Check for start or end values, and commence conditional timing string creation if self.params['startVal'].val or self.params['stopVal'].val: if self.params['startType'].val == 'time (s)': # if startVal is an empty string then set to be 0.0 if (isinstance(self.params['startVal'].val, str) and not self.params['startVal'].val.strip()): self.params['startVal'].val = '0.0' # Begin string construction for start values if startType == 't': code = (('if ' + startType + ' >= %(startVal)s') % self.params) elif startType == 'frameN': code = (('if ' + startType + ' >= %(startVal)s') % self.params) elif self.params['startType'].val == 'condition': code = ('if bool(%(startVal)s)' % self.params) # Begin string construction for end values if not self.params['stopVal'].val: code += (':\n' % self.params) # Duration types must be calculated elif u'duration' in self.params['stopType'].val: if 'frame' in self.params['startType'].val and 'frame' in self.params['stopType'].val \ or '(s)' in self.params['startType'].val and '(s)' in self.params['stopType'].val: endTime = str((float(self.params['startVal'].val) + float(self.params['stopVal'].val))) else: # do not add mismatching value types endTime = self.params['stopVal'].val code += (' and ' + endType + ' <= ' + endTime + ':\n' % (self.params)) elif endType == 't' : code += (' and ' + endType + ' <= %(stopVal)s:\n' % (self.params)) elif endType == 'frameN' : code += (' and ' + endType + ' <= %(stopVal)s:\n' % (self.params)) elif self.params['stopType'].val == 'condition': code += (' and bool(%(stopVal)s):\n' % self.params) code += ''.join([' ' + lines + '\n' for lines in frameCode.splitlines()]) else: code = frameCode buff.writeIndentedLines(code) def writeRoutineEndCode(self, buff): """Write the code that will be called at the end of the Routine.""" code = '' if self.params['saveStartExp'] == True and not self.params['startExpValue'] == '': code = ("thisExp.addData('%(name)s.expStartVal', %(startExpValue)s) # Save exp start value\n") if self.params['saveEndRoutine'] == True and not self.params['startRoutineValue'] == '': code += ("thisExp.addData('%(name)s.routineEndVal', %(name)s) # Save end Routine value\n") if not self.params['startFrameValue'] == '': if self.params['saveFrameValue'] == 'last': code += ("thisExp.addData('%(name)s.frameEndVal', %(name)sContainer[-1]) # Save end frame value\n") elif self.params['saveFrameValue'] == 'first': code += ("thisExp.addData('%(name)s.frameStartVal', %(name)sContainer[0]) # Save start frame value\n") elif self.params['saveFrameValue'] == 'all': code += ("thisExp.addData('%(name)s.allFrameVal', %(name)sContainer) # Save all frame value\n") buff.writeIndentedLines(code % self.params) def writeExperimentEndCode(self, buff): """Write the code that will be called at the end of the experiment.""" code='' writeData = [] # For saveEndExp, check whether any values were initiated. for vals in ['startExpValue', 'startRoutineValue', 'startFrameValue']: if not self.params[vals] == '': writeData.append(True) # Write values to file if requested, and if any variables defined if self.params['saveEndExp'] == True and np.any(writeData): code = ("thisExp.addData('%(name)s.endExpVal', %(name)s) # Save end experiment value\n") buff.writeIndentedLines(code % self.params)
9,829
Python
.py
169
45.798817
123
0.576257
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,623
__init__.py
psychopy_psychopy/psychopy/experiment/components/static/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Part of the PsychoPy library Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. Distributed under the terms of the GNU General Public License (GPL). """ from pathlib import Path from psychopy.experiment.components import BaseComponent, Param, _translate __author__ = 'Jon Peirce' class StaticComponent(BaseComponent): """A Static Component, allowing frame rendering to pause. E.g., pause while disk is accessed for loading an image """ # override the categories property below # an attribute of the class, determines the section in the components panel categories = ['Custom'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'static.png' tooltip = _translate('Static: Static screen period (e.g. an ISI). ' 'Useful for pre-loading stimuli.') def __init__( self, exp, parentName, # basic name='ISI', startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=0.5, startEstim='', durationEstim='', # custom code="", # data saveData=False ): BaseComponent.__init__( self, exp, parentName, name=name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim ) self.updatesList = [] # a list of dicts {compParams, fieldName} self.type = 'Static' self.url = "https://www.psychopy.org/builder/components/static.html" # --- Custom params --- self.order += [ "code", "saveData", ] self.params['code'] = Param( code, valType='code', inputType="multi", categ='Custom', label=_translate("Custom code"), hint=_translate( "Custom code to be run during the static period (after updates)" ) ) self.params['saveData'] = Param( saveData, valType="code", inputType="bool", categ="Custom", label=_translate("Save data during"), hint=_translate( "While the frame loop is paused, should we take the opportunity to save data now? " "This is only relevant locally, online data saving is either periodic or on close." ) ) def addComponentUpdate(self, routine, compName, fieldName): self.updatesList.append({'compName': compName, 'fieldName': fieldName, 'routine': routine}) def remComponentUpdate(self, routine, compName, fieldName): # have to do this in a loop rather than a simple remove target = {'compName': compName, 'fieldName': fieldName, 'routine': routine} for item in self.updatesList: # check if dict has the same fields for key in ('compName', 'fieldName', 'routine'): if item[key] != target[key]: break else: self.updatesList.remove(item) # NB - should we break out of it here if an item is found? def writeInitCode(self, buff): code = ("%(name)s = clock.StaticPeriod(win=win, " "screenHz=expInfo['frameRate'], name='%(name)s')\n") buff.writeIndented(code % self.params) def writeInitCodeJS(self, buff): code = ( "%(name)s = new core.MinimalStim({\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(+1, relative=True) code = ( "name: \"%(name)s\", \n" "win: psychoJS.window,\n" "autoDraw: false, \n" "autoLog: true, \n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ( "});\n" ) buff.writeIndented(code % self.params) def writeFrameCode(self, buff): if self.writeStartTestCode(buff): buff.setIndentLevel(-1, relative=True) self.writeStopTestCode(buff) def writeFrameCodeJS(self, buff): # Start test indent = self.writeStartTestCodeJS(buff) if indent: buff.writeIndentedLines("%(name)s.status = PsychoJS.Status.STARTED;\n" % self.params) self.writeParamUpdates(buff, target="PsychoJS") buff.setIndentLevel(-indent, relative=True) buff.writeIndentedLines("}") # Stop test, with stop actions indent = self.writeStopTestCodeJS(buff) if indent: for update in self.updatesList: # Get params for update compName = update['compName'] fieldName = update['fieldName'] # routine = self.exp.routines[update['routine']] if hasattr(compName, 'params'): prms = compName.params # it's already a compon so get params else: # it's a name so get compon and then get params prms = self.exp.getComponentFromName(str(compName)).params if prms[fieldName].valType == "file": # Check resource manager status code = ( f"if (psychoJS.serverManager.getResourceStatus({prms[fieldName]}) === core.ServerManager.ResourceStatus.DOWNLOADED) {{\n" ) buff.writeIndentedLines(code % self.params) # Print confirmation buff.setIndentLevel(+1, relative=True) code = ( "console.log('finished downloading resources specified by component %(name)s');\n" ) buff.writeIndentedLines(code % self.params) # else... buff.setIndentLevel(-1, relative=True) code = ( "} else {\n" ) buff.writeIndentedLines(code % self.params) # Print warning if not downloaded buff.setIndentLevel(+1, relative=True) code = ( f"console.log('resource specified in %(name)s took longer than expected to download');\n" f"await waitForResources(resources = {prms[fieldName]})" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("}\n") buff.writeIndentedLines("%(name)s.status = PsychoJS.Status.FINISHED;\n" % self.params) # Escape stop code indent buff.setIndentLevel(-indent, relative=True) buff.writeIndentedLines("}\n") def writeStartTestCode(self, buff): """This will be executed as the final component in the routine """ buff.writeIndented("# *%s* period\n" % (self.params['name'])) needsUnindent = BaseComponent.writeStartTestCode(self, buff) if needsUnindent: if self.params['stopType'].val == 'time (s)': durationSecsStr = "%(stopVal)s-t" % (self.params) elif self.params['stopType'].val == 'duration (s)': durationSecsStr = "%(stopVal)s" % (self.params) elif self.params['stopType'].val == 'duration (frames)': durationSecsStr = "%(stopVal)s*frameDur" % (self.params) elif self.params['stopType'].val == 'frame N': durationSecsStr = "(%(stopVal)s-frameN)*frameDur" % (self.params) else: msg = ("Couldn't deduce end point for startType=%(startType)s, " "stopType=%(stopType)s") raise Exception(msg % self.params) # save data if self.params['saveData']: code = ( "# take the opportunity to save data file now (to be updated later)\n" "_%(name)sLastFileNames = thisExp.save()\n" "thisExp.queueNextCollision('overwrite', fileName=_%(name)sLastFileNames)\n" ) buff.writeIndentedLines(code % self.params) # start static code = ( "# start the static period\n" "%(name)s.start({})\n" ).format(durationSecsStr) buff.writeIndentedLines(code % self.params) return needsUnindent def writeStopTestCode(self, buff): """Test whether we need to stop """ code = ("elif %(name)s.status == STARTED: # one frame should " "pass before updating params and completing\n") buff.writeIndented(code % self.params) buff.setIndentLevel(+1, relative=True) # entered an if statement self.writeParamUpdates(buff) code = "%(name)s.complete() # finish the static period\n" buff.writeIndented(code % self.params) # Calculate stop time if self.params['stopType'].val == 'time (s)': code = "%(name)s.tStop = %(stopVal)s # record stop time\n" elif self.params['stopType'].val == 'duration (s)': code = "%(name)s.tStop = %(name)s.tStart + %(stopVal)s # record stop time\n" elif self.params['stopType'].val == 'duration (frames)': code = "%(name)s.tStop = %(name)s.tStart + %(stopVal)s*frameDur # record stop time\n" elif self.params['stopType'].val == 'frame N': code = "%(name)s.tStop = %(stopVal)s*frameDur # record stop time\n" else: msg = ("Couldn't deduce end point for startType=%(startType)s, " "stopType=%(stopType)s") raise Exception(msg % self.params) # Store stop time buff.writeIndented(code % self.params) # to get out of the if statement buff.setIndentLevel(-1, relative=True) # pass # the clock.StaticPeriod class handles its own stopping def writeParamUpdates(self, buff, updateType=None, paramNames=None, target="PsychoPy"): """Write updates. Unlike most components, which us this method to update themselves, the Static Component uses this to update *other* components """ if updateType == 'set every repeat': return # the static component doesn't need to change itself if len(self.updatesList): # Comment to mark start of updates if target == "PsychoJS": code = "// Updating other components during *%s*\n" else: code = "# Updating other components during *%s*\n" buff.writeIndented(code % self.params['name']) # Do updates for update in self.updatesList: compName = update['compName'] fieldName = update['fieldName'] # get component if hasattr(compName, 'params'): comp = compName else: comp = self.exp.getComponentFromName(str(compName)) # component may be disabled or otherwise not present - skip it if so if comp is None: return # get params prms = comp.params # it's already a compon so get params # If in JS, prepare resources if target == "PsychoJS" and prms[fieldName].valType == "file": # Do resource manager stuff code = ( f"console.log('register and start downloading resources specified by component %(name)s');\n" f"await psychoJS.serverManager.prepareResources(%({fieldName})s);\n" f"{self.params['name']}.status = PsychoJS.Status.STARTED;\n" ) buff.writeIndentedLines(code % prms) # Set values self.writeParamUpdate(buff, compName=compName, paramName=fieldName, val=prms[fieldName], updateType=prms[fieldName].updates, params=prms, target=target) # Comment to mark end of updates if target == "PsychoJS": code = "// Component updates done\n" else: code = "# Component updates done\n" buff.writeIndentedLines(code) # Write custom code if self.params['code']: # Comment to mark start of custom code if target == "PsychoJS": code = "// Adding custom code for %(name)s\n" else: code = "# Adding custom code for %(name)s\n" buff.writeIndentedLines(code % self.params) # Write custom code code = "%(code)s\n" buff.writeIndentedLines(code % self.params)
13,263
Python
.py
277
33.938628
145
0.548136
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,624
__init__.py
psychopy_psychopy/psychopy/experiment/components/button/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from os import path from pathlib import Path from psychopy.alerts import alerttools from psychopy.experiment.components import BaseVisualComponent, Param, getInitVals, _translate from psychopy.experiment.py2js_transpiler import translatePythonToJavaScript class ButtonComponent(BaseVisualComponent): """ This component allows you to show a static textbox which ends the routine and/or triggers a "callback" (some custom code) when pressed. The nice thing about the button component is that you can allow mouse/touch responses with a single component instead of needing 3 separate components i.e. a textbox component (to display as a "clickable" thing), a mouse component (to click the textbox) and a code component (not essential, but for example to check if a clicked response was correct or incorrect). """ categories = ['Responses'] targets = ['PsychoPy', 'PsychoJS'] version = "2021.1.0" iconFile = Path(__file__).parent / 'button.png' tooltip = _translate('Button: A clickable textbox') beta = True def __init__(self, exp, parentName, name="button", startType='time (s)', startVal=0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim='', text=_translate("Click here"), font='Arvo', pos=(0, 0), size=(0.5, 0.5), padding="", anchor='center', units='from exp settings', ori=0, color="white", fillColor="darkgrey", borderColor="None", borderWidth=0, colorSpace='rgb', opacity="", letterHeight=0.05, bold=True, italic=False, callback="", save='every click', timeRelativeTo='button onset', forceEndRoutine=True, oncePerClick=True): super(ButtonComponent, self).__init__(exp, parentName, name, units=units, color=color, fillColor=fillColor, borderColor=borderColor, colorSpace=colorSpace, pos=pos, ori=ori, size=size, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Button' self.url = "https://www.psychopy.org/builder/components/button.html" self.order += [ # controls order of params within tabs "forceEndRoutine", "text", "callback", "oncePerClick", # Basic tab "borderWidth", "opacity", # Appearance tab "font", "letterHeight", "lineSpacing", "bold", "italic", # Formatting tab ] # params _allow3 = ['constant', 'set every repeat', 'set every frame'] # list self.params['color'].label = _translate("Text color") self.params['forceEndRoutine'] = Param( forceEndRoutine, valType='bool', inputType="bool", categ='Basic', updates='constant', direct=False, hint=_translate("Should a response force the end of the Routine " "(e.g end the trial)?"), label=_translate("Force end of Routine")) # If force end routine, then once per click doesn't make sense self.depends += [ { "dependsOn": "forceEndRoutine", "condition": "==True", "param": "oncePerClick", "true": "disable", # what to do with param if condition is True "false": "enable", # permitted: hide, show, enable, disable } ] self.params['oncePerClick'] = Param( oncePerClick, valType='bool', inputType="bool", allowedTypes=[], categ='Basic', updates='constant', hint=_translate("Should the callback run once per click (True), or each frame until click is released (False)"), label=_translate("Run once per click") ) self.params['callback'] = Param( callback, valType='extendedCode', inputType="multi", allowedTypes=[], categ='Basic', updates='constant', hint=_translate("Code to run when button is clicked"), label=_translate("Callback function")) self.params['text'] = Param( text, valType='str', inputType="single", allowedTypes=[], categ='Basic', updates='constant', allowedUpdates=_allow3[:], # copy the list hint=_translate("The text to be displayed"), label=_translate("Button text")) self.params['font'] = Param( font, valType='str', inputType="single", allowedTypes=[], categ='Formatting', updates='constant', allowedUpdates=_allow3[:], # copy the list hint=_translate("The font name (e.g. Comic Sans)"), label=_translate("Font")) self.params['letterHeight'] = Param( letterHeight, valType='num', inputType="single", allowedTypes=[], categ='Formatting', updates='constant', allowedUpdates=_allow3[:], # copy the list hint=_translate("Specifies the height of the letter (the width" " is then determined by the font)"), label=_translate("Letter height")) self.params['italic'] = Param( italic, valType='bool', inputType="bool", allowedTypes=[], categ='Formatting', updates='constant', hint=_translate("Should text be italic?"), label=_translate("Italic")) self.params['bold'] = Param( bold, valType='bool', inputType="bool", allowedTypes=[], categ='Formatting', updates='constant', hint=_translate("Should text be bold?"), label=_translate("Bold")) self.params['padding'] = Param( padding, valType='num', inputType="single", allowedTypes=[], categ='Layout', updates='constant', allowedUpdates=_allow3[:], hint=_translate("Defines the space between text and the textbox border"), label=_translate("Padding")) self.params['anchor'] = Param( anchor, valType='str', inputType="choice", categ='Layout', allowedVals=['center', 'top-center', 'bottom-center', 'center-left', 'center-right', 'top-left', 'top-right', 'bottom-left', 'bottom-right', ], updates='constant', hint=_translate("Should text anchor to the top, center or bottom of the box?"), label=_translate("Anchor")) self.params['borderWidth'] = Param( borderWidth, valType='num', inputType="single", allowedTypes=[], categ='Appearance', updates='constant', allowedUpdates=_allow3[:], hint=_translate("Textbox border width"), label=_translate("Border width")) self.params['save'] = Param( save, valType='str', inputType="choice", categ='Data', allowedVals=['first click', 'last click', 'every click', 'none'], hint=_translate( "What clicks on this button should be saved to the data output?"), direct=False, label=_translate("Record clicks")) self.params['timeRelativeTo'] = Param( timeRelativeTo, valType='str', inputType="choice", categ='Data', allowedVals=['button onset', 'experiment', 'routine'], updates='constant', direct=False, hint=_translate( "What should the values of mouse.time should be " "relative to?"), label=_translate("Time relative to")) def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s," % self.params # do writing of init inits = getInitVals(self.params, 'PsychoPy') inits['depth'] = -self.getPosInRoutine() code = ( "%(name)s = visual.ButtonStim(win, \n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "text=%(text)s, font=%(font)s,\n" "pos=%(pos)s," + unitsStr + "\n" "letterHeight=%(letterHeight)s,\n" "size=%(size)s, \n" "ori=%(ori)s\n," "borderWidth=%(borderWidth)s,\n" "fillColor=%(fillColor)s, borderColor=%(borderColor)s,\n" "color=%(color)s, colorSpace=%(colorSpace)s,\n" "opacity=%(opacity)s,\n" "bold=%(bold)s, italic=%(italic)s,\n" "padding=%(padding)s,\n" "anchor=%(anchor)s,\n" "name='%(name)s',\n" "depth=%(depth)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( ")\n" "%(name)s.buttonClock = core.Clock()" ) buff.writeIndentedLines(code % inits) def writeInitCodeJS(self, buff): inits = getInitVals(self.params, 'PsychoJS') inits['depth'] = -self.getPosInRoutine() code = ( "%(name)s = new visual.ButtonStim({\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "win: psychoJS.window,\n" "name: '%(name)s',\n" "text: %(text)s,\n" "fillColor: %(fillColor)s,\n" "borderColor: %(borderColor)s,\n" "color: %(color)s,\n" "colorSpace: %(colorSpace)s,\n" "pos: %(pos)s,\n" "letterHeight: %(letterHeight)s,\n" "size: %(size)s,\n" "ori: %(ori)s\n,\n" "depth: %(depth)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "});\n" "%(name)s.clock = new util.Clock();\n\n" ) buff.writeIndentedLines(code % inits) def writeRoutineStartCode(self, buff): # Write base code BaseVisualComponent.writeRoutineStartCode(self, buff) # If mouse is on button and already clicked, mark as `wasClicked` so button knows click is not new code = ( "# reset %(name)s to account for continued clicks & clear times on/off\n" "%(name)s.reset()\n" ) buff.writeIndentedLines(code % self.params) def writeRoutineStartCodeJS(self, buff): # Write base code BaseVisualComponent.writeRoutineStartCodeJS(self, buff) # If mouse is on button and already clicked, mark as `wasClicked` so button knows click is not new code = ( "// reset %(name)s to account for continued clicks & clear times on/off\n" "%(name)s.reset()\n" ) buff.writeIndentedLines(code % self.params) def writeFrameCode(self, buff): # Get callback from params if self.params['callback'].val: callback = str(self.params['callback'].val) else: callback = "pass" # String to get time if self.params['timeRelativeTo'] == 'button onset': timing = "%(name)s.buttonClock.getTime()" elif self.params['timeRelativeTo'] == 'experiment': timing = "globalClock.getTime()" elif self.params['timeRelativeTo'] == 'routine': timing = "routineTimer.getTime()" else: timing = "globalClock.getTime()" # Write comment code = ( "# *%(name)s* updates\n" ) buff.writeIndentedLines(code % self.params) # Start code indented = self.writeStartTestCode(buff) if indented: code = ( "win.callOnFlip(%(name)s.buttonClock.reset)\n" "%(name)s.setAutoDraw(True)\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-indented, relative=True) # Active code indented = self.writeActiveTestCode(buff) if indented: code = ( f"# check whether %(name)s has been pressed\n" f"if %(name)s.isClicked:\n" ) buff.writeIndentedLines(code % self.params) # If clicked... buff.setIndentLevel(1, relative=True) code = ( f"if not %(name)s.wasClicked:\n" f" # if this is a new click, store time of first click and clicked until\n" f" %(name)s.timesOn.append({timing})\n" f" %(name)s.timesOff.append({timing})\n" f"elif len(%(name)s.timesOff):\n" f" # if click is continuing from last frame, update time of clicked until\n" f" %(name)s.timesOff[-1] = {timing}\n" ) buff.writeIndentedLines(code % self.params) # Handle force end routine if self.params['forceEndRoutine']: code = ( f"if not %(name)s.wasClicked:\n" f" # end routine when %(name)s is clicked\n" f" continueRoutine = False\n" ) buff.writeIndentedLines(code % self.params) # Callback code if self.params['oncePerClick']: code = ( f"if not %(name)s.wasClicked:\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(1, relative=True) code = ( f"# run callback code when %(name)s is clicked\n" ) buff.writeIndentedLines(code % self.params) buff.writeIndentedLines(callback % self.params) if self.params['oncePerClick']: buff.setIndentLevel(-1, relative=True) buff.setIndentLevel(-1, relative=True) buff.setIndentLevel(-indented, relative=True) # Update wasClicked code = ( f"# take note of whether %(name)s was clicked, so that next frame we know if clicks are new\n" f"%(name)s.wasClicked = %(name)s.isClicked and %(name)s.status == STARTED\n" ) buff.writeIndentedLines(code % self.params) # Stop code indented = self.writeStopTestCode(buff) if indented: code = ( "%(name)s.setAutoDraw(False)\n" ) buff.writeIndentedLines(code % self.params) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) def writeFrameCodeJS(self, buff): BaseVisualComponent.writeFrameCodeJS(self, buff) # do writing of init inits = getInitVals(self.params, 'PsychoJS') # Get callback from params callback = inits['callback'] if inits['callback'].val not in [None, "None", "none", "undefined"]: callback = translatePythonToJavaScript(str(callback)) else: callback = "" # Check for current and last button press code = ( "if (%(name)s.status === PsychoJS.Status.STARTED) {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "// check whether %(name)s has been pressed\n" "if (%(name)s.isClicked) {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "if (!%(name)s.wasClicked) {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "// store time of first click\n" "%(name)s.timesOn.push(%(name)s.clock.getTime());\n" "// store time clicked until\n" "%(name)s.timesOff.push(%(name)s.clock.getTime());\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "} else {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "// update time clicked until;\n" "%(name)s.timesOff[%(name)s.timesOff.length - 1] = %(name)s.clock.getTime();\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) if self.params['oncePerClick'] or self.params['forceEndRoutine']: code = ( "if (!%(name)s.wasClicked) {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) if self.params['forceEndRoutine']: code = ( "// end routine when %(name)s is clicked\n" "continueRoutine = false;\n" ) buff.writeIndentedLines(code % inits) if self.params['oncePerClick']: buff.writeIndentedLines(callback % inits) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) if not self.params['oncePerClick']: buff.writeIndentedLines(callback % inits) # Store current button press as last code = ( "// if %(name)s is still clicked next frame, it is not a new click\n" "%(name)s.wasClicked = true;\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "} else {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "// if %(name)s is clicked next frame, it is a new click\n" "%(name)s.wasClicked = false;\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "} else {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "// keep clock at 0 if %(name)s hasn't started / has finished\n" "%(name)s.clock.reset();\n" "// if %(name)s is clicked next frame, it is a new click\n" "%(name)s.wasClicked = false;\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code % inits) def writeRoutineEndCode(self, buff): BaseVisualComponent.writeRoutineEndCode(self, buff) if len(self.exp.flow._loopList): currLoop = self.exp.flow._loopList[-1] # last (outer-most) loop else: currLoop = self.exp._expHandler name = self.params['name'] if self.params['save'] == 'first click': index = "[0]" elif self.params['save'] == 'last click': index = "[-1]" else: index = "" if self.params['save'] != 'none': code = ( f"{currLoop.params['name']}.addData('{name}.numClicks', {name}.numClicks)\n" f"if {name}.numClicks:\n" f" {currLoop.params['name']}.addData('{name}.timesOn', {name}.timesOn{index})\n" f" {currLoop.params['name']}.addData('{name}.timesOff', {name}.timesOff{index})\n" f"else:\n" f" {currLoop.params['name']}.addData('{name}.timesOn', \"\")\n" f" {currLoop.params['name']}.addData('{name}.timesOff', \"\")\n" ) buff.writeIndentedLines(code) def writeRoutineEndCodeJS(self, buff): # Save data code = ( "psychoJS.experiment.addData('%(name)s.numClicks', %(name)s.numClicks);\n" "psychoJS.experiment.addData('%(name)s.timesOn', %(name)s.timesOn);\n" "psychoJS.experiment.addData('%(name)s.timesOff', %(name)s.timesOff);\n" ) buff.writeIndentedLines(code % self.params) def integrityCheck(self): super().integrityCheck() # run parent class checks first alerttools.testFont(self) # Test whether font is available locally
21,714
Python
.py
469
32.829424
124
0.536997
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,625
__init__.py
psychopy_psychopy/psychopy/experiment/components/sound/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Part of the PsychoPy library Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. Distributed under the terms of the GNU General Public License (GPL). """ from pathlib import Path from psychopy.experiment.components import BaseDeviceComponent, Param, getInitVals, \ _translate from psychopy.experiment.utils import canBeNumeric from psychopy.tools.audiotools import knownNoteNames class SoundComponent(BaseDeviceComponent): """An event class for presenting sound stimuli""" categories = ['Stimuli'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'sound.png' tooltip = _translate('Sound: play recorded files or generated sounds', ) deviceClasses = ["psychopy.hardware.speaker.SpeakerDevice"] def __init__(self, exp, parentName, # basic name='sound_1', sound='A', startType='time (s)', startVal='0.0', stopType='duration (s)', stopVal='1.0', startEstim='', durationEstim='', syncScreenRefresh=True, # device deviceLabel="", speakerIndex=-1, # playback volume=1, stopWithRoutine=True, forceEndRoutine=False): super(SoundComponent, self).__init__( exp, parentName, name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim, deviceLabel=deviceLabel ) self.type = 'Sound' self.url = "https://www.psychopy.org/builder/components/sound.html" self.exp.requirePsychopyLibs(['sound']) # --- Basic params --- self.order += [ "sound", "syncScreenRefresh", ] hnt = _translate("When does the Component end? (blank to use the " "duration of the media)") self.params['stopVal'].hint = hnt hnt = _translate("A sound can be a note name (e.g. A or Bf), a number" " to specify Hz (e.g. 440) or a filename") self.params['sound'] = Param( sound, valType='str', inputType="file", allowedTypes=[], updates='constant', categ='Basic', allowedUpdates=['set every repeat'], hint=hnt, label=_translate("Sound")) _allowed = ['constant', 'set every repeat', 'set every frame'] msg = _translate( "A reaction time to a sound stimulus should be based on when " "the screen flipped") self.params['syncScreenRefresh'] = Param( syncScreenRefresh, valType='bool', inputType="bool", categ='Basic', updates='constant', hint=msg, label=_translate("Sync start with screen")) # --- Playback params --- self.order += [ "volume", "hamming", "stopWithRoutine", "forceEndRoutine", ] self.params['volume'] = Param( volume, valType='num', inputType="single", allowedTypes=[], updates='constant', categ='Playback', allowedUpdates=_allowed[:], # use a copy hint=_translate("The volume (in range 0 to 1)"), label=_translate("Volume") ) self.params['hamming'] = Param( True, valType='bool', inputType="bool", updates='constant', categ='Playback', hint=_translate( "For tones we can apply a hamming window to prevent 'clicks' that " "are caused by a sudden onset. This delays onset by roughly 1ms."), label=_translate("Hamming window")) self.params['stopWithRoutine'] = Param( stopWithRoutine, valType='bool', inputType="bool", updates='constant', categ='Playback', hint=_translate( "Should playback cease when the Routine ends? Untick to continue playing " "after the Routine has finished."), label=_translate('Stop with Routine?')) self.params['forceEndRoutine'] = Param( forceEndRoutine, valType="bool", inputType="bool", updates="constant", categ="Playback", hint=_translate( "Should the end of the sound cause the end of the Routine (e.g. trial)?" ), label=_translate("Force end of Routine")) # --- Device params --- self.order += [ "speakerIndex" ] def getSpeakerLabels(): from psychopy.hardware.speaker import SpeakerDevice labels = [_translate("Default")] for profile in SpeakerDevice.getAvailableDevices(): labels.append(profile['deviceName']) return labels def getSpeakerValues(): from psychopy.hardware.speaker import SpeakerDevice vals = [-1] for profile in SpeakerDevice.getAvailableDevices(): vals.append(profile['index']) return vals self.params['speakerIndex'] = Param( speakerIndex, valType="str", inputType="choice", categ="Device", allowedVals=getSpeakerValues, allowedLabels=getSpeakerLabels, hint=_translate( "What speaker to play this sound on" ), label=_translate("Speaker")) def writeDeviceCode(self, buff): inits = getInitVals(self.params) # initialise speaker code = ( "# create speaker %(deviceLabel)s\n" "deviceManager.addDevice(\n" " deviceName=%(deviceLabel)s,\n" " deviceClass='psychopy.hardware.speaker.SpeakerDevice',\n" " index=%(speakerIndex)s\n" ")\n" ) buff.writeOnceIndentedLines(code % inits) def writeInitCode(self, buff): # replaces variable params with sensible defaults inits = getInitVals(self.params) if not canBeNumeric(inits['stopVal'].val): inits['stopVal'].val = -1 else: if inits['stopVal'].val in ['', None, 'None']: inits['stopVal'].val = -1 elif float(inits['stopVal'].val) > 2: inits['stopVal'].val = -1 # are we forcing stereo? inits['forceStereo'] = self.exp.settings.params['Force stereo'] # write init code code = ( "%(name)s = sound.Sound(\n" " %(sound)s, \n" " secs=%(stopVal)s, \n" " stereo=%(forceStereo)s, \n" " hamming=%(hamming)s, \n" " speaker=%(deviceLabel)s," " name='%(name)s'\n" ")\n" ) buff.writeIndentedLines(code % inits) buff.writeIndented("%(name)s.setVolume(%(volume)s)\n" % inits) def writeRoutineStartCode(self, buff): if self.params['stopVal'].val in [None, 'None', '']: buff.writeIndentedLines("%(name)s.setSound(%(sound)s, hamming=%(hamming)s)\n" "%(name)s.setVolume(%(volume)s, log=False)\n" % self.params) else: buff.writeIndentedLines("%(name)s.setSound(%(sound)s, secs=%(stopVal)s, hamming=%(hamming)s)\n" "%(name)s.setVolume(%(volume)s, log=False)\n" % self.params) code = ( "%(name)s.seek(0)\n" ) buff.writeIndentedLines(code % self.params) def writeInitCodeJS(self, buff): # replaces variable params with sensible defaults inits = getInitVals(self.params) if not canBeNumeric(inits['stopVal'].val): inits['stopVal'].val = -1 elif inits['stopVal'].val in ['', None, 'None']: inits['stopVal'].val = -1 elif float(inits['stopVal'].val) > 2: inits['stopVal'].val = -1 buff.writeIndented("%s = new sound.Sound({\n" " win: psychoJS.window,\n" " value: %s,\n" " secs: %s,\n" " });\n" % (inits['name'], inits['sound'], inits['stopVal'])) buff.writeIndented("%(name)s.setVolume(%(volume)s);\n" % (inits)) # until isFinished and isPlaying are added in JS, we can immitate them here code = ( "%(name)s.isPlaying = false;\n" "%(name)s.isFinished = false;\n" ) buff.writeIndentedLines(code % self.params) def writeRoutineStartCodeJS(self, buff): stopVal = self.params['stopVal'] if stopVal in ['', None, 'None']: stopVal = -1 if self.params['sound'].updates == 'set every repeat': buff.writeIndented("%(name)s.setValue(%(sound)s);\n" % self.params) if stopVal == -1: buff.writeIndentedLines("%(name)s.setVolume(%(volume)s);\n" % self.params) else: buff.writeIndentedLines("%(name)s.secs=%(stopVal)s;\n" "%(name)s.setVolume(%(volume)s);\n" % self.params) def writeFrameCode(self, buff): """Write the code that will be called every frame """ # Write start code to update parameters. Unlike BaseVisualComponents, which # inserts writeActiveTestCode() after the start code, we need to insert it # here before the start code to provide the correct parameters for calling # the play() method. buff.writeIndented("\n") buff.writeIndented(f"# *{self.params['name']}* updates\n") self.writeParamUpdates(buff, 'set every frame') # write code for starting indented = self.writeStartTestCode(buff) if indented: if self.params['syncScreenRefresh'].val: code = ("%(name)s.play(when=win) # sync with win flip\n") else: code = "%(name)s.play() # start the sound (it finishes automatically)\n" buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-indented, relative=True) # write code for stopping indented = self.writeStopTestCode(buff, extra=" or %(name)s.isFinished") if indented: # stop playback code = ( "%(name)s.stop()\n" ) buff.writeIndentedLines(code % self.params) # force end of Routine if asked if self.params['forceEndRoutine']: code = ( "# %(name)s has finished playback, so force end Routine\n" "continueRoutine = False\n" ) buff.writeIndentedLines(code % self.params) # because of the 'if' statement of the time test buff.setIndentLevel(-indented, relative=True) def writeFrameCodeJS(self, buff): """Write the code that will be called every frame """ # until isFinished and isPlaying are added in JS, we can immitate them here code = ( "if (%(name)s.status === STARTED) {\n" " %(name)s.isPlaying = true;\n" " if (t >= (%(name)s.getDuration() + %(name)s.tStart)) {\n" " %(name)s.isFinished = true;\n" " }\n" "}\n" ) buff.writeIndentedLines(code % self.params) # the sound object is unusual, because it is controlling the playback stream buff.writeIndented("// start/stop %(name)s\n" % (self.params)) # do this EVERY frame, even before/after playing? self.writeParamUpdates(buff, 'set every frame', target="PsychoJS") self.writeStartTestCodeJS(buff) if self.params['syncScreenRefresh'].val: code = ("psychoJS.window.callOnFlip(function(){ %(name)s.play(); }); // screen flip\n") else: code = "%(name)s.play(); // start the sound (it finishes automatically)\n" code += "%(name)s.status = PsychoJS.Status.STARTED;\n" buff.writeIndentedLines(code % self.params) # because of the 'if' statement of the time test buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines('}\n') # are we stopping this frame? indented = self.writeStopTestCodeJS(buff, extra=" || %(name)s.isFinished") if indented: # stop playback code = ( "// stop playback\n" "%(name)s.stop();\n" ) buff.writeIndentedLines(code % self.params) # end Routine if asked if self.params['forceEndRoutine']: code = ( "// %(name)s has finished playback, so force end Routine\n" "continueRoutine = false;\n" ) buff.writeIndentedLines(code % self.params) # exit if statement(s) for n in range(indented): buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("}\n") def writeRoutineEndCode(self, buff): if self.params['stopWithRoutine']: # stop at the end of the Routine, if requested code = ( "%(name)s.pause() # ensure sound has stopped at end of Routine\n" ) buff.writeIndentedLines(code % self.params) # get parent to write code too (e.g. store onset/offset times) super().writeRoutineEndCode(buff) # noinspection def writeRoutineEndCodeJS(self, buff): if self.params['stopWithRoutine']: # stop at the end of the Routine, if requested code = ( "%(name)s.stop(); // ensure sound has stopped at end of Routine\n" ) buff.writeIndentedLines(code % self.params) def writeParamUpdate( self, buff, compName, paramName, val, updateType, params=None, target="PsychoPy", ): """ Overload BaseComponent.writeParamUpdate to handle special case for SoundComponent """ # when writing param updates for Sound.sound, needs to be `setValue` in JS # (this is intended as a temporary patch - please delete when `setSound` in JS can accept # the same range of values as in Py) if target == 'PsychoJS' and paramName == "sound": # get logging string if updateType == 'set every frame' and target == 'PsychoJS': loggingStr = ', false' else: loggingStr = '' # write setValue code code = ( f"{compName}.setValue({val}{loggingStr});\n" ) buff.writeIndented(code) else: # do normal stuff for every other param BaseDeviceComponent.writeParamUpdate( self, buff, compName, paramName, val, updateType, params=params, target=target, )
15,307
Python
.py
344
32.241279
109
0.552334
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,626
__init__.py
psychopy_psychopy/psychopy/experiment/components/movie/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from pathlib import Path import copy from psychopy.experiment.components import BaseVisualComponent, getInitVals, Param, _translate class MovieComponent(BaseVisualComponent): """An event class for presenting movie-based stimuli""" categories = ['Stimuli'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'movie.png' tooltip = _translate('Movie: play movie files') def __init__(self, exp, parentName, name='movie', movie='', units='from exp settings', pos=(0, 0), size=(0.5, 0.5), anchor="center", ori=0, startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim='', forceEndRoutine=False, backend='ffpyplayer', loop=False, volume=1, noAudio=False, stopWithRoutine=True ): super(MovieComponent, self).__init__( exp, parentName, name=name, units=units, pos=pos, size=size, ori=ori, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Movie' self.url = "https://www.psychopy.org/builder/components/movie.html" # comes immediately after name and timing params self.order += ['movie', 'forceEndRoutine', # Basic tab 'loop', 'No audio', 'backend', ] # params self.params['stopVal'].hint = _translate( "When does the Component end? (blank to use the duration of " "the media)") msg = _translate("A filename for the movie (including path)") self.params['movie'] = Param( movie, valType='file', inputType="file", allowedTypes=[], categ='Basic', updates='constant', allowedUpdates=['constant', 'set every repeat'], hint=msg, label=_translate("Movie file")) msg = _translate("What underlying lib to use for loading movies") self.params['backend'] = Param( backend, valType='str', inputType="choice", categ='Playback', allowedVals=['ffpyplayer', 'moviepy', 'opencv', 'vlc'], hint=msg, direct=False, label=_translate("Backend")) msg = _translate("Prevent the audio stream from being loaded/processed " "(moviepy and opencv only)") self.params["No audio"] = Param( noAudio, valType='bool', inputType="bool", categ='Playback', hint=msg, label=_translate("No audio")) self.depends.append( {"dependsOn": "No audio", # must be param name "condition": "==True", # val to check for "param": "volume", # param property to alter "true": "hide", # what to do with param if condition is True "false": "show", # permitted: hide, show, enable, disable } ) msg = _translate("How loud should audio be played?") self.params["volume"] = Param( volume, valType='num', inputType="single", categ='Playback', hint=msg, label=_translate("Volume")) msg = _translate("Should the end of the movie cause the end of " "the Routine (e.g. trial)?") self.params['forceEndRoutine'] = Param( forceEndRoutine, valType='bool', inputType="bool", allowedTypes=[], categ='Basic', updates='constant', allowedUpdates=[], hint=msg, label=_translate("Force end of Routine")) msg = _translate("Whether the movie should loop back to the beginning " "on completion.") self.params['loop'] = Param( loop, valType='bool', inputType="bool", categ='Playback', hint=msg, label=_translate("Loop playback")) self.params['stopWithRoutine'] = Param( stopWithRoutine, valType='bool', inputType="bool", updates='constant', categ='Playback', hint=_translate( "Should playback cease when the Routine ends? Untick to continue playing " "after the Routine has finished."), label=_translate('Stop with Routine?')) self.params['anchor'] = Param( anchor, valType='str', inputType="choice", categ='Layout', allowedVals=['center', 'top-center', 'bottom-center', 'center-left', 'center-right', 'top-left', 'top-right', 'bottom-left', 'bottom-right', ], updates='constant', hint=_translate("Which point on the stimulus should be anchored to its exact position?"), label=_translate("Anchor")) # these are normally added but we don't want them for a movie del self.params['color'] del self.params['colorSpace'] del self.params['fillColor'] del self.params['borderColor'] def _writeCreationCode(self, buff, useInits): # This will be called by either self.writeInitCode() or # self.writeRoutineStartCode() # # The reason for this is that moviestim is actually created fresh each # time the movie is loaded. # # leave units blank if not needed if self.params['units'].val == 'from exp settings': unitsStr = "units=''" else: unitsStr = "units=%(units)s" % self.params # If we're in writeInitCode then we need to convert params to initVals # because some (variable) params haven't been created yet. if useInits: params = getInitVals(self.params) else: params = self.params if self.params['backend'].val == 'moviepy': code = ("%s = visual.MovieStim3(\n" % params['name'] + " win=win, name='%s', %s,\n" % ( params['name'], unitsStr) + " noAudio = %(No audio)s,\n" % params) elif self.params['backend'].val == 'avbin': code = ("%s = visual.MovieStim(\n" % params['name'] + " win=win, name='%s', %s,\n" % ( params['name'], unitsStr)) elif self.params['backend'].val == 'vlc': code = ("%s = visual.VlcMovieStim(\n" % params['name'] + " win=win, name='%s', %s,\n" % ( params['name'], unitsStr)) else: code = ("%s = visual.MovieStim2(\n" % params['name'] + " win=win, name='%s', %s,\n" % ( params['name'], unitsStr) + " noAudio=%(No audio)s,\n" % params) code += (" filename=%(movie)s,\n" " ori=%(ori)s, pos=%(pos)s, opacity=%(opacity)s,\n" " loop=%(loop)s, anchor=%(anchor)s,\n" % params) buff.writeIndentedLines(code) if self.params['size'].val != '': buff.writeIndented(" size=%(size)s,\n" % params) depth = -self.getPosInRoutine() code = (" depth=%.1f,\n" " )\n") buff.writeIndentedLines(code % depth) def _writeCreationCodeJS(self, buff, useInits): # If we're in writeInitCode then we need to convert params to initVals # because some (variable) params haven't been created yet. if useInits: inits = getInitVals(self.params) else: inits = copy.deepcopy(self.params) inits['depth'] = -self.getPosInRoutine() noAudio = '{}'.format(inits['No audio'].val).lower() loop = '{}'.format(inits['loop'].val).lower() for param in inits: if inits[param] in ['', None, 'None', 'none', 'from exp settings']: inits[param].val = 'undefined' inits[param].valType = 'code' code = "{name}Clock = new util.Clock();\n".format(**inits) buff.writeIndented(code) code = ("{name} = new visual.MovieStim({{\n" " win: psychoJS.window,\n" " name: '{name}',\n" " units: {units},\n" " movie: {movie},\n" " pos: {pos},\n" " anchor: {anchor},\n" " size: {size},\n" " ori: {ori},\n" " opacity: {opacity},\n" " loop: {loop},\n" " noAudio: {noAudio},\n" " depth: {depth}\n" " }});\n").format(name=inits['name'], movie=inits['movie'], units=inits['units'], pos=inits['pos'], anchor=inits['anchor'], size=inits['size'], ori=inits['ori'], loop=loop, opacity=inits['opacity'], noAudio=noAudio, depth=inits['depth']) buff.writeIndentedLines(code) def writeInitCode(self, buff): # Get init values params = getInitVals(self.params) params['depth'] = -self.getPosInRoutine() # synonymise "from experiment settings" with None if params["units"].val.lower() == "from exp settings": params["units"].valType = "code" params["units"].val = None # Handle old backends if self.params['backend'].val in ('moviepy', 'avbin', 'vlc', 'opencv'): if self.params['movie'].updates == 'constant': # create the code using init vals self._writeCreationCode(buff, useInits=True) return code = ( "%(name)s = visual.MovieStim(\n" ) buff.writeIndentedLines(code % params) buff.setIndentLevel(+1, relative=True) code = ( "win, name='%(name)s',\n" "filename=%(movie)s, movieLib=%(backend)s,\n" "loop=%(loop)s, volume=%(volume)s, noAudio=%(No audio)s,\n" "pos=%(pos)s, size=%(size)s, units=%(units)s,\n" "ori=%(ori)s, anchor=%(anchor)s," "opacity=%(opacity)s, contrast=%(contrast)s,\n" "depth=%(depth)s\n" ) buff.writeIndentedLines(code % params) buff.setIndentLevel(-1, relative=True) code = ( ")\n" ) buff.writeIndentedLines(code % params) def writeInitCodeJS(self, buff): # create the code using init vals self._writeCreationCodeJS(buff, useInits=True) def writeFrameCode(self, buff): """Write the code that will be called every frame """ buff.writeIndented("\n") buff.writeIndented("# *%s* updates\n" % self.params['name']) # set parameters that need updating every frame # do any params need updating? (this method inherited from _base) if self.checkNeedToUpdate('set every frame'): code = "if %(name)s.status == STARTED: # only update if being drawn\n" % self.params buff.writeIndented(code) buff.setIndentLevel(+1, relative=True) # to enter the if block self.writeParamUpdates(buff, 'set every frame') buff.setIndentLevel(-1, relative=True) # to exit the if block # writes an if statement to determine whether to draw etc indented = self.writeStartTestCode(buff) if indented: code = ( "%(name)s.setAutoDraw(True)\n" ) if self.params['backend'].val not in ('moviepy', 'avbin', 'vlc'): code += "%(name)s.play()\n" buff.writeIndentedLines(code % self.params) # because of the 'if' statement of the time test buff.setIndentLevel(-indented, relative=True) # write code for stopping indented = self.writeStopTestCode(buff, extra=" or %(name)s.isFinished") if indented: code = ( "%(name)s.setAutoDraw(False)\n" ) if self.params['backend'].val not in ('moviepy', 'avbin', 'vlc'): code += "%(name)s.stop()\n" buff.writeIndentedLines(code % self.params) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) # do force end of trial code if self.params['forceEndRoutine'].val is True: code = ("if %s.isFinished: # force-end the Routine\n" " continueRoutine = False\n" % self.params['name']) buff.writeIndentedLines(code) def writeFrameCodeJS(self, buff): """Write the code that will be called every frame """ buff.writeIndented("\n") buff.writeIndented("// *{name}* updates\n".format(**self.params)) # writes an if statement to determine whether to draw etc self.writeStartTestCodeJS(buff) buff.writeIndentedLines("{name}.setAutoDraw(true);\n".format(**self.params)) buff.writeIndentedLines("{name}.play();\n".format(**self.params)) # because of the 'if' statement of the time test buff.setIndentLevel(-1, relative=True) buff.writeIndented("}\n\n") if self.params['stopVal'].val not in ['', None, -1, 'None']: # writes an if statement to determine whether to draw etc self.writeStopTestCodeJS(buff) buff.writeIndentedLines("{name}.setAutoDraw(false);\n".format(**self.params)) # to get out of the if statement buff.setIndentLevel(-1, relative=True) buff.writeIndented("}\n\n") # set parameters that need updating every frame # do any params need updating? (this method inherited from _base) if self.checkNeedToUpdate('set every frame'): code = ("if ({name}.status === PsychoJS.Status.STARTED) {{" " // only update if being drawn\n").format(**self.params) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) # to enter the if block self.writeParamUpdatesJS(buff, 'set every frame') buff.setIndentLevel(-1, relative=True) # to exit the if block buff.writeIndentedLines("}\n") # do force end of trial code if self.params['forceEndRoutine'].val is True: code = ("if ({name}.status === PsychoJS.Status.FINISHED) {{ // force-end the Routine\n" " continueRoutine = false;\n" "}}\n".format(**self.params)) buff.writeIndentedLines(code) def writeRoutineEndCode(self, buff): if self.params['stopWithRoutine']: # stop at the end of the Routine, if requested code = ( "%(name)s.stop() # ensure movie has stopped at end of Routine\n" ) buff.writeIndentedLines(code % self.params) def writeRoutineEndCodeJS(self, buff): if self.params['stopWithRoutine']: # stop at the end of the Routine, if requested code = ( "%(name)s.stop(); // ensure movie has stopped at end of Routine\n" ) buff.writeIndentedLines(code % self.params)
15,891
Python
.py
325
35.756923
101
0.54259
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,627
__init__.py
psychopy_psychopy/psychopy/experiment/components/buttonBox/__init__.py
from pathlib import Path from psychopy.experiment.components import BaseComponent, BaseDeviceComponent, Param, getInitVals from psychopy.experiment.plugins import PluginDevicesMixin, DeviceBackend from psychopy.localization import _translate class ButtonBoxComponent(BaseDeviceComponent, PluginDevicesMixin): """ Component for getting button presses from a button box device. """ categories = ['Responses'] # which section(s) in the components panel targets = ['PsychoPy'] iconFile = Path(__file__).parent / 'buttonBox.png' tooltip = _translate('Button Box: Get input from a button box') beta = True def __init__( self, exp, parentName, # basic name='buttonBox', startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim='', forceEndRoutine=True, # device deviceLabel="", deviceBackend="keyboard", # data registerOn=True, store='first', allowedButtons="", storeCorrect=False, correctAns="", # testing disabled=False, ): # initialise base class BaseDeviceComponent.__init__( self, exp, parentName, name=name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim, deviceLabel=deviceLabel, disabled=disabled ) self.type = "ButtonBox" self.exp.requireImport( importName="ButtonBox", importFrom="psychopy.hardware.button" ) # --- Basic params --- self.order += [ "forceEndRoutine" ] self.params['forceEndRoutine'] = Param( forceEndRoutine, valType='bool', inputType="bool", categ='Basic', hint=_translate( "Should a response force the end of the Routine (e.g end the trial)?" ), label=_translate("Force end of Routine")) # --- Data params --- self.order += [ "registerOn", "store", "allowedButtons", "storeCorrect", "correctAns", ] self.params['registerOn'] = Param( registerOn, valType='code', inputType='choice', categ='Data', allowedVals=[True, False], allowedLabels=[_translate("Press"), _translate("Release")], hint=_translate( "When should the button press be registered? As soon as pressed, or when released?" ), label=_translate("Register button press on...") ) self.params['store'] = Param( store, valType='str', inputType="choice", categ='Data', allowedVals=['last', 'first', 'all', 'nothing'], allowedLabels=[_translate("Last button"), _translate("First button"), _translate( "All buttons"), _translate("Nothing")], updates='constant', direct=False, hint=_translate( "Choose which (if any) responses to store at the end of a trial" ), label=_translate("Store")) self.params['allowedButtons'] = Param( allowedButtons, valType='list', inputType="single", categ='Data', hint=_translate( "A comma-separated list of button indices (should be whole numbers), leave blank " "to listen for all buttons." ), label=_translate("Allowed buttons")) self.params['storeCorrect'] = Param( storeCorrect, valType='bool', inputType="bool", categ='Data', updates='constant', hint=_translate( "Do you want to save the response as correct/incorrect?" ), label=_translate("Store correct")) self.depends.append( { "dependsOn": "storeCorrect", # if... "condition": f"== True", # meets... "param": "correctAns", # then... "true": "show", # should... "false": "hide", # otherwise... } ) self.params['correctAns'] = Param( correctAns, valType='list', inputType="single", categ='Data', hint=_translate( "What is the 'correct' key? Might be helpful to add a correctAns column and use " "$correctAns to compare to the key press. " ), label=_translate("Correct answer"), direct=False) # --- Device params --- self.order += [ "deviceBackend", ] self.params['deviceBackend'] = Param( deviceBackend, valType="str", inputType="choice", categ="Device", allowedVals=self.getBackendKeys, allowedLabels=self.getBackendLabels, label=_translate("Device backend"), hint=_translate( "What kind of button box is it? What package/plugin should be used to talk to it?" ), direct=False ) # add params for any backends self.loadBackends() def writeInitCode(self, buff): inits = getInitVals(self.params) # code to create object code = ( "%(name)s = ButtonBox(\n" " device=%(deviceLabel)s\n" ")\n" ) buff.writeIndentedLines(code % inits) def writeRoutineStartCode(self, buff): # choose a clock to sync to according to component's params if "syncScreenRefresh" in self.params and self.params['syncScreenRefresh']: clockStr = "" else: clockStr = "clock=routineTimer" # sync component start/stop timers with validator clocks code = ( f"# synchronise device clock for %(name)s with Routine timer\n" f"%(name)s.resetTimer({clockStr})\n" ) buff.writeIndentedLines(code % self.params) # clear keys code = ( "# clear %(name)s button presses\n" "%(name)s.buttons = []\n" "%(name)s.times = []\n" "%(name)s.corr = []\n" ) buff.writeIndentedLines(code % self.params) def writeFrameCode(self, buff): params = self.params code = ( "\n" "# *%(name)s* updates\n" ) buff.writeIndentedLines(code % params) # writes an if statement to determine whether to draw etc indented = self.writeStartTestCode(buff) if indented: # dispatch and clear messages code = ( "# clear any messages from before starting\n" "%(name)s.responses = []\n" "%(name)s.clearResponses()\n" ) buff.writeIndentedLines(code % params) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) # test for started (will update parameters each frame as needed) indented = self.writeActiveTestCode(buff) if indented: # write code to get messages code = ( "# ask for messages from %(name)s device this frame\n" "for _thisResp in %(name)s.getResponses(\n" " state=%(registerOn)s, channel=%(allowedButtons)s, clear=True\n" "):\n" ) if self.params['store'] == "all": # if storing all, append code += ( " %(name)s.buttons.append(_thisResp.channel)\n" " %(name)s.times.append(_thisResp.t)\n" ) # include code to get correct if self.params['storeCorrect']: code += ( " if _thisResp.channel in %(correctAns)s or _thisResp.channel == %(correctAns)s:\n" " %(name)s.corr.append(1)\n" " else:\n" " %(name)s.corr.append(0)\n" ) elif self.params['store'] == "last": # if storing last, replace code += ( " %(name)s.buttons = _thisResp.channel\n" " %(name)s.times = _thisResp.t\n" ) # include code to get correct if self.params['storeCorrect']: code += ( " if _thisResp.channel in %(correctAns)s or _thisResp.channel == %(correctAns)s:\n" " %(name)s.corr = 1\n" " else:\n" " %(name)s.corr = 0\n" ) elif self.params['store'] == "first": # if storing first, replace but only if empty code += ( " if not %(name)s.buttons:\n" " %(name)s.buttons = _thisResp.channel\n" " %(name)s.times = _thisResp.t\n" ) # include code to get correct if self.params['storeCorrect']: code += ( " if _thisResp.channel in %(correctAns)s or _thisResp.channel == %(correctAns)s:\n" " %(name)s.corr = 1\n" " else:\n" " %(name)s.corr = 0\n" ) else: code = "pass\n" buff.writeIndentedLines(code % params) # code to end Routine if self.params['forceEndRoutine']: code = ( "# end Routine if %(name)s got valid response\n" "if %(name)s.buttons or %(name)s.buttons == 0:\n" " continueRoutine = False\n" ) buff.writeIndentedLines(code % params) # to get out of the if statement buff.setIndentLevel(-indented, relative=True) # test for stop (only if there was some setting for duration or stop) indented = self.writeStopTestCode(buff) if indented: # to get out of the if statement buff.setIndentLevel(-indented, relative=True) def writeRoutineEndCode(self, buff): BaseComponent.writeRoutineEndCode(self, buff) params = self.params # write code to save responses code = ( "# store data from %(name)s\n" "thisExp.addData('%(name)s.buttons', %(name)s.buttons)\n" "thisExp.addData('%(name)s.times', %(name)s.times)\n" "thisExp.addData('%(name)s.corr', %(name)s.corr)\n" ) buff.writeIndentedLines(code % params) class KeyboardButtonBoxBackend(DeviceBackend): """ Adds a basic keyboard emulation backend for ButtonBoxComponent, as well as acting as an example for implementing other ButtonBoxBackends. """ key = "keyboard" label = _translate("Keyboard") component = ButtonBoxComponent deviceClasses = ['psychopy.hardware.button.KeyboardButtonBox'] def getParams(self: ButtonBoxComponent): # define order order = [ "kbButtonAliases", ] # define params params = {} params['kbButtonAliases'] = Param( "'q', 'w', 'e'", valType="list", inputType="single", categ="Device", label=_translate("Buttons"), hint=_translate( "Keys to treat as buttons (in order of what button index you want them to be). " "Must be the same length as the number of buttons." ) ) return params, order def addRequirements(self): # no requirements needed - so just return return def writeDeviceCode(self: ButtonBoxComponent, buff): # get inits inits = getInitVals(self.params) # make ButtonGroup object code = ( "deviceManager.addDevice(\n" " deviceClass='psychopy.hardware.button.KeyboardButtonBox',\n" " deviceName=%(deviceLabel)s,\n" " buttons=%(kbButtonAliases)s,\n" ")\n" ) buff.writeOnceIndentedLines(code % inits)
12,382
Python
.py
301
28.903654
106
0.531956
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,628
__init__.py
psychopy_psychopy/psychopy/experiment/components/unknownPlugin/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path from psychopy.experiment.components import BaseComponent, Param, _translate class UnknownPluginComponent(BaseComponent): """This is used by Builder to represent a component that was not known by the current installed version of PsychoPy (most likely from the future). We want this to be loaded, represented and saved but not used in any script-outputs. It should have nothing but a name - other params will be added by the loader """ targets = ['PsychoPy'] categories = ['Other'] targets = ['PsychoPy'] iconFile = Path(__file__).parent / 'unknownPlugin.png' tooltip = _translate('Unknown: A component which comes from a plugin which you do not have installed & activated.') def __init__(self, exp, parentName, name='', compType="UnknownPluginComponent"): self.exp = exp # so we can access the experiment if necess self.parentName = parentName # to access the routine too if needed self.params = {} self.depends = [] super(UnknownPluginComponent, self).__init__(exp, parentName, name=name) # replace default type with the type given self.type = compType @property def _xml(self): # make XML node with tag from self.type rather than class name return self.makeXmlNode(self.type) # make sure nothing gets written into experiment for an unknown object # class! def writeRoutineStartCode(self, buff): pass def writeStartCode(self, buff): pass def writeInitCode(self, buff): code = ( "\n" "# Unknown component ignored: %(name)s\n" "\n" ) buff.writeIndentedLines(code % self.params) def writeInitCodeJS(self, buff): code = ( "\n" "// Unknown component ignored: %(name)s\n" "\n" ) buff.writeIndentedLines(code % self.params) def writeFrameCode(self, buff): pass def writeRoutineEndCode(self, buff): pass def writeExperimentEndCode(self, buff): pass def writeTimeTestCode(self, buff): pass def writeStartTestCode(self, buff): pass def writeStopTestCode(self, buff): pass def writeParamUpdates(self, buff, updateType, paramNames=None): pass def writeParamUpdate(self, buff, compName, paramName, val, updateType, params=None): pass
2,522
Python
.py
65
31.215385
119
0.651354
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,629
__init__.py
psychopy_psychopy/psychopy/experiment/components/unknown/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path from psychopy.experiment.components import BaseComponent, Param, _translate class UnknownComponent(BaseComponent): """This is used by Builder to represent a component that was not known by the current installed version of PsychoPy (most likely from the future). We want this to be loaded, represented and saved but not used in any script-outputs. It should have nothing but a name - other params will be added by the loader """ targets = ['PsychoPy'] categories = ['Other'] targets = ['PsychoPy'] iconFile = Path(__file__).parent / 'unknown.png' tooltip = _translate('Unknown: A component that is not known by the current ' 'installed version of PsychoPy\n(most likely from the ' 'future)') def __init__(self, exp, parentName, name='', compType="UnknownComponent"): self.exp = exp # so we can access the experiment if necess self.parentName = parentName # to access the routine too if needed self.params = {} self.depends = [] super(UnknownComponent, self).__init__(exp, parentName, name=name) self.type = compType @property def _xml(self): # make XML node with tag from self.type rather than class name return self.makeXmlNode(self.type) # make sure nothing gets written into experiment for an unknown object # class! def writeRoutineStartCode(self, buff): pass def writeStartCode(self, buff): pass def writeInitCode(self, buff): code = ( "\n" "# Unknown component ignored: %(name)s\n" "\n" ) buff.writeIndentedLines(code % self.params) def writeInitCodeJS(self, buff): code = ( "\n" "// Unknown component ignored: %(name)s\n" "\n" ) buff.writeIndentedLines(code % self.params) def writeFrameCode(self, buff): pass def writeRoutineEndCode(self, buff): pass def writeExperimentEndCode(self, buff): pass def writeTimeTestCode(self, buff): pass def writeStartTestCode(self, buff): pass def writeStopTestCode(self, buff): pass def writeParamUpdates(self, buff, updateType, paramNames=None): pass def writeParamUpdate(self, buff, compName, paramName, val, updateType, params=None): pass
2,526
Python
.py
66
30.151515
81
0.634986
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,630
_inpout.py
psychopy_psychopy/psychopy/parallel/_inpout.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # We deliberately delay importing the inpout32 or inpoutx64 module until we try # to use it - this allows us to import the class on machines # which don't have it and then worry about dealing with # using the right one later class PParallelInpOut: """This class provides read/write access to the parallel port on a PC using inpout32 or inpoutx64 (for instance for Windows 7 64-bit) """ def __init__(self, address=0x0378): """Set the memory address of your parallel port, to be used in subsequent calls to this object Common port addresses:: LPT1 = 0x0378 or 0x03BC LPT2 = 0x0278 or 0x0378 LPT3 = 0x0278 """ from numpy import uint8 from ctypes import windll import platform if isinstance(address, str) and address.startswith('0x'): # convert u"0x0378" into 0x0378 self.base = int(address, 16) else: self.base = address if platform.architecture()[0] == '32bit': self.port = getattr(windll, 'inpout32') elif platform.architecture()[0] == '64bit': self.port = getattr(windll, 'inpoutx64') BYTEMODEMASK = uint8(1 << 5 | 1 << 6 | 1 << 7) # Put the port into Byte Mode (ECP register) _inp = self.port.Inp32(self.base + 0x402) self.port.Out32(self.base + 0x402, int((_inp & ~BYTEMODEMASK) | (1 << 5))) # Now to make sure the port is in output mode we need to make # sure that bit 5 of the control register is not set _inp = self.port.Inp32(self.base + 2) self.port.Out32(self.base + 2, int(_inp & ~uint8(1 << 5))) self.status = None def setData(self, data): """Set the data to be presented on the parallel port (one ubyte). Alternatively you can set the value of each pin (data pins are pins 2-9 inclusive) using :func:`setPin` Examples:: p.setData(0) # sets all pins low p.setData(255) # sets all pins high p.setData(2) # sets just pin 3 high (remember that pin2=bit0) p.setData(3) # sets just pins 2 and 3 high You can easily convert base 2 to int in python:: p.setData(int("00000011", 2)) # pins 2 and 3 high p.setData(int("00000101", 2)) # pins 2 and 4 high """ self.port.Out32(self.base, data) def setPin(self, pinNumber, state): """Set a desired pin to be high(1) or low(0). Only pins 2-9 (incl) are normally used for data output:: parallel.setPin(3, 1) # sets pin 3 high parallel.setPin(3, 0) # sets pin 3 low """ # I can't see how to do this without reading and writing the data _inp = self.port.Inp32(self.base) if state: val = _inp | 2**(pinNumber - 2) else: val = _inp & (255 ^ 2**(pinNumber - 2)) self.port.Out32(self.base, val) def readData(self): """Return the value currently set on the data pins (2-9) """ return self.port.Inp32(self.base) def readPin(self, pinNumber): """Determine whether a desired (input) pin is high(1) or low(0). Pins 2-13 and 15 are currently read here """ _base = self.port.Inp32(self.base + 1) if pinNumber == 10: # 10 = ACK return (_base >> 6) & 1 elif pinNumber == 11: # 11 = BUSY return (_base >> 7) & 1 elif pinNumber == 12: # 12 = PAPER-OUT return (_base >> 5) & 1 elif pinNumber == 13: # 13 = SELECT return (_base >> 4) & 1 elif pinNumber == 15: # 15 = ERROR return (_base >> 3) & 1 elif 2 <= pinNumber <= 9: return (self.port.Inp32(self.base) >> (pinNumber - 2)) & 1 else: msg = 'Pin %i cannot be read (by PParallelInpOut32.readPin())' print(msg % pinNumber)
4,120
Python
.py
97
32.536082
79
0.56525
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,631
_linux.py
psychopy_psychopy/psychopy/parallel/_linux.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # We deliberately delay importing the pyparallel module until we try # to use it - this allows us to import the class on machines # which don't have it and then worry about dealing with # using the right one later # This is necessary to stop the local parallel.py masking the module # we actually want to find! # We duck-type the parallel port objects class PParallelLinux: """This class provides read/write access to the parallel port for linux using pyparallel. Note that you must have the lp module removed and the ppdev module loaded to use this code:: sudo rmmod lp sudo modprobe ppdev """ def __init__(self, address='/dev/parport0'): """Set the device node of your parallel port Common port addresses:: LPT1 = /dev/parport0 LPT2 = /dev/parport1 LPT3 = /dev/parport2 """ import parallel as pyp if not hasattr(pyp, 'Parallel'): # We failed to import pyparallel properly # We probably ended up with psychopy.parallel instead... raise Exception('Failed to import pyparallel - is it installed?') self.port = pyp.Parallel(address) self.status = None def __del__(self): if hasattr(self, 'port'): del self.port def setData(self, data): """Set the data to be presented on the parallel port (one ubyte). Alternatively you can set the value of each pin (data pins are pins 2-9 inclusive) using :func:`~psychopy.parallel.setPin` Examples:: p.setData(0) # sets all pins low p.setData(255) # sets all pins high p.setData(2) # sets just pin 3 high (remember that pin2=bit0) p.setData(3) # sets just pins 2 and 3 high You can also convert base 2 to int easily in python:: parallel.setData(int("00000011", 2)) # pins 2 and 3 high parallel.setData(int("00000101", 2)) # pins 2 and 4 high """ self.port.setData(data) def setPin(self, pinNumber, state): """Set a desired pin to be high(1) or low(0). Only pins 2-9 (incl) are normally used for data output:: p.setPin(3, 1) # sets pin 3 high p.setPin(3, 0) # sets pin 3 low """ # I can't see how to do this without reading and writing the data if state: self.port.setData(self.port.PPRDATA() | (2**(pinNumber - 2))) else: self.port.setData(self.port.PPRDATA() & (255 ^ 2**(pinNumber - 2))) def readData(self): """Return the value currently set on the data pins (2-9) """ return self.port.PPRDATA() def readPin(self, pinNumber): """Determine whether a desired (input) pin is high(1) or low(0). Pins 2-13 and 15 are currently read here """ if pinNumber == 10: return self.port.getInAcknowledge() elif pinNumber == 11: return self.port.getInBusy() elif pinNumber == 12: return self.port.getInPaperOut() elif pinNumber == 13: return self.port.getInSelected() elif pinNumber == 15: return self.port.getInError() elif 2 <= pinNumber <= 9: return (self.port.PPRDATA() >> (pinNumber - 2)) & 1 else: msg = 'Pin %i cannot be read (by PParallelLinux.readPin())' print(msg % pinNumber)
3,517
Python
.py
82
33.902439
79
0.608441
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,632
_dlportio.py
psychopy_psychopy/psychopy/parallel/_dlportio.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # This code is heavily based upon winioport.py # Provides hardware port access for Python under Windows 95/98/NT/2000 # # Original Author: Dincer Aydin dinceraydin@gmx.net www.dinceraydin.com # Merged directly into psychopy by: Mark Hymers <mark.hymers@ynic.york.ac.uk> # All bugs are Mark's fault. # # This module depends on: # ctypes Copyright (c) 2000, 2001, 2002, 2003 Thomas Heller # DLPortIO Win32 DLL hardware I/O functions & Kernel mode driver for WinNT # # In this package you will find almost any sort of port IO function one may # imagine. Values of port registers are srored in temporary variables. This is # for the bit set/reset functions to work right Some register bits are # inverted. on the port pins, but you need not worry about them. The functions # in this module take this into account. For eaxample when you call # winioport.pportDataStrobe(1) the data strobe pin of the printer port will go # HIGH. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files , to deal in the # Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish,and distribute copies of the Software, # and to permit persons to whom the Software is furnished to do so, subject # to the following conditions: # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. class PParallelDLPortIO: """This class provides read/write access to the parallel port on a PC. This is a wrapper around Dincer Aydin's `winioport`_ for reading and writing to the parallel port, but adds the following additional functions for convenience. On windows `winioport`_ requires the `PortIO driver`_ to be installed. An alternative on Linux might be to use PyParallel An alternative on other versions of Windows might be to use inpout32. . _winioport: http://www.dinceraydin.com/python/indexeng.html .. _PortIO driver: https://www.winford.com/support/download.php """ def __init__(self, address=0x0378): """Set the memory address of your parallel port, to be used in subsequent method calls on this class. Common port addresses:: LPT1 = 0x0378 or 0x03BC LPT2 = 0x0278 or 0x0378 LPT3 = 0x0278 """ from ctypes import windll try: # Load dlportio.dll functions self.port = windll.dlportio except Exception as e: print("Could not import DLportIO driver, " "parallel Ports not available") raise e if isinstance(address, str) and address.startswith('0x'): # convert u"0x0378" into 0x0378 self.base = int(address, 16) else: self.base = address self.status = None def setData(self, data): """Set the data to be presented on the parallel port (one ubyte). Alternatively you can set the value of each pin (data pins are pins 2-9 inclusive) using :func:`setPin` Examples:: p.setData(0) # sets all pins low p.setData(255) # sets all pins high p.setData(2) # sets just pin 3 high (remember that pin2=bit0) p.setData(3) # sets just pins 2 and 3 high You can also convert base 2 to int v easily in python:: p.setData( int("00000011", 2) ) # pins 2 and 3 high p.setData( int("00000101", 2) ) # pins 2 and 4 high """ self.port.DlPortWritePortUchar(self.base, data) def setPin(self, pinNumber, state): """Set a desired pin to be high(1) or low(0). Only pins 2-9 (incl) are normally used for data output:: p.setPin(3, 1) # sets pin 3 high p.setPin(3, 0) # sets pin 3 low """ # I can't see how to do this without reading and writing the data # or caching the registers which seems like a very bad idea... _uchar = self.port.DlPortReadPortUchar(self.base) if state: val = _uchar | 2**(pinNumber - 2) else: val = _uchar & (255 ^ 2**(pinNumber - 2)) self.port.DlPortWritePortUchar(self.base, val) def readData(self): """Return the value currently set on the data pins (2-9) """ return self.port.DlPortReadPortUchar(self.base) def readPin(self, pinNumber): """Determine whether a desired (input) pin is high(1) or low(0). Pins 2-13 and 15 are currently read here """ val = self.port.DlPortReadPortUchar(self.base + 1) if pinNumber == 10: # 10 = ACK return (val >> 6) & 1 elif pinNumber == 11: # 11 = BUSY return (val >> 7) & 1 elif pinNumber == 12: # 12 = PAPER-OUT return (val >> 5) & 1 elif pinNumber == 13: # 13 = SELECT return (val >> 4) & 1 elif pinNumber == 15: # 15 = ERROR return (val >> 3) & 1 elif 2 <= pinNumber <= 9: val = self.port.DlPortReadPortUchar(self.base) return (val >> (pinNumber - 2)) & 1 else: msg = 'Pin %i cannot be read (by PParallelDLPortIO.readPin())' print(msg % pinNumber)
5,783
Python
.py
126
38.357143
78
0.649743
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,633
__init__.py
psychopy_psychopy/psychopy/parallel/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module provides read / write access to the parallel port for Linux or Windows. The :class:`~psychopy.parallel.Parallel` class described below will attempt to load whichever parallel port driver is first found on your system and should suffice in most instances. If you need to use a specific driver then, instead of using :class:`~psychopy.parallel.ParallelPort` shown below you can use one of the following as drop-in replacements, forcing the use of a specific driver: - `psychopy.parallel.PParallelInpOut` - `psychopy.parallel.PParallelDLPortIO` - `psychopy.parallel.PParallelLinux` Either way, each instance of the class can provide access to a different parallel port. There is also a legacy API which consists of the routines which are directly in this module. That API assumes you only ever want to use a single parallel port at once. """ import sys from psychopy import logging # To make life easier, only try drivers which have a hope in heck of working. # Because hasattr() in connection to windll ends up in an OSError trying to # load 32bit drivers in a 64bit environment, different drivers defined in # the dictionary 'drivers' are tested. if sys.platform.startswith('linux'): from ._linux import PParallelLinux ParallelPort = PParallelLinux elif sys.platform == 'win32': drivers = dict(inpout32=('_inpout', 'PParallelInpOut'), inpoutx64=('_inpout', 'PParallelInpOut'), dlportio=('_dlportio', 'PParallelDLPortIO')) from ctypes import windll from importlib import import_module ParallelPort = None for key, val in drivers.items(): driver_name, class_name = val try: hasattr(windll, key) ParallelPort = getattr(import_module('.'+driver_name, __name__), class_name) break except (OSError, KeyError, NameError): ParallelPort = None continue if ParallelPort is None: logging.warning("psychopy.parallel has been imported but no " "parallel port driver found. Install either " "inpout32, inpoutx64 or dlportio") else: logging.warning("psychopy.parallel has been imported on a Mac " "(which doesn't have a parallel port?)") # macOS doesn't have a parallel port but write the class for doc purps class ParallelPort: """Class for read/write access to the parallel port on Windows & Linux Usage:: from psychopy import parallel port = parallel.ParallelPort(address=0x0378) port.setData(4) port.readPin(2) port.setPin(2, 1) """ def __init__(self, address): """This is just a dummy constructor to avoid errors when the parallel port cannot be initiated """ msg = ("psychopy.parallel has been imported but (1) no parallel " "port driver could be found or accessed on Windows or " "(2) PsychoPy is run on a Mac (without parallel-port " "support for now)") logging.warning(msg) def setData(self, data): """Set the data to be presented on the parallel port (one ubyte). Alternatively you can set the value of each pin (data pins are pins 2-9 inclusive) using :func:`~psychopy.parallel.setPin` Examples:: from psychopy import parallel port = parallel.ParallelPort(address=0x0378) port.setData(0) # sets all pins low port.setData(255) # sets all pins high port.setData(2) # sets just pin 3 high (pin2 = bit0) port.setData(3) # sets just pins 2 and 3 high You can also convert base 2 to int easily in python:: port.setData( int("00000011", 2) ) # pins 2 and 3 high port.setData( int("00000101", 2) ) # pins 2 and 4 high """ sys.stdout.flush() raise NotImplementedError("Parallel ports don't work on a Mac") def readData(self): """Return the value currently set on the data pins (2-9) """ raise NotImplementedError("Parallel ports don't work on a Mac") def readPin(self, pinNumber): """Determine whether a desired (input) pin is high(1) or low(0). Pins 2-13 and 15 are currently read here """ raise NotImplementedError("Parallel ports don't work on a Mac") # In order to maintain API compatibility, we have to manage # the old, non-object-based, calls. This necessitates keeping a # global object referring to a port. We initialise it the first time # that the person calls PORT = None # don't create a port until necessary def setPortAddress(address=0x0378): """Set the memory address or device node for your parallel port of your parallel port, to be used in subsequent commands Common port addresses:: LPT1 = 0x0378 or 0x03BC LPT2 = 0x0278 or 0x0378 LPT3 = 0x0278 or for Linux:: /dev/parport0 This routine will attempt to find a usable driver depending on your platform """ global PORT # convert u"0x0378" into 0x0378 if isinstance(address, str) and address.startswith('0x'): address = int(address, 16) # This is useful with the Linux-based driver where deleting # the port object ensures that we're not longer holding the # device node open and that we won't error if we end up # re-opening it if PORT is not None: del PORT try: PORT = ParallelPort(address=address) except Exception as exp: logging.warning('Could not initiate port: %s' % str(exp)) PORT = None def setData(data): """Set the data to be presented on the parallel port (one ubyte). Alternatively you can set the value of each pin (data pins are pins 2-9 inclusive) using :func:`~psychopy.parallel.setPin` Examples:: parallel.setData(0) # sets all pins low parallel.setData(255) # sets all pins high parallel.setData(2) # sets just pin 3 high (remember that pin2=bit0) parallel.setData(3) # sets just pins 2 and 3 high You can also convert base 2 to int v easily in python:: parallel.setData(int("00000011", 2)) # pins 2 and 3 high parallel.setData(int("00000101", 2)) # pins 2 and 4 high """ global PORT if PORT is None: raise RuntimeError('Port address must be set using setPortAddress') PORT.setData(data) def setPin(pinNumber, state): """Set a desired pin to be high (1) or low (0). Only pins 2-9 (incl) are normally used for data output:: parallel.setPin(3, 1) # sets pin 3 high parallel.setPin(3, 0) # sets pin 3 low """ global PORT PORT.setPin(pinNumber, state) def readPin(pinNumber): """Determine whether a desired (input) pin is high(1) or low(0). Pins 2-13 and 15 are currently read here """ global PORT return PORT.readPin(pinNumber)
7,239
Python
.py
161
36.73913
78
0.652638
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,634
lazy_import.py
psychopy_psychopy/psychopy/contrib/lazy_import.py
# Copyright (C) 2006-2010 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # NB This file comes unaltered (apart from this sentence) from the bzrlib # by Canonical (the library supporting the Bazaar code versioning system) """Functionality to create lazy evaluation objects. This includes waiting to import a module until it is actually used. Most commonly, the 'lazy_import' function is used to import other modules in an on-demand fashion. Typically use looks like:: from bzrlib.lazy_import import lazy_import lazy_import(globals(), ''' from bzrlib import ( errors, osutils, branch, ) import bzrlib.branch ''') Then 'errors, osutils, branch' and 'bzrlib' will exist as lazy-loaded objects which will be replaced with a real object on first use. In general, it is best to only load modules in this way. This is because it isn't safe to pass these variables to other functions before they have been replaced. This is especially true for constants, sometimes true for classes or functions (when used as a factory, or you want to inherit from them). """ class ScopeReplacer(): """A lazy object that will replace itself in the appropriate scope. This object sits, ready to create the real object the first time it is needed. """ __slots__ = ('_scope', '_factory', '_name', '_real_obj') # If you to do x = y, setting this to False will disallow access to # members from the second variable (i.e. x). This should normally # be enabled for reasons of thread safety and documentation, but # will be disabled during the selftest command to check for abuse. _should_proxy = True def __init__(self, scope, factory, name): """Create a temporary object in the specified scope. Once used, a real object will be placed in the scope. :param scope: The scope the object should appear in :param factory: A callable that will create the real object. It will be passed (self, scope, name) :param name: The variable name in the given scope. """ object.__setattr__(self, '_scope', scope) object.__setattr__(self, '_factory', factory) object.__setattr__(self, '_name', name) object.__setattr__(self, '_real_obj', None) scope[name] = self def _resolve(self): """Return the real object for which this is a placeholder""" name = object.__getattribute__(self, '_name') real_obj = object.__getattribute__(self, '_real_obj') if real_obj is None: # No obj generated previously, so generate from factory and scope. factory = object.__getattribute__(self, '_factory') scope = object.__getattribute__(self, '_scope') obj = factory(self, scope, name) if obj is self: raise ValueError(name, msg="Object tried" " to replace itself, check it's not using its own scope.") # Check if another thread has jumped in while obj was generated. real_obj = object.__getattribute__(self, '_real_obj') if real_obj is None: # Still no preexisting obj, so go ahead and assign to scope and # return. There is still a small window here where races will # not be detected, but safest to avoid additional locking. object.__setattr__(self, '_real_obj', obj) scope[name] = obj return obj # Raise if proxying is disabled as obj has already been generated. if not ScopeReplacer._should_proxy: raise ValueError( name, msg="Object already replaced, did you assign it" " to another variable?") return real_obj def __getattribute__(self, attr): obj = object.__getattribute__(self, '_resolve')() return getattr(obj, attr) def __setattr__(self, attr, value): obj = object.__getattribute__(self, '_resolve')() return setattr(obj, attr, value) def __call__(self, *args, **kwargs): obj = object.__getattribute__(self, '_resolve')() return obj(*args, **kwargs) def disallow_proxying(): """Disallow lazily imported modules to be used as proxies. Calling this function might cause problems with concurrent imports in multithreaded environments, but will help detecting wasteful indirection, so it should be called when executing unit tests. Only lazy imports that happen after this call are affected. """ ScopeReplacer._should_proxy = False class ImportReplacer(ScopeReplacer): """This is designed to replace only a portion of an import list. It will replace itself with a module, and then make children entries also ImportReplacer objects. At present, this only supports 'import foo.bar.baz' syntax. """ # '_import_replacer_children' is intentionally a long semi-unique name # that won't likely exist elsewhere. This allows us to detect an # ImportReplacer object by using # object.__getattribute__(obj, '_import_replacer_children') # We can't just use 'isinstance(obj, ImportReplacer)', because that # accesses .__class__, which goes through __getattribute__, and triggers # the replacement. __slots__ = ('_import_replacer_children', '_member', '_module_path') def __init__(self, scope, name, module_path, member=None, children={}): """Upon request import 'module_path' as the name 'module_name'. When imported, prepare children to also be imported. :param scope: The scope that objects should be imported into. Typically this is globals() :param name: The variable name. Often this is the same as the module_path. 'bzrlib' :param module_path: A list for the fully specified module path ['bzrlib', 'foo', 'bar'] :param member: The member inside the module to import, often this is None, indicating the module is being imported. :param children: Children entries to be imported later. This should be a map of children specifications. :: {'foo':(['bzrlib', 'foo'], None, {'bar':(['bzrlib', 'foo', 'bar'], None {})}) } Examples:: import foo => name='foo' module_path='foo', member=None, children={} import foo.bar => name='foo' module_path='foo', member=None, children={'bar':(['foo', 'bar'], None, {}} from foo import bar => name='bar' module_path='foo', member='bar' children={} from foo import bar, baz would get translated into 2 import requests. On for 'name=bar' and one for 'name=baz' """ if (member is not None) and children: raise ValueError('Cannot supply both a member and children') object.__setattr__(self, '_import_replacer_children', children) object.__setattr__(self, '_member', member) object.__setattr__(self, '_module_path', module_path) # Indirecting through __class__ so that children can # override _import (especially our instrumented version) cls = object.__getattribute__(self, '__class__') ScopeReplacer.__init__(self, scope=scope, name=name, factory=cls._import) def _import(self, scope, name): children = object.__getattribute__(self, '_import_replacer_children') member = object.__getattribute__(self, '_member') module_path = object.__getattribute__(self, '_module_path') module_python_path = '.'.join(module_path) if member is not None: module = __import__(module_python_path, scope, scope, [member], level=0) return getattr(module, member) else: module = __import__(module_python_path, scope, scope, [], level=0) for path in module_path[1:]: module = getattr(module, path) # Prepare the children to be imported for child_name, (child_path, child_member, grandchildren) in \ children.items(): # Using self.__class__, so that children get children classes # instantiated. (This helps with instrumented tests) cls = object.__getattribute__(self, '__class__') cls(module.__dict__, name=child_name, module_path=child_path, member=child_member, children=grandchildren) return module class ImportProcessor(): """Convert text that users input into lazy import requests""" # TODO: jam 20060912 This class is probably not strict enough about # what type of text it allows. For example, you can do: # import (foo, bar), which is not allowed by python. # For now, it should be supporting a superset of python import # syntax which is all we really care about. __slots__ = ['imports', '_lazy_import_class'] def __init__(self, lazy_import_class=None): self.imports = {} if lazy_import_class is None: self._lazy_import_class = ImportReplacer else: self._lazy_import_class = lazy_import_class def lazy_import(self, scope, text): """Convert the given text into a bunch of lazy import objects. This takes a text string, which should be similar to normal python import markup. """ self._build_map(text) self._convert_imports(scope) def _convert_imports(self, scope): # Now convert the map into a set of imports for name, info in self.imports.items(): self._lazy_import_class(scope, name=name, module_path=info[0], member=info[1], children=info[2]) def _build_map(self, text): """Take a string describing imports, and build up the internal map""" for line in self._canonicalize_import_text(text): if line.startswith('import '): self._convert_import_str(line) elif line.startswith('from '): self._convert_from_str(line) else: raise ValueError(line, "doesn't start with 'import ' or 'from '") def _convert_import_str(self, import_str): """This converts a import string into an import map. This only understands 'import foo, foo.bar, foo.bar.baz as bing' :param import_str: The import string to process """ if not import_str.startswith('import '): raise ValueError('bad import string %r' % (import_str,)) import_str = import_str[len('import '):] for path in import_str.split(','): path = path.strip() if not path: continue as_hunks = path.split(' as ') if len(as_hunks) == 2: # We have 'as' so this is a different style of import # 'import foo.bar.baz as bing' creates a local variable # named 'bing' which points to 'foo.bar.baz' name = as_hunks[1].strip() module_path = as_hunks[0].strip().split('.') if name in self.imports: raise ValueError(name) # No children available in 'import foo as bar' self.imports[name] = (module_path, None, {}) else: # Now we need to handle module_path = path.split('.') name = module_path[0] if name not in self.imports: # This is a new import that we haven't seen before module_def = ([name], None, {}) self.imports[name] = module_def else: module_def = self.imports[name] cur_path = [name] cur = module_def[2] for child in module_path[1:]: cur_path.append(child) if child in cur: cur = cur[child][2] else: next = (cur_path[:], None, {}) cur[child] = next cur = next[2] def _convert_from_str(self, from_str): """This converts a 'from foo import bar' string into an import map. :param from_str: The import string to process """ if not from_str.startswith('from '): raise ValueError('bad from/import %r' % from_str) from_str = from_str[len('from '):] from_module, import_list = from_str.split(' import ') from_module_path = from_module.split('.') for path in import_list.split(','): path = path.strip() if not path: continue as_hunks = path.split(' as ') if len(as_hunks) == 2: # We have 'as' so this is a different style of import # 'import foo.bar.baz as bing' creates a local variable # named 'bing' which points to 'foo.bar.baz' name = as_hunks[1].strip() module = as_hunks[0].strip() else: name = module = path if name in self.imports: raise ValueError(name) self.imports[name] = (from_module_path, module, {}) def _canonicalize_import_text(self, text): """Take a list of imports, and split it into regularized form. This is meant to take regular import text, and convert it to the forms that the rest of the converters prefer. """ out = [] cur = None continuing = False for line in text.split('\n'): line = line.strip() loc = line.find('#') if loc != -1: line = line[:loc].strip() if not line: continue if cur is not None: if line.endswith(')'): out.append(cur + ' ' + line[:-1]) cur = None else: cur += ' ' + line else: if '(' in line and ')' not in line: cur = line.replace('(', '') else: out.append(line.replace('(', '').replace(')', '')) if cur is not None: raise ValueError(cur, 'Unmatched parenthesis') return out def lazy_import(scope, text, lazy_import_class=None): """Create lazy imports for all of the imports in text. This is typically used as something like:: from bzrlib.lazy_import import lazy_import lazy_import(globals(), ''' from bzrlib import ( foo, bar, baz, ) import bzrlib.branch import bzrlib.transport ''') Then 'foo, bar, baz' and 'bzrlib' will exist as lazy-loaded objects which will be replaced with a real object on first use. In general, it is best to only load modules in this way. This is because other objects (functions/classes/variables) are frequently used without accessing a member, which means we cannot tell they have been used. """ # This is just a helper around ImportProcessor.lazy_import proc = ImportProcessor(lazy_import_class=lazy_import_class) return proc.lazy_import(scope, text)
16,238
Python
.py
335
37.814925
84
0.5977
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,635
quest.py
psychopy_psychopy/psychopy/contrib/quest.py
#!/usr/bin/env python # Copyright (c) 1996-2002 Denis G. Pelli # Copyright (c) 1996-9 David Brainard # Copyright (c) 2004-7 Andrew D. Straw # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # a. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # b. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # c. Neither the name of the Enthought nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH # DAMAGE. __all__ = ['QuestObject'] import math import copy import warnings import random import sys import time import numpy as num def getinf(x): return num.nonzero( num.isinf( num.atleast_1d(x) ) ) class QuestObject(): """Measure threshold using a Weibull psychometric function. Threshold 't' is measured on an abstract 'intensity' scale, which usually corresponds to log10 contrast. The Weibull psychometric function: p2=delta*gamma+(1-delta)*(1-(1-gamma)*exp(-10**(beta*(x2+xThreshold)))) where x2 represents log10 intensity relative to threshold (i.e., x2 = x - T, where x is intensity, and T is threshold intensity). xThreshold shifts the psychometric function along the intensity axis such that threshold performance (specified as pThreshold below) will occur at intensity x = T, i.e., x2 = x - T = 0. In the Watson & Pelli (1983) paper, xThreshold is denoted as epsilon and used to perform testing at the "ideal sweat factor". The Weibull function itself appears only in recompute(), which uses the specified parameter values in self to compute a psychometric function and store it in self. All the other methods simply use the psychometric function stored as instance variables. recompute() is called solely by __init__() and beta_analysis() (and possibly by a few user programs). Thus, if you prefer to use a different kind of psychometric function, called Foo, you need only subclass QuestObject, overriding __init__(), recompute(), and (if you need it) beta_analysis(). instance variables: tGuess is your prior threshold estimate. tGuessSd is the standard deviation you assign to that guess. pThreshold is your threshold criterion expressed as probability of response==1. An intensity offset is introduced into the psychometric function so that threshold (i.e. the midpoint of the table) yields pThreshold. beta, delta, and gamma are the parameters of a Weibull psychometric function. beta controls the steepness of the psychometric function. Typically 3.5. delta is the fraction of trials on which the observer presses blindly. Typically 0.01. gamma is the fraction of trials that will generate response 1 when intensity==-inf. grain is the quantization of the internal table. E.g. 0.01. range is the intensity difference between the largest and smallest intensity that the internal table can store. E.g. 5. This interval will be centered on the initial guess tGuess, i.e. [tGuess-range/2, tGuess+range/2]. QUEST assumes that intensities outside of this interval have zero prior probability, i.e. they are impossible. """ def __init__(self,tGuess,tGuessSd,pThreshold,beta,delta,gamma,grain=0.01,range=None): """Initialize Quest parameters. Create an instance of QuestObject with all the information necessary to measure threshold. This was converted from the Psychtoolbox's QuestCreate function. """ super(QuestObject, self).__init__() grain = float(grain) # make sure grain is a float if range is None: dim = 500 else: if range <= 0: raise ValueError('argument "range" must be greater than zero.') dim=range/grain dim=2*math.ceil(dim/2.0) # round up to even integer self.updatePdf = True self.warnPdf = True self.normalizePdf = False self.tGuess = tGuess self.tGuessSd = tGuessSd self.pThreshold = pThreshold self.beta = beta self.delta = delta self.gamma = gamma self.grain = grain self.dim = dim self.recompute() def beta_analysis(self,stream=None): """Analyze the quest function with beta as a free parameter. It returns the mean estimates of alpha (as logC) and beta. Gamma is left at whatever value the user fixed it at. """ def _beta_analysis1(stream=None): """private function called by beta_analysis()""" if stream is None: stream=sys.stdout q2 = [] for i in range(1,17): q_copy=copy.copy(self) q_copy.beta=2**(i/4.0) q_copy.dim=250 q_copy.grain=0.02 q_copy.recompute() q2.append(q_copy) na = num.array # shorthand t2 = na([q2i.mean() for q2i in q2]) p2 = na([q2i.pdf_at(t2i) for q2i,t2i in zip(q2,t2)]) sd2 = na([q2i.sd() for q2i in q2]) beta2 = na([q2i.beta for q2i in q2]) i=num.argsort(p2)[-1] t=t2[i] sd=q2[i].sd() p=num.sum(p2) betaMean=num.sum(p2*beta2)/p betaSd=math.sqrt(num.sum(p2*beta2**2)/p-(num.sum(p2*beta2)/p)**2) iBetaMean=num.sum(p2/beta2)/p iBetaSd=math.sqrt(num.sum(p2/beta2**2)/p-(num.sum(p2/beta2)/p)**2) stream.write('%5.2f %5.2f %4.1f %4.1f %6.3f\n'%(t, sd, 1/iBetaMean, betaSd, self.gamma)) print('Now re-analyzing with beta as a free parameter. . . .') if stream is None: stream=sys.stdout stream.write('logC sd beta sd gamma\n'); _beta_analysis1(stream) def mean(self): """Mean of Quest posterior pdf. Get the mean threshold estimate. This was converted from the Psychtoolbox's QuestMean function. """ return self.tGuess + num.sum(self.pdf*self.x)/num.sum(self.pdf) def mode(self): """Mode of Quest posterior pdf. t,p=q.mode() 't' is the mode threshold estimate 'p' is the value of the (unnormalized) pdf at t. This was converted from the Psychtoolbox's QuestMode function. """ iMode = num.argsort(self.pdf)[-1] p=self.pdf[iMode] t=self.x[iMode]+self.tGuess return t,p def p(self,x): """probability of correct response at intensity x. p=q.p(x) The probability of a correct (or yes) response at intensity x, assuming threshold is at x=0. This was converted from the Psychtoolbox's QuestP function. """ if x < self.x2[0]: return self.x2[0] if x > self.x2[-1]: return self.x2[-1] return num.interp(x,self.x2,self.p2) def pdf_at(self,t): """The (unnormalized) probability density of candidate threshold 't'. This was converted from the Psychtoolbox's QuestPdf function. """ i=int(round((t-self.tGuess)/self.grain))+1+self.dim/2 i=min(len(self.pdf),max(1,i))-1 p=self.pdf[i] return p def quantile(self,quantileOrder=None): """Get Quest recommendation for next trial level. intensity=q.quantile([quantileOrder]) Gets a quantile of the pdf in the struct q. You may specify the desired quantileOrder, e.g. 0.5 for median, or, making two calls, 0.05 and 0.95 for a 90confidence interval. If the 'quantileOrder' argument is not supplied, then it's taken from the QuestObject instance. __init__() uses recompute() to compute the optimal quantileOrder and saves that in the QuestObject instance; this quantileOrder yields a quantile that is the most informative intensity for the next trial. This was converted from the Psychtoolbox's QuestQuantile function. """ if quantileOrder is None: quantileOrder = self.quantileOrder p = num.cumsum(self.pdf) if len(getinf(p[-1])[0]): raise RuntimeError('pdf is not finite') if p[-1]==0: raise RuntimeError('pdf is all zero') m1p = num.concatenate(([-1],p)) index = num.nonzero( m1p[1:]-m1p[:-1] )[0] if len(index) < 2: raise RuntimeError('pdf has only %g nonzero point(s)'%len(index)) ires = num.interp([quantileOrder*p[-1]],p[index],self.x[index])[0] return self.tGuess+ires def sd(self): """Standard deviation of Quest posterior pdf. Get the sd of the threshold distribution. This was converted from the Psychtoolbox's QuestSd function.""" p=num.sum(self.pdf) sd=math.sqrt(num.sum(self.pdf*self.x**2)/p-(num.sum(self.pdf*self.x)/p)**2) return sd def simulate(self,tTest,tActual): """Simulate an observer with given Quest parameters. response=QuestSimulate(q,intensity,tActual) Simulate the response of an observer with threshold tActual. This was converted from the Psychtoolbox's QuestSimulate function.""" t = min( max(tTest-tActual, self.x2[0]), self.x2[-1] ) response= num.interp([t],self.x2,self.p2)[0] > random.random() return response def recompute(self): """Recompute the psychometric function & pdf. Call this immediately after changing a parameter of the psychometric function. recompute() uses the specified parameters in 'self' to recompute the psychometric function. It then uses the newly computed psychometric function and the history in self.intensity and self.response to recompute the pdf. (recompute() does nothing if q.updatePdf is False.) This was converted from the Psychtoolbox's QuestRecompute function.""" if not self.updatePdf: return if self.gamma > self.pThreshold: warnings.warn( 'reducing gamma from %.2f to 0.5'%self.gamma) self.gamma = 0.5 self.i = num.arange(-self.dim/2, self.dim/2+1) self.x = self.i * self.grain self.pdf = num.exp(-0.5*(self.x/self.tGuessSd)**2) self.pdf = self.pdf/num.sum(self.pdf) i2 = num.arange(-self.dim,self.dim+1) self.x2 = i2*self.grain self.p2 = self.delta*self.gamma+(1-self.delta)*(1-(1-self.gamma)*num.exp(-10**(self.beta*self.x2))) if self.p2[0] >= self.pThreshold or self.p2[-1] <= self.pThreshold: raise RuntimeError('psychometric function range [%.2f %.2f] omits %.2f threshold'%(self.p2[0],self.p2[-1],self.pThreshold)) # XXX if len(getinf(self.p2)[0]): raise RuntimeError('psychometric function p2 is not finite') index = num.nonzero( self.p2[1:]-self.p2[:-1] )[0] # strictly monotonic subset if len(index) < 2: raise RuntimeError('psychometric function has only %g strictly monotonic points'%len(index)) self.xThreshold = num.interp([self.pThreshold],self.p2[index],self.x2[index])[0] self.p2 = self.delta*self.gamma+(1-self.delta)*(1-(1-self.gamma)*num.exp(-10**(self.beta*(self.x2+self.xThreshold)))) if len(getinf(self.p2)[0]): raise RuntimeError('psychometric function p2 is not finite') self.s2 = num.array( ((1-self.p2)[::-1], self.p2[::-1]) ) if not hasattr(self,'intensity') or not hasattr(self,'response'): self.intensity = [] self.response = [] if len(getinf(self.s2)[0]): raise RuntimeError('psychometric function s2 is not finite') eps = 1e-14 pL = self.p2[0] pH = self.p2[-1] pE = pH*math.log(pH+eps)-pL*math.log(pL+eps)+(1-pH+eps)*math.log(1-pH+eps)-(1-pL+eps)*math.log(1-pL+eps) pE = 1/(1+math.exp(pE/(pL-pH))) self.quantileOrder=(pE-pL)/(pH-pL) if len(getinf(self.pdf)[0]): raise RuntimeError('prior pdf is not finite') # recompute the pdf from the historical record of trials for intensity, response in zip(self.intensity, self.response): inten = max(-1e10,min(1e10, intensity)) # make intensity finite ii = len(self.pdf) + self.i-round((inten-self.tGuess)/self.grain)-1 if ii[0]<0: ii = ii-ii[0] if ii[-1]>=self.s2.shape[1]: ii = ii+self.s2.shape[1]-ii[-1]-1 iii = ii.astype(num.int_) if not num.allclose(ii,iii): raise ValueError('truncation error') self.pdf = self.pdf*self.s2[response,iii] if self.normalizePdf and ii % 100 == 0: self.pdf = self.pdf/num.sum(self.pdf) # avoid underflow; keep the pdf normalized if self.normalizePdf: self.pdf = self.pdf/num.sum(self.pdf) # avoid underflow; keep the pdf normalized if len(getinf(self.pdf)[0]): raise RuntimeError('prior pdf is not finite') def update(self,intensity,response): """Update Quest posterior pdf. Update self to reflect the results of this trial. The historical records self.intensity and self.response are always updated, but self.pdf is only updated if self.updatePdf is true. You can always call QuestRecompute to recreate q.pdf from scratch from the historical record. This was converted from the Psychtoolbox's QuestUpdate function.""" if response < 0 or response > self.s2.shape[0]: raise RuntimeError('response %g out of range 0 to %d'%(response,self.s2.shape[0])) if self.updatePdf: inten = max(-1e10,min(1e10,intensity)) # make intensity finite ii = len(self.pdf) + self.i-round((inten-self.tGuess)/self.grain)-1 if ii[0]<0 or ii[-1] > self.s2.shape[1]: if self.warnPdf: low=(1-len(self.pdf)-self.i[0])*self.grain+self.tGuess high=(self.s2.shape[1]-len(self.pdf)-self.i[-1])*self.grain+self.tGuess warnings.warn( 'intensity %.2f out of range %.2f to %.2f. Pdf will be inexact.'%(intensity,low,high), RuntimeWarning,stacklevel=2) if ii[0]<0: ii = ii-ii[0] else: ii = ii+self.s2.shape[1]-ii[-1]-1 iii = ii.astype(num.int_) if not num.allclose(ii,iii): raise ValueError('truncation error') self.pdf = self.pdf*self.s2[response,iii] if self.normalizePdf: self.pdf=self.pdf/num.sum(self.pdf) # keep a historical record of the trials self.intensity.append(intensity) self.response.append(response) def demo(): """Demo script for Quest routines. By commenting and uncommenting a few lines in this function, you can use this file to implement three QUEST-related procedures for measuring threshold. QuestMode: In the original algorithm of Watson & Pelli (1983) each trial and the final estimate are at the MODE of the posterior pdf. QuestMean: In the improved algorithm of King-Smith et al. (1994). each trial and the final estimate are at the MEAN of the posterior pdf. QuestQuantile & QuestMean: In the ideal algorithm of Pelli (1987) each trial is at the best QUANTILE, and the final estimate is at the MEAN of the posterior pdf. This was converted from the Psychtoolbox's QuestDemo function. King-Smith, P. E., Grigsby, S. S., Vingrys, A. J., Benes, S. C., and Supowit, A. (1994) Efficient and unbiased modifications of the QUEST threshold method: theory, simulations, experimental evaluation and practical implementation. Vision Res, 34 (7), 885-912. Pelli, D. G. (1987) The ideal psychometric procedure. Investigative Ophthalmology & Visual Science, 28 (Suppl), 366. Watson, A. B. and Pelli, D. G. (1983) QUEST: a Bayesian adaptive psychometric method. Percept Psychophys, 33 (2), 113-20. """ print('The intensity scale is abstract, but usually we think of it as representing log contrast.') tActual = None while tActual is None: inputStr = input('Specify true threshold of simulated observer: ') try: tActual = float(inputStr) except Exception: pass tGuess = None while tGuess is None: inputStr = input('Estimate threshold: ') try: tGuess = float(inputStr) except Exception: pass tGuessSd = 2.0 # sd of Gaussian before clipping to specified range pThreshold = 0.82 beta = 3.5 delta = 0.01 gamma = 0.5 q=QuestObject(tGuess,tGuessSd,pThreshold,beta,delta,gamma) # Simulate a series of trials. trialsDesired=100 wrongRight = 'wrong', 'right' timeZero=time.time() for k in range(trialsDesired): # Get recommended level. Choose your favorite algorithm. tTest=q.quantile() #tTest=q.mean() #tTest=q.mode() tTest=tTest+random.choice([-0.1,0,0.1]) # Simulate a trial timeSplit=time.time(); # omit simulation and printing from reported time/trial. response=q.simulate(tTest,tActual) print('Trial %3d at %4.1f is %s'%(k+1,tTest,wrongRight[int(response)])) timeZero=timeZero+time.time()-timeSplit; # Update the pdf q.update(tTest,response); # Print results of timing. print('%.0f ms/trial'%(1000*(time.time()-timeZero)/trialsDesired)) # Get final estimate. t=q.mean() sd=q.sd() print('Mean threshold estimate is %4.2f +/- %.2f'%(t,sd)) #t=QuestMode(q); #print('Mode threshold estimate is %4.2f'%t) print('\nQuest beta analysis. Beta controls the steepness of the Weibull function.\n') q.beta_analysis() print('Actual parameters of simulated observer:') print('logC beta gamma') print('%5.2f %4.1f %5.2f'%(tActual,q.beta,q.gamma)) if __name__ == '__main__': demo() # run the demo
19,360
Python
.py
402
39.731343
141
0.646747
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,636
psi.py
psychopy_psychopy/psychopy/contrib/psi.py
# Copyright 2015 Joseph J Glavan # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # Please see <http://www.gnu.org/licenses/> for a copy of the GNU General Public License. __all__ = ['PsiObject'] from numpy import * class PsiObject(): """Special class to handle internal array and functions of Psi adaptive psychophysical method (Kontsevich & Tyler, 1999).""" def __init__(self, x, alpha, beta, xPrecision, aPrecision, bPrecision, delta=0, stepType='lin', TwoAFC=False, prior=None): global stats from scipy import stats # takes a while to load so do it lazy self._TwoAFC = TwoAFC #Save dimensions if stepType == 'lin': self.x = linspace(x[0], x[1], int(round((x[1]-x[0])/xPrecision)+1), True) elif stepType == 'log': self.x = logspace(log10(x[0]), log10(x[1]), xPrecision, True) else: raise RuntimeError('Invalid step type. Unable to initialize PsiObject.') self.alpha = linspace(alpha[0], alpha[1], int(round((alpha[1]-alpha[0])/aPrecision)+1), True) self.beta = linspace(beta[0], beta[1], int(round((beta[1]-beta[0])/bPrecision)+1), True) self.r = array(list(range(2))) self.delta = delta # Change x,a,b,r arrays to matrix computation compatible orthogonal 4D arrays # ALWAYS use the order for P(r|lambda,x); i.e. [r,a,b,x] self._r = self.r.reshape((self.r.size,1,1,1)) self._alpha = self.alpha.reshape((1,self.alpha.size,1,1)) self._beta = self.beta.reshape((1,1,self.beta.size,1)) self._x = self.x.reshape((1,1,1,self.x.size)) #Create P(lambda) if prior is None or prior.shape != (1, len(self.alpha),len(self.beta), 1): if prior is not None: warnings.warn("Prior has incompatible dimensions. Using uniform (1/N) probabilities.") self._probLambda = ndarray(shape=(1,len(self.alpha),len(self.beta),1)) self._probLambda.fill(1/(len(self.alpha)*len(self.beta))) else: if prior.shape == (1, len(self.alpha), len(self.beta), 1): self._probLambda = prior else: self._probLambda = prior.reshape(1, len(self.alpha), len(self.beta), 1) #Create P(r | lambda, x) if TwoAFC: self._probResponseGivenLambdaX = (1-self._r) + (2*self._r-1) * ((.5 + .5 * stats.norm.cdf(self._x, self._alpha, self._beta)) * (1 - self.delta) + self.delta / 2) else: # Yes/No self._probResponseGivenLambdaX = (1-self._r) + (2*self._r-1) * (stats.norm.cdf(self._x, self._alpha, self._beta)*(1-self.delta)+self.delta/2) def update(self, response=None): if response is not None: #response should only be None when Psi is first initialized self._probLambda = self._probLambdaGivenXResponse[response,:,:,self.nextIntensityIndex].reshape((1,len(self.alpha),len(self.beta),1)) #Create P(r | x) self._probResponseGivenX = sum(self._probResponseGivenLambdaX * self._probLambda, axis=(1,2)).reshape((len(self.r),1,1,len(self.x))) #Create P(lambda | x, r) self._probLambdaGivenXResponse = self._probLambda*self._probResponseGivenLambdaX/self._probResponseGivenX #Create H(x, r) self._entropyXResponse = -1* sum(self._probLambdaGivenXResponse * log10(self._probLambdaGivenXResponse), axis=(1,2)).reshape((len(self.r),1,1,len(self.x))) #Create E[H(x)] self._expectedEntropyX = sum(self._entropyXResponse * self._probResponseGivenX, axis=0).reshape((1,1,1,len(self.x))) #Generate next intensity self.nextIntensityIndex = argmin(self._expectedEntropyX, axis=3)[0][0][0] self.nextIntensity = self.x[self.nextIntensityIndex] def estimateLambda(self): return (sum(sum(self._alpha.reshape((len(self.alpha),1))*self._probLambda.squeeze(), axis=1)), sum(sum(self._beta.reshape((1,len(self.beta)))*self._probLambda.squeeze(), axis=1))) def estimateThreshold(self, thresh, lam): if lam is None: lamb = self.estimateLambda() else: lamb = lam if self._TwoAFC: return stats.norm.ppf((2*thresh-1)/(1-self.delta), lamb[0], lamb[1]) else: return stats.norm.ppf((thresh-self.delta/2)/(1-self.delta), lamb[0], lamb[1]) def savePosterior(self, file): save(file, self._probLambda)
4,993
Python
.py
81
51.91358
187
0.643051
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,637
tesselate.py
psychopy_psychopy/psychopy/contrib/tesselate.py
# JRG: add contrib/tesselate.py, copied from svgbatch / svgload project # bug ??FIXED: `pointer` not defined in `combineCallback()`, removed # changed: explicitly use the default winding rule GLU_TESS_WINDING_ODD # downloaded Nov 2015 https://github.com/tartley/svgload/blob/master # svgload LICENSE.txt contains: ''' This is a BSD license. http://www.opensource.org/licenses/bsd-license.php tessellate.py Copyright (c) 2008, Martin O'Leary The remainder Copyright (c) 2009, Jonathan Hartley All rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name(s) of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ''' # Many thanks to Martin O'Leary of supereffective.org, whose Squirtle module # formed a major inspiration for this entire project [svgbatch], and in particular for # his sublime tesselation code. This has been copied wholesale, under the terms # of the BSD. # http://www.supereffective.org/pages/Squirtle-SVG-Library from ctypes import CFUNCTYPE, POINTER, byref, cast import sys from pyglet.gl import ( GLdouble, GLenum, GLfloat, GLvoid, GL_TRIANGLES, GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP, gluErrorString, gluNewTess, gluTessBeginContour, gluTessBeginPolygon, gluTessCallback, gluTessEndContour, gluTessEndPolygon, gluTessNormal, gluTessProperty, gluTessVertex, GLU_TESS_BEGIN, GLU_TESS_COMBINE, GLU_TESS_END, GLU_TESS_ERROR, GLU_TESS_VERTEX, GLU_TESS_WINDING_ODD, GLU_TESS_WINDING_RULE, ) class TesselateError(Exception): pass tess = gluNewTess() gluTessNormal(tess, 0, 0, 1) default_winding_rule = GLU_TESS_WINDING_ODD gluTessProperty(tess, GLU_TESS_WINDING_RULE, default_winding_rule) if sys.platform == 'win32': from ctypes import WINFUNCTYPE c_functype = WINFUNCTYPE else: c_functype = CFUNCTYPE callback_types = { GLU_TESS_VERTEX: c_functype(None, POINTER(GLvoid)), GLU_TESS_BEGIN: c_functype(None, GLenum), GLU_TESS_END: c_functype(None), GLU_TESS_ERROR: c_functype(None, GLenum), GLU_TESS_COMBINE: c_functype( None, POINTER(GLdouble), POINTER(POINTER(GLvoid)), POINTER(GLfloat), POINTER(POINTER(GLvoid)) ) } def tesselate(loops): return Tesselate().tesselate(loops) def set_tess_callback(which): def set_call(func): cb = callback_types[which](func) gluTessCallback(tess, which, cast(cb, CFUNCTYPE(None))) return cb return set_call class Tesselate(): def fan_to_triangles(self): c = self.curr_shape.pop(0) p1 = self.curr_shape.pop(0) while self.curr_shape: p2 = self.curr_shape.pop(0) self.tlist.extend([c, p1, p2]) p1 = p2 def strip_to_triangles(self): p1 = self.curr_shape.pop(0) p2 = self.curr_shape.pop(0) while self.curr_shape: p3 = self.curr_shape.pop(0) self.tlist.extend([p1, p2, p3]) p1 = p2 p2 = p3 def tesselate(self, looplist): self.tlist = [] self.curr_shape = [] spareverts = [] @set_tess_callback(GLU_TESS_VERTEX) def vertexCallback(vertex): vertex = cast(vertex, POINTER(GLdouble)) self.curr_shape.append(tuple(vertex[0:2])) @set_tess_callback(GLU_TESS_BEGIN) def beginCallback(which): self.tess_style = which @set_tess_callback(GLU_TESS_END) def endCallback(): if self.tess_style == GL_TRIANGLE_FAN: self.fan_to_triangles() elif self.tess_style == GL_TRIANGLE_STRIP: self.strip_to_triangles() elif self.tess_style == GL_TRIANGLES: self.tlist.extend(self.curr_shape) else: self.warn("Unknown tesselation style: %d" % (self.tess_style,)) self.tess_style = None self.curr_shape = [] @set_tess_callback(GLU_TESS_ERROR) def errorCallback(code): ptr = gluErrorString(code) err = '' idx = 0 while ptr[idx]: err += chr(ptr[idx]) idx += 1 self.warn("GLU Tesselation Error: " + err) @set_tess_callback(GLU_TESS_COMBINE) def combineCallback(coords, vertex_data, weights, dataOut): x, y, z = coords[0:3] data = (GLdouble * 3)(x, y, z) #dataOut[0] = cast(pointer(data), POINTER(GLvoid)) # original dataOut[0] = cast(data, POINTER(GLvoid)) spareverts.append(data) data_lists = self.create_data_lists(looplist) return self.perform_tessellation(data_lists) def create_data_lists(self, looplist): data_lists = [] for vlist in looplist: d_list = [] for x, y in vlist: v_data = (GLdouble * 3)(x, y, 0) d_list.append(v_data) data_lists.append(d_list) return data_lists def perform_tessellation(self, data_lists): gluTessBeginPolygon(tess, None) for d_list in data_lists: gluTessBeginContour(tess) for v_data in d_list: gluTessVertex(tess, v_data, v_data) gluTessEndContour(tess) gluTessEndPolygon(tess) return self.tlist def warn(self, message): raise TesselateError(message)
6,670
Python
.py
154
35.948052
86
0.675255
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,638
mseqSearch.py
psychopy_psychopy/psychopy/contrib/mseqSearch.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ % Maximum length sequence assuming distinct values = baseVal % % original matlab code (C) Written by Giedrius T. Buracas, SNL-B, Salk Institute % and Center for Functional MRI, UCSD -------------------------------------------------------------------------------- Python translation from matlab: (c) Jeremy R. Gray, April 2011; distributed under the BSD license tested with python 2.7, numpy 1.5.1 lines in this file that start with % or #% are from GTB's matlab code Usage: in a script: from psychopy.contrib import mseqSearch mseqSearch.mseqSearch(3,3) # (baseVal, powerVal) mseqSearch.mseq_search(5,4,1,60) # (baseVal, powerVal, shift, timeout) returns a numpy.array(): m-sequence, or ['timed out'] from command line: ./mseqSearch.py 3 4 # 3^4 ./mseqSearch.py 3 4 1 10 # 3^4, shift 1, timeout after 10 seconds prints an m-sequence, time taken, and the first 10 auto-correlation values -------------------------------------------------------------------------------- % Maximum length sequence assuming distinct values = baseVal % % [ms]=mseqSearch(powerVal,baseVal) % % OUTPUT: % ms: generated maximum length sequence, of length basisVal^powerVal-1 % such that all values occur with equal frequency except zero % % INPUT: % baseVal: any prime number up to 31 % powerVal: an integer % NB: the algorithm is performing search in m-sequence register space % so the calculation time grows with baseVal and powerVal % Tested on Matlab 7.9.0 (R2009b) % % Copyright (c) 2010, Giedrius Buracas % All rights reserved. % %Redistribution and use in source and binary forms, with or without %modification, are permitted provided that the following conditions are %met: % % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in % the documentation and/or other materials provided with the distribution % %THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" %AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE %IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE %ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE %LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR %CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF %SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS %INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN %CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) %ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE %POSSIBILITY OF SUCH DAMAGE. """ import numpy import sys import time digits = "0123456789abcdefghijklmnopqrstuvwxyz" def _dec2base(n, base): """convert positive decimal integer n to equivalent in another base (2-36) http://code.activestate.com/recipes/65212-convert-from-decimal-to-any-base-number/ """ if n < 0 or base < 2 or base > 36: return "" s = "" while True: r = n % base s = digits[r] + s n = n // base if n == 0: break return s def mseqSearch(baseVal, powerVal, shift=0, max_time=10): """search for an M-sequence, default time-out after 10 seconds """ if not baseVal in [2,3,5,7,11,13,17,19,23,29]: raise ValueError("base must be a prime number < 30") seqLen = baseVal**powerVal-1 register = numpy.array([1 for i in range(powerVal)]) regLen = len(register) # == powerVal tap = numpy.array([0 for i in range(regLen)]) isM = False #% is m-sequence? count = 0 t0 = time.time() ms = numpy.array([0 for i in range(seqLen*2)]) weights = [] while not isM and count < seqLen * 4: noContinue = False count += 1 #% now generate taps incrementally tap = _dec2base(count, baseVal).zfill(regLen) weights = numpy.array([int(tap[i], baseVal) for i in range(regLen)]) for seq in range(2*regLen, 2*seqLen-2, 2): ms[:seq] = [0 for i in range(seq)] for i in range(seq): #% calculating next digit with modulo powerVal arithmetic #% updating the register ms[i] = (sum(weights*register) + baseVal) % baseVal register = numpy.append(ms[i], register[:-1]) foo = sum(ms[:seq//2] == ms[seq//2:seq]) if foo == seq//2: # first half same as last half noContinue = True register = numpy.array([1 for i in range(powerVal)]) break if time.time() - t0 > max_time: return ['timed out at %d sec' % max_time] if not noContinue: for i in range(seqLen*2): #% calculating next digit with modulo powerVal arithmetic ms[i] = (sum(weights*register) + baseVal) % baseVal #% updating the register register = numpy.append(ms[i], register[:-1]) foo = sum(ms[:seqLen] == ms[seqLen:]) if foo == seqLen: # first half same as last half isM = True ms = ms[:seqLen] if shift: shift = shift % len(ms) ms = numpy.append(ms[shift:], ms[:shift]) if not isM: ms = [] return ms def _abs_auto(ms): """return absolute value of auto-correlations for lags 1 to 10 """ num_acs = min(11, len(ms)) if num_acs: auto_corrs = [numpy.corrcoef(ms, numpy.append(ms[i:], ms[:i]))[1][0] for i in range(1,num_acs)] return list(map(abs, auto_corrs)) def test(): print('no tests; auto-correlations are computed for each sequence generated') if __name__=='__main__': if 'test' in sys.argv: test() else: try: args = list(map(int, sys.argv[1:])) except Exception: raise ValueError("expected 2-4 integer arguments: base power " +\ "[shift [max time to search in sec]]") if not args[0] in [2,3,5,7,11,13,17,19,23,29]: raise ValueError("base must be a prime number < 30") t0 = time.time() ms = mseqSearch(*args) t1 = time.time() - t0 print(ms, '\ntime: %.3f' % t1, 'sec') if len(ms) > 1: ac_10 = _abs_auto(ms) # list of auto-correlations print('seq length:', len(ms), '\nauto-corr, first %d: ' % len(ac_10), end='') for a in ac_10: print("%.3f" % a, end='') print() assert max(ac_10) < 1./(len(ms) - 3) or max(ac_10) < .10
7,016
Python
.py
162
36.654321
103
0.614668
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,639
mseq.py
psychopy_psychopy/psychopy/contrib/mseq.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' % Maximum length sequence assuming 2,3,5 distinct values % % original matlab code (C) Written by Giedrius T. Buracas, SNL-B, Salk Institute % and Center for Functional MRI, UCSD % http://www.mathworks.com/matlabcentral/fileexchange/990-m-sequence-generation-program -------------------------------------------------------------------------------- Python translation from matlab & tests: (c) Jeremy R. Gray, April 2011; distributed under the BSD license tested with python 2.7, numpy 1.5.1 Usage: in a script: from psychopy.contrib import mseq print(mseq.mseq(2,3,1,1)) # base, power, shift, which-sequence from command line: ./mseq.py 2 3 1 1 run tests with: ./mseq.py test -------------------------------------------------------------------------------- % Maximum length sequence assuming 2,3,5 distinct values % % [ms]=MSEQ(baseVal,powerVal[,shift,whichSeq]) % % OUTPUT: % ms = generated maximum length sequence, of length basisVal^powerVal-1 % % INPUT: % baseVal -nuber of sequence levels (2,3, or 5 allowed) % powerVal -power, so that sequence length is baseVal^powerVal-1 % shift -cyclical shift of the sequence % whichSeq -sequence istantiation to use % (number of sequences varies with powerVal - see the code) % % (c) Giedrius T. Buracas, SNL-B, Salk Institute % Register values are taken from: WDT Davies, System Identification % for self-adaptive control. Wiley-Interscience, 1970 % When using mseq code for design of FMRI experiments, please, cite: % G.T.Buracas & G.M.Boynton (2002) Efficient Design of Event-Related fMRI % Experiments Using M-sequences. NeuroImage, 16, 801-813. ''' import sys import numpy def _get_tap(baseVal, powerVal): """Retrieve pre-defined list of tap sequences for a given base & power, or raise ValueError. """ if not baseVal in [2,3,5,9]: raise ValueError('baseVal must be in [2,3,5,9], not %s' % str(baseVal)) tap = [] if baseVal == 2: if powerVal == 2: tap = [[1,2]] elif powerVal == 3: tap = [[1,3], [2,3]] elif powerVal == 4: tap = [[1,4], [3,4]] elif powerVal == 5: tap = [[2,5], [3,5], [1,2,3,5], [2,3,4,5], [1,2,4,5], [1,3,4,5]] elif powerVal == 6: tap = [[1,6], [5,6], [1,2,5,6], [1,4,5,6], [1,3,4,6], [2,3,5,6]] elif powerVal == 7: tap = [[1,7], [6,7], [3,7], [4,7], [1,2,3,7], [4,5,6,7], [1,2,5,7], [2,5,6,7], [2,3,4,7], [3,4,5,7], [1,3,5,7], [2,4,6,7], [1,3,6,7], [1,4,6,7], [2,3,4,5,6,7], [1,2,3,4,5,7], [1,2,4,5,6,7], [1,2,3,5,6,7] ] elif powerVal == 8: tap = [[1,2,7,8], [1,6,7,8], [1,3,5,8], [3,5,7,8], [2,3,4,8], [4,5,6,8], [2,3,5,8], [3,5,6,8], [2,3,6,8], [2,5,6,8], [2,3,7,8], [1,5,6,8], [1,2,3,4,6,8], [2,4,5,6,7,8], [1,2,3,6,7,8], [1,2,5,6,7,8] ] elif powerVal == 9: tap = [[4,9], [5,9], [3,4,6,9], [3,5,6,9], [4,5,8,9], [1,4,5,9], [1,4,8,9], [1,5,8,9], [2,3,5,9], [4,6,7,9], [5,6,8,9], [1,3,4,9], [2,7,8,9], [1,2,7,9], [2,4,7,9], [2,5,7,9], [2,4,8,9], [1,5,7,9], [1,2,4,5,6,9], [3,4,5,7,8,9], [1,3,4,6,7,9], [2,3,5,6,8,9], [3,5,6,7,8,9], [1,2,3,4,6,9], [1,5,6,7,8,9], [1,2,3,4,8,9], [1,2,3,7,8,9], [1,2,6,7,8,9], [1,3,5,6,8,9], [1,3,4,6,8,9], [1,2,3,5,6,9], [3,4,6,7,8,9], [2,3,6,7,8,9], [1,2,3,6,7,9], [1,4,5,6,8,9], [1,3,4,5,8,9], [1,3,6,7,8,9], [1,2,3,6,8,9], [2,3,4,5,6,9], [3,4,5,6,7,9], [2,4,6,7,8,9], [1,2,3,5,7,9], [2,3,4,5,7,9], [2,4,5,6,7,9], [1,2,4,5,7,9], [2,4,5,6,7,9], [1,3,4,5,6,7,8,9], [1,2,3,4,5,6,8,9] ] elif powerVal == 10: tap = [[3,10], [7,10], [2,3,8,10], [2,7,8,10], [1,3,4,10], [6,7,9,10], [1,5,8,10], [2,5,9,10], [4,5,8,10], [2,5,6,10], [1,4,9,10], [1,6,9,10], [3,4,8,10], [2,6,7,10], [2,3,5,10], [5,7,8,10], [1,2,5,10], [5,8,9,10], [2,4,9,10], [1,6,8,10], [3,7,9,10], [1,3,7,10], [1,2,3,5,6,10], [4,5,7,8,9,10], [2,3,6,8,9,10], [1,2,4,7,8,10], [1,5,6,8,9,10], [1,2,4,5,9,10], [2,5,6,7,8,10], [2,3,4,5,8,10], [2,4,6,8,9,10], [1,2,4,6,8,10], [1,2,3,7,8,10], [2,3,7,8,9,10], [3,4,5,8,9,10], [1,2,5,6,7,10], [1,4,6,7,9,10], [1,3,4,6,9,10], [1,2,6,8,9,10], [1,2,4,8,9,10], [1,4,7,8,9,10], [1,2,3,6,9,10], [1,2,6,7,8,10], [2,3,4,8,9,10], [1,2,4,6,7,10], [3,4,6,8,9,10], [2,4,5,7,9,10], [1,3,5,6,8,10], [3,4,5,6,9,10], [1,4,5,6,7,10], [1,3,4,5,6,7,8,10], [2,3,4,5,6,7,9,10], [3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,10], [1,2,3,4,5,6,9,10], [1,4,5,6,7,8,9,10], [2,3,4,5,6,8,9,10], [1,2,4,5,6,7,8,10], [1,2,3,4,6,7,9,10], [1,3,4,6,7,8,9,10]] elif powerVal == 11: tap = [[9,11]] elif powerVal == 12: tap = [[6,8,11,12]] elif powerVal == 13: tap = [[9,10,12,13]] elif powerVal == 14: tap = [[4,8,13,14]] elif powerVal == 15: tap = [[14,15]] elif powerVal == 16: tap = [[4,13,15,16]] elif powerVal == 17: tap = [[14,17]] elif powerVal == 18: tap = [[11,18]] elif powerVal == 19: tap = [[14,17,18,19]] elif powerVal == 20: tap = [[17,20]] elif powerVal == 21: tap = [[19,21]] elif powerVal == 22: tap = [[21,22]] elif powerVal == 23: tap = [[18,23]] elif powerVal == 24: tap = [[17,22,23,24]] elif powerVal == 25: tap = [[22,25]] elif powerVal == 26: tap = [[20,24,25,26]] elif powerVal == 27: tap = [[22,25,26,27]] elif powerVal == 28: tap = [[25,28]] elif powerVal == 29: tap = [[27,29]] elif powerVal == 30: tap = [[7,28,29,30]] elif baseVal == 3: if powerVal == 2: tap = [[2,1], [1,1]] elif powerVal == 3: tap = [[0,1,2], [1,0,2], [1,2,2], [2,1,2]] elif powerVal == 4: tap = [[0,0,2,1], [0,0,1,1], [2,0,0,1], [2,2,1,1], [2,1,1,1], [1,0,0,1], [1,2,2,1], [1,1,2,1] ] elif powerVal == 5: tap = [[0,0,0,1,2], [0,0,0,1,2], [0,0,1,2,2], [0,2,1,0,2], [0,2,1,1,2], [0,1,2,0,2], [0,1,1,2,2], [2,0,0,1,2], [2,0,2,0,2], [2,0,2,2,2], [2,2,0,2,2], [2,2,2,1,2], [2,2,1,2,2], [2,1,2,2,2], [2,1,1,0,2], [1,0,0,0,2], [1,0,0,2,2], [1,0,1,1,2], [1,2,2,2,2], [1,1,0,1,2], [1,1,2,0,2]] elif powerVal == 6: tap = [[0,0,0,0,2,1], [0,0,0,0,1,1], [0,0,2,0,2,1], [0,0,1,0,1,1], [0,2,0,1,2,1], [0,2,0,1,1,1], [0,2,2,0,1,1], [0,2,2,2,1,1], [2,1,1,1,0,1], [1,0,0,0,0,1], [1,0,2,1,0,1], [1,0,1,0,0,1], [1,0,1,2,1,1], [1,0,1,1,1,1], [1,2,0,2,2,1], [1,2,0,1,0,1], [1,2,2,1,2,1], [1,2,1,0,1,1], [1,2,1,2,1,1], [1,2,1,1,2,1], [1,1,2,1,0,1], [1,1,1,0,1,1], [1,1,1,2,0,1], [1,1,1,1,1,1] ] elif powerVal == 7: tap = [[0,0,0,0,2,1,2], [0,0,0,0,1,0,2], [0,0,0,2,0,2,2], [0,0,0,2,2,2,2], [0,0,0,2,1,0,2], [0,0,0,1,1,2,2], [0,0,0,1,1,1,2], [0,0,2,2,2,0,2], [0,0,2,2,1,2,2], [0,0,2,1,0,0,2], [0,0,2,1,2,2,2], [0,0,1,0,2,1,2], [0,0,1,0,1,1,2], [0,0,1,1,0,1,2], [0,0,1,1,2,0,2], [0,2,0,0,0,2,2], [0,2,0,0,1,0,2], [0,2,0,0,1,1,2], [0,2,0,2,2,0,2], [0,2,0,2,1,2,2], [0,2,0,1,1,0,2], [0,2,2,0,2,0,2], [0,2,2,0,1,2,2], [0,2,2,2,2,1,2], [0,2,2,2,1,0,2], [0,2,2,1,0,1,2], [0,2,2,1,2,2,2] ] elif baseVal == 5: if powerVal == 2: tap = [[4,3], [3,2], [2,2], [1,3]] elif powerVal == 3: tap = [[0,2,3], [4,1,2], [3,0,2], [3,4,2], [3,3,3], [3,3,2], [3,1,3], [2,0,3], [2,4,3], [2,3,3], [2,3,2], [2,1,2], [1,0,2], [1,4,3], [1,1,3]] elif powerVal == 4: tap = [[0,4,3,3], [0,4,3,2], [0,4,2,3], [0,4,2,2], [0,1,4,3], [0,1,4,2], [0,1,1,3], [0,1,1,2], [4,0,4,2], [4,0,3,2], [4,0,2,3], [4,0,1,3], [4,4,4,2], [4,3,0,3], [4,3,4,3], [4,2,0,2], [4,2,1,3], [4,1,1,2], [3,0,4,2], [3,0,3,3], [3,0,2,2], [3,0,1,3], [3,4,3,2], [3,3,0,2], [3,3,3,3], [3,2,0,3], [3,2,2,3], [3,1,2,2], [2,0,4,3], [2,0,3,2], [2,0,2,3], [2,0,1,2], [2,4,2,2], [2,3,0,2], [2,3,2,3], [2,2,0,3], [2,2,3,3], [2,1,3,2], [1,0,4,3], [1,0,3,3], [1,0,2,2], [1,0,1,2], [1,4,1,2], [1,3,0,3], [1,3,1,3], [1,2,0,2], [1,2,4,3], [1,1,4,2]] elif baseVal == 9: if powerVal == 2: tap = [[1,1]] if not tap: raise ValueError('M-sequence %.0f^%.0f is not defined by this function' % (baseVal, powerVal)) return tap def mseq(baseVal, powerVal, shift=1, whichSeq=None): """Return one of over 200 different M-sequences, for base 2, 3, or 5 items. This is a python translation of Giedrius T. Buracas' matlab implementation (mseq.m). Citation: G.T.Buracas & G.M.Boynton (2002) NeuroImage, 16, 801-813. http://www.ncbi.nlm.nih.gov/pubmed/12169264 """ tap = _get_tap(baseVal, powerVal) # get a list of sequences, select one seq below seq_len = baseVal ** powerVal - 1 ms = numpy.array([0 for i in range(seq_len)]) if not whichSeq: whichSeq = numpy.random.randint(0, len(tap)) else: whichSeq -= 1 # matlab -> python indexing if whichSeq >= len(tap) or whichSeq < 0: whichSeq = whichSeq % len(tap) print('whichSeq wrapped around to %d' % whichSeq) # convert tap -> python numpy array; adjust for python 0-indexing tap_py = numpy.array(tap[whichSeq]) if baseVal == 2: # zeros unless index is in tap weights = numpy.array([int(i+1 in tap_py) for i in range(powerVal)]) elif baseVal > 2: weights = tap_py register = numpy.array([1 for i in range(powerVal)]) for i in range(seq_len): ms[i] = (sum(weights*register) + baseVal) % baseVal register = numpy.append(ms[i], register[:-1]) if shift: shift = shift % len(ms) ms = numpy.append(ms[shift:], ms[:shift]) return numpy.array(ms) def _center(ms, baseVal): if baseVal == 2: ms = ms * 2 - 1 elif baseVal == 3: ms = [-1 if x == 2 else x for x in ms] elif baseVal == 5: ms = [-1 if x == 4 else x for x in ms] ms = [-2 if x == 3 else x for x in ms] else: # baseVal == 9: ms = [-1 if x == 5 else x for x in ms] ms = [-2 if x == 6 else x for x in ms] ms = [-3 if x == 7 else x for x in ms] ms = [-4 if x == 8 else x for x in ms] return ms def _test(): """generate the mseq for most combinations of bases, powers, and sequences, two shift values (only base 9 and 2^9 and higher are skipped). assert that the autocorrelation is acceptably small. prints the first 10 items of the sequence, to allow checking against other implementations. """ print('testing 2,3,5:') powers = {2:list(range(2,9)), 3:list(range(2,8)), 5:list(range(2,5)), 9:[2]} for base in [2,3,5]: for power in powers[base]: tap = _get_tap(base, power) for t in tap: whichSeq = tap.index(t) for shift in [1,4]: ms = mseq(base, power, shift, whichSeq) seq_len = base ** power - 1 print('mseq(%d,%d,%d,%d)' % (base, power, shift, whichSeq), ms[:10], 'len=%d' % seq_len, end='') assert len(ms) == seq_len if seq_len > 10: autocorr_first10 = [numpy.corrcoef(ms, numpy.append(ms[i:], ms[:i]))[1][0] for i in range(1,10)] # for base 3, autocorrelation at offset seq_len / 2 is perfectly correlated max_abs_auto = max(list(map(abs, autocorr_first10))) print("max_abs_autocorr_first10=%.4f < 1/(len-2)" % max_abs_auto) if base == 5 and power == 2: print(' *** skipping assert 5 ^ 2 (fails) ***') else: assert max_abs_auto < 1.0/(seq_len-2) or max_abs_auto < .10 else: print() print('2,3,5 ok; skipped auto-corr for 5^2 (fails on 0.4545); completely skipped 2^%d and higher' % (powers[2][-1] +1)) if __name__ == '__main__': if 'test' in sys.argv: _test() else: try: args = list(map(int, sys.argv[1:])) except Exception: raise ValueError("expected integer arguments: base power [shift [which-sequence]]") print(mseq(*args))
13,213
Python
.py
248
42.282258
123
0.456373
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,640
__init__.py
psychopy_psychopy/psychopy/contrib/configobj/__init__.py
# configobj.py # -*- coding: utf-8 -*- # pylint: disable=bad-continuation """A config file reader/writer that supports nested sections in config files.""" # Copyright (C) 2005-2014: # (name) : (email) # Michael Foord: fuzzyman AT voidspace DOT org DOT uk # Nicola Larosa: nico AT tekNico DOT net # Rob Dennis: rdennis AT gmail DOT com # Eli Courtwright: eli AT courtwright DOT org # This software is licensed under the terms of the BSD license. # http://opensource.org/licenses/BSD-3-Clause # ConfigObj 5 - main repository for documentation and issue tracking: # https://github.com/DiffSK/configobj import os import re import sys import copy from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE try: # Python 3 from collections.abc import Mapping except ImportError: # Python 2.7 from collections import Mapping import six # imported lazily to avoid startup performance hit if it isn't used compiler = None # A dictionary mapping BOM to # the encoding to decode with, and what to set the # encoding attribute to. BOMS = { BOM_UTF8: ('utf_8', None), BOM_UTF16_BE: ('utf16_be', 'utf_16'), BOM_UTF16_LE: ('utf16_le', 'utf_16'), BOM_UTF16: ('utf_16', 'utf_16'), } # All legal variants of the BOM codecs. BOM_LIST = { 'utf_16': 'utf_16', 'utf16': 'utf_16', 'utf-16': 'utf_16', 'utf_16_be': 'utf16_be', 'utf-16be': 'utf16_be', 'utf_16_le': 'utf16_le', 'utf-16le': 'utf16_le', 'utf_8': 'utf_8', 'utf8': 'utf_8', 'utf-8': 'utf_8', 'u16': 'utf_16', # Add mapping for 'u16' 'u8': 'utf_8', # Add mapping for 'u8' } # Add regular expressions for matching variations for encoding in ['utf-16', 'utf-8']: regex = re.compile(fr'{encoding}(?:_|\-)?(?:be|le)?|u16|u8', re.IGNORECASE) for match in filter(regex.fullmatch, BOM_LIST.keys()): BOM_LIST[match] = BOM_LIST[encoding] # Map of encodings to the BOM to write. BOM_SET = { 'utf_8': BOM_UTF8, 'utf_16': BOM_UTF16, 'utf16_be': BOM_UTF16_BE, 'utf16_le': BOM_UTF16_LE, None: BOM_UTF8 } def match_utf8(encoding): return BOM_LIST.get(encoding.lower()) == 'utf_8' # Quote strings used for writing values squot = "'%s'" dquot = '"%s"' noquot = "%s" wspace_plus = ' \r\n\v\t\'"' tsquot = '"""%s"""' tdquot = "'''%s'''" # Sentinel for use in getattr calls to replace hasattr MISSING = object() __all__ = ( 'DEFAULT_INDENT_TYPE', 'DEFAULT_INTERPOLATION', 'ConfigObjError', 'NestingError', 'ParseError', 'DuplicateError', 'ConfigspecError', 'ConfigObj', 'SimpleVal', 'InterpolationError', 'InterpolationLoopError', 'MissingInterpolationOption', 'RepeatSectionError', 'ReloadError', 'UnreprError', 'UnknownType', 'flatten_errors', 'get_extra_values' ) DEFAULT_INTERPOLATION = 'configparser' DEFAULT_INDENT_TYPE = ' ' MAX_INTERPOL_DEPTH = 10 OPTION_DEFAULTS = { 'interpolation': True, 'raise_errors': False, 'list_values': True, 'create_empty': False, 'file_error': False, 'configspec': None, 'stringify': True, # option may be set to one of ('', ' ', '\t') 'indent_type': None, 'encoding': None, 'default_encoding': None, 'unrepr': False, 'write_empty_values': False, } # this could be replaced if six is used for compatibility, or there are no # more assertions about items being a string def getObj(s): global compiler if compiler is None: import compiler s = "a=" + s p = compiler.parse(s) return p.getChildren()[1].getChildren()[0].getChildren()[1] class UnknownType(Exception): pass def unrepr(s): if not s: return s # this is supposed to be safe import ast return ast.literal_eval(s) class ConfigObjError(SyntaxError): """ This is the base class for all errors that ConfigObj raises. It is a subclass of SyntaxError. """ def __init__(self, message='', line_number=None, line=''): self.line = line self.line_number = line_number SyntaxError.__init__(self, message) class NestingError(ConfigObjError): """ This error indicates a level of nesting that doesn't match. """ class ParseError(ConfigObjError): """ This error indicates that a line is badly written. It is neither a valid ``key = value`` line, nor a valid section marker line. """ class ReloadError(IOError): """ A 'reload' operation failed. This exception is a subclass of ``IOError``. """ def __init__(self): IOError.__init__(self, 'reload failed, filename is not set.') class DuplicateError(ConfigObjError): """ The keyword or section specified already exists. """ class ConfigspecError(ConfigObjError): """ An error occurred whilst parsing a configspec. """ class InterpolationError(ConfigObjError): """Base class for the two interpolation errors.""" class InterpolationLoopError(InterpolationError): """Maximum interpolation depth exceeded in string interpolation.""" def __init__(self, option): InterpolationError.__init__( self, 'interpolation loop detected in value "%s".' % option) class RepeatSectionError(ConfigObjError): """ This error indicates additional sections in a section with a ``__many__`` (repeated) section. """ class MissingInterpolationOption(InterpolationError): """A value specified for interpolation was missing.""" def __init__(self, option): msg = 'missing option "%s" in interpolation.' % option InterpolationError.__init__(self, msg) class UnreprError(ConfigObjError): """An error parsing in unrepr mode.""" class InterpolationEngine: """ A helper class to help perform string interpolation. This class is an abstract base class; its descendants perform the actual work. """ # compiled regexp to use in self.interpolate() _KEYCRE = re.compile(r"%\(([^)]*)\)s") _cookie = '%' def __init__(self, section): # the Section instance that "owns" this engine self.section = section def interpolate(self, key, value): # short-cut if not self._cookie in value: return value def recursive_interpolate(key, value, section, backtrail): """The function that does the actual work. ``value``: the string we're trying to interpolate. ``section``: the section in which that string was found ``backtrail``: a dict to keep track of where we've been, to detect and prevent infinite recursion loops This is similar to a depth-first-search algorithm. """ # Have we been here already? if (key, section.name) in backtrail: # Yes - infinite loop detected raise InterpolationLoopError(key) # Place a marker on our backtrail so we won't come back here again backtrail[(key, section.name)] = 1 # Now start the actual work match = self._KEYCRE.search(value) while match: # The actual parsing of the match is implementation-dependent, # so delegate to our helper function k, v, s = self._parse_match(match) if k is None: # That's the signal that no further interpolation is needed replacement = v else: # Further interpolation may be needed to obtain final value replacement = recursive_interpolate(k, v, s, backtrail) # Replace the matched string with its final value start, end = match.span() value = ''.join((value[:start], replacement, value[end:])) new_search_start = start + len(replacement) # Pick up the next interpolation key, if any, for next time # through the while loop match = self._KEYCRE.search(value, new_search_start) # Now safe to come back here again; remove marker from backtrail del backtrail[(key, section.name)] return value # Back in interpolate(), all we have to do is kick off the recursive # function with appropriate starting values value = recursive_interpolate(key, value, self.section, {}) return value def _fetch(self, key): """Helper function to fetch values from owning section. Returns a 2-tuple: the value, and the section where it was found. """ # switch off interpolation before we try and fetch anything ! save_interp = self.section.main.interpolation self.section.main.interpolation = False # Start at section that "owns" this InterpolationEngine current_section = self.section while True: # try the current section first val = current_section.get(key) if val is not None and not isinstance(val, Section): break # try "DEFAULT" next val = current_section.get('DEFAULT', {}).get(key) if val is not None and not isinstance(val, Section): break # move up to parent and try again # top-level's parent is itself if current_section.parent is current_section: # reached top level, time to give up break current_section = current_section.parent # restore interpolation to previous value before returning self.section.main.interpolation = save_interp if val is None: raise MissingInterpolationOption(key) return val, current_section def _parse_match(self, match): """Implementation-dependent helper function. Will be passed a match object corresponding to the interpolation key we just found (e.g., "%(foo)s" or "$foo"). Should look up that key in the appropriate config file section (using the ``_fetch()`` helper function) and return a 3-tuple: (key, value, section) ``key`` is the name of the key we're looking for ``value`` is the value found for that key ``section`` is a reference to the section where it was found ``key`` and ``section`` should be None if no further interpolation should be performed on the resulting value (e.g., if we interpolated "$$" and returned "$"). """ raise NotImplementedError() class ConfigParserInterpolation(InterpolationEngine): """Behaves like ConfigParser.""" _cookie = '%' _KEYCRE = re.compile(r"%\(([^)]*)\)s") def _parse_match(self, match): key = match.group(1) value, section = self._fetch(key) return key, value, section class TemplateInterpolation(InterpolationEngine): """Behaves like string.Template.""" _cookie = '$' _delimiter = '$' _KEYCRE = re.compile(r""" \$(?: (?P<escaped>\$) | # Two $ signs (?P<named>[_a-z][_a-z0-9]*) | # $name format {(?P<braced>[^}]*)} # ${name} format ) """, re.IGNORECASE | re.VERBOSE) def _parse_match(self, match): # Valid name (in or out of braces): fetch value from section key = match.group('named') or match.group('braced') if key is not None: value, section = self._fetch(key) return key, value, section # Escaped delimiter (e.g., $$): return single delimiter if match.group('escaped') is not None: # Return None for key and section to indicate it's time to stop return None, self._delimiter, None # Anything else: ignore completely, just return it unchanged return None, match.group(), None interpolation_engines = { 'configparser': ConfigParserInterpolation, 'template': TemplateInterpolation, } def __newobj__(cls, *args): # Hack for pickle return cls.__new__(cls, *args) class Section(dict): """ A dictionary-like object that represents a section in a config file. It does string interpolation if the 'interpolation' attribute of the 'main' object is set to True. Interpolation is tried first from this object, then from the 'DEFAULT' section of this object, next from the parent and its 'DEFAULT' section, and so on until the main object is reached. A Section will behave like an ordered dictionary - following the order of the ``scalars`` and ``sections`` attributes. You can use this to change the order of members. Iteration follows the order: scalars, then sections. """ def __setstate__(self, state): dict.update(self, state[0]) self.__dict__.update(state[1]) def __reduce__(self): state = (dict(self), self.__dict__) return (__newobj__, (self.__class__,), state) def __init__(self, parent, depth, main, indict=None, name=None): """ * parent is the section above * depth is the depth level of this section * main is the main ConfigObj * indict is a dictionary to initialise the section with """ if indict is None: indict = {} dict.__init__(self) # used for nesting level *and* interpolation self.parent = parent # used for the interpolation attribute self.main = main # level of nesting depth of this Section self.depth = depth # purely for information self.name = name # self._initialise() # we do this explicitly so that __setitem__ is used properly # (rather than just passing to ``dict.__init__``) for entry, value in indict.items(): self[entry] = value def _initialise(self): # the sequence of scalar values in this Section self.scalars = [] # the sequence of sections in this Section self.sections = [] # for comments :-) self.comments = {} self.inline_comments = {} # the configspec self.configspec = None # for defaults self.defaults = [] self.default_values = {} self.extra_values = [] self._created = False def _interpolate(self, key, value): try: # do we already have an interpolation engine? engine = self._interpolation_engine except AttributeError: # not yet: first time running _interpolate(), so pick the engine name = self.main.interpolation if name == True: # note that "if name:" would be incorrect here # backwards-compatibility: interpolation=True means use default name = DEFAULT_INTERPOLATION name = name.lower() # so that "Template", "template", etc. all work class_ = interpolation_engines.get(name, None) if class_ is None: # invalid value for self.main.interpolation self.main.interpolation = False return value else: # save reference to engine so we don't have to do this again engine = self._interpolation_engine = class_(self) # let the engine do the actual work return engine.interpolate(key, value) def __getitem__(self, key): """Fetch the item and do string interpolation.""" # Get the value from a dict as normal val = dict.__getitem__(self, key) if self.main.interpolation: if isinstance(val, six.string_types): return self._interpolate(key, val) if isinstance(val, list): def _check(entry): if isinstance(entry, six.string_types): return self._interpolate(key, entry) return entry new = [_check(entry) for entry in val] if new != val: return new return val def __setitem__(self, key, value, unrepr=False): """ Correctly set a value. Making dictionary values Section instances. (We have to special case 'Section' instances - which are also dicts) Keys must be strings. Values need only be strings (or lists of strings) if ``main.stringify`` is set. ``unrepr`` must be set when setting a value to a dictionary, without creating a new sub-section. """ if not isinstance(key, six.string_types): raise ValueError('The key "%s" is not a string.' % key) # add the comment if key not in self.comments: self.comments[key] = [] self.inline_comments[key] = '' # remove the entry from defaults if key in self.defaults: self.defaults.remove(key) # if isinstance(value, Section): if key not in self: self.sections.append(key) dict.__setitem__(self, key, value) elif isinstance(value, Mapping) and not unrepr: # First create the new depth level, # then create the section if key not in self: self.sections.append(key) new_depth = self.depth + 1 dict.__setitem__( self, key, Section( self, new_depth, self.main, indict=value, name=key)) else: if key not in self: self.scalars.append(key) if not self.main.stringify: if isinstance(value, six.string_types): pass elif isinstance(value, (list, tuple)): for entry in value: if not isinstance(entry, six.string_types): raise TypeError('Value is not a string "%s".' % entry) else: raise TypeError('Value is not a string "%s".' % value) dict.__setitem__(self, key, value) def __delitem__(self, key): """Remove items from the sequence when deleting.""" dict. __delitem__(self, key) if key in self.scalars: self.scalars.remove(key) else: self.sections.remove(key) del self.comments[key] del self.inline_comments[key] def get(self, key, default=None): """A version of ``get`` that doesn't bypass string interpolation.""" try: return self[key] except KeyError: return default def update(self, indict): """ A version of update that uses our ``__setitem__``. """ for entry in indict: self[entry] = indict[entry] def pop(self, key, default=MISSING): """ 'D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised' """ try: val = self[key] except KeyError: if default is MISSING: raise val = default else: del self[key] return val def popitem(self): """Pops the first (key,val)""" sequence = (self.scalars + self.sections) if not sequence: raise KeyError(": 'popitem(): dictionary is empty'") key = sequence[0] val = self[key] del self[key] return key, val def clear(self): """ A version of clear that also affects scalars/sections Also clears comments and configspec. Leaves other attributes alone : depth/main/parent are not affected """ dict.clear(self) self.scalars = [] self.sections = [] self.comments = {} self.inline_comments = {} self.configspec = None self.defaults = [] self.extra_values = [] def setdefault(self, key, default=None): """A version of setdefault that sets sequence if appropriate.""" try: return self[key] except KeyError: self[key] = default return self[key] def items(self): """D.items() -> list of D's (key, value) pairs, as 2-tuples""" return [(key, self[key]) for key in self.keys()] def keys(self): """D.keys() -> list of D's keys""" return self.scalars + self.sections def values(self): """D.values() -> list of D's values""" return [self[key] for key in self.keys()] def iteritems(self): """D.iteritems() -> an iterator over the (key, value) items of D""" return iter(self.items()) def iterkeys(self): """D.iterkeys() -> an iterator over the keys of D""" return iter(self.keys()) __iter__ = iterkeys def itervalues(self): """D.itervalues() -> an iterator over the values of D""" return iter(self.values()) def __repr__(self): """x.__repr__() <==> repr(x)""" def _getval(key): try: return self[key] except MissingInterpolationOption: return dict.__getitem__(self, key) return '{%s}' % ', '.join([('{}: {}'.format(repr(key), repr(_getval(key)))) for key in (self.scalars + self.sections)]) __str__ = __repr__ __str__.__doc__ = "x.__str__() <==> str(x)" # Extra methods - not in a normal dictionary def dict(self): """ Return a deepcopy of self as a dictionary. All members that are ``Section`` instances are recursively turned to ordinary dictionaries - by calling their ``dict`` method. >>> n = a.dict() >>> n == a 1 >>> n is a 0 """ newdict = {} for entry in self: this_entry = self[entry] if isinstance(this_entry, Section): this_entry = this_entry.dict() elif isinstance(this_entry, list): # create a copy rather than a reference this_entry = list(this_entry) elif isinstance(this_entry, tuple): # create a copy rather than a reference this_entry = tuple(this_entry) newdict[entry] = this_entry return newdict def merge(self, indict, decoupled=False): """ A recursive update - useful for merging config files. Note: if ``decoupled`` is ``True``, then the target object (self) gets its own copy of any mutable objects in the source dictionary (both sections and values), paid for by more work for ``merge()`` and more memory usage. >>> a = '''[section1] ... option1 = True ... [[subsection]] ... more_options = False ... # end of file'''.splitlines() >>> b = '''# File is user.ini ... [section1] ... option1 = False ... # end of file'''.splitlines() >>> c1 = ConfigObj(b) >>> c2 = ConfigObj(a) >>> c2.merge(c1) >>> c2 ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}) """ for key, val in indict.items(): if decoupled: val = copy.deepcopy(val) if (key in self and isinstance(self[key], Mapping) and isinstance(val, Mapping)): self[key].merge(val, decoupled=decoupled) else: self[key] = val def rename(self, oldkey, newkey): """ Change a keyname to another, without changing position in sequence. Implemented so that transformations can be made on keys, as well as on values. (used by encode and decode) Also renames comments. """ if oldkey in self.scalars: the_list = self.scalars elif oldkey in self.sections: the_list = self.sections else: raise KeyError('Key "%s" not found.' % oldkey) pos = the_list.index(oldkey) # val = self[oldkey] dict.__delitem__(self, oldkey) dict.__setitem__(self, newkey, val) the_list.remove(oldkey) the_list.insert(pos, newkey) comm = self.comments[oldkey] inline_comment = self.inline_comments[oldkey] del self.comments[oldkey] del self.inline_comments[oldkey] self.comments[newkey] = comm self.inline_comments[newkey] = inline_comment def walk(self, function, raise_errors=True, call_on_sections=False, **keywargs): """ Walk every member and call a function on the keyword and value. Return a dictionary of the return values If the function raises an exception, raise the error unless ``raise_errors=False``, in which case set the return value to ``False``. Any unrecognised keyword arguments you pass to walk, will be passed on to the function you pass in. Note: if ``call_on_sections`` is ``True`` then - on encountering a subsection, *first* the function is called for the *whole* subsection, and then recurses into it's members. This means your function must be able to handle strings, dictionaries and lists. This allows you to change the key of subsections as well as for ordinary members. The return value when called on the whole subsection has to be discarded. See the encode and decode methods for examples, including functions. .. admonition:: caution You can use ``walk`` to transform the names of members of a section but you mustn't add or delete members. >>> config = '''[XXXXsection] ... XXXXkey = XXXXvalue'''.splitlines() >>> cfg = ConfigObj(config) >>> cfg ConfigObj({'XXXXsection': {'XXXXkey': 'XXXXvalue'}}) >>> def transform(section, key): ... val = section[key] ... newkey = key.replace('XXXX', 'CLIENT1') ... section.rename(key, newkey) ... if isinstance(val, (tuple, list, dict)): ... pass ... else: ... val = val.replace('XXXX', 'CLIENT1') ... section[newkey] = val >>> cfg.walk(transform, call_on_sections=True) {'CLIENT1section': {'CLIENT1key': None}} >>> cfg ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}}) """ out = {} # scalars first for i in range(len(self.scalars)): entry = self.scalars[i] try: val = function(self, entry, **keywargs) # bound again in case name has changed entry = self.scalars[i] out[entry] = val except Exception: if raise_errors: raise else: entry = self.scalars[i] out[entry] = False # then sections for i in range(len(self.sections)): entry = self.sections[i] if call_on_sections: try: function(self, entry, **keywargs) except Exception: if raise_errors: raise else: entry = self.sections[i] out[entry] = False # bound again in case name has changed entry = self.sections[i] # previous result is discarded out[entry] = self[entry].walk( function, raise_errors=raise_errors, call_on_sections=call_on_sections, **keywargs) return out def as_bool(self, key): """ Accepts a key as input. The corresponding value must be a string or the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to retain compatibility with Python 2.2. If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns ``True``. If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns ``False``. ``as_bool`` is not case sensitive. Any other input will raise a ``ValueError``. >>> a = ConfigObj() >>> a['a'] = 'fish' >>> a.as_bool('a') Traceback (most recent call last): ValueError: Value "fish" is neither True nor False >>> a['b'] = 'True' >>> a.as_bool('b') 1 >>> a['b'] = 'off' >>> a.as_bool('b') 0 """ val = self[key] if val == True: return True elif val == False: return False else: try: if not isinstance(val, six.string_types): # TODO: Why do we raise a KeyError here? raise KeyError() else: return self.main._bools[val.lower()] except KeyError: raise ValueError('Value "%s" is neither True nor False' % val) def as_int(self, key): """ A convenience method which coerces the specified value to an integer. If the value is an invalid literal for ``int``, a ``ValueError`` will be raised. >>> a = ConfigObj() >>> a['a'] = 'fish' >>> a.as_int('a') Traceback (most recent call last): ValueError: invalid literal for int() with base 10: 'fish' >>> a['b'] = '1' >>> a.as_int('b') 1 >>> a['b'] = '3.2' >>> a.as_int('b') Traceback (most recent call last): ValueError: invalid literal for int() with base 10: '3.2' """ return int(self[key]) def as_float(self, key): """ A convenience method which coerces the specified value to a float. If the value is an invalid literal for ``float``, a ``ValueError`` will be raised. >>> a = ConfigObj() >>> a['a'] = 'fish' >>> a.as_float('a') #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ValueError: invalid literal for float(): fish >>> a['b'] = '1' >>> a.as_float('b') 1.0 >>> a['b'] = '3.2' >>> a.as_float('b') #doctest: +ELLIPSIS 3.2... """ return float(self[key]) def as_list(self, key): """ A convenience method which fetches the specified value, guaranteeing that it is a list. >>> a = ConfigObj() >>> a['a'] = 1 >>> a.as_list('a') [1] >>> a['a'] = (1,) >>> a.as_list('a') [1] >>> a['a'] = [1] >>> a.as_list('a') [1] """ result = self[key] if isinstance(result, (tuple, list)): return list(result) return [result] def restore_default(self, key): """ Restore (and return) default value for the specified key. This method will only work for a ConfigObj that was created with a configspec and has been validated. If there is no default value for this key, ``KeyError`` is raised. """ default = self.default_values[key] dict.__setitem__(self, key, default) if key not in self.defaults: self.defaults.append(key) return default def restore_defaults(self): """ Recursively restore default values to all members that have them. This method will only work for a ConfigObj that was created with a configspec and has been validated. It doesn't delete or modify entries without default values. """ for key in self.default_values: self.restore_default(key) for section in self.sections: self[section].restore_defaults() def _get_triple_quote(value): """Helper for triple-quoting round-trips.""" if ('"""' in value) and ("'''" in value): raise ConfigObjError('Value cannot be safely quoted: {!r}'.format(value)) return tsquot if "'''" in value else tdquot class ConfigObj(Section): """An object to read, create, and write config files.""" MAX_PARSE_ERROR_DETAILS = 5 # Override/append to this class variable for alternative comment markers # TODO: also support inline comments (needs dynamic compiling of the regex below) COMMENT_MARKERS = ['#'] _keyword = re.compile(r'''^ # line start (\s*) # indentation ( # keyword (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'"=].*?) # no quotes ) \s*=\s* # divider (.*) # value (including list values and comments) $ # line end ''', re.VERBOSE) _sectionmarker = re.compile(r'''^ (\s*) # 1: indentation ((?:\[\s*)+) # 2: section marker open ( # 3: section name open (?:"\s*\S.*?\s*")| # at least one non-space with double quotes (?:'\s*\S.*?\s*')| # at least one non-space with single quotes (?:[^'"\s].*?) # at least one non-space unquoted ) # section name close ((?:\s*\])+) # 4: section marker close (\s*(?:\#.*)?)? # 5: optional comment $''', re.VERBOSE) # this regexp pulls list values out as a single string # or single values and comments # FIXME: this regex adds a '' to the end of comma terminated lists # workaround in ``_handle_value`` _valueexp = re.compile(r'''^ (?: (?: ( (?: (?: (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\#][^,\#]*?) # unquoted ) \s*,\s* # comma )* # match all list items ending in a comma (if any) ) ( (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\#\s][^,]*?)| # unquoted (?:(?<!,)) # Empty value )? # last item in a list - or string value )| (,) # alternatively a single comma - empty list ) (\s*(?:\#.*)?)? # optional comment $''', re.VERBOSE) # use findall to get the members of a list value _listvalueexp = re.compile(r''' ( (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\#]?.*?) # unquoted ) \s*,\s* # comma ''', re.VERBOSE) # this regexp is used for the value # when lists are switched off _nolistvalue = re.compile(r'''^ ( (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'"\#].*?)| # unquoted (?:) # Empty value ) (\s*(?:\#.*)?)? # optional comment $''', re.VERBOSE) # regexes for finding triple quoted values on one line _triple_trailer = r"(\s*(?:#.*)?)?$" _single_line_single = re.compile(r"^'''(.*?)'''" + _triple_trailer) _single_line_double = re.compile(r'^"""(.*?)"""' + _triple_trailer) _multi_line_single = re.compile(r"^(.*?)'''" + _triple_trailer) _multi_line_double = re.compile(r'^(.*?)"""' + _triple_trailer) _triple_quote = { "'''": (_single_line_single, _multi_line_single), '"""': (_single_line_double, _multi_line_double), } # Used by the ``istrue`` Section method _bools = { 'yes': True, 'no': False, 'on': True, 'off': False, '1': True, '0': False, 'true': True, 'false': False, } def __init__(self, infile=None, options=None, configspec=None, encoding=None, interpolation=True, raise_errors=False, list_values=True, create_empty=False, file_error=False, stringify=True, indent_type=None, default_encoding=None, unrepr=False, write_empty_values=False, _inspec=False): """ Parse a config file or create a config file object. ``ConfigObj(infile=None, configspec=None, encoding=None, interpolation=True, raise_errors=False, list_values=True, create_empty=False, file_error=False, stringify=True, indent_type=None, default_encoding=None, unrepr=False, write_empty_values=False, _inspec=False)`` """ self._inspec = _inspec # init the superclass Section.__init__(self, self, 0, self) infile = infile or [] _options = {'configspec': configspec, 'encoding': encoding, 'interpolation': interpolation, 'raise_errors': raise_errors, 'list_values': list_values, 'create_empty': create_empty, 'file_error': file_error, 'stringify': stringify, 'indent_type': indent_type, 'default_encoding': default_encoding, 'unrepr': unrepr, 'write_empty_values': write_empty_values} if options is None: options = _options else: import warnings warnings.warn('Passing in an options dictionary to ConfigObj() is ' 'deprecated. Use **options instead.', DeprecationWarning) # TODO: check the values too. for entry in options: if entry not in OPTION_DEFAULTS: raise TypeError('Unrecognised option "%s".' % entry) for entry, value in list(OPTION_DEFAULTS.items()): if entry not in options: options[entry] = value keyword_value = _options[entry] if value != keyword_value: options[entry] = keyword_value # XXXX this ignores an explicit list_values = True in combination # with _inspec. The user should *never* do that anyway, but still... if _inspec: options['list_values'] = False self._initialise(options) configspec = options['configspec'] self._original_configspec = configspec self._load(infile, configspec) def _load(self, infile, configspec): try: infile = infile.__fspath__() except AttributeError: pass if isinstance(infile, six.string_types): self.filename = infile if os.path.isfile(infile): with open(infile, 'rb') as h: content = h.readlines() or [] elif self.file_error: # raise an error if the file doesn't exist raise IOError('Config file not found: "%s".' % self.filename) else: # file doesn't already exist if self.create_empty: # this is a good test that the filename specified # isn't impossible - like on a non-existent device with open(infile, 'w') as h: h.write('') content = [] elif isinstance(infile, (list, tuple)): content = list(infile) elif isinstance(infile, dict): # initialise self # the Section class handles creating subsections if isinstance(infile, ConfigObj): # get a copy of our ConfigObj def set_section(in_section, this_section): for entry in in_section.scalars: this_section[entry] = in_section[entry] for section in in_section.sections: this_section[section] = {} set_section(in_section[section], this_section[section]) set_section(infile, self) else: for entry in infile: self[entry] = infile[entry] del self._errors if configspec is not None: self._handle_configspec(configspec) else: self.configspec = None return elif getattr(infile, 'read', MISSING) is not MISSING: # This supports file like objects content = infile.read() or [] # needs splitting into lines - but needs doing *after* decoding # in case it's not an 8 bit encoding else: raise TypeError('infile must be a path-like object, file like object, or list of lines.') if content: # don't do it for the empty ConfigObj content = self._handle_bom(content) # infile is now *always* a list # # Set the newlines attribute (first line ending it finds) # and strip trailing '\n' or '\r' from lines for line in content: if (not line) or (line[-1] not in ('\r', '\n')): continue for end in ('\r\n', '\n', '\r'): if line.endswith(end): self.newlines = end break break assert all(isinstance(line, six.string_types) for line in content), repr(content) content = [line.rstrip('\r\n') for line in content] self._parse(content) # if we had any errors, now is the time to raise them if self._errors: if len(self._errors) > 1: msg = ["Parsing failed with {} errors.".format(len(self._errors))] for error in self._errors[:self.MAX_PARSE_ERROR_DETAILS]: msg.append(str(error)) if len(self._errors) > self.MAX_PARSE_ERROR_DETAILS: msg.append("{} more error(s)!" .format(len(self._errors) - self.MAX_PARSE_ERROR_DETAILS)) error = ConfigObjError('\n '.join(msg)) else: error = self._errors[0] # set the errors attribute; it's a list of tuples: # (error_type, message, line_number) error.errors = self._errors # set the config attribute error.config = self raise error # delete private attributes del self._errors if configspec is None: self.configspec = None else: self._handle_configspec(configspec) def _initialise(self, options=None): if options is None: options = OPTION_DEFAULTS # initialise a few variables self.filename = None self._errors = [] self.raise_errors = options['raise_errors'] self.interpolation = options['interpolation'] self.list_values = options['list_values'] self.create_empty = options['create_empty'] self.file_error = options['file_error'] self.stringify = options['stringify'] self.indent_type = options['indent_type'] self.encoding = options['encoding'] self.default_encoding = options['default_encoding'] self.BOM = False self.newlines = None self.write_empty_values = options['write_empty_values'] self.unrepr = options['unrepr'] self.initial_comment = [] self.final_comment = [] self.configspec = None if self._inspec: self.list_values = False # Clear section attributes as well Section._initialise(self) def __repr__(self): def _getval(key): try: return self[key] except MissingInterpolationOption: return dict.__getitem__(self, key) return ('{}({{{}}})'.format(self.__class__.__name__, ', '.join([('{}: {}'.format(repr(key), repr(_getval(key)))) for key in (self.scalars + self.sections)]))) def _handle_bom(self, infile): """ Handle any BOM, and decode if necessary. If an encoding is specified, that *must* be used - but the BOM should still be removed (and the BOM attribute set). (If the encoding is wrongly specified, then a BOM for an alternative encoding won't be discovered or removed.) If an encoding is not specified, UTF8 or UTF16 BOM will be detected and removed. The BOM attribute will be set. UTF16 will be decoded to unicode. NOTE: This method must not be called with an empty ``infile``. Specifying the *wrong* encoding is likely to cause a ``UnicodeDecodeError``. ``infile`` must always be returned as a list of lines, but may be passed in as a single string. """ if ((self.encoding is not None) and (self.encoding.lower() not in BOM_LIST)): # No need to check for a BOM # the encoding specified doesn't have one # just decode return self._decode(infile, self.encoding) if isinstance(infile, (list, tuple)): line = infile[0] else: line = infile if isinstance(line, six.text_type): # it's already decoded and there's no need to do anything # else, just use the _decode utility method to handle # listifying appropriately return self._decode(infile, self.encoding) if self.encoding is not None: # encoding explicitly supplied # And it could have an associated BOM # TODO: if encoding is just UTF16 - we ought to check for both # TODO: big endian and little endian versions. enc = BOM_LIST[self.encoding.lower()] if enc == 'utf_16': # For UTF16 we try big endian and little endian for BOM, (encoding, final_encoding) in list(BOMS.items()): if not final_encoding: # skip UTF8 continue if infile.startswith(BOM): ### BOM discovered ##self.BOM = True # Don't need to remove BOM return self._decode(infile, encoding) # If we get this far, will *probably* raise a DecodeError # As it doesn't appear to start with a BOM return self._decode(infile, self.encoding) # Must be UTF8 BOM = BOM_SET[enc] if not line.startswith(BOM): return self._decode(infile, self.encoding) newline = line[len(BOM):] # BOM removed if isinstance(infile, (list, tuple)): infile[0] = newline else: infile = newline self.BOM = True return self._decode(infile, self.encoding) # No encoding specified - so we need to check for UTF8/UTF16 for BOM, (encoding, final_encoding) in list(BOMS.items()): if not isinstance(line, six.binary_type) or not line.startswith(BOM): # didn't specify a BOM, or it's not a bytestring continue else: # BOM discovered self.encoding = final_encoding if not final_encoding: self.BOM = True # UTF8 # remove BOM newline = line[len(BOM):] if isinstance(infile, (list, tuple)): infile[0] = newline else: infile = newline # UTF-8 if isinstance(infile, six.text_type): return infile.splitlines(True) elif isinstance(infile, six.binary_type): return infile.decode('utf-8').splitlines(True) else: return self._decode(infile, 'utf-8') # UTF16 - have to decode return self._decode(infile, encoding) if six.PY2 and isinstance(line, str): # don't actually do any decoding, since we're on python 2 and # returning a bytestring is fine return self._decode(infile, None) # No BOM discovered and no encoding specified, default to UTF-8 if isinstance(infile, six.binary_type): return infile.decode('utf-8').splitlines(True) else: return self._decode(infile, 'utf-8') def _decode(self, infile, encoding): """ Decode infile to unicode. Using the specified encoding. if is a string, it also needs converting to a list. """ if isinstance(infile, six.binary_type): # NOTE: Could raise a ``UnicodeDecodeError`` if encoding: return infile.decode(encoding).splitlines(True) else: return infile.splitlines(True) if isinstance(infile, six.string_types): return infile.splitlines(True) if encoding: for i, line in enumerate(infile): if isinstance(line, six.binary_type): # NOTE: The isinstance test here handles mixed lists of unicode/string # NOTE: But the decode will break on any non-string values # NOTE: Or could raise a ``UnicodeDecodeError`` infile[i] = line.decode(encoding) return infile def _decode_element(self, line): """Decode element to unicode if necessary.""" if isinstance(line, six.binary_type) and self.default_encoding: return line.decode(self.default_encoding) else: return line # TODO: this may need to be modified def _str(self, value): """ Used by ``stringify`` within validate, to turn non-string values into strings. """ if not isinstance(value, six.string_types): # intentionally 'str' because it's just whatever the "normal" # string type is for the python version we're dealing with return str(value) else: return value def _parse(self, infile): """Actually parse the config file.""" temp_list_values = self.list_values if self.unrepr: self.list_values = False comment_list = [] done_start = False this_section = self maxline = len(infile) - 1 cur_index = -1 reset_comment = False comment_markers = tuple(self.COMMENT_MARKERS) while cur_index < maxline: if reset_comment: comment_list = [] cur_index += 1 line = infile[cur_index] sline = line.strip() # do we have anything on the line ? if not sline or sline.startswith(comment_markers): reset_comment = False comment_list.append(line) continue if not done_start: # preserve initial comment self.initial_comment = comment_list comment_list = [] done_start = True reset_comment = True # first we check if it's a section marker mat = self._sectionmarker.match(line) if mat is not None: # is a section line (indent, sect_open, sect_name, sect_close, comment) = mat.groups() if indent and (self.indent_type is None): self.indent_type = indent cur_depth = sect_open.count('[') if cur_depth != sect_close.count(']'): self._handle_error("Cannot compute the section depth", NestingError, infile, cur_index) continue if cur_depth < this_section.depth: # the new section is dropping back to a previous level try: parent = self._match_depth(this_section, cur_depth).parent except SyntaxError: self._handle_error("Cannot compute nesting level", NestingError, infile, cur_index) continue elif cur_depth == this_section.depth: # the new section is a sibling of the current section parent = this_section.parent elif cur_depth == this_section.depth + 1: # the new section is a child the current section parent = this_section else: self._handle_error("Section too nested", NestingError, infile, cur_index) continue sect_name = self._unquote(sect_name) if sect_name in parent: self._handle_error('Duplicate section name', DuplicateError, infile, cur_index) continue # create the new section this_section = Section( parent, cur_depth, self, name=sect_name) parent[sect_name] = this_section parent.inline_comments[sect_name] = comment parent.comments[sect_name] = comment_list continue # # it's not a section marker, # so it should be a valid ``key = value`` line mat = self._keyword.match(line) if mat is None: self._handle_error( 'Invalid line ({!r}) (matched as neither section nor keyword)'.format(line), ParseError, infile, cur_index) else: # is a keyword value # value will include any inline comment (indent, key, value) = mat.groups() if indent and (self.indent_type is None): self.indent_type = indent # check for a multiline value if value[:3] in ['"""', "'''"]: try: value, comment, cur_index = self._multiline( value, infile, cur_index, maxline) except SyntaxError: self._handle_error( 'Parse error in multiline value', ParseError, infile, cur_index) continue else: if self.unrepr: comment = '' try: value = unrepr(value) except Exception as cause: if isinstance(cause, UnknownType): msg = 'Unknown name or type in value' else: msg = 'Parse error from unrepr-ing multiline value' self._handle_error(msg, UnreprError, infile, cur_index) continue else: if self.unrepr: comment = '' try: value = unrepr(value) except Exception as cause: if isinstance(cause, UnknownType): msg = 'Unknown name or type in value' else: msg = 'Parse error from unrepr-ing value' self._handle_error(msg, UnreprError, infile, cur_index) continue else: # extract comment and lists try: (value, comment) = self._handle_value(value) except SyntaxError: self._handle_error( 'Parse error in value', ParseError, infile, cur_index) continue # key = self._unquote(key) if key in this_section: self._handle_error( 'Duplicate keyword name', DuplicateError, infile, cur_index) continue # add the key. # we set unrepr because if we have got this far we will never # be creating a new section this_section.__setitem__(key, value, unrepr=True) this_section.inline_comments[key] = comment this_section.comments[key] = comment_list continue # if self.indent_type is None: # no indentation used, set the type accordingly self.indent_type = '' # preserve the final comment if not self and not self.initial_comment: self.initial_comment = comment_list elif not reset_comment: self.final_comment = comment_list self.list_values = temp_list_values def _match_depth(self, sect, depth): """ Given a section and a depth level, walk back through the sections parents to see if the depth level matches a previous section. Return a reference to the right section, or raise a SyntaxError. """ while depth < sect.depth: if sect is sect.parent: # we've reached the top level already raise SyntaxError() sect = sect.parent if sect.depth == depth: return sect # shouldn't get here raise SyntaxError() def _handle_error(self, text, ErrorClass, infile, cur_index): """ Handle an error according to the error settings. Either raise the error or store it. The error will have occurred at ``cur_index`` """ line = infile[cur_index] cur_index += 1 message = '{} at line {}.'.format(text, cur_index) error = ErrorClass(message, cur_index, line) if self.raise_errors: # raise the error - parsing stops here raise error # store the error # reraise when parsing has finished self._errors.append(error) def _unquote(self, value): """Return an unquoted version of a value""" if not value: # should only happen during parsing of lists raise SyntaxError if (value[0] == value[-1]) and (value[0] in ('"', "'")): value = value[1:-1] return value def _quote(self, value, multiline=True): """ Return a safely quoted version of a value. Raise a ConfigObjError if the value cannot be safely quoted. If multiline is ``True`` (default) then use triple quotes if necessary. * Don't quote values that don't need it. * Recursively quote members of a list and return a comma joined list. * Multiline is ``False`` for lists. * Obey list syntax for empty and single member lists. If ``list_values=False`` then the value is only quoted if it contains a ``\\n`` (is multiline) or '#'. If ``write_empty_values`` is set, and the value is an empty string, it won't be quoted. """ if multiline and self.write_empty_values and value == '': # Only if multiline is set, so that it is used for values not # keys, and not values that are part of a list return '' if multiline and isinstance(value, (list, tuple)): if not value: return ',' elif len(value) == 1: return self._quote(value[0], multiline=False) + ',' return ', '.join([self._quote(val, multiline=False) for val in value]) if not isinstance(value, six.string_types): if self.stringify: # intentionally 'str' because it's just whatever the "normal" # string type is for the python version we're dealing with value = str(value) else: raise TypeError('Value "%s" is not a string.' % value) if not value: return '""' no_lists_no_quotes = not self.list_values and '\n' not in value and '#' not in value need_triple = multiline and ((("'" in value) and ('"' in value)) or ('\n' in value )) hash_triple_quote = multiline and not need_triple and ("'" in value) and ('"' in value) and ('#' in value) check_for_single = (no_lists_no_quotes or not need_triple) and not hash_triple_quote if check_for_single: if not self.list_values: # we don't quote if ``list_values=False`` quot = noquot # for normal values either single or double quotes will do elif '\n' in value: # will only happen if multiline is off - e.g. '\n' in key raise ConfigObjError('Value cannot be safely quoted: {!r}'.format(value)) elif ((value[0] not in wspace_plus) and (value[-1] not in wspace_plus) and (',' not in value)): quot = noquot else: quot = self._get_single_quote(value) else: # if value has '\n' or "'" *and* '"', it will need triple quotes quot = _get_triple_quote(value) if quot == noquot and '#' in value and self.list_values: quot = self._get_single_quote(value) return quot % value def _get_single_quote(self, value): if ("'" in value) and ('"' in value): raise ConfigObjError('Value cannot be safely quoted: {!r}'.format(value)) elif '"' in value: quot = squot else: quot = dquot return quot def _handle_value(self, value): """ Given a value string, unquote, remove comment, handle lists. (including empty and single member lists) """ if self._inspec: # Parsing a configspec so don't handle comments return (value, '') # do we look for lists in values ? if not self.list_values: mat = self._nolistvalue.match(value) if mat is None: raise SyntaxError() # NOTE: we don't unquote here return mat.groups() # mat = self._valueexp.match(value) if mat is None: # the value is badly constructed, probably badly quoted, # or an invalid list raise SyntaxError() (list_values, single, empty_list, comment) = mat.groups() if (list_values == '') and (single is None): # change this if you want to accept empty values raise SyntaxError() # NOTE: note there is no error handling from here if the regex # is wrong: then incorrect values will slip through if empty_list is not None: # the single comma - meaning an empty list return ([], comment) if single is not None: # handle empty values if list_values and not single: # FIXME: the '' is a workaround because our regex now matches # '' at the end of a list if it has a trailing comma single = None else: single = single or '""' single = self._unquote(single) if list_values == '': # not a list value return (single, comment) the_list = self._listvalueexp.findall(list_values) the_list = [self._unquote(val) for val in the_list] if single is not None: the_list += [single] return (the_list, comment) def _multiline(self, value, infile, cur_index, maxline): """Extract the value, where we are in a multiline situation.""" quot = value[:3] newvalue = value[3:] single_line = self._triple_quote[quot][0] multi_line = self._triple_quote[quot][1] mat = single_line.match(value) if mat is not None: retval = list(mat.groups()) retval.append(cur_index) return retval elif newvalue.find(quot) != -1: # somehow the triple quote is missing raise SyntaxError() # while cur_index < maxline: cur_index += 1 newvalue += '\n' line = infile[cur_index] if line.find(quot) == -1: newvalue += line else: # end of multiline, process it break else: # we've got to the end of the config, oops... raise SyntaxError() mat = multi_line.match(line) if mat is None: # a badly formed line raise SyntaxError() (value, comment) = mat.groups() return (newvalue + value, comment, cur_index) def _handle_configspec(self, configspec): """Parse the configspec.""" # FIXME: Should we check that the configspec was created with the # correct settings ? (i.e. ``list_values=False``) if not isinstance(configspec, ConfigObj): try: configspec = ConfigObj(configspec, raise_errors=True, file_error=True, _inspec=True) except ConfigObjError as cause: # FIXME: Should these errors have a reference # to the already parsed ConfigObj ? raise ConfigspecError('Parsing configspec failed: %s' % cause) except IOError as cause: raise IOError('Reading configspec failed: %s' % cause) self.configspec = configspec def _set_configspec(self, section, copy): """ Called by validate. Handles setting the configspec on subsections including sections to be validated by __many__ """ configspec = section.configspec many = configspec.get('__many__') if isinstance(many, dict): for entry in section.sections: if entry not in configspec: section[entry].configspec = many for entry in configspec.sections: if entry == '__many__': continue if entry not in section: section[entry] = {} section[entry]._created = True if copy: # copy comments section.comments[entry] = configspec.comments.get(entry, []) section.inline_comments[entry] = configspec.inline_comments.get(entry, '') # Could be a scalar when we expect a section if isinstance(section[entry], Section): section[entry].configspec = configspec[entry] def _write_line(self, indent_string, entry, this_entry, comment): """Write an individual line, for the write method""" # NOTE: the calls to self._quote here handles non-StringType values. if not self.unrepr: val = self._decode_element(self._quote(this_entry)) else: val = repr(this_entry) return '%s%s%s%s%s' % (indent_string, self._decode_element(self._quote(entry, multiline=False)), ' = ', val, self._decode_element(comment)) def _write_marker(self, indent_string, depth, entry, comment): """Write a section marker line""" entry_str = self._decode_element(entry) title = self._quote(entry_str, multiline=False) if entry_str and title[0] in '\'"' and title[1:-1] == entry_str: # titles are in '[]' already, so quoting for contained quotes is not necessary (#74) title = entry_str return '%s%s%s%s%s' % (indent_string, '[' * depth, title, ']' * depth, self._decode_element(comment)) def _handle_comment(self, comment): """Deal with a comment.""" if not comment.strip(): return comment or '' # return trailing whitespace as-is start = self.indent_type if not comment.lstrip().startswith('#'): start += ' # ' return (start + comment) # Public methods def write(self, outfile=None, section=None): """ Write the current ConfigObj as a file tekNico: FIXME: use StringIO instead of real files >>> filename = a.filename >>> a.filename = 'test.ini' >>> a.write() >>> a.filename = filename >>> a == ConfigObj('test.ini', raise_errors=True) 1 >>> import os >>> os.remove('test.ini') """ if self.indent_type is None: # this can be true if initialised from a dictionary self.indent_type = DEFAULT_INDENT_TYPE out = [] comment_markers = tuple(self.COMMENT_MARKERS) comment_marker_default = comment_markers[0] + ' ' if section is None: int_val = self.interpolation self.interpolation = False section = self for line in self.initial_comment: line = self._decode_element(line) stripped_line = line.strip() if stripped_line and not stripped_line.startswith(comment_markers): line = comment_marker_default + line out.append(line) indent_string = self.indent_type * section.depth for entry in (section.scalars + section.sections): if entry in section.defaults: # don't write out default values continue for comment_line in section.comments[entry]: comment_line = self._decode_element(comment_line.lstrip()) if comment_line and not comment_line.startswith(comment_markers): comment_line = comment_marker_default + comment_line out.append(indent_string + comment_line) this_entry = section[entry] comment = self._handle_comment(section.inline_comments[entry]) if isinstance(this_entry, Section): # a section out.append(self._write_marker( indent_string, this_entry.depth, entry, comment)) out.extend(self.write(section=this_entry)) else: out.append(self._write_line( indent_string, entry, this_entry, comment)) if section is self: for line in self.final_comment: line = self._decode_element(line) stripped_line = line.strip() if stripped_line and not stripped_line.startswith(comment_markers): line = comment_marker_default + line out.append(line) self.interpolation = int_val if section is not self: return out if (self.filename is None) and (outfile is None): # output a list of lines # might need to encode # NOTE: This will *screw* UTF16, each line will start with the BOM if self.encoding: out = [l.encode(self.encoding) for l in out] if (self.BOM and ((self.encoding is None) or (BOM_LIST.get(self.encoding.lower()) == 'utf_8'))): # Add the UTF8 BOM if not out: out.append('') out[0] = BOM_UTF8 + out[0] return out # Turn the list to a string, joined with correct newlines newline = self.newlines or os.linesep if (getattr(outfile, 'mode', None) is not None and outfile.mode == 'w' and sys.platform == 'win32' and newline == '\r\n'): # Windows specific hack to avoid writing '\r\r\n' newline = '\n' output = newline.join(out) if not output.endswith(newline): output += newline if isinstance(output, six.binary_type): output_bytes = output else: output_bytes = output.encode(self.encoding or self.default_encoding or 'ascii') if self.BOM and ((self.encoding is None) or match_utf8(self.encoding)): # Add the UTF8 BOM output_bytes = BOM_UTF8 + output_bytes if outfile is not None: outfile.write(output_bytes) else: with open(self.filename, 'wb') as h: h.write(output_bytes) def validate(self, validator, preserve_errors=False, copy=False, section=None): """ Test the ConfigObj against a configspec. It uses the ``validator`` object from *validate.py*. To run ``validate`` on the current ConfigObj, call: :: test = config.validate(validator) (Normally having previously passed in the configspec when the ConfigObj was created - you can dynamically assign a dictionary of checks to the ``configspec`` attribute of a section though). It returns ``True`` if everything passes, or a dictionary of pass/fails (True/False). If every member of a subsection passes, it will just have the value ``True``. (It also returns ``False`` if all members fail). In addition, it converts the values from strings to their native types if their checks pass (and ``stringify`` is set). If ``preserve_errors`` is ``True`` (``False`` is default) then instead of a marking a fail with a ``False``, it will preserve the actual exception object. This can contain info about the reason for failure. For example the ``VdtValueTooSmallError`` indicates that the value supplied was too small. If a value (or section) is missing it will still be marked as ``False``. You must have the validate module to use ``preserve_errors=True``. You can then use the ``flatten_errors`` function to turn your nested results dictionary into a flattened list of failures - useful for displaying meaningful error messages. """ if section is None: if self.configspec is None: raise ValueError('No configspec supplied.') if preserve_errors: # We do this once to remove a top level dependency on the validate module # Which makes importing configobj faster from .validate import VdtMissingValue self._vdtMissingValue = VdtMissingValue section = self if copy: section.initial_comment = section.configspec.initial_comment section.final_comment = section.configspec.final_comment section.encoding = section.configspec.encoding section.BOM = section.configspec.BOM section.newlines = section.configspec.newlines section.indent_type = section.configspec.indent_type # # section.default_values.clear() #?? configspec = section.configspec self._set_configspec(section, copy) def validate_entry(entry, spec, val, missing, ret_true, ret_false): section.default_values.pop(entry, None) try: section.default_values[entry] = validator.get_default_value(configspec[entry]) except (KeyError, AttributeError, validator.baseErrorClass): # No default, bad default or validator has no 'get_default_value' # (e.g. SimpleVal) pass try: check = validator.check(spec, val, missing=missing ) except validator.baseErrorClass as cause: if not preserve_errors or isinstance(cause, self._vdtMissingValue): out[entry] = False else: # preserve the error out[entry] = cause ret_false = False ret_true = False else: ret_false = False out[entry] = True if self.stringify or missing: # if we are doing type conversion # or the value is a supplied default if not self.stringify: if isinstance(check, (list, tuple)): # preserve lists check = [self._str(item) for item in check] elif missing and check is None: # convert the None from a default to a '' check = '' else: check = self._str(check) if (check != val) or missing: section[entry] = check if not copy and missing and entry not in section.defaults: section.defaults.append(entry) return ret_true, ret_false # out = {} ret_true = True ret_false = True unvalidated = [k for k in section.scalars if k not in configspec] incorrect_sections = [k for k in configspec.sections if k in section.scalars] incorrect_scalars = [k for k in configspec.scalars if k in section.sections] for entry in configspec.scalars: if entry in ('__many__', '___many___'): # reserved names continue if (not entry in section.scalars) or (entry in section.defaults): # missing entries # or entries from defaults missing = True val = None if copy and entry not in section.scalars: # copy comments section.comments[entry] = ( configspec.comments.get(entry, [])) section.inline_comments[entry] = ( configspec.inline_comments.get(entry, '')) # else: missing = False val = section[entry] ret_true, ret_false = validate_entry(entry, configspec[entry], val, missing, ret_true, ret_false) many = None if '__many__' in configspec.scalars: many = configspec['__many__'] elif '___many___' in configspec.scalars: many = configspec['___many___'] if many is not None: for entry in unvalidated: val = section[entry] ret_true, ret_false = validate_entry(entry, many, val, False, ret_true, ret_false) unvalidated = [] for entry in incorrect_scalars: ret_true = False if not preserve_errors: out[entry] = False else: ret_false = False msg = 'Value %r was provided as a section' % entry out[entry] = validator.baseErrorClass(msg) for entry in incorrect_sections: ret_true = False if not preserve_errors: out[entry] = False else: ret_false = False msg = 'Section %r was provided as a single value' % entry out[entry] = validator.baseErrorClass(msg) # Missing sections will have been created as empty ones when the # configspec was read. for entry in section.sections: # FIXME: this means DEFAULT is not copied in copy mode if section is self and entry == 'DEFAULT': continue if section[entry].configspec is None: unvalidated.append(entry) continue if copy: section.comments[entry] = configspec.comments.get(entry, []) section.inline_comments[entry] = configspec.inline_comments.get(entry, '') check = self.validate(validator, preserve_errors=preserve_errors, copy=copy, section=section[entry]) out[entry] = check if check == False: ret_true = False elif check == True: ret_false = False else: ret_true = False section.extra_values = unvalidated if preserve_errors and not section._created: # If the section wasn't created (i.e. it wasn't missing) # then we can't return False, we need to preserve errors ret_false = False # if ret_false and preserve_errors and out: # If we are preserving errors, but all # the failures are from missing sections / values # then we can return False. Otherwise there is a # real failure that we need to preserve. ret_false = not any(out.values()) if ret_true: return True elif ret_false: return False return out def reset(self): """Clear ConfigObj instance and restore to 'freshly created' state.""" self.clear() self._initialise() # FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload) # requires an empty dictionary self.configspec = None # Just to be sure ;-) self._original_configspec = None def reload(self): """ Reload a ConfigObj from file. This method raises a ``ReloadError`` if the ConfigObj doesn't have a filename attribute pointing to a file. """ if not isinstance(self.filename, six.string_types): raise ReloadError() filename = self.filename current_options = {} for entry in OPTION_DEFAULTS: if entry == 'configspec': continue current_options[entry] = getattr(self, entry) configspec = self._original_configspec current_options['configspec'] = configspec self.clear() self._initialise(current_options) self._load(filename, configspec) class SimpleVal: """ A simple validator. Can be used to check that all members expected are present. To use it, provide a configspec with all your members in (the value given will be ignored). Pass an instance of ``SimpleVal`` to the ``validate`` method of your ``ConfigObj``. ``validate`` will return ``True`` if all members are present, or a dictionary with True/False meaning present/missing. (Whole missing sections will be replaced with ``False``) """ def __init__(self): self.baseErrorClass = ConfigObjError def check(self, check, member, missing=False): """A dummy check method, always returns the value unchanged.""" if missing: raise self.baseErrorClass() return member def flatten_errors(cfg, res, levels=None, results=None): """ An example function that will turn a nested dictionary of results (as returned by ``ConfigObj.validate``) into a flat list. ``cfg`` is the ConfigObj instance being checked, ``res`` is the results dictionary returned by ``validate``. (This is a recursive function, so you shouldn't use the ``levels`` or ``results`` arguments - they are used by the function.) Returns a list of keys that failed. Each member of the list is a tuple:: ([list of sections...], key, result) If ``validate`` was called with ``preserve_errors=False`` (the default) then ``result`` will always be ``False``. *list of sections* is a flattened list of sections that the key was found in. If the section was missing (or a section was expected and a scalar provided - or vice-versa) then key will be ``None``. If the value (or section) was missing then ``result`` will be ``False``. If ``validate`` was called with ``preserve_errors=True`` and a value was present, but failed the check, then ``result`` will be the exception object returned. You can use this as a string that describes the failure. For example *The value "3" is of the wrong type*. """ if levels is None: # first time called levels = [] results = [] if res == True: return sorted(results) if res == False or isinstance(res, Exception): results.append((levels[:], None, res)) if levels: levels.pop() return sorted(results) for (key, val) in list(res.items()): if val == True: continue if isinstance(cfg.get(key), Mapping): # Go down one level levels.append(key) flatten_errors(cfg[key], val, levels, results) continue results.append((levels[:], key, val)) # # Go up one level if levels: levels.pop() # return sorted(results) def get_extra_values(conf, _prepend=()): """ Find all the values and sections not in the configspec from a validated ConfigObj. ``get_extra_values`` returns a list of tuples where each tuple represents either an extra section, or an extra value. The tuples contain two values, a tuple representing the section the value is in and the name of the extra values. For extra values in the top level section the first member will be an empty tuple. For values in the 'foo' section the first member will be ``('foo',)``. For members in the 'bar' subsection of the 'foo' section the first member will be ``('foo', 'bar')``. NOTE: If you call ``get_extra_values`` on a ConfigObj instance that hasn't been validated it will return an empty list. """ out = [] out.extend([(_prepend, name) for name in conf.extra_values]) for name in conf.sections: if name not in conf.extra_values: out.extend(get_extra_values(conf[name], _prepend + (name,))) return out """*A programming language is a medium of expression.* - Paul Graham"""
88,180
Python
.py
2,068
30.661025
114
0.546842
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,641
validate.py
psychopy_psychopy/psychopy/contrib/configobj/validate.py
# validate.py # -*- coding: utf-8 -*- # pylint: disable= # # A Validator object. # # Copyright (C) 2005-2014: # (name) : (email) # Michael Foord: fuzzyman AT voidspace DOT org DOT uk # Mark Andrews: mark AT la-la DOT com # Nicola Larosa: nico AT tekNico DOT net # Rob Dennis: rdennis AT gmail DOT com # Eli Courtwright: eli AT courtwright DOT org # This software is licensed under the terms of the BSD license. # http://opensource.org/licenses/BSD-3-Clause # ConfigObj 5 - main repository for documentation and issue tracking: # https://github.com/DiffSK/configobj """ The Validator object is used to check that supplied values conform to a specification. The value can be supplied as a string - e.g. from a config file. In this case the check will also *convert* the value to the required type. This allows you to add validation as a transparent layer to access data stored as strings. The validation checks that the data is correct *and* converts it to the expected type. Some standard checks are provided for basic data types. Additional checks are easy to write. They can be provided when the ``Validator`` is instantiated or added afterwards. The standard functions work with the following basic data types : * integers * floats * booleans * strings * ip_addr plus lists of these datatypes Adding additional checks is done through coding simple functions. The full set of standard checks are : * 'integer': matches integer values (including negative) Takes optional 'min' and 'max' arguments : :: integer() integer(3, 9) # any value from 3 to 9 integer(min=0) # any positive value integer(max=9) * 'float': matches float values Has the same parameters as the integer check. * 'boolean': matches boolean values - ``True`` or ``False`` Acceptable string values for True are : true, on, yes, 1 Acceptable string values for False are : false, off, no, 0 Any other value raises an error. * 'ip_addr': matches an Internet Protocol address, v.4, represented by a dotted-quad string, i.e. '1.2.3.4'. * 'string': matches any string. Takes optional keyword args 'min' and 'max' to specify min and max lengths of the string. * 'list': matches any list. Takes optional keyword args 'min', and 'max' to specify min and max sizes of the list. (Always returns a list.) * 'tuple': matches any tuple. Takes optional keyword args 'min', and 'max' to specify min and max sizes of the tuple. (Always returns a tuple.) * 'int_list': Matches a list of integers. Takes the same arguments as list. * 'float_list': Matches a list of floats. Takes the same arguments as list. * 'bool_list': Matches a list of boolean values. Takes the same arguments as list. * 'ip_addr_list': Matches a list of IP addresses. Takes the same arguments as list. * 'string_list': Matches a list of strings. Takes the same arguments as list. * 'mixed_list': Matches a list with different types in specific positions. List size must match the number of arguments. Each position can be one of : 'integer', 'float', 'ip_addr', 'string', 'boolean' So to specify a list with two strings followed by two integers, you write the check as : :: mixed_list('string', 'string', 'integer', 'integer') * 'pass': This check matches everything ! It never fails and the value is unchanged. It is also the default if no check is specified. * 'option': This check matches any from a list of options. You specify this check with : :: option('option 1', 'option 2', 'option 3') You can supply a default value (returned if no value is supplied) using the default keyword argument. You specify a list argument for default using a list constructor syntax in the check : :: checkname(arg1, arg2, default=list('val 1', 'val 2', 'val 3')) A badly formatted set of arguments will raise a ``VdtParamError``. """ import re import sys from pprint import pprint __version__ = '1.0.1' __all__ = ( 'dottedQuadToNum', 'numToDottedQuad', 'ValidateError', 'VdtUnknownCheckError', 'VdtParamError', 'VdtTypeError', 'VdtValueError', 'VdtValueTooSmallError', 'VdtValueTooBigError', 'VdtValueTooShortError', 'VdtValueTooLongError', 'VdtMissingValue', 'Validator', 'is_integer', 'is_float', 'is_boolean', 'is_list', 'is_tuple', 'is_ip_addr', 'is_string', 'is_int_list', 'is_bool_list', 'is_float_list', 'is_string_list', 'is_ip_addr_list', 'is_mixed_list', 'is_option', # '__docformat__', -- where is this supposed to come from? [jhe 2015-04-11] ) _list_arg = re.compile(r''' (?: ([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*list\( ( (?: \s* (?: (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\s\)][^,\)]*?) # unquoted ) \s*,\s* )* (?: (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\s\)][^,\)]*?) # unquoted )? # last one ) \) ) ''', re.VERBOSE | re.DOTALL) # two groups _list_members = re.compile(r''' ( (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\s=][^,=]*?) # unquoted ) (?: (?:\s*,\s*)|(?:\s*$) # comma ) ''', re.VERBOSE | re.DOTALL) # one group _paramstring = r''' (?: ( (?: [a-zA-Z_][a-zA-Z0-9_]*\s*=\s*list\( (?: \s* (?: (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\s\)][^,\)]*?) # unquoted ) \s*,\s* )* (?: (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\s\)][^,\)]*?) # unquoted )? # last one \) )| (?: (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\s=][^,=]*?)| # unquoted (?: # keyword argument [a-zA-Z_][a-zA-Z0-9_]*\s*=\s* (?: (?:".*?")| # double quotes (?:'.*?')| # single quotes (?:[^'",\s=][^,=]*?) # unquoted ) ) ) ) (?: (?:\s*,\s*)|(?:\s*$) # comma ) ) ''' _matchstring = '^%s*' % _paramstring def dottedQuadToNum(ip): """ Convert decimal dotted quad string to long integer >>> int(dottedQuadToNum('1 ')) 1 >>> int(dottedQuadToNum('1.2.3.4')) 16909060 """ # import here to avoid it when ip_addr values are not used import socket, struct try: return struct.unpack('!L', socket.inet_aton(ip.strip()))[0] except socket.error: raise ValueError('Not a good dotted-quad IP: %s' % ip) return def numToDottedQuad(num): """ Convert int or long int to dotted quad string >>> numToDottedQuad(int(-1)) Traceback (most recent call last): ValueError: Not a good numeric IP: -1 >>> numToDottedQuad(int(1)) '0.0.0.1' >>> numToDottedQuad(16777218) '1.0.0.2' >>> numToDottedQuad(16908291) '1.2.0.3' >>> numToDottedQuad(16909060) '1.2.3.4' >>> numToDottedQuad(4294967295) '255.255.255.255' >>> numToDottedQuad(4294967296) Traceback (most recent call last): ValueError: Not a good numeric IP: 4294967296 >>> numToDottedQuad(-1) Traceback (most recent call last): ValueError: Not a good numeric IP: -1 >>> numToDottedQuad(1) '0.0.0.1' >>> numToDottedQuad(16777218) '1.0.0.2' >>> numToDottedQuad(16908291) '1.2.0.3' >>> numToDottedQuad(16909060) '1.2.3.4' >>> numToDottedQuad(4294967295) '255.255.255.255' >>> numToDottedQuad(4294967296) Traceback (most recent call last): ValueError: Not a good numeric IP: 4294967296 """ # import here to avoid it when ip_addr values are not used import socket, struct # no need to intercept here, 4294967295L is fine if num > long(4294967295) or num < 0: raise ValueError('Not a good numeric IP: %s' % num) try: return socket.inet_ntoa( struct.pack('!L', long(num))) except (socket.error, struct.error, OverflowError): raise ValueError('Not a good numeric IP: %s' % num) class ValidateError(Exception): """ This error indicates that the check failed. It can be the base class for more specific errors. Any check function that fails ought to raise this error. (or a subclass) >>> raise ValidateError Traceback (most recent call last): ValidateError """ class VdtMissingValue(ValidateError): """No value was supplied to a check that needed one.""" class VdtUnknownCheckError(ValidateError): """An unknown check function was requested""" def __init__(self, value): """ >>> raise VdtUnknownCheckError('yoda') Traceback (most recent call last): VdtUnknownCheckError: the check "yoda" is unknown. """ ValidateError.__init__(self, 'the check "{}" is unknown.'.format(value)) class VdtParamError(SyntaxError): """An incorrect parameter was passed""" NOT_GIVEN = object() def __init__(self, name_or_msg, value=NOT_GIVEN): """ >>> raise VdtParamError('yoda', 'jedi') Traceback (most recent call last): VdtParamError: passed an incorrect value "jedi" for parameter "yoda". >>> raise VdtParamError('preformatted message') Traceback (most recent call last): VdtParamError: preformatted message """ if value is self.NOT_GIVEN: SyntaxError.__init__(self, name_or_msg) else: SyntaxError.__init__(self, 'passed an incorrect value "{}" for parameter "{}".'.format(value, name_or_msg)) class VdtTypeError(ValidateError): """The value supplied was of the wrong type""" def __init__(self, value): """ >>> raise VdtTypeError('jedi') Traceback (most recent call last): VdtTypeError: the value "jedi" is of the wrong type. """ ValidateError.__init__(self, 'the value "{}" is of the wrong type.'.format(value)) class VdtValueError(ValidateError): """The value supplied was of the correct type, but was not an allowed value.""" def __init__(self, value): """ >>> raise VdtValueError('jedi') Traceback (most recent call last): VdtValueError: the value "jedi" is unacceptable. """ ValidateError.__init__(self, 'the value "{}" is unacceptable.'.format(value)) class VdtValueTooSmallError(VdtValueError): """The value supplied was of the correct type, but was too small.""" def __init__(self, value): """ >>> raise VdtValueTooSmallError('0') Traceback (most recent call last): VdtValueTooSmallError: the value "0" is too small. """ ValidateError.__init__(self, 'the value "{}" is too small.'.format(value)) class VdtValueTooBigError(VdtValueError): """The value supplied was of the correct type, but was too big.""" def __init__(self, value): """ >>> raise VdtValueTooBigError('1') Traceback (most recent call last): VdtValueTooBigError: the value "1" is too big. """ ValidateError.__init__(self, 'the value "{}" is too big.'.format(value)) class VdtValueTooShortError(VdtValueError): """The value supplied was of the correct type, but was too short.""" def __init__(self, value): """ >>> raise VdtValueTooShortError('jed') Traceback (most recent call last): VdtValueTooShortError: the value "jed" is too short. """ ValidateError.__init__( self, 'the value "{}" is too short.'.format(value)) class VdtValueTooLongError(VdtValueError): """The value supplied was of the correct type, but was too long.""" def __init__(self, value): """ >>> raise VdtValueTooLongError('jedie') Traceback (most recent call last): VdtValueTooLongError: the value "jedie" is too long. """ ValidateError.__init__(self, 'the value "{}" is too long.'.format(value)) class Validator: """ Validator is an object that allows you to register a set of 'checks'. These checks take input and test that it conforms to the check. This can also involve converting the value from a string into the correct datatype. The ``check`` method takes an input string which configures which check is to be used and applies that check to a supplied value. An example input string would be: 'int_range(param1, param2)' You would then provide something like: >>> def int_range_check(value, min, max): ... # turn min and max from strings to integers ... min = int(min) ... max = int(max) ... # check that value is of the correct type. ... # possible valid inputs are integers or strings ... # that represent integers ... if not isinstance(value, (int, str)): ... raise VdtTypeError(value) ... elif isinstance(value, str): ... # if we are given a string ... # attempt to convert to an integer ... try: ... value = int(value) ... except ValueError: ... raise VdtValueError(value) ... # check the value is between our constraints ... if not min <= value: ... raise VdtValueTooSmallError(value) ... if not value <= max: ... raise VdtValueTooBigError(value) ... return value >>> fdict = {'int_range': int_range_check} >>> vtr1 = Validator(fdict) >>> vtr1.check('int_range(20, 40)', '30') 30 >>> vtr1.check('int_range(20, 40)', '60') Traceback (most recent call last): VdtValueTooBigError: the value "60" is too big. New functions can be added with : :: >>> vtr2 = Validator() >>> vtr2.functions['int_range'] = int_range_check Or by passing in a dictionary of functions when Validator is instantiated. Your functions *can* use keyword arguments, but the first argument should always be 'value'. If the function doesn't take additional arguments, the parentheses are optional in the check. It can be written with either of : :: keyword = function_name keyword = function_name() The first program to utilise Validator() was Michael Foord's ConfigObj, an alternative to ConfigParser which supports lists and can validate a config file using a config schema. For more details on using Validator with ConfigObj see: https://configobj.readthedocs.io/en/latest/configobj.html """ # this regex does the initial parsing of the checks _func_re = re.compile(r'(.+?)\((.*)\)', re.DOTALL) # this regex takes apart keyword arguments _key_arg = re.compile(r'^([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*(.*)$', re.DOTALL) # this regex finds keyword=list(....) type values _list_arg = _list_arg # this regex takes individual values out of lists - in one pass _list_members = _list_members # These regexes check a set of arguments for validity # and then pull the members out _paramfinder = re.compile(_paramstring, re.VERBOSE | re.DOTALL) _matchfinder = re.compile(_matchstring, re.VERBOSE | re.DOTALL) def __init__(self, functions=None): """ >>> vtri = Validator() """ self.functions = { '': self._pass, 'integer': is_integer, 'float': is_float, 'boolean': is_boolean, 'ip_addr': is_ip_addr, 'string': is_string, 'list': is_list, 'tuple': is_tuple, 'int_list': is_int_list, 'float_list': is_float_list, 'bool_list': is_bool_list, 'ip_addr_list': is_ip_addr_list, 'string_list': is_string_list, 'mixed_list': is_mixed_list, 'pass': self._pass, 'option': is_option, 'force_list': force_list, } if functions is not None: self.functions.update(functions) # tekNico: for use by ConfigObj self.baseErrorClass = ValidateError self._cache = {} def check(self, check, value, missing=False): """ Usage: check(check, value) Arguments: check: string representing check to apply (including arguments) value: object to be checked Returns value, converted to correct type if necessary If the check fails, raises a ``ValidateError`` subclass. >>> vtor.check('yoda', '') Traceback (most recent call last): VdtUnknownCheckError: the check "yoda" is unknown. >>> vtor.check('yoda()', '') Traceback (most recent call last): VdtUnknownCheckError: the check "yoda" is unknown. >>> vtor.check('string(default="")', '', missing=True) '' """ fun_name, fun_args, fun_kwargs, default = self._parse_with_caching(check) if missing: if default is None: # no information needed here - to be handled by caller raise VdtMissingValue() value = self._handle_none(default) if value is None: return None return self._check_value(value, fun_name, fun_args, fun_kwargs) def _handle_none(self, value): if value == 'None': return None elif value in ("'None'", '"None"'): # Special case a quoted None value = self._unquote(value) return value def _parse_with_caching(self, check): if check in self._cache: fun_name, fun_args, fun_kwargs, default = self._cache[check] # We call list and dict below to work with *copies* of the data # rather than the original (which are mutable of course) fun_args = list(fun_args) fun_kwargs = dict(fun_kwargs) else: fun_name, fun_args, fun_kwargs, default = self._parse_check(check) fun_kwargs = {str(key): value for (key, value) in list(fun_kwargs.items())} self._cache[check] = fun_name, list(fun_args), dict(fun_kwargs), default return fun_name, fun_args, fun_kwargs, default def _check_value(self, value, fun_name, fun_args, fun_kwargs): try: fun = self.functions[fun_name] except KeyError: raise VdtUnknownCheckError(fun_name) else: return fun(value, *fun_args, **fun_kwargs) def _parse_check(self, check): fun_match = self._func_re.match(check) if fun_match: fun_name = fun_match.group(1) arg_string = fun_match.group(2) arg_match = self._matchfinder.match(arg_string) if arg_match is None: # Bad syntax raise VdtParamError('Bad syntax in check "%s".' % check) fun_args = [] fun_kwargs = {} # pull out args of group 2 for arg in self._paramfinder.findall(arg_string): # args may need whitespace removing (before removing quotes) arg = arg.strip() listmatch = self._list_arg.match(arg) if listmatch: key, val = self._list_handle(listmatch) fun_kwargs[key] = val continue keymatch = self._key_arg.match(arg) if keymatch: val = keymatch.group(2) if not val in ("'None'", '"None"'): # Special case a quoted None val = self._unquote(val) fun_kwargs[keymatch.group(1)] = val continue fun_args.append(self._unquote(arg)) else: # allows for function names without (args) return check, (), {}, None # Default must be deleted if the value is specified too, # otherwise the check function will get a spurious "default" keyword arg default = fun_kwargs.pop('default', None) return fun_name, fun_args, fun_kwargs, default def _unquote(self, val): """Unquote a value if necessary.""" if (len(val) >= 2) and (val[0] in ("'", '"')) and (val[0] == val[-1]): val = val[1:-1] return val def _list_handle(self, listmatch): """Take apart a ``keyword=list('val, 'val')`` type string.""" out = [] name = listmatch.group(1) args = listmatch.group(2) for arg in self._list_members.findall(args): out.append(self._unquote(arg)) return name, out def _pass(self, value): """ Dummy check that always passes >>> vtor.check('', 0) 0 >>> vtor.check('', '0') '0' """ return value def get_default_value(self, check): """ Given a check, return the default value for the check (converted to the right type). If the check doesn't specify a default value then a ``KeyError`` will be raised. """ fun_name, fun_args, fun_kwargs, default = self._parse_with_caching(check) if default is None: raise KeyError('Check "%s" has no default value.' % check) value = self._handle_none(default) if value is None: return value return self._check_value(value, fun_name, fun_args, fun_kwargs) def _is_num_param(names, values, to_float=False): """ Return numbers from inputs or raise VdtParamError. Lets ``None`` pass through. Pass in keyword argument ``to_float=True`` to use float for the conversion rather than int. >>> _is_num_param(('', ''), (0, 1.0)) [0, 1] >>> _is_num_param(('', ''), (0, 1.0), to_float=True) [0.0, 1.0] >>> _is_num_param(('a'), ('a')) Traceback (most recent call last): VdtParamError: passed an incorrect value "a" for parameter "a". """ fun = to_float and float or int out_params = [] for (name, val) in zip(names, values): if val is None: out_params.append(val) elif isinstance(val, (int, float, str)): try: out_params.append(fun(val)) except ValueError: raise VdtParamError(name, val) else: raise VdtParamError(name, val) return out_params # built in checks # you can override these by setting the appropriate name # in Validator.functions # note: if the params are specified wrongly in your input string, # you will also raise errors. def is_integer(value, min=None, max=None): """ A check that tests that a given value is an integer (int, or long) and optionally, between bounds. A negative value is accepted, while a float will fail. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. >>> vtor.check('integer', '-1') -1 >>> vtor.check('integer', '0') 0 >>> vtor.check('integer', 9) 9 >>> vtor.check('integer', 'a') Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. >>> vtor.check('integer', '2.2') Traceback (most recent call last): VdtTypeError: the value "2.2" is of the wrong type. >>> vtor.check('integer(10)', '20') 20 >>> vtor.check('integer(max=20)', '15') 15 >>> vtor.check('integer(10)', '9') Traceback (most recent call last): VdtValueTooSmallError: the value "9" is too small. >>> vtor.check('integer(10)', 9) Traceback (most recent call last): VdtValueTooSmallError: the value "9" is too small. >>> vtor.check('integer(max=20)', '35') Traceback (most recent call last): VdtValueTooBigError: the value "35" is too big. >>> vtor.check('integer(max=20)', 35) Traceback (most recent call last): VdtValueTooBigError: the value "35" is too big. >>> vtor.check('integer(0, 9)', False) 0 """ (min_val, max_val) = _is_num_param( # pylint: disable=unbalanced-tuple-unpacking ('min', 'max'), (min, max)) if not isinstance(value, (int, str)): raise VdtTypeError(value) if isinstance(value, str): # if it's a string - does it represent an integer ? try: value = int(value) except ValueError: raise VdtTypeError(value) if (min_val is not None) and (value < min_val): raise VdtValueTooSmallError(value) if (max_val is not None) and (value > max_val): raise VdtValueTooBigError(value) return value def is_float(value, min=None, max=None): """ A check that tests that a given value is a float (an integer will be accepted), and optionally - that it is between bounds. If the value is a string, then the conversion is done - if possible. Otherwise a VdtError is raised. This can accept negative values. >>> vtor.check('float', '2') 2.0 From now on we multiply the value to avoid comparing decimals >>> vtor.check('float', '-6.8') * 10 -68.0 >>> vtor.check('float', '12.2') * 10 122.0 >>> vtor.check('float', 8.4) * 10 84.0 >>> vtor.check('float', 'a') Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. >>> vtor.check('float(10.1)', '10.2') * 10 102.0 >>> vtor.check('float(max=20.2)', '15.1') * 10 151.0 >>> vtor.check('float(10.0)', '9.0') Traceback (most recent call last): VdtValueTooSmallError: the value "9.0" is too small. >>> vtor.check('float(max=20.0)', '35.0') Traceback (most recent call last): VdtValueTooBigError: the value "35.0" is too big. """ (min_val, max_val) = _is_num_param( # pylint: disable=unbalanced-tuple-unpacking ('min', 'max'), (min, max), to_float=True) if not isinstance(value, (int, float, str)): raise VdtTypeError(value) if not isinstance(value, float): # if it's a string - does it represent a float ? try: value = float(value) except ValueError: raise VdtTypeError(value) if (min_val is not None) and (value < min_val): raise VdtValueTooSmallError(value) if (max_val is not None) and (value > max_val): raise VdtValueTooBigError(value) return value bool_dict = { True: True, 'on': True, '1': True, 'true': True, 'yes': True, False: False, 'off': False, '0': False, 'false': False, 'no': False, } def is_boolean(value): """ Check if the value represents a boolean. >>> vtor.check('boolean', 0) 0 >>> vtor.check('boolean', False) 0 >>> vtor.check('boolean', '0') 0 >>> vtor.check('boolean', 'off') 0 >>> vtor.check('boolean', 'false') 0 >>> vtor.check('boolean', 'no') 0 >>> vtor.check('boolean', 'nO') 0 >>> vtor.check('boolean', 'NO') 0 >>> vtor.check('boolean', 1) 1 >>> vtor.check('boolean', True) 1 >>> vtor.check('boolean', '1') 1 >>> vtor.check('boolean', 'on') 1 >>> vtor.check('boolean', 'true') 1 >>> vtor.check('boolean', 'yes') 1 >>> vtor.check('boolean', 'Yes') 1 >>> vtor.check('boolean', 'YES') 1 >>> vtor.check('boolean', '') Traceback (most recent call last): VdtTypeError: the value "" is of the wrong type. >>> vtor.check('boolean', 'up') Traceback (most recent call last): VdtTypeError: the value "up" is of the wrong type. """ if isinstance(value, str): try: return bool_dict[value.lower()] except KeyError: raise VdtTypeError(value) # we do an equality test rather than an identity test # this ensures Python 2.2 compatibility # and allows 0 and 1 to represent True and False if value == False: return False elif value == True: return True else: raise VdtTypeError(value) def is_ip_addr(value): """ Check that the supplied value is an Internet Protocol address, v.4, represented by a dotted-quad string, i.e. '1.2.3.4'. >>> vtor.check('ip_addr', '1 ') '1' >>> vtor.check('ip_addr', ' 1.2') '1.2' >>> vtor.check('ip_addr', ' 1.2.3 ') '1.2.3' >>> vtor.check('ip_addr', '1.2.3.4') '1.2.3.4' >>> vtor.check('ip_addr', '0.0.0.0') '0.0.0.0' >>> vtor.check('ip_addr', '255.255.255.255') '255.255.255.255' >>> vtor.check('ip_addr', '255.255.255.256') Traceback (most recent call last): VdtValueError: the value "255.255.255.256" is unacceptable. >>> vtor.check('ip_addr', '1.2.3.4.5') Traceback (most recent call last): VdtValueError: the value "1.2.3.4.5" is unacceptable. >>> vtor.check('ip_addr', 0) Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. """ if not isinstance(value, str): raise VdtTypeError(value) value = value.strip() try: dottedQuadToNum(value) except ValueError: raise VdtValueError(value) return value def is_list(value, min=None, max=None): """ Check that the value is a list of values. You can optionally specify the minimum and maximum number of members. It does no check on list members. >>> vtor.check('list', ()) [] >>> vtor.check('list', []) [] >>> vtor.check('list', (1, 2)) [1, 2] >>> vtor.check('list', [1, 2]) [1, 2] >>> vtor.check('list(3)', (1, 2)) Traceback (most recent call last): VdtValueTooShortError: the value "(1, 2)" is too short. >>> vtor.check('list(max=5)', (1, 2, 3, 4, 5, 6)) Traceback (most recent call last): VdtValueTooLongError: the value "(1, 2, 3, 4, 5, 6)" is too long. >>> vtor.check('list(min=3, max=5)', (1, 2, 3, 4)) [1, 2, 3, 4] >>> vtor.check('list', 0) Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. >>> vtor.check('list', '12') Traceback (most recent call last): VdtTypeError: the value "12" is of the wrong type. """ (min_len, max_len) = _is_num_param( # pylint: disable=unbalanced-tuple-unpacking ('min', 'max'), (min, max)) if isinstance(value, str): raise VdtTypeError(value) try: num_members = len(value) except TypeError: raise VdtTypeError(value) if min_len is not None and num_members < min_len: raise VdtValueTooShortError(value) if max_len is not None and num_members > max_len: raise VdtValueTooLongError(value) return list(value) def is_tuple(value, min=None, max=None): """ Check that the value is a tuple of values. You can optionally specify the minimum and maximum number of members. It does no check on members. >>> vtor.check('tuple', ()) () >>> vtor.check('tuple', []) () >>> vtor.check('tuple', (1, 2)) (1, 2) >>> vtor.check('tuple', [1, 2]) (1, 2) >>> vtor.check('tuple(3)', (1, 2)) Traceback (most recent call last): VdtValueTooShortError: the value "(1, 2)" is too short. >>> vtor.check('tuple(max=5)', (1, 2, 3, 4, 5, 6)) Traceback (most recent call last): VdtValueTooLongError: the value "(1, 2, 3, 4, 5, 6)" is too long. >>> vtor.check('tuple(min=3, max=5)', (1, 2, 3, 4)) (1, 2, 3, 4) >>> vtor.check('tuple', 0) Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. >>> vtor.check('tuple', '12') Traceback (most recent call last): VdtTypeError: the value "12" is of the wrong type. """ return tuple(is_list(value, min, max)) def is_string(value, min=None, max=None): """ Check that the supplied value is a string. You can optionally specify the minimum and maximum number of members. >>> vtor.check('string', '0') '0' >>> vtor.check('string', 0) Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. >>> vtor.check('string(2)', '12') '12' >>> vtor.check('string(2)', '1') Traceback (most recent call last): VdtValueTooShortError: the value "1" is too short. >>> vtor.check('string(min=2, max=3)', '123') '123' >>> vtor.check('string(min=2, max=3)', '1234') Traceback (most recent call last): VdtValueTooLongError: the value "1234" is too long. """ if not isinstance(value, str): raise VdtTypeError(value) (min_len, max_len) = _is_num_param( # pylint: disable=unbalanced-tuple-unpacking ('min', 'max'), (min, max)) try: num_members = len(value) except TypeError: raise VdtTypeError(value) if min_len is not None and num_members < min_len: raise VdtValueTooShortError(value) if max_len is not None and num_members > max_len: raise VdtValueTooLongError(value) return value def is_int_list(value, min=None, max=None): """ Check that the value is a list of integers. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is an integer. >>> vtor.check('int_list', ()) [] >>> vtor.check('int_list', []) [] >>> vtor.check('int_list', (1, 2)) [1, 2] >>> vtor.check('int_list', [1, 2]) [1, 2] >>> vtor.check('int_list', [1, 'a']) Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. """ return [is_integer(mem) for mem in is_list(value, min, max)] def is_bool_list(value, min=None, max=None): """ Check that the value is a list of booleans. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a boolean. >>> vtor.check('bool_list', ()) [] >>> vtor.check('bool_list', []) [] >>> check_res = vtor.check('bool_list', (True, False)) >>> check_res == [True, False] 1 >>> check_res = vtor.check('bool_list', [True, False]) >>> check_res == [True, False] 1 >>> vtor.check('bool_list', [True, 'a']) Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. """ return [is_boolean(mem) for mem in is_list(value, min, max)] def is_float_list(value, min=None, max=None): """ Check that the value is a list of floats. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a float. >>> vtor.check('float_list', ()) [] >>> vtor.check('float_list', []) [] >>> vtor.check('float_list', (1, 2.0)) [1.0, 2.0] >>> vtor.check('float_list', [1, 2.0]) [1.0, 2.0] >>> vtor.check('float_list', [1, 'a']) Traceback (most recent call last): VdtTypeError: the value "a" is of the wrong type. """ return [is_float(mem) for mem in is_list(value, min, max)] def is_string_list(value, min=None, max=None): """ Check that the value is a list of strings. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is a string. >>> vtor.check('string_list', ()) [] >>> vtor.check('string_list', []) [] >>> vtor.check('string_list', ('a', 'b')) ['a', 'b'] >>> vtor.check('string_list', ['a', 1]) Traceback (most recent call last): VdtTypeError: the value "1" is of the wrong type. >>> vtor.check('string_list', 'hello') Traceback (most recent call last): VdtTypeError: the value "hello" is of the wrong type. """ if isinstance(value, str): raise VdtTypeError(value) return [is_string(mem) for mem in is_list(value, min, max)] def is_ip_addr_list(value, min=None, max=None): """ Check that the value is a list of IP addresses. You can optionally specify the minimum and maximum number of members. Each list member is checked that it is an IP address. >>> vtor.check('ip_addr_list', ()) [] >>> vtor.check('ip_addr_list', []) [] >>> vtor.check('ip_addr_list', ('1.2.3.4', '5.6.7.8')) ['1.2.3.4', '5.6.7.8'] >>> vtor.check('ip_addr_list', ['a']) Traceback (most recent call last): VdtValueError: the value "a" is unacceptable. """ return [is_ip_addr(mem) for mem in is_list(value, min, max)] def force_list(value, min=None, max=None): """ Check that a value is a list, coercing strings into a list with one member. Useful where users forget the trailing comma that turns a single value into a list. You can optionally specify the minimum and maximum number of members. A minimum of greater than one will fail if the user only supplies a string. >>> vtor.check('force_list', ()) [] >>> vtor.check('force_list', []) [] >>> vtor.check('force_list', 'hello') ['hello'] """ if not isinstance(value, (list, tuple)): value = [value] return is_list(value, min, max) fun_dict = { int: is_integer, 'int': is_integer, 'integer': is_integer, float: is_float, 'float': is_float, 'ip_addr': is_ip_addr, str: is_string, 'str': is_string, 'string': is_string, bool: is_boolean, 'bool': is_boolean, 'boolean': is_boolean, } def is_mixed_list(value, *args): """ Check that the value is a list. Allow specifying the type of each member. Work on lists of specific lengths. You specify each member as a positional argument specifying type Each type should be one of the following strings : 'integer', 'float', 'ip_addr', 'string', 'boolean' So you can specify a list of two strings, followed by two integers as : mixed_list('string', 'string', 'integer', 'integer') The length of the list must match the number of positional arguments you supply. >>> mix_str = "mixed_list('integer', 'float', 'ip_addr', 'string', 'boolean')" >>> check_res = vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a', True)) >>> check_res == [1, 2.0, '1.2.3.4', 'a', True] 1 >>> check_res = vtor.check(mix_str, ('1', '2.0', '1.2.3.4', 'a', 'True')) >>> check_res == [1, 2.0, '1.2.3.4', 'a', True] 1 >>> vtor.check(mix_str, ('b', 2.0, '1.2.3.4', 'a', True)) Traceback (most recent call last): VdtTypeError: the value "b" is of the wrong type. >>> vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a')) Traceback (most recent call last): VdtValueTooShortError: the value "(1, 2.0, '1.2.3.4', 'a')" is too short. >>> vtor.check(mix_str, (1, 2.0, '1.2.3.4', 'a', 1, 'b')) Traceback (most recent call last): VdtValueTooLongError: the value "(1, 2.0, '1.2.3.4', 'a', 1, 'b')" is too long. >>> vtor.check(mix_str, 0) Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. >>> vtor.check('mixed_list("yoda")', ('a')) Traceback (most recent call last): VdtParamError: passed an incorrect value "KeyError('yoda',)" for parameter "'mixed_list'" """ try: length = len(value) except TypeError: raise VdtTypeError(value) if length < len(args): raise VdtValueTooShortError(value) elif length > len(args): raise VdtValueTooLongError(value) try: return [fun_dict[arg](val) for arg, val in zip(args, value)] except KeyError as cause: raise VdtParamError('mixed_list', cause) def is_option(value, *options): """ This check matches the value to any of a set of options. >>> vtor.check('option("yoda", "jedi")', 'yoda') 'yoda' >>> vtor.check('option("yoda", "jedi")', 'jed') Traceback (most recent call last): VdtValueError: the value "jed" is unacceptable. >>> vtor.check('option("yoda", "jedi")', 0) Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. """ if not isinstance(value, str): raise VdtTypeError(value) if not value in options: raise VdtValueError(value) return value def _test(value, *args, **keywargs): """ A function that exists for test purposes. >>> checks = [ ... '3, 6, min=1, max=3, test=list(a, b, c)', ... '3', ... '3, 6', ... '3,', ... 'min=1, test="a b c"', ... 'min=5, test="a, b, c"', ... 'min=1, max=3, test="a, b, c"', ... 'min=-100, test=-99', ... 'min=1, max=3', ... '3, 6, test="36"', ... '3, 6, test="a, b, c"', ... '3, max=3, test=list("a", "b", "c")', ... '''3, max=3, test=list("'a'", 'b', "x=(c)")''', ... "test='x=fish(3)'", ... ] >>> v = Validator({'test': _test}) >>> for entry in checks: ... pprint(v.check(('test(%s)' % entry), 3)) (3, ('3', '6'), {'max': '3', 'min': '1', 'test': ['a', 'b', 'c']}) (3, ('3',), {}) (3, ('3', '6'), {}) (3, ('3',), {}) (3, (), {'min': '1', 'test': 'a b c'}) (3, (), {'min': '5', 'test': 'a, b, c'}) (3, (), {'max': '3', 'min': '1', 'test': 'a, b, c'}) (3, (), {'min': '-100', 'test': '-99'}) (3, (), {'max': '3', 'min': '1'}) (3, ('3', '6'), {'test': '36'}) (3, ('3', '6'), {'test': 'a, b, c'}) (3, ('3',), {'max': '3', 'test': ['a', 'b', 'c']}) (3, ('3',), {'max': '3', 'test': ["'a'", 'b', 'x=(c)']}) (3, (), {'test': 'x=fish(3)'}) >>> v = Validator() >>> v.check('integer(default=6)', '3') 3 >>> v.check('integer(default=6)', None, True) 6 >>> v.get_default_value('integer(default=6)') 6 >>> v.get_default_value('float(default=6)') 6.0 >>> v.get_default_value('pass(default=None)') >>> v.get_default_value("string(default='None')") 'None' >>> v.get_default_value('pass') Traceback (most recent call last): KeyError: 'Check "pass" has no default value.' >>> v.get_default_value('pass(default=list(1, 2, 3, 4))') ['1', '2', '3', '4'] >>> v = Validator() >>> v.check("pass(default=None)", None, True) >>> v.check("pass(default='None')", None, True) 'None' >>> v.check('pass(default="None")', None, True) 'None' >>> v.check('pass(default=list(1, 2, 3, 4))', None, True) ['1', '2', '3', '4'] Bug test for unicode arguments >>> v = Validator() >>> v.check('string(min=4)', 'test') == 'test' True >>> v = Validator() >>> v.get_default_value('string(min=4, default="1234")') == '1234' True >>> v.check('string(min=4, default="1234")', 'test') == 'test' True >>> v = Validator() >>> default = v.get_default_value('string(default=None)') >>> default == None 1 """ return (value, args, keywargs) def _test2(): """ >>> >>> v = Validator() >>> v.get_default_value('string(default="#ff00dd")') '#ff00dd' >>> v.get_default_value('integer(default=3) # comment') 3 """ def _test3(): r""" >>> vtor.check('string(default="")', '', missing=True) '' >>> vtor.check('string(default="\n")', '', missing=True) '\n' >>> print(vtor.check('string(default="\n")', '', missing=True)) <BLANKLINE> <BLANKLINE> >>> vtor.check('string()', '\n') '\n' >>> vtor.check('string(default="\n\n\n")', '', missing=True) '\n\n\n' >>> vtor.check('string()', 'random \n text goes here\n\n') 'random \n text goes here\n\n' >>> vtor.check('string(default=" \nrandom text\ngoes \n here\n\n ")', ... '', missing=True) ' \nrandom text\ngoes \n here\n\n ' >>> vtor.check("string(default='\n\n\n')", '', missing=True) '\n\n\n' >>> vtor.check("option('\n','a','b',default='\n')", '', missing=True) '\n' >>> vtor.check("string_list()", ['foo', '\n', 'bar']) ['foo', '\n', 'bar'] >>> vtor.check("string_list(default=list('\n'))", '', missing=True) ['\n'] """ if __name__ == '__main__': # run the code tests in doctest format import sys import doctest m = sys.modules.get('__main__') globs = m.__dict__.copy() globs.update({ 'vtor': Validator(), }) failures, tests = doctest.testmod( m, globs=globs, optionflags=doctest.IGNORE_EXCEPTION_DETAIL | doctest.ELLIPSIS) print('{} {} failures out of {} tests' .format("FAIL" if failures else "*OK*", failures, tests)) sys.exit(bool(failures))
46,077
Python
.py
1,223
30.410466
119
0.572357
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,642
__init__.py
psychopy_psychopy/psychopy/devices/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from psychopy.hardware.keyboard import Keyboard
278
Python
.py
6
45
79
0.762963
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,643
sshkeys.py
psychopy_psychopy/psychopy/projects/sshkeys.py
from psychopy import prefs import os import sys import subprocess from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.backends import default_backend # https://stackoverflow.com/questions/28291909/gitpython-and-ssh-keys: # import os # from git import Repo # from git import Git # # git_ssh_identity_file = os.path.expanduser('~/.ssh/id_rsa') # git_ssh_cmd = 'ssh -i %s' % git_ssh_identity_file # # with Git().custom_environment(GIT_SSH_COMMAND=git_ssh_cmd): # Repo.clone_from('git@....', '/path', branch='my-branch') def saveKeyPair(filepath, comment=''): """Generate and save a key pair (private and public) and return the public key as text filepath : unicode path to the (private) key. The public key will be filepath+'.pub' For PsychoPy on Pavlovia the filepath should be os.path.join(psychopy.prefs.paths['userprefs'], "ssh", username) """ if type(comment) is not bytes: comment = comment.encode('utf-8') if type(filepath) is not bytes: filepath = filepath.encode('utf-8') try: # try using ssh-keygen (more standard and probably faster) folder = os.path.split(filepath)[0] if not os.path.isdir(folder): os.mkdir(folder) output = subprocess.check_output([b'ssh-keygen', b'-C', comment, b'-f', filepath, b'-P', b'']) # then read it back in to pass back public_key = getPublicKey(filepath + b".pub") except subprocess.CalledProcessError: # generate private/public key pair key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=4096) # get public key in OpenSSH format public_key = key.public_key().public_bytes( serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH) # get private key in PEM container format pem = key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()) # check that the root folder exists folder = os.path.dirname(filepath) if not os.path.exists(folder): os.makedirs(folder) # save private key with open(filepath, 'wb') as f: f.write(pem) os.chmod(filepath, 0o400) # make sure the private key is only self-readable with open(filepath+'.pub', 'wb') as f: f.write(public_key) # whether we used ssh-keygen or home-grown we should try to ssh-add # because we're using a non-standard location if sys.platform == 'win32': pass # not clear that this command exists on win32! # response = subprocess.check_output(['cmd', 'ssh-add', filepath]) else: response = subprocess.check_output(['ssh-add', filepath]) return public_key def getPublicKey(filepath): """ For PsychoPy on Pavlovia the filepath should be os.path.join(psychopy.prefs.paths['userprefs'], "ssh", username) """ if os.path.isfile(filepath): with open(filepath, 'rb') as f: pubKey = f.read() else: raise IOError("No ssh public key file found at {}".format(filepath)) if type(pubKey) == bytes: # in Py3 convert to UTF-8 pubKey = pubKey.decode('utf-8') return pubKey if __name__ == '__main__': from psychopy import prefs username = 'jon' fileRoot = os.path.join(prefs.paths['userPrefsDir'], "ssh", username) print(saveKeyPair(fileRoot)) print(getPublicKey(fileRoot+'.pub'))
3,890
Python
.py
89
35.224719
84
0.631774
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,644
pavlovia.py
psychopy_psychopy/psychopy/projects/pavlovia.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). """Helper functions in PsychoPy for interacting with Pavlovia.org """ import glob import json import pathlib import os import re import time import subprocess import traceback import pandas from packaging.version import Version from psychopy import logging, prefs, exceptions from psychopy.tools.filetools import DictStorage, KnownProjects from psychopy import app from psychopy.localization import _translate import wx from ..app.errorDlg import exceptionCallback from ..tools.apptools import SortTerm try: import git # must import psychopy constants before this (custom git path) haveGit = True except ImportError: haveGit = False import requests import gitlab import gitlab.v4.objects # for authentication from . import sshkeys from uuid import uuid4 from .gitignore import gitIgnoreText from urllib import parse urlencode = parse.quote # TODO: test what happens if we have a network initially but lose it # TODO: test what happens if we have a network but pavlovia times out pavloviaPrefsDir = os.path.join(prefs.paths['userPrefsDir'], 'pavlovia') rootURL = "https://gitlab.pavlovia.org" client_id = '944b87ee0e6b4f510881d6f6bc082f64c7bba17d305efdb829e6e0e7ed466b34' code_challenge = None code_verifier = None scopes = [] redirect_url = 'https://gitlab.pavlovia.org/' knownUsers = DictStorage( filename=os.path.join(pavloviaPrefsDir, 'users.json')) # knownProjects is a dict stored by id ("namespace/name") knownProjects = KnownProjects( filename=os.path.join(pavloviaPrefsDir, 'projects.json')) # knownProjects stores the gitlab id to check if it's the same exact project # We add to the knownProjects when project.local is set (ie when we have a # known local location for the project) permissions = { # for ref see https://docs.gitlab.com/ee/user/permissions.html 'guest': 10, 'reporter': 20, 'developer': 30, # (can push to non-protected branches) 'maintainer': 30, 'owner': 50} MISSING_REMOTE = -1 OK = 1 def getAuthURL(): # starting state state = str(uuid4()) # create a private "state" based on uuid # code challenge and verifier need to be global so we can access them later global code_challenge, code_verifier # generate code challenge and corresponding verifier code_verifier, code_challenge = generateCodeChallengePair() # construct auth url auth_url = ('https://gitlab.pavlovia.org/oauth/authorize?client_id={}' '&redirect_uri={}&response_type=code&state={}&code_challenge={}&code_challenge_method=S256' .format(client_id, redirect_url, state, code_challenge)) return auth_url, state def generateCodeChallengePair(): """ Create a unique random string and its corresponding encoded challenge. Returns ------- str A code verifier - a random collection of characters str A code challenge - the code verifier transformed using a particular algorithm """ from numpy.random import randint, choice as randchoice import hashlib import base64 # characters valid for a code verifier... validChars = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~") # first make the answer - pick random alphanumeric chars code_verifier = "" for n in range(randint(44, 127)): code_verifier += randchoice(validChars) # transform to make code_challenge code_challenge = code_verifier # SHA-256 digest code_verifier_hash = hashlib.sha256(code_verifier.encode("utf-8")).digest() # Base64 urlsafe encode without padding code_challenge = base64.urlsafe_b64encode(code_verifier_hash).decode("utf-8").rstrip("=") return code_verifier, code_challenge def login(tokenOrUsername, rememberMe=True): """Sets the current user by means of a token Parameters ---------- token """ currentSession = getCurrentSession() if not currentSession: exceptionCallback(exc_type=requests.exceptions.ConnectionError) return # would be nice here to test whether this is a token or username logging.debug('pavloviaTokensCurrently: {}'.format(knownUsers)) if tokenOrUsername in knownUsers: token = knownUsers[tokenOrUsername] # username so fetch token else: token = tokenOrUsername # it might still be a dict that *contains* the token if type(token) == dict and 'token' in token: token = token['token'] # try actually logging in with token currentSession.setToken(token) if currentSession.user is not None: user = currentSession.user prefs.appData['projects']['pavloviaUser'] = user['username'] # update Pavlovia button(s) appInstance = app.getAppInstance() if appInstance: for btn in appInstance.pavloviaButtons['user'] + appInstance.pavloviaButtons['project']: btn.updateInfo() def logout(): """Log the current user out of pavlovia. NB This function does not delete the cookie from the wx mini-browser if that has been set. Use pavlovia_ui for that. - set the user for the currentSession to None - save the appData so that the user is blank """ # create a new currentSession with no auth token global _existingSession _existingSession = None # set appData to None prefs.appData['projects']['pavloviaUser'] = None prefs.saveAppData() for frameWeakref in app.openFrames: frame = frameWeakref() if hasattr(frame, 'setUser'): frame.setUser(None) # update Pavlovia button(s) for btn in app.getAppInstance().pavloviaButtons['user'] + app.getAppInstance().pavloviaButtons['project']: btn.updateInfo() class User(dict): """Class to combine what we know about the user locally and on gitlab (from previous logins and from the current session)""" def __init__(self, id, rememberMe=True): # Get info from Pavlovia if isinstance(id, (float, int, str)): # If given a number or string, treat it as a user ID / username self.info = self.session.session.get( "https://pavlovia.org/api/v2/designers/" + str(id) ).json()['designer'] # Make sure self.info has necessary keys assert 'gitlabId' in self.info, _translate( "Could not retrieve user info for user {}, server returned:\n" "{}" ).format(id,self.info) elif isinstance(id, dict) and 'gitlabId' in id: # If given a dict from Pavlovia rather than an ID, store it rather than requesting again self.info = id else: raise TypeError(f"ID must be either an integer representing the user's numeric ID or a string " f"representing their username, not `{id}`.") # Store own ID self.id = int(self.info['gitlabId']) # Get user object from GitLab self.user = self.session.gitlab.users.get(self.id) # Add user email (mostly redundant but necessary for saving) self.user.email = self.info['email'] # Init dict dict.__init__(self, self.info) # Update local if rememberMe: self.saveLocal() def __getitem__(self, key): # Get either from self or project.attributes try: value = dict.__getitem__(self, key) except KeyError: value = self.user.attributes[key] return value def __setitem__(self, key, value): dict.__setitem__(self, key, value) self.user.__setattr__(key, value) def __str__(self): return "pavlovia.User <{}>".format(self['username']) def __eq__(self, other): if isinstance(other, self.__class__): # Compare gitlab ID for two User objects return int(self['id']) == int(other['id']) elif isinstance(other, (int, float)) or (isinstance(other, str) and other.isnumeric()): # Compare gitlab ID for an int or int-like return int(self['id']) == int(other) elif isinstance(other, str): # Compare username for a string return self['username'] == other @property def session(self): # Cache session if not cached if not hasattr(self, "_session"): self._session = getCurrentSession() # Return cached session return self._session def saveLocal(self): """Saves the data on the current user in the pavlovia/users json file""" knownUsers[self['username']] = self.user.attributes knownUsers[self['username']]['token'] = self.session.getToken() knownUsers.save() def save(self): self.user.save() class PavloviaSession: """A class to track a session with the server. The session will store a token, which can then be used to authenticate for project read/write access """ def __init__(self, token=None, remember_me=True): """Create a session to send requests with the pavlovia server Provide either username and password for authentication with a new token, or provide a token from a previous session, or nothing for an anonymous user """ self.username = None self.userID = None # populate when token property is set self.userFullName = None self.remember_me = remember_me self.authenticated = False self.setToken(token) logging.debug("PavloviaLoggedIn") @property def currentProject(self): if hasattr(self, "_currentProject"): return self._currentProject @currentProject.setter def currentProject(self, value): self._currentProject = PavloviaProject(value) def createProject(self, name, description="", tags=(), visibility='private', localRoot='', namespace=''): """Returns a PavloviaProject object (derived from a gitlab.project) Parameters ---------- name description tags visibility local Returns ------- a PavloviaProject object """ if not self.user: raise exceptions.NoUserError("Tried to create project with no user logged in") # NB gitlab also supports "internal" (public to registered users) if type(visibility) == bool and visibility: visibility = 'public' elif type(visibility) == bool and not visibility: visibility = 'private' projDict = {} projDict['name'] = name projDict['description'] = description projDict['issues_enabled'] = True projDict['visibility'] = visibility projDict['wiki_enabled'] = True if namespace and namespace != self.username: namespaceRaw = self.getNamespace(namespace) if namespaceRaw: projDict['namespace_id'] = namespaceRaw.id else: dlg = wx.MessageDialog(None, message=_translate( "PavloviaSession.createProject was given a namespace ({namespace}) that couldn't be found " "on gitlab." ).format(namespace=namespace), style=wx.ICON_WARNING) dlg.ShowModal() return # Create project on GitLab try: gitlabProj = self.gitlab.projects.create(projDict) except gitlab.exceptions.GitlabCreateError as e: if 'has already been taken' in str(e.error_message): # If name is taken, get instead of create gitlabProj = self.gitlab.projects.get(f"{self.username}/{name}") else: # Otherwise, raise original error raise e # Check for bare remote bareRemote = False try: gitlabProj.repository_tree() except gitlab.exceptions.GitlabGetError: # If we've made it thus far but can't get a tree, the remote is bare bareRemote = True # If remote is populated, handle and return if not bareRemote: dlg = wx.MessageDialog(None, message=_translate( "Project `{namespace}/{name}` already exists, please choose another name." ).format(namespace=namespace, name=name), style=wx.ICON_WARNING) dlg.ShowModal() return # Otherwise, continue as normal (bare remote is fine to replace) # Create pavlovia project object pavProject = PavloviaProject(gitlabProj.get_id(), localRoot=localRoot) return pavProject def getProject(self, id, localRoot=""): """Gets a Pavlovia project from an ID number or namespace/name Parameters ---------- id : float Numeric ID of the project localRoot : str or Path Path of the project root Returns ------- pavlovia.PavloviaProject or None """ if id: return PavloviaProject(id, localRoot=localRoot) else: return None def findProjects(self, search_str='', tags="psychopy"): """ Parameters ---------- search_str : str The string to search for in the title of the project tags : str Comma-separated string containing tags Returns ------- A list of OSFProject objects """ rawProjs = self.gitlab.projects.list( search=search_str, as_list=False) # iterator not list for auto-pagination projs = [PavloviaProject(proj) for proj in rawProjs if proj.id] return projs def listUserGroups(self, namesOnly=True): gps = self.gitlab.groups.list(member=True) if namesOnly: gps = [this.name for this in gps] return gps def findUserProjects(self, searchStr=''): """Finds all readable projects of a given user_id (None for current user) """ try: own = self.gitlab.projects.list(owned=True, search=searchStr) except Exception as e: print(e) own = self.gitlab.projects.list(owned=True, search=searchStr) group = self.gitlab.projects.list(owned=False, membership=True, search=searchStr) projs = [] projIDs = [] for proj in own + group: if proj.id not in projIDs and proj.id not in projs: projs.append(PavloviaProject(proj.id)) projIDs.append(proj.id) return projs def findUsers(self, search_str): """Find user IDs whose name matches a given search string """ return self.gitlab.users def getToken(self): """The authorisation token for the current logged in user """ return self.__dict__['token'] def setToken(self, token): """Set the token for this session and check that it works for auth """ self.__dict__['token'] = token self.startSession(token) def getNamespace(self, namespace): """Returns a namespace object for the given name if an exact match is found """ spaces = self.gitlab.namespaces.list(search=namespace) # might be more than one, with for thisSpace in spaces: if thisSpace.path == namespace: return thisSpace def startSession(self, token): """Start a gitlab session as best we can (if no token then start an empty session)""" self.session = requests.Session() if prefs.connections['proxy']: # if we have a proxy then we'll need to use # the requests session to set the proxy self.session.proxies = { 'https': prefs.connections['proxy'], 'http': prefs.connections['proxy'] } if token: if len(token) < 64: raise ValueError( "Trying to login with token {} which is shorter " "than expected length ({} not 64) for gitlab token" .format(repr(token), len(token))) # Setup gitlab session self.gitlab = gitlab.Gitlab(rootURL, oauth_token=token, timeout=10, session=self.session, per_page=100) try: self.gitlab.auth() except gitlab.exceptions.GitlabParsingError as err: raise ConnectionError( "Failed to authenticate with the gitlab.pavlovia.org server. " "Received a string that could not be parsed by the gitlab library. " "This may be caused by having an institutional proxy server but " "not setting the proxy setting in PsychoPy preferences. If that " "isn't the case for you, then please get in touch so we can work out " "what the cause was in your case! support@opensciencetools.org") self.username = self.gitlab.user.username self.userID = self.gitlab.user.id # populate when token property is set self.userFullName = self.gitlab.user.name self.authenticated = True # add the token (although this is also in the gitlab object) self.session.headers = {'OauthToken': token} else: self.gitlab = gitlab.Gitlab(rootURL, timeout=10, session=self.session, per_page=100) @property def user(self): if not hasattr(self, "_user") or self._user is None: try: self._user = User(self.gitlab.user.username) except AttributeError: return None return self._user @user.setter def user(self, value): if isinstance(value, User) or value is None: self._user = value else: self._user = User(value) class PavloviaSearch(pandas.DataFrame): # List all possible sort terms sortTerms = [ SortTerm("nbStars", dLabel=_translate("Most stars"), aLabel=_translate("Least stars"), ascending=False), SortTerm("nbForks", dLabel=_translate("Most forks"), aLabel=_translate("Least forks"), ascending=False), SortTerm("updateDate", dLabel=_translate("Last edited"), aLabel=_translate("Longest since edited"), ascending=False), SortTerm("creationDate", dLabel=_translate("Last created"), aLabel=_translate("First created"), ascending=False), SortTerm("name", dLabel=_translate("Name (Z-A)"), aLabel=_translate("Name (A-Z)"), ascending=True), SortTerm("pathWithNamespace", dLabel=_translate("Author (Z-A)"), aLabel=_translate("Author (A-Z)"), ascending=True), ] class FilterTerm(dict): # Map filter menu items to project columns filterMap = { "Author": "designer", "Status": "status", "Platform": "platform", "Visibility": "visibility", "Tags": "tags", } def __str__(self): # Start off with blank str terms = "" # Synonymise visibility unspecified with visibility all ticked (compensate for back-end being # exploration focussed) if "Visibility" not in self or not self['Visibility']: self['Visibility'] = ["owned", "private", "public"] # Iterate through values for key, value in self.items(): # Ensure value is iterable and mutable if not isinstance(value, (list, tuple)): value = [value] value = list(value) # Ensure each sub-value is a string for i in range(len(value)): value[i] = str(value[i]) # Skip empty terms if len(value) == 0: continue # Alias keys if key in self.filterMap: key = self.filterMap[key] # Add this term terms += f"&{key}={','.join(value)}" return terms def __bool__(self): return any(self.values()) def __init__(self, term, sortBy=None, filterBy=None, mine=False): # Replace default filter if filterBy is None: filterBy = {} # Ensure filter is a FilterTerm filterBy = self.FilterTerm(filterBy) # Do search session = getCurrentSession() if mine: # Display experiments by current user data = session.session.get( f"https://pavlovia.org/api/v2/designers/{session.userID}/experiments?search={term}{filterBy}", timeout=10 ).json() elif term or filterBy: data = session.session.get( f"https://pavlovia.org/api/v2/experiments?search={term}{filterBy}", timeout=10 ).json() else: # Display demos for blank search data = session.session.get( "https://pavlovia.org/api/v2/experiments?search=demos&designer=demos", timeout=10 ).json() # Construct dataframe pandas.DataFrame.__init__(self, data=data['experiments']) # Do any requested sorting if sortBy is not None: self.sort_values(sortBy) def sort_values(self, by, inplace=True, ignore_index=True, **kwargs): if isinstance(by, (str, int)): by = [str(by)] # Add mapped and selected menu items to sort keys list sortKeys = [] ascending = [] for item in by: if item.value in self.columns: sortKeys.append(item.value) ascending.append(item.ascending) # Add pavlovia score as final sort option sortKeys.append("pavloviaScore") ascending += [False] # Do actual sorting if sortKeys: pandas.DataFrame.sort_values(self, sortKeys, inplace=inplace, ascending=ascending, ignore_index=ignore_index, **kwargs) class PavloviaProject(dict): """A Pavlovia project, with name, url etc .pavlovia will point to a gitlab project on gitlab.pavlovia.org - None if the session couldn't be opened - False if the session is open but the repo isn't there (deleted?) .repo will will be a local gitpython repo .localRoot is the path to the root of the repo .id is the namespace/name (e.g. peircej/stroop) .idNumber is gitlab numeric id .title .tags .group is technically the namespace. Get the owner from .attributes['owner'] .localRoot is the path to the local root """ # list of keys which we expect to be datetimes _datetimeKeys = ("created_at", "last_activity_at") def __init__(self, id, localRoot=None): # Cache whatever form of ID is given, to avoid unneccesary calls to Pavlovia/GitLab later if isinstance(id, int): # If created using a numeric ID... self.numericId = id elif isinstance(id, str): # If created using a "namespace/name" string... self.stringId = id else: # If created using a dict with info from Pavlovia... self._info = dict(id) if 'gitlabId' in self._info: self.numericId = int(self._info['gitlabId']) if 'pathWithNamespace' in self._info: self.stringId = self._info['pathWithNamespace'] # Set local root if localRoot is not None: self.localRoot = localRoot def __getitem__(self, key): # Get either from self or project.attributes try: value = dict.__getitem__(self, key) except KeyError: # if no project, return None if self.project is None: return None # otherwise, get from attributes if key in self.project.attributes: value = self.project.attributes[key] elif hasattr(self, "_info") and key in self._info: return self._info[key] else: value = None # Transform datetimes if key in self._datetimeKeys: value = pandas.to_datetime(value, format=None, errors='coerce') return value def __setitem__(self, key, value): dict.__setitem__(self, key, value) self.project.__setattr__(key, value) @property def id(self): """ ID of this project - will be either a numeric ID or a "namespace/name" string depending on which is available. If both are available, "namespace/name" is prioritised. """ if hasattr(self, "stringId"): return self.stringId elif hasattr(self, "numericId"): return self.numericId @property def info(self): """ Returns the info about the project from Pavlovia API. This may have a delay after changes to the GitLab API calls, as the info filters through so use with caution. This can be updated with self.refresh() """ if not self._info: self.refresh() return self._info def refresh(self): """ Update the info about the project from Pavlovia API. This may have a delay after changes to the GitLab API calls, as the info filters through so use with caution. """ # Update Pavlovia info start = time.time() self._info = None # for a new project it may take time for Pavlovia to register the new ID so try for a while while self._info is None and (time.time() - start) < 30: requestVal = self.session.session.get( f"https://pavlovia.org/api/v2/experiments/{self.id}", ).json() self._info = requestVal['experiment'] if self._info is None: raise ValueError(f"Could not find project with id `{self.id}` on Pavlovia: {requestVal}") # Store received ID values from Pavlovia if 'gitlabId' in self._info: self.numericId = int(self._info['gitlabId']) if 'pathWithNamespace' in self._info: self.stringId = self._info['pathWithNamespace'] if self.project is not None: # Reinitialise dict dict.__init__(self, self.project.attributes) # Convert datetime for key in self._info: if key in self._datetimeKeys: self._info[key] = pandas.to_datetime(self._info[key], format=None, errors='coerce') # Update base dict self.update(self.project.attributes) @property def session(self): # If previous value is cached, return it if hasattr(self, "_session"): return self._session # Get and cache current session self._session = getCurrentSession() return self._session @property def project(self): # If previous value is cached, return it if hasattr(self, "_project"): return self._project # Get and cache gitlab project try: self._project = self.session.gitlab.projects.get(self.id) return self._project except gitlab.exceptions.GitlabGetError as e: # dlg = wx.MessageDialog( # parent=None, # message=_translate( # "Could not find GitLab project with id {}.\n" # "\n" # "Please check that the project exists on Pavlovia, that you are logged in as the correct user in " # "the PsychoPy app, and that your account has access to the project." # ).format(self.id), # style=wx.ICON_ERROR # ) # dlg.ShowModal() return None @property def editable(self): """ Whether or not the project is editable by the current user """ # If previous value is cached, return it if hasattr(self, "_editable") and self._lastEditableCheckUser == self.session.user: return self._editable # Otherwise, figure it out if self.session.user: # Get current user id _id = self.session.user['id'] # Get gitlab project users _users = self.project.users.list() # Return whether or not current user in in project users self._editable = _id in [user.id for user in _users] else: # If there's no user, they can't edit, so return False self._editable = False # Store user when last checked self._lastEditableCheckUser = self.session.user return self._editable @property def owned(self): """ Whether or not the project is owned by the current user """ if bool(self.session.user): # If there is a user, return True if they're the owner of this project return self['path_with_namespace'].split('/')[0] == self.session.user['username'] else: # If there isn't a user, then they can't own this project, so return False return False @property def starred(self): """ Star/unstar the project, or view starred status """ # If previous value is cached, return it if hasattr(self, "_starred"): return self._starred # Otherwise, return whether this project is in the list of starred projects self._starred = bool(self.session.gitlab.projects.list(starred=True, search=str(self.id))) return self._starred @starred.setter def starred(self, value): # Enforce bool value = bool(value) # Store value self._starred = value # Set on gitlab if value: self.project.star() else: self.project.unstar() # Get info from Pavlovia again, as star count will have changed self.refresh() @property def remoteHTTPS(self): """ The URL for the https access to thr git repo """ return self.project.http_url_to_repo @property def remoteSSH(self): """ The URL for the ssh access to the git repo """ return self.project.ssh_url_to_repo @property def localRoot(self): if hasattr(self, "stringId") and self.stringId in knownProjects: # If project has known local store, return its root return knownProjects[self.stringId]['localRoot'] elif hasattr(self, "_localRootStatic"): # If project has local root stored as static value, return it return self._localRootStatic else: # Otherwise, return blank return "" @localRoot.setter def localRoot(self, value): if hasattr(self, "stringId") and self.stringId in knownProjects: # If project has known local store, update its root knownProjects[self.stringId]['localRoot'] = str(value) knownProjects.save() elif hasattr(self, "stringId") and hasattr(self, "numericId"): # If project has no known local store and we are able to, create one knownProjects[self.stringId] = { 'id': self.stringId, 'idNumber': self.numericId, 'localRoot': str(value), 'remoteHTTPS': f"https://gitlab.pavlovia.org/{self.stringId}.git", 'remoteSSH': f"git@gitlab.pavlovia.org:{self.stringId}.git" } knownProjects.save() else: # If we don't have enough info to save to knownProjects, just store the value given self._localRootStatic = value def sync(self, infoStream=None): """Performs a pull-and-push operation on the remote Will check for a local folder and whether that is already (in) a repo. If we have a local folder and it is not a git project already then this function will also clone the remote to that local folder Optional params infoStream is needed if you want to update a sync window/panel """ # get info stream if not given if infoStream is None: infoStream = getInfoStream() # Error catch local root if not self.localRoot: dlg = wx.MessageDialog(self, message=_translate( "Can't sync project without a local root. Please specify a local root then try again." ), style=wx.ICON_ERROR | wx.OK) dlg.ShowModal() return # Error catch logged out if not self.session.user: dlg = wx.MessageDialog(self, message=_translate( "You are not logged in to Pavlovia. Please log in to sync project." ), style=wx.ICON_ERROR | wx.OK) dlg.ShowModal() return if self.project is not None: # Jot down start time t0 = time.time() # make repo if needed if self.repo is None: repo = self.newRepo(infoStream) if repo is None: return 0 # If first commit (besides repo creation), do initial push if len(self.project.commits.list()) < 2: self.firstPush(infoStream=infoStream) # Pull and push self.pull(infoStream) self.push(infoStream) # Write updates t1 = time.time() msg = ( "Successful sync at: {}, took {:.3f}s. View synced project here:\n" "{}\n".format( time.strftime("%H:%M:%S", time.localtime()), t1 - t0, "https://pavlovia.org/" + self['path_with_namespace'] ) ) logging.info(msg) if infoStream: infoStream.write(msg + "\n") time.sleep(0.5) # Refresh info self.refresh() else: # If project doesn't exist, tell the user infoStream.write( _translate("Sync failed - could not find project with id {}\n\n").format(self.id) ) return 1 def pull(self, infoStream=None): """Pull from remote to local copy of the repository Parameters ---------- infoStream Returns ------- 1 if successful -1 if project is deleted on remote """ # get info stream if not given if infoStream is None: infoStream = getInfoStream() if infoStream: infoStream.write("Pulling changes from remote...\n") if self.repo is None: self.cloneRepo(infoStream) try: info = self.repo.git.pull(self.remoteWithToken, 'master') if infoStream: infoStream.write("{}\n".format(info)) except git.exc.GitCommandError as e: if ("The project you were looking for could not be found" in traceback.format_exc()): # pointing to a project at pavlovia but it doesn't exist logging.warning("Project not found on gitlab.pavlovia.org") return MISSING_REMOTE else: raise e logging.debug('pull complete: {}'.format(self.project.http_url_to_repo)) if infoStream: infoStream.write("done\n") return 1 def push(self, infoStream=None): """Push to remote from local copy of the repository Parameters ---------- infoStream Returns ------- 1 if successful -1 if project deleted on remote """ # get info stream if not given if infoStream is None: infoStream = getInfoStream() if infoStream: infoStream.write("Pushing changes to remote...\n") try: info = self.repo.git.push(self.remoteWithToken, 'master') if infoStream and len(info): infoStream.write("{}\n".format(info)) except git.exc.GitCommandError as e: if ("The project you were looking for could not be found" in traceback.format_exc()): # pointing to a project at pavlovia but it doesn't exist logging.warning("Project not found on gitlab.pavlovia.org") return MISSING_REMOTE else: raise e logging.debug('push complete: {}'.format(self.project.http_url_to_repo)) if infoStream: infoStream.write("done\n") return 1 @property def repo(self): """Will always try to return a valid local git repo Will try to clone if local is empty and remote is not""" # If there's no local root, we can't find the repo if not self.localRoot: raise gitlab.GitlabGetError("Cannot fetch a PavloviaProject until we have chosen a local folder.") # If repo is cached, return it if hasattr(self, "_repo") and self._repo: return self._repo # Get git root gitRoot = getGitRoot(self.localRoot) if gitRoot is None: self._repo = self.newRepo() elif gitRoot not in [self.localRoot, str(pathlib.Path(self.localRoot).absolute())]: # this indicates that the requested root is inside another repo raise AttributeError("The requested local path for project\n\t{}\n" "sits inside another folder, which git will " "not permit. You might like to set the " "project local folder to be \n\t{}" .format(repr(self.localRoot), repr(gitRoot))) else: # If there's a git root, return the associated repo self._repo = git.Repo(gitRoot) self.configGitLocal() self.writeGitIgnore() return self._repo @repo.setter def repo(self, value): self._repo = value @property def remoteWithToken(self): """The remote for git sync using an oauth token (always as a bytes obj) """ return f"https://oauth2:{self.session.token}@gitlab.pavlovia.org/{self['path_with_namespace']}" def writeGitIgnore(self): """Check that a .gitignore file exists and add it if not""" gitIgnorePath = os.path.join(self.localRoot, '.gitignore') if not os.path.exists(gitIgnorePath): with open(gitIgnorePath, 'w') as f: f.write(gitIgnoreText) def newRepo(self, infoStream=None): """Will either git.init and git.push or git.clone depending on state of local files. Use newRemote if we know that the remote has only just been created and is empty """ # get info stream if not given if infoStream is None: infoStream = getInfoStream() localFiles = glob.glob(os.path.join(self.localRoot, "*")) # glob doesn't match hidden files by default so search for them localFiles.extend(glob.glob(os.path.join(self.localRoot, ".*"))) # there's no project at all so create one if not self.localRoot: raise AttributeError("Cannot fetch a PavloviaProject until we have " "chosen a local folder.") if not os.path.exists(self.localRoot): os.makedirs(self.localRoot) # check if the remote repo is empty (if so then to init/push) if self.project: try: self.project.repository_tree() bareRemote = False except gitlab.GitlabGetError as e: if "Tree Not Found" in str(e): bareRemote = True else: bareRemote = False repo = None # if remote is new (or existed but is bare) then init and push if localFiles and bareRemote: # existing folder repo = git.Repo.init(self.localRoot) self.configGitLocal() # sets user.email and user.name # add origin remote and master branch (but no push) repo.create_remote('origin', url=self.project.http_url_to_repo) repo.git.checkout(b="master") self.writeGitIgnore() self.stageFiles(['.gitignore']) self.commit('Create repository (including .gitignore)') self._newRemote = False elif localFiles: # get project name if "/" in self.stringId: _, projectName = self.stringId.split("/") else: projectName = self.stringId # ask user if they want to clone to a subfolder msg = _translate( "Folder '{localRoot}' is not empty, use '{localRoot}/{projectName}' instead?" ) dlg = wx.MessageDialog( None, msg.format(localRoot=self.localRoot, projectName=projectName), style=wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL) resp = dlg.ShowModal() if resp == wx.ID_YES: # if yes, update local root self.localRoot = pathlib.Path(self.localRoot) / projectName # try again self.newRepo(infoStream=infoStream) elif resp == wx.ID_CANCEL: # if they cancelled, stop infoStream.write( "Clone cancelled by user.\n" ) repo = None else: # no files locally so safe to try and clone from remote repo = self.cloneRepo(infoStream=infoStream) return repo def firstPush(self, infoStream): # get info stream if not given if infoStream is None: infoStream = getInfoStream() if infoStream: infoStream.write("Pushing to Pavlovia for the first time...\n") # construct initial commit self.stageFiles(infoStream=infoStream) info = self.commit( _translate("Push initial project files") ) if infoStream and len(info): infoStream.write("{}\n".format(info)) # push info = self.repo.git.push('-u', self.remoteWithToken, 'master') self.project.attributes['default_branch'] = 'master' if infoStream: if len(info): infoStream.write("{}\n".format(info)) infoStream.write("Success!\n".format(info)) def cloneRepo(self, infoStream=None): """Gets the git.Repo object for this project, creating one if needed Will check for a local folder and whether that is already (in) a repo. If we have a local folder and it is not a git project already then this function will also clone the remote to that local folder Parameters ---------- infoStream Returns ------- git.Repo object Raises ------ AttributeError if the local project is inside a git repo """ # get info stream if not given if infoStream is None: infoStream = getInfoStream() if not self.localRoot: raise AttributeError("Cannot fetch a PavloviaProject until we have " "chosen a local folder.") if infoStream: infoStream.write("Cloning from remote...\n") repo = git.Repo.clone_from( self.remoteWithToken, self.localRoot, ) # now change the remote to be the standard (without password token) repo.remotes.origin.set_url(self.project.http_url_to_repo) self._lastKnownSync = time.time() self._newRemote = False return repo def configGitLocal(self): """Set the local repo to have the correct name and email for user Returns ------- None """ localConfig = self.repo.git.config(l=True, local=True) # list local if self.session.user['email'] in localConfig: return # we already have it set up so can return # set the local config with self.repo.config_writer() as config: config.set_value("user", "email", self.session.user['email']) config.set_value("user", "name", self.session.user['name']) def fork(self, to=None): # Sub in current user if none given if to is None: to = self.session.user['username'] # Do fork try: glProj = self.project.forks.create({'namespace': to}) except gitlab.GitlabCreateError: raise gitlab.GitlabCreateError(f"Project {self.session.user['username']}/{self['name']} already exists!") # Get new project proj = PavloviaProject(glProj.id) # Return new project return proj def getChanges(self): """Find all the not-yet-committed changes in the repository""" changeDict = {} changeList = [] # if we don't have a repo object, there's no changes if not hasattr(self, "_repo") or self._repo is None: return changeDict, changeList # get changes changeDict['untracked'] = self.repo.untracked_files changeDict['changed'] = [] changeDict['deleted'] = [] changeDict['renamed'] = [] for this in self.repo.index.diff(None): # change type, identifying possible ways a blob can have changed # A = Added # D = Deleted # R = Renamed # M = Modified # T = Changed in the type if this.change_type == 'D': changeDict['deleted'].append(this.b_path) elif this.change_type == 'R': # only if git rename had been called? changeDict['renamed'].append((this.rename_from, this.rename_to)) elif this.change_type == 'M': changeDict['changed'].append(this.b_path) elif this.change_type == 'U': changeDict['changed'].append(this.b_path) else: raise ValueError("Found an unexpected change_type '{}' in gitpython Diff".format(this.change_type)) for categ in changeDict: changeList.extend(changeDict[categ]) return changeDict, changeList def stageFiles(self, files=None, infoStream=None): """Adds changed files to the stage (index) ready for commit. The files is a list and can include new/changed/deleted If files=None this is like `git add -u` (all files added/deleted) """ # get info stream if not given if infoStream is None: infoStream = getInfoStream() if files: if type(files) not in (list, tuple): raise TypeError( 'The `files` provided to PavloviaProject.stageFiles ' 'should be a list not a {}'.format(type(files))) try: for thisFile in files: self.repo.git.add(thisFile) except git.exc.GitCommandError: if infoStream: infoStream.SetValue(traceback.format_exc()) else: diffsDict, diffsList = self.getChanges() if diffsDict['untracked']: self.repo.git.add(diffsDict['untracked']) if diffsDict['deleted']: self.repo.git.add(diffsDict['deleted']) if diffsDict['changed']: self.repo.git.add(diffsDict['changed']) def getStagedFiles(self): """Retrieves the files that are already staged ready for commit""" return self.repo.index.diff("HEAD") def unstageFiles(self, files): """Removes changed files from the stage (index) preventing their commit. The files in question can be new/changed/deleted """ self.repo.git.reset('--', files) def commit(self, message): """Commits the staged changes""" info = self.repo.git.commit('-m', message) time.sleep(0.1) # then get a new copy of the repo self.repo = git.Repo(self.localRoot) return info def save(self): """Saves the metadata to gitlab.pavlovia.org""" try: self.project.save() return True except gitlab.GitlabUpdateError as err: msgRoot = "Could not sync project.\n\n" if err.response_code == 400: # Error: Avatar is too big msg = msgRoot + _translate("Avatar is too big, should be at most 200 KB.") dlg = wx.MessageDialog(None, msg, style=wx.ICON_ERROR) dlg.ShowModal() # Reset avatar self['avatar_url'] = "" return False # note that saving info locally about known projects is done # by the knownProjects DictStorage class @property def pavloviaStatus(self): return self.__dict__['pavloviaStatus'] @pavloviaStatus.setter def pavloviaStatus(self, newStatus): url = 'https://pavlovia.org/server?command=update_project' data = {'projectId': self.id, 'projectStatus': 'ACTIVATED'} resp = requests.put(url, data) if resp.status_code == 200: self.__dict__['pavloviaStatus'] = newStatus else: print(resp) @property def permissions(self): """This returns the user's overall permissions for the project as int. Unlike the project.attribute['permissions'] which returns a dict of permissions for group/project which is sometimes also a dict and sometimes an int! returns ------------ permissions as an int: -1 = probably not logged in? None = logged in but no permissions """ if not getCurrentSession().user: return -1 if 'permissions' in self.attributes: # collect perms for both group and individual access allPerms = [] permsDict = self.attributes['permissions'] if 'project_access' in permsDict: allPerms.append(permsDict['project_access']) if 'group_access' in permsDict: allPerms.append(permsDict['group_access']) # make ints and find the max permission of the project/group permInts = [] for thisPerm in allPerms: # check if deeper in dict if type(thisPerm) == dict: thisPerm = thisPerm['access_level'] # we have a single value (but might still be None) if thisPerm is not None: permInts.append(thisPerm) if permInts: perms = max(permInts) else: perms = None elif hasattr(self, 'project_access') and self.project_access: perms = self.project_access if type(perms) == dict: perms = perms['access_level'] else: perms = None # not sure if this ever occurs when logged in return perms def getGitRoot(p): """Return None or the root path of the repository""" if not haveGit: raise exceptions.DependencyError( "gitpython and a git installation required for getGitRoot()") p = pathlib.Path(p).absolute() if not p.is_dir(): p = p.parent # given a file instead of folder? proc = subprocess.Popen('git branch --show-current', stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=str(p), shell=True, universal_newlines=True) # newlines forces stdout to unicode stdout, stderr = proc.communicate() if 'not a git repository' in (stdout + stderr): return None else: # this should have been possible with git rev-parse --top-level # but that sometimes returns a virtual symlink that is not the normal folder name # e.g. some other mount point? selfAndParents = [p] + list(p.parents) for thisPath in selfAndParents: if list(thisPath.glob('.git')): return str(thisPath) # convert Path back to str def getNameWithNamespace(p): """ Return None or the root path of the repository """ # Work out cwd if not haveGit: raise exceptions.DependencyError( "gitpython and a git installation required for getGitRoot()") p = pathlib.Path(p).absolute() if not p.is_dir(): p = p.parent # given a file instead of folder? # Open git process proc = subprocess.Popen('git config --get remote.origin.url', stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=str(p), shell=True, universal_newlines=True) # newlines forces stdout to unicode stdout, stderr = proc.communicate() # Find a gitlab url in the response url = re.match(r"https:\/\/gitlab\.pavlovia\.org\/\w*\/\w*\.git", stdout) if url: # Get contents of url from response url = url.string[url.pos:url.endpos] # Get namespace/name string from url path = url path = re.sub(r"\.git[.\n]*", "", path) path = re.sub(r"[.\n]*https:\/\/gitlab\.pavlovia\.org\/", "", path) return path else: return None def getProject(filename): """Will try to find (locally synced) pavlovia Project for the filename """ # Check that we have Git if not haveGit: raise exceptions.DependencyError( "gitpython and a git installation required for getProject()") # Get git root gitRoot = getGitRoot(filename) # Get name with namespace path = getNameWithNamespace(filename) # Get session session = getCurrentSession() # Start off with proj as None proj = None # If already found, return if (knownProjects is not None) and (path in knownProjects) and ('idNumber' in knownProjects[path]): # Make sure we are logged in nameSpace, projectName = path.split("/") # Try to log in if not logged in if not session.user: if nameSpace in knownUsers: # Log in if user is known login(nameSpace, rememberMe=True) else: # Check whether project repo is found in any of the known users accounts for user in knownUsers: try: login(user) except requests.exceptions.ConnectionError: break thisId = knownProjects[path]['id'] # Check that project still exists on Pavlovia requestVal = session.session.get( f"https://pavlovia.org/api/v2/experiments/{thisId}", ).json() if requestVal['experiment'] is None: # If project has been deleted, return None return None # If project is still there, get it try: return PavloviaProject(thisId, localRoot=gitRoot) except LookupError as err: # If project not found, print warning and return None logging.warn(str(err)) return None elif gitRoot: # Existing repo but not in our knownProjects. Investigate logging.info("Investigating repo at {}".format(gitRoot)) localRepo = git.Repo(gitRoot) for remote in localRepo.remotes: for url in remote.urls: if "gitlab.pavlovia.org" in url: # Get namespace from url # could be 'https://gitlab.pavlovia.org/NameSpace/Name.git' # or may be 'git@gitlab.pavlovia.org:NameSpace/Name.git' namespaceName = url.split('gitlab.pavlovia.org')[1] # remove the first char if it's : or / if namespaceName[0] in ['/', ':']: namespaceName = namespaceName[1:] # Remove .git namespaceName = namespaceName.replace(".git", "") # Split to get namespace nameSpace, projectName = namespaceName.split('/') # Get current session pavSession = getCurrentSession() # Try to log in if not logged in if not pavSession.user: if nameSpace in knownUsers: # Log in if user is known login(nameSpace, rememberMe=True) else: # Check whether project repo is found in any of the known users accounts for user in knownUsers: try: login(user) except requests.exceptions.ConnectionError: break foundProject = False for repo in pavSession.findUserProjects(): if namespaceName in repo: foundProject = True logging.info("Logging in as {}".format(user)) break if not foundProject: logging.warning("Could not find {namespace} in your Pavlovia accounts. " "Logging in as {user}.".format(namespace=namespaceName, user=user)) if pavSession.user: # Get PavloviaProject via id proj = pavSession.getProject(namespaceName, localRoot=gitRoot) proj.repo = localRepo else: # If we are still logged out, prompt user logging.warning(_translate("We found a repository pointing to {} " "but no user is logged in for us to check it".format(url))) return proj if proj is None: # Warn user if still no project logging.warning("We found a repository at {} but it " "doesn't point to gitlab.pavlovia.org. " "You could create that as a remote to " "sync from PsychoPy.".format(gitRoot)) global _existingSession _existingSession = None # create an instance of that def getCurrentSession(): """Returns the current Pavlovia session, creating one if not yet present Returns ------- """ global _existingSession if _existingSession: return _existingSession else: _existingSession = PavloviaSession() return _existingSession def refreshSession(): """Restarts the session with the same user logged in""" global _existingSession if _existingSession and _existingSession.getToken(): _existingSession = PavloviaSession( token=_existingSession.getToken() ) else: _existingSession = PavloviaSession() return _existingSession def getInfoStream(): """ Get the Git output panel in the Runner frame, if any is active. Returns ------- ScriptOutputCtrl Ctrl to write to """ # attempt to get the Runner frame frame = app.getAppFrame("runner") # get ctrl from runner if frame is not None: return frame.getOutputPanel("git").ctrl
60,859
Python
.py
1,423
31.512298
125
0.585998
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,645
__init__.py
psychopy_psychopy/psychopy/projects/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2024 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). """Helper functions in PsychoPy for interacting with projects (e.g. from pavlovia) """ from . import pavlovia
341
Python
.py
8
41.25
82
0.748485
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,646
gitignore.py
psychopy_psychopy/psychopy/projects/gitignore.py
gitIgnoreText = """ # Byte-compiled / optimized / DLL files __pycache__/ *.pyc *.pyo *.pyd *.so # Backup files *.bak ~$*.xls* ~$*.doc* ~$*.ppt* # Jupyter Notebook .ipynb_checkpoints # Virtual Environment files .env .venv env/ venv/ ENV/ # Spyder project settings .spyderproject .spyproject # OS generated files .DS_Store .directory .gdb_history ehthumbs.db Icon? *.orig old Thumbs.db .Spotlight-V100 .Trashes # lib files used for local debugging /lib/ /html/lib/ """
474
Python
.py
38
11.289474
39
0.764569
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,647
start_iohub_process.py
psychopy_psychopy/psychopy/iohub/start_iohub_process.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import json import os import sys import tempfile import gevent try: if os.name == 'nt': # Try to get gevent to use libev, not the default libuv. # Libuv only has 1 msec loop resolution (at least on Windows # not sure about other OS'es) gevent.config.loop = "libev-cext" except ValueError: # libev-cext is not available on the gevent build being used pass except Exception: pass import psutil import psychopy import psychopy.clock as clock from psychopy.iohub import IOHUB_DIRECTORY from psychopy.iohub.devices import Computer Computer.is_iohub_process = True from psychopy.iohub.errors import printExceptionDetailsToStdErr from psychopy.iohub.server import ioServer from psychopy.iohub.util import updateDict, yload, yLoader def run(rootScriptPathDir, configFilePath): s = None try: psychopy.iohub.EXP_SCRIPT_DIRECTORY = rootScriptPathDir tdir = tempfile.gettempdir() cdir, _ = os.path.split(configFilePath) if tdir == cdir: tf = open(configFilePath) ioHubConfig = json.loads(tf.read()) tf.close() os.remove(configFilePath) else: ioHubConfig = yload(open(configFilePath, 'r'), Loader=yLoader) hub_config_path = os.path.join(IOHUB_DIRECTORY, 'default_config.yaml') hub_defaults_config = yload(open(hub_config_path, 'r'), Loader=yLoader) updateDict(ioHubConfig, hub_defaults_config) s = ioServer(rootScriptPathDir, ioHubConfig) udp_port = s.config.get('udp_port', 9000) s.log("Receiving diagram's on: {}".format(udp_port)) s.udpService.start() s.setStatus("INITIALIZING") msgpump_interval = s.config.get('msgpump_interval', 0.001) glets = [] tlet = gevent.spawn(s.pumpMsgTasklet, msgpump_interval) glets.append(tlet) for m in s.deviceMonitors: m.start() glets.append(m) tlet = gevent.spawn(s.processEventsTasklet, 0.01) glets.append(tlet) if Computer.psychopy_process: tlet = gevent.spawn(s.checkForPsychopyProcess, 0.5) glets.append(tlet) s.setStatus("RUNNING") if hasattr(gevent, 'run'): gevent.run() glets = [] else: gevent.joinall(glets) # Wait for the server to be ready to shutdown gevent.wait() lrtime = Computer.global_clock.getLastResetTime() s.log('Server END Time Offset: {0}'.format(lrtime), 'DEBUG') return True except Exception: # pylint: disable=broad-except printExceptionDetailsToStdErr() if s: s.shutdown() return False if __name__ == '__main__': psychopy_pid = None initial_offset = 0.0 scriptPathDir = None configFileName = None prog = sys.argv[0] if len(sys.argv) >= 2: initial_offset = float(sys.argv[1]) if len(sys.argv) >= 3: scriptPathDir = sys.argv[2] if len(sys.argv) >= 4: configFileName = sys.argv[3] if len(sys.argv) >= 5: psychopy_pid = int(sys.argv[4]) if len(sys.argv) < 2: psychopy_pid = None configFileName = None scriptPathDir = None initial_offset = Computer.getTime() if psychopy_pid: Computer.psychopy_process = psutil.Process(psychopy_pid) Computer.global_clock = clock.MonotonicClock(initial_offset) run(rootScriptPathDir=scriptPathDir, configFilePath=configFileName)
3,735
Python
.py
101
29.881188
85
0.65855
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,648
lazy_import.py
psychopy_psychopy/psychopy/iohub/lazy_import.py
# Copyright (C) 2006-2010 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # NB This file comes unaltered (apart from this sentence) from the bzrlib # by Canonical (the library supporting the Bazaar code versioning system) """Functionality to create lazy evaluation objects. This includes waiting to import a module until it is actually used. Most commonly, the 'lazy_import' function is used to import other modules in an on-demand fashion. Typically use looks like:: from bzrlib.lazy_import import lazy_import lazy_import(globals(), ''' from bzrlib import ( errors, osutils, branch, ) import bzrlib.branch ''') Then 'errors, osutils, branch' and 'bzrlib' will exist as lazy-loaded objects which will be replaced with a real object on first use. In general, it is best to only load modules in this way. This is because it isn't safe to pass these variables to other functions before they have been replaced. This is especially true for constants, sometimes true for classes or functions (when used as a factory, or you want to inherit from them). """ class BzrError(Exception): """Base class for errors raised by bzrlib. :cvar internal_error: if True this was probably caused by a bzr bug and should be displayed with a traceback; if False (or absent) this was probably a user or environment error and they don't need the gory details. (That can be overridden by -Derror on the command line.) :cvar _fmt: Format string to display the error; this is expanded by the instance's dict. """ internal_error = False def __init__(self, msg=None, **kwds): """Construct a new BzrError. There are two alternative forms for constructing these objects. Either a preformatted string may be passed, or a set of named arguments can be given. The first is for generic "user" errors which are not intended to be caught and so do not need a specific subclass. The second case is for use with subclasses that provide a _fmt format string to print the arguments. Keyword arguments are taken as parameters to the error, which can be inserted into the format string template. It's recommended that subclasses override the __init__ method to require specific parameters. :param msg: If given, this is the literal complete text for the error, not subject to expansion. 'msg' is used instead of 'message' because python evolved and, in 2.6, forbids the use of 'message'. """ Exception.__init__(self) if msg is not None: # I was going to deprecate this, but it actually turns out to be # quite handy - mbp 20061103. self._preformatted_string = msg else: self._preformatted_string = None for key, value in kwds.items(): setattr(self, key, value) def _format(self): s = getattr(self, '_preformatted_string', None) if s is not None: # contains a preformatted message return s try: fmt = self._get_format_string() if fmt: d = dict(self.__dict__) s = fmt % d # __str__() should always return a 'str' object # never a 'unicode' object. return s except Exception as e: pass # just bind to 'e' for formatting below else: e = None return 'Unprintable exception %s: dict=%r, fmt=%r, error=%r' \ % (self.__class__.__name__, self.__dict__, getattr(self, '_fmt', None), e) def __unicode__(self): u = self._format() if isinstance(u, bytes): # Try decoding the str using the default encoding. u = str(u) elif not isinstance(u, str): # Try to make a unicode object from it, because __unicode__ must # return a unicode object. u = u'{}'.format(u) return u def __str__(self): s = self._format() if isinstance(s, str): s = s.encode('utf8') else: # __str__ must return a str. s = str(s) return s def __repr__(self): return '%s(%s)' % (self.__class__.__name__, str(self)) def _get_format_string(self): """Return format string for this exception or None.""" fmt = getattr(self, '_fmt', None) if fmt is not None: #from bzrlib.i18n import gettext def gettext(t): return t return gettext(str(fmt)) # _fmt strings should be ascii def __eq__(self, other): if self.__class__ is not other.__class__: return NotImplemented return self.__dict__ == other.__dict__ class InternalBzrError(BzrError): """Base class for errors that are internal in nature. This is a convenience class for errors that are internal. The internal_error attribute can still be altered in subclasses, if needed. Using this class is simply an easy way to get internal errors. """ internal_error = True class IllegalUseOfScopeReplacer(InternalBzrError): _fmt = ('ScopeReplacer object %(name)r was used incorrectly:' ' %(msg)s%(extra)s') def __init__(self, name, msg, extra=None): BzrError.__init__(self) self.name = name self.msg = msg if extra: self.extra = ': ' + str(extra) else: self.extra = '' class InvalidImportLine(InternalBzrError): _fmt = 'Not a valid import statement: %(msg)\n%(text)s' def __init__(self, text, msg): BzrError.__init__(self) self.text = text self.msg = msg class ImportNameCollision(InternalBzrError): _fmt = ('Tried to import an object to the same name as' ' an existing object. %(name)s') def __init__(self, name): BzrError.__init__(self) self.name = name class ScopeReplacer(): """A lazy object that will replace itself in the appropriate scope. This object sits, ready to create the real object the first time it is needed. """ __slots__ = ('_scope', '_factory', '_name', '_real_obj') # If you to do x = y, setting this to False will disallow access to # members from the second variable (i.e. x). This should normally # be enabled for reasons of thread safety and documentation, but # will be disabled during the selftest command to check for abuse. _should_proxy = True def __init__(self, scope, factory, name): """Create a temporary object in the specified scope. Once used, a real object will be placed in the scope. :param scope: The scope the object should appear in :param factory: A callable that will create the real object. It will be passed (self, scope, name) :param name: The variable name in the given scope. """ object.__setattr__(self, '_scope', scope) object.__setattr__(self, '_factory', factory) object.__setattr__(self, '_name', name) object.__setattr__(self, '_real_obj', None) scope[name] = self def _resolve(self): """Return the real object for which this is a placeholder.""" name = object.__getattribute__(self, '_name') real_obj = object.__getattribute__(self, '_real_obj') if real_obj is None: # No obj generated previously, so generate from factory and scope. factory = object.__getattribute__(self, '_factory') scope = object.__getattribute__(self, '_scope') obj = factory(self, scope, name) if obj is self: raise IllegalUseOfScopeReplacer( name, msg='Object tried' " to replace itself, check it's not using its own scope.") # Check if another thread has jumped in while obj was generated. real_obj = object.__getattribute__(self, '_real_obj') if real_obj is None: # Still no preexisting obj, so go ahead and assign to scope and # return. There is still a small window here where races will # not be detected, but safest to avoid additional locking. object.__setattr__(self, '_real_obj', obj) scope[name] = obj return obj # Raise if proxying is disabled as obj has already been generated. if not ScopeReplacer._should_proxy: raise IllegalUseOfScopeReplacer( name, msg='Object already replaced, did you assign it' ' to another variable?') return real_obj def __getattribute__(self, attr): obj = object.__getattribute__(self, '_resolve')() return getattr(obj, attr) def __setattr__(self, attr, value): obj = object.__getattribute__(self, '_resolve')() return setattr(obj, attr, value) def __call__(self, *args, **kwargs): obj = object.__getattribute__(self, '_resolve')() return obj(*args, **kwargs) def disallow_proxying(): """Disallow lazily imported modules to be used as proxies. Calling this function might cause problems with concurrent imports in multithreaded environments, but will help detecting wasteful indirection, so it should be called when executing unit tests. Only lazy imports that happen after this call are affected. """ ScopeReplacer._should_proxy = False class ImportReplacer(ScopeReplacer): """This is designed to replace only a portion of an import list. It will replace itself with a module, and then make children entries also ImportReplacer objects. At present, this only supports 'import foo.bar.baz' syntax. """ # '_import_replacer_children' is intentionally a long semi-unique name # that won't likely exist elsewhere. This allows us to detect an # ImportReplacer object by using # object.__getattribute__(obj, '_import_replacer_children') # We can't just use 'isinstance(obj, ImportReplacer)', because that # accesses .__class__, which goes through __getattribute__, and triggers # the replacement. __slots__ = ('_import_replacer_children', '_member', '_module_path') def __init__(self, scope, name, module_path, member=None, children={}): """Upon request import 'module_path' as the name 'module_name'. When imported, prepare children to also be imported. :param scope: The scope that objects should be imported into. Typically this is globals() :param name: The variable name. Often this is the same as the module_path. 'bzrlib' :param module_path: A list for the fully specified module path ['bzrlib', 'foo', 'bar'] :param member: The member inside the module to import, often this is None, indicating the module is being imported. :param children: Children entries to be imported later. This should be a map of children specifications. :: {'foo':(['bzrlib', 'foo'], None, {'bar':(['bzrlib', 'foo', 'bar'], None {})}) } Examples:: import foo => name='foo' module_path='foo', member=None, children={} import foo.bar => name='foo' module_path='foo', member=None, children={'bar':(['foo', 'bar'], None, {}} from foo import bar => name='bar' module_path='foo', member='bar' children={} from foo import bar, baz would get translated into 2 import requests. On for 'name=bar' and one for 'name=baz' """ if (member is not None) and children: raise ValueError('Cannot supply both a member and children') object.__setattr__(self, '_import_replacer_children', children) object.__setattr__(self, '_member', member) object.__setattr__(self, '_module_path', module_path) # Indirecting through __class__ so that children can # override _import (especially our instrumented version) cls = object.__getattribute__(self, '__class__') ScopeReplacer.__init__(self, scope=scope, name=name, factory=cls._import) def _import(self, scope, name): children = object.__getattribute__(self, '_import_replacer_children') member = object.__getattribute__(self, '_member') module_path = object.__getattribute__(self, '_module_path') module_python_path = '.'.join(module_path) if member is not None: module = __import__( module_python_path, scope, scope, [member], level=0) return getattr(module, member) else: module = __import__(module_python_path, scope, scope, [], level=0) for path in module_path[1:]: module = getattr(module, path) # Prepare the children to be imported for child_name, (child_path, child_member, grandchildren) in \ children.items(): # Using self.__class__, so that children get children classes # instantiated. (This helps with instrumented tests) cls = object.__getattribute__(self, '__class__') cls(module.__dict__, name=child_name, module_path=child_path, member=child_member, children=grandchildren) return module class ImportProcessor(): """Convert text that users input into lazy import requests.""" # TODO: jam 20060912 This class is probably not strict enough about # what type of text it allows. For example, you can do: # import (foo, bar), which is not allowed by python. # For now, it should be supporting a superset of python import # syntax which is all we really care about. __slots__ = ['imports', '_lazy_import_class'] def __init__(self, lazy_import_class=None): self.imports = {} if lazy_import_class is None: self._lazy_import_class = ImportReplacer else: self._lazy_import_class = lazy_import_class def lazy_import(self, scope, text): """Convert the given text into a bunch of lazy import objects. This takes a text string, which should be similar to normal python import markup. """ self._build_map(text) self._convert_imports(scope) def _convert_imports(self, scope): # Now convert the map into a set of imports for name, info in self.imports.items(): self._lazy_import_class(scope, name=name, module_path=info[0], member=info[1], children=info[2]) def _build_map(self, text): """Take a string describing imports, and build up the internal map.""" for line in self._canonicalize_import_text(text): if line.startswith('import '): self._convert_import_str(line) elif line.startswith('from '): self._convert_from_str(line) else: raise InvalidImportLine( line, "doesn't start with 'import ' or 'from '") def _convert_import_str(self, import_str): """This converts a import string into an import map. This only understands 'import foo, foo.bar, foo.bar.baz as bing' :param import_str: The import string to process """ if not import_str.startswith('import '): raise ValueError('bad import string %r' % (import_str,)) import_str = import_str[len('import '):] for path in import_str.split(','): path = path.strip() if not path: continue as_hunks = path.split(' as ') if len(as_hunks) == 2: # We have 'as' so this is a different style of import # 'import foo.bar.baz as bing' creates a local variable # named 'bing' which points to 'foo.bar.baz' name = as_hunks[1].strip() module_path = as_hunks[0].strip().split('.') if name in self.imports: raise ImportNameCollision(name) # No children available in 'import foo as bar' self.imports[name] = (module_path, None, {}) else: # Now we need to handle module_path = path.split('.') name = module_path[0] if name not in self.imports: # This is a new import that we haven't seen before module_def = ([name], None, {}) self.imports[name] = module_def else: module_def = self.imports[name] cur_path = [name] cur = module_def[2] for child in module_path[1:]: cur_path.append(child) if child in cur: cur = cur[child][2] else: next = (cur_path[:], None, {}) cur[child] = next cur = next[2] def _convert_from_str(self, from_str): """This converts a 'from foo import bar' string into an import map. :param from_str: The import string to process """ if not from_str.startswith('from '): raise ValueError('bad from/import %r' % from_str) from_str = from_str[len('from '):] from_module, import_list = from_str.split(' import ') from_module_path = from_module.split('.') for path in import_list.split(','): path = path.strip() if not path: continue as_hunks = path.split(' as ') if len(as_hunks) == 2: # We have 'as' so this is a different style of import # 'import foo.bar.baz as bing' creates a local variable # named 'bing' which points to 'foo.bar.baz' name = as_hunks[1].strip() module = as_hunks[0].strip() else: name = module = path if name in self.imports: raise ImportNameCollision(name) self.imports[name] = (from_module_path, module, {}) def _canonicalize_import_text(self, text): """Take a list of imports, and split it into regularized form. This is meant to take regular import text, and convert it to the forms that the rest of the converters prefer. """ out = [] cur = None continuing = False for line in text.split('\n'): line = line.strip() loc = line.find('#') if loc != -1: line = line[:loc].strip() if not line: continue if cur is not None: if line.endswith(')'): out.append(cur + ' ' + line[:-1]) cur = None else: cur += ' ' + line else: if '(' in line and ')' not in line: cur = line.replace('(', '') else: out.append(line.replace('(', '').replace(')', '')) if cur is not None: raise InvalidImportLine(cur, 'Unmatched parenthesis') return out def lazy_import(scope, text, lazy_import_class=None): """Create lazy imports for all of the imports in text. This is typically used as something like:: from bzrlib.lazy_import import lazy_import lazy_import(globals(), ''' from bzrlib import ( foo, bar, baz, ) import bzrlib.branch import bzrlib.transport ''') Then 'foo, bar, baz' and 'bzrlib' will exist as lazy-loaded objects which will be replaced with a real object on first use. In general, it is best to only load modules in this way. This is because other objects (functions/classes/variables) are frequently used without accessing a member, which means we cannot tell they have been used. """ # This is just a helper around ImportProcessor.lazy_import proc = ImportProcessor(lazy_import_class=lazy_import_class) return proc.lazy_import(scope, text) # The only module that this module depends on is 'bzrlib.errors'. But it # can actually be imported lazily, since we only need it if there is a # problem. lazy_import(globals(), """ from bzrlib import errors """)
21,623
Python
.py
467
35.910064
79
0.594981
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,649
net.py
psychopy_psychopy/psychopy/iohub/net.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import struct from weakref import proxy from gevent import sleep, Greenlet import msgpack try: import msgpack_numpy msgpack_numpy.patch() except ImportError: from .errors import print2err print2err("Warning: msgpack_numpy could not be imported. ", "This may cause issues for iohub.") from .devices import Computer from .errors import print2err, printExceptionDetailsToStdErr from .util import NumPyRingBuffer as RingBuffer if Computer.platform == 'win32': MAX_PACKET_SIZE = 64 * 1024 else: MAX_PACKET_SIZE = 16 * 1024 class SocketConnection(): # pylint: disable=too-many-instance-attributes def __init__( self, local_host=None, local_port=None, remote_host=None, remote_port=None, rcvBufferLength=1492, broadcast=False, blocking=0, timeout=0): self._local_port = local_port self._local_host = local_host self._remote_host = remote_host self._remote_port = remote_port self._rcvBufferLength = rcvBufferLength self.lastAddress = None self.sock = None self.initSocket(broadcast, blocking, timeout) self.coder = msgpack self.packer = msgpack.Packer() self.unpacker = msgpack.Unpacker(use_list=True) self.pack = self.packer.pack self.feed = self.unpacker.feed self.unpack = self.unpacker.unpack def initSocket(self, broadcast=False, blocking=0, timeout=0): if Computer.is_iohub_process is True: from gevent import socket else: import socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if broadcast is True: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, struct.pack('@i', 1)) if blocking: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.settimeout(timeout) self.sock.setblocking(blocking) def sendTo(self, data, address=None): if address is None: address = self._remote_host, self._remote_port max_pkt_sz = 8192 packed_data = self.pack(data) payload_size = len(packed_data) if payload_size > max_pkt_sz: # Send multi packet request to server pkt_cnt = int(payload_size // max_pkt_sz) + 1 mpr_payload = ('IOHUB_MULTIPACKET_REQUEST', pkt_cnt) self.sock.sendto(self.pack(mpr_payload), address) for p in range(pkt_cnt): si = p * max_pkt_sz self.sock.sendto(packed_data[si:si + max_pkt_sz], address) else: self.sock.sendto(packed_data, address) return len(packed_data) def receive(self): try: data, address = self.sock.recvfrom(self._rcvBufferLength) self.lastAddress = address self.feed(data) result = self.unpack() if result[0] == 'IOHUB_MULTIPACKET_RESPONSE': num_packets = result[1] while num_packets > 0: data, address = self.sock.recvfrom(self._rcvBufferLength) self.feed(data) num_packets = num_packets - 1 result = self.unpack() return result, address except: pass def close(self): self.sock.close() class UDPClientConnection(SocketConnection): def __init__(self, remote_host='127.0.0.1', remote_port=9000, rcvBufferLength=MAX_PACKET_SIZE, broadcast=False, blocking=1, timeout=None): SocketConnection.__init__(self, remote_host=remote_host, remote_port=remote_port, rcvBufferLength=rcvBufferLength, broadcast=broadcast, blocking=blocking, timeout=timeout) self.sock.settimeout(timeout) def initSocket(self, broadcast=False, blocking=1, timeout=None): if Computer.is_iohub_process is True: from gevent import socket else: import socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, MAX_PACKET_SIZE) self.sock.settimeout(timeout) self.sock.setblocking(blocking) ##### TIME SYNC CLASS ###### class ioHubTimeSyncConnection(UDPClientConnection): """A special purpose version of the UDPClientConnection class which has the only job of sending and receiving time sync rmessage requests and responses with a remote ioHub Server instance.""" def __init__(self, remote_address): self.remote_iohub_address = tuple(remote_address) UDPClientConnection.__init__( self, remote_host=self.remote_iohub_address[0], remote_port=self.remote_iohub_address[1], rcvBufferLength=MAX_PACKET_SIZE, broadcast=False, blocking=1, timeout=1) self.sync_batch_size = 5 def sync(self): sync_count = self.sync_batch_size sync_data = ['SYNC_REQ', ] feed = self.feed unpack = self.unpack pack = self.pack recvfrom = self.sock.recvfrom rcvBufferLength = self._rcvBufferLength remote_address = self.remote_iohub_address sendto = self.sock.sendto min_delay = 1000.0 min_local_time = 0.0 min_remote_time = 0.0 while sync_count > 0: # send sync request sync_start = Computer.getTime() sendto(pack(sync_data), remote_address) sync_start2 = Computer.getTime() # get reply feed(recvfrom(rcvBufferLength)[0]) _, remote_time = unpack() sync_end = Computer.getTime() rtt = sync_end - (sync_start + sync_start2) / 2.0 old_delay = min_delay min_delay = min(min_delay, rtt) if old_delay != min_delay: min_local_time = (sync_end + sync_start) / 2.0 min_remote_time = remote_time sync_count = sync_count - 1 return min_delay, min_local_time, min_remote_time class ioHubTimeGreenSyncManager(Greenlet): """The time synchronization manager class used within an ioHub Server when a ioHubRemoteEventSubscriber device is running. The time synchronization manager monitors and calculates the ongoing offset and drift between the local ioHub instance and a remote ioHub instance running on another computer that is publishing events that are being received by the local ioHubRemoteEventSubscriber. """ def __init__(self, remote_address, sync_state_target): try: Greenlet.__init__(self) self._sync_socket = None self.initial_sync_interval = 0.2 self._remote_address = remote_address while self._sync_socket is None: self._sync_socket = ioHubTimeSyncConnection(remote_address) sleep(1) self.sync_state_target = proxy(sync_state_target) self._running = False except Exception: # pylint: disable=broad-except print2err( '** Exception during ioHubTimeGreenSyncManager.__init__: ', self._remote_address) printExceptionDetailsToStdErr() def _run(self): # pylint: disable=method-hidden self._running = True while self._sync(False) is False: sleep(0.5) self._sync(False) while self._running is True: sleep(self.initial_sync_interval) r = self._sync() if r is False: print2err( 'SYNC FAILED: ioHubTimeGreenSyncManager {0}.'.format( self._remote_address)) self._close() def _sync(self, calc_drift_and_offset=True): try: if self._sync_socket: r = self._sync_socket.sync() min_delay, min_local_time, min_remote_time = r sync_state_target = self.sync_state_target sync_state_target.RTTs.append(min_delay) sync_state_target.L_times.append(min_local_time) sync_state_target.R_times.append(min_remote_time) if calc_drift_and_offset is True: l1 = sync_state_target.L_times[-2] l2 = sync_state_target.L_times[-1] r1 = sync_state_target.R_times[-2] r2 = sync_state_target.R_times[-1] self.sync_state_target.drifts.append((r2 - r1) / (l2 - l1)) l = sync_state_target.L_times[-1] r = sync_state_target.R_times[-1] self.sync_state_target.offsets = (r - l) except Exception: # pylint: disable=broad-except return False return True def _close(self): if self._sync_socket: self._running = False self._sync_socket.close() self._sync_socket = None def __del__(self): self._close() class ioHubTimeSyncManager(): def __init__(self, remote_address, sync_state_target): self.initial_sync_interval = 0.2 self._remote_address = remote_address self._sync_socket = ioHubTimeSyncConnection(remote_address) self.sync_state_target = proxy(sync_state_target) def sync(self, calc_drift_and_offset=True): if self._sync_socket: r = self._sync_socket.sync() min_delay, min_local_time, min_remote_time = r sync_state_target = self.sync_state_target sync_state_target.RTTs.append(min_delay) sync_state_target.L_times.append(min_local_time) sync_state_target.R_times.append(min_remote_time) if calc_drift_and_offset is True: l1 = sync_state_target.L_times[-2] l2 = sync_state_target.L_times[-1] r1 = sync_state_target.R_times[-2] r2 = sync_state_target.R_times[-1] self.sync_state_target.drifts.append((r2 - r1) / (l2 - l1)) l = sync_state_target.L_times[-1] r = sync_state_target.R_times[-1] self.sync_state_target.offsets = (r - l) def close(self): if self._sync_socket: self._sync_socket.close() self._sync_socket = None def __del__(self): self.close() class TimeSyncState(): """Container class used by an ioHubSyncManager to hold the data necessary to calculate the current time base offset and drift between an ioHub Server and a ioHubRemoteEventSubscriber client.""" RTTs = RingBuffer(10) L_times = RingBuffer(10) R_times = RingBuffer(10) drifts = RingBuffer(20) offsets = RingBuffer(20) def getDrift(self): """Current drift between two time bases.""" return self.drifts.mean() def getOffset(self): """Current offset between two time bases.""" return self.offsets.mean() def getAccuracy(self): """Current accuracy of the time synchronization, as calculated as the. average of the last 10 round trip time sync request - response delays divided by two. """ return self.RTTs.mean() / 2.0 def local2RemoteTime(self, local_time=None): """Converts a local time (sec.msec format) to the corresponding remote computer time, using the current offset and drift measures.""" if local_time is None: local_time = Computer.getTime() return self.getDrift() * local_time + self.getOffset() def remote2LocalTime(self, remote_time): """Converts a remote computer time (sec.msec format) to the corresponding local time, using the current offset and drift measures.""" return (remote_time - self.getOffset()) / self.getDrift()
12,510
Python
.py
289
32.266436
85
0.600937
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,650
errors.py
psychopy_psychopy/psychopy/iohub/errors.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import sys import traceback def print2err(*args): """ Note: As of at least Jan-2020, this function seems to cause iohub to fail to start if the script is started from Coder. try: except: at least stops whatever is crashing, (Appears to be use of sys.stderr.write) but prints() do not appear in Coder Console. Not sure how to get iohub process prints to appear in Builder Console...??? Issue is specific to running script from Coder. Using the standard python print() function from the iohub server process will not print anything to the psychopy process stdout. Use print2err for this purpose. Each element of *args is unicode formatted and then written to sys.stderr. :param args: 0 to N objects of any type. """ try: for a in args: sys.stderr.write("{0}".format(a)) sys.stderr.write("\n") sys.stderr.flush() except: for a in args: print("{0}".format(a)) print() def printExceptionDetailsToStdErr(): """ Print the last raised exception in the iohub (well, calling) process to the psychopy process stderr. """ try: traceback.print_exc(file=sys.stderr) sys.stderr.flush() except: traceback.print_exc() class ioHubError(Exception): #TODO: Fix the way exceptions raised in the iohub process are handled # and reported to the psychopy process. def __init__(self, *args, **kwargs): Exception.__init__(self, *args) self.args = args self.kwargs = kwargs def __str__(self): return repr(self) def __repr__(self): r = 'ioHubError:\nArgs: {0}\n'.format(self.args) for k, v in self.kwargs.items(): r += '\t{0}: {1}\n'.format(k, v) return r
2,035
Python
.py
53
31.924528
85
0.653551
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,651
constants.py
psychopy_psychopy/psychopy/iohub/constants.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import sys from .errors import print2err # pylint: disable=too-many-lines class Constants: UNDEFINED = 0 _keys = None _names = None _classes = None _initialized = False @classmethod def getName(cls, cid): """Return the constant's name given a valid constant id. Args: cid (int): Constant's id representation. Returns: str: The name for the given constant id. """ return cls._names.get(cid, cls._names[cls.UNDEFINED]) @classmethod def getID(cls, name): """Return the constant's id given a valid constant name string. Args: name (str): Constant's name representation. Returns: int: The id for the given constant name. """ return cls._names.get(name, None) @classmethod def getClass(cls, cid): """Return the constant's ioHub CLass Name given constant id. If no class is associated with the specified constant value, None is returned. Args: cid (int): Constant's id representation. Returns: class: The ioHub class for the constant id provided. """ return cls._classes.get(cid, None) @classmethod def initialize(cls, starting_index=1): if cls._initialized: return for i, a in enumerate(dir(cls)): if ((a[0] != '_') and (not callable(getattr(cls, a))) and (getattr(cls, a) < 0)): setattr(cls, a, i + starting_index) cls._names = dict([(getattr(cls, a), a) for a in dir(cls) if ( (a[0] != '_') and (not callable(getattr(cls, a))))]) cls._keys = list(cls._names.keys()) cls._names.update(dict([(v, k) for k, v in cls._names.items()])) cls._initialized = True @classmethod def getConstants(cls): return cls._names class EventConstants(Constants): """ EventConstants contains ioHub Device Event type constants, with methods to convert between the different associated constant value types for a given event type: * int constant * str constant * event class associated with a constant Access event constants using the EventConstants class attributes & methods. """ KEYBOARD_INPUT = 20 #: Constant for a Keyboard Press Event. KEYBOARD_PRESS = 22 #: Constant for a Keyboard Release Event. KEYBOARD_RELEASE = 23 MOUSE_INPUT = 30 MOUSE_BUTTON = 31 #: Constant for a Mouse Button Press Event. MOUSE_BUTTON_PRESS = 32 #: Constant for a Mouse Button Release Event. MOUSE_BUTTON_RELEASE = 33 #: Constant for a Mouse Double Click Event. #: Deprecated for MOUSE_MULTI_CLICK in 0.6RC1 MOUSE_DOUBLE_CLICK = 34 #: Constant for a Mouse Multiple Click Event. MOUSE_MULTI_CLICK = 34 #: Constant for a Mouse Scroll Wheel Event. MOUSE_SCROLL = 35 #: Constant for a Mouse Move Event. MOUSE_MOVE = 36 #: Constant for a Mouse Drag Event. MOUSE_DRAG = 37 TOUCH = 40 #: Constant for a Touch motion Event. TOUCH_MOVE = 41 #: Constant for an initial Touch press Event. TOUCH_PRESS = 42 #: Constant for a Touch release Event. TOUCH_RELEASE = 43 EYETRACKER = 50 #: Constant for an Eye Tracker Monocular Sample Event. MONOCULAR_EYE_SAMPLE = 51 #: Constant for an Eye Tracker Binocular Sample Event. BINOCULAR_EYE_SAMPLE = 52 #: Constant for an Eye Tracker Fixation Start Event. FIXATION_START = 53 #: Constant for an Eye Tracker Fixation End Event. FIXATION_END = 54 #: Constant for an Eye Tracker Saccade Start Event. SACCADE_START = 55 #: Constant for an Eye Tracker Saccade End Event. SACCADE_END = 56 #: Constant for an Eye Tracker Blink Start Event. BLINK_START = 57 #: Constant for an Eye Tracker Blink End Event. BLINK_END = 58 #: Constant for a Basic Eye Tracker Sample Event. EYE_SAMPLE = 59 #: Constant for a GazePoint specific Sample Event. GAZEPOINT_SAMPLE = 60 #: Constant for a Gamepad Event. GAMEPAD_STATE_CHANGE = 81 GAMEPAD_DISCONNECT = 82 WINTAB_INPUT = 90 #: Constant for a WinTab Pen Sample Event. WINTAB_SAMPLE = 91 #: Constant for a WinTab Pen Region Entered Event. WINTAB_ENTER_REGION = 92 #: Constant for a WinTab Pen Region Leave Event. WINTAB_LEAVE_REGION = 93 #: Constant for MCU digital input Event. DIGITAL_INPUT = 101 #: Constant for MCU analog input Event. ANALOG_INPUT = 102 #: Constant for MCU analog threshold state change Event. THRESHOLD = 103 #: Constant for a general purpose Serial Rx Event. SERIAL_INPUT = 105 #: Constant for a serial event due to a rx stream byte value diff. SERIAL_BYTE_CHANGE = 106 #: Constant for a PST Box event due to a button state change. PSTBOX_BUTTON = 107 #: Constant for an Eight Channel Analog Input Sample Event. MULTI_CHANNEL_ANALOG_INPUT = 122 #: Constant for an Experiment Message Event. MESSAGE = 151 #: Constant for an Experiment Log Event. LOG = 152 def __init__(self): pass @classmethod def addClassMappings(cls, device_event_ids, event_classes): if cls._classes is None: cls._classes = {} for event_id in device_event_ids: event_constant_string = cls.getName(event_id) event_class = None for event_class in event_classes.values(): if event_class.EVENT_TYPE_ID == event_id: cls._classes[event_id] = event_class cls._classes[event_class] = event_id break if event_id not in cls._classes: print2err('\t*** ERROR ADDING EVENT CLASS MAPPING:', ' Could not find class: ', event_constant_string, ' = ', event_id) EventConstants.initialize() EYE_SAMPLE_TYPES = [EventConstants.EYE_SAMPLE, EventConstants.MONOCULAR_EYE_SAMPLE, EventConstants.BINOCULAR_EYE_SAMPLE, EventConstants.GAZEPOINT_SAMPLE] class DeviceConstants(Constants): """ DeviceConstants contains the ioHub Device type constants, with methods to convert between the different associated constant value types for a given device type:: * int constant * str constant * device class associated with a constant Access device constants using the DeviceConstants class attributes & methods. """ #: Constant for a Device Type not currently categorized. OTHER = 1 #: Constant for a Keyboard Device. KEYBOARD = 20 #: Constant for a Mouse Device. MOUSE = 30 #: Constant for a Touch Device. TOUCH = 40 #: Constant for an EyeTracker Device. EYETRACKER = 50 #: Constant for a Network Device EVENTPUBLISHER = 61 #: Constant for a Network Device REMOTEEVENTSUBSCRIBER = 62 XINPUT = 70 #: Constant for Gamepad Device. GAMEPAD = 80 #: Constant for Tablet Device that uses WinTab DLL. WINTAB = 90 #: Constant for a MCU Device. MCU = 100 #: Constant for a General Purpose Serial Interface Device. SERIAL = 110 #: Constant for PST Serial Response Box PSTBOX = 111 #: Constant for an AnalogInput Device. ANALOGINPUT = 120 #: Constant for an Experiment Device. EXPERIMENT = 150 #: Constant for a Display Device. DISPLAY = 190 #: Constant for a Computer Device. COMPUTER = 200 def __init__(self): pass @classmethod def addClassMapping(cls, device_class): if cls._classes is None: cls._classes = {} device_constant_string = device_class.__name__.upper() device_id = getattr(cls, device_constant_string) cls._classes[device_id] = device_class cls._classes[device_class] = device_id DeviceConstants.initialize() class MouseConstants(Constants): """MouseConstants provides access to ioHub Mouse Device specific constants.""" #: Constant representing that no Mouse buttons are pressed. MOUSE_BUTTON_NONE = 0 #: Constant representing that the left Mouse button is pressed. MOUSE_BUTTON_LEFT = 1 #: Constant representing that the right Mouse button is pressed. MOUSE_BUTTON_RIGHT = 2 #: Constant representing that the middle Mouse button is pressed. MOUSE_BUTTON_MIDDLE = 4 #: Constant representing a mouse button is in a released state. MOUSE_BUTTON_STATE_RELEASED = 10 #: Constant representing a mouse button is in a pressed state. MOUSE_BUTTON_STATE_PRESSED = 11 #: Constant representing a mouse is in a multiple click state. MOUSE_BUTTON_STATE_MULTI_CLICK = 12 MOUSE_BUTTON_4 = 8 MOUSE_BUTTON_5 = 16 MOUSE_BUTTON_6 = 32 MOUSE_BUTTON_7 = 64 MOUSE_BUTTON_8 = 128 MOUSE_BUTTON_9 = 256 def __init__(self): pass MouseConstants.initialize() # pylint: disable=protected-access if sys.platform == 'win32': class AsciiConstants(Constants): # Mainly from the pyHook lookup Table, some from Pyglet BACKSPACE = 0x08 TAB = 0x09 LINEFEED = 0x0A CLEAR = 0x0B RETURN = 0x0D SYSREQ = 0x15 ESCAPE = 0x1B SPACE = 0x20 EXCLAMATION = 0x21 DOUBLEQUOTE = 0x22 POUND = 0x23 DOLLAR = 0x24 PERCENT = 0x25 AMPERSAND = 0x26 APOSTROPHE = 0x27 PARENLEFT = 0x28 PARENRIGHT = 0x29 ASTERISK = 0x2A PLUS = 0x2B COMMA = 0x2C MINUS = 0x2D PERIOD = 0x2E SLASH = 0x2F n0_ = 0x30 n1_ = 0x31 n2_ = 0x32 n3_ = 0x33 n4_ = 0x34 n5_ = 0x35 n6_ = 0x36 n7_ = 0x37 n8_ = 0x38 n9_ = 0x39 COLON = 0x3A SEMICOLON = 0x3B LESS = 0x3C EQUAL = 0x3D GREATER = 0x3E QUESTION = 0x3F AT = 0x40 A = 0x41 B = 0x42 C = 0x43 D = 0x44 E = 0x45 F = 0x46 G = 0x47 H = 0x48 I = 0x49 J = 0x4A K = 0x4B L = 0x4C M = 0x4D N = 0x4E O = 0x4F P = 0x50 Q = 0x51 R = 0x52 S = 0x53 T = 0x54 U = 0x55 V = 0x56 W = 0x57 X = 0x58 Y = 0x59 Z = 0x5A BRACKETLEFT = 0x5B BACKSLASH = 0x5C BRACKETRIGHT = 0x5D ASCIICIRCUM = 0x5E UNDERSCORE = 0x5F GRAVE = 0x60 a = 0x61 b = 0x62 c = 0x63 d = 0x64 e = 0x65 f = 0x66 g = 0x67 h = 0x68 i = 0x69 j = 0x6A k = 0x6B l = 0x6C m = 0x6D n = 0x6E o = 0x6F p = 0x70 q = 0x71 r = 0x72 s = 0x73 t = 0x74 u = 0x75 v = 0x76 w = 0x77 x = 0x78 y = 0x79 z = 0x7A BRACELEFT = 0x7B BAR = 0x7C BRACERIGHT = 0x7D ASCIITILDE = 0x7E @classmethod def getName(cls, cid): return cls._names.get(cid, None) AsciiConstants.initialize() class VirtualKeyCodes(Constants): # Mainly from the pyHook lookup Table, some from Pyglet VK_CANCEL = 0x03 VK_BACKSPACE = 0x08 VK_TAB = 0x09 VK_CLEAR = 0x0C VK_RETURN = 0x0D VK_SHIFT = 0x10 VK_CONTROL = 0x11 VK_MENU = 0x12 VK_PAUSE = 0x13 VK_capslock = 0x14 VK_CAPITAL = 0x14 VK_CAPS_LOCK = 0x14 VK_HANGUL = 0x15 VK_JUNJA = 0x17 VK_FINAL = 0x18 VK_HANJA = 0x19 VK_ESCAPE = 0x1B VK_CONVERT = 0x1C VK_NONCONVERT = 0x1D VK_ACCEPT = 0x1E VK_MODECHANGE = 0x1F VK_SPACE = 0x20 VK_PAGEUP = 0x21 VK_PAGEDOWN = 0x22 VK_END = 0x23 VK_HOME = 0x24 VK_LEFT = 0x25 VK_UP = 0x26 VK_RIGHT = 0x27 VK_DOWN = 0x28 VK_SELECT = 0x29 VK_PRINT = 0x2A VK_EXECUTE = 0x2B VK_PRINT_SCREEN = 0x2C VK_INSERT = 0x2D VK_DELETE = 0x2E VK_HELP = 0x2F VK_LWIN = 0x5B VK_RWIN = 0x5C VK_APPS = 0x5D VK_lcmd = 0x5B VK_rcmd = 0x5C VK_menu = 0x5D VK_NUMPAD0 = 0x60 VK_NUMPAD1 = 0x61 VK_NUMPAD2 = 0x62 VK_NUMPAD3 = 0x63 VK_NUMPAD4 = 0x64 VK_NUMPAD5 = 0x65 VK_NUMPAD6 = 0x66 VK_NUMPAD7 = 0x67 VK_NUMPAD8 = 0x68 VK_NUMPAD9 = 0x69 VK_NUMPADMULTIPLY = 0x6A VK_NUMPADADD = 0x6B VK_SEPARATOR = 0x6C VK_NUMPADSUBTRACT = 0x6D VK_NUMPADDECIMAL = 0x6E VK_NUMPADDIVIDE = 0x6F VK_F1 = 0x70 VK_F2 = 0x71 VK_F3 = 0x72 VK_F4 = 0x73 VK_F5 = 0x74 VK_F6 = 0x75 VK_F7 = 0x76 VK_F8 = 0x77 VK_F9 = 0x78 VK_F10 = 0x79 VK_F11 = 0x7A VK_F12 = 0x7B VK_F13 = 0x7C VK_F14 = 0x7D VK_F15 = 0x7E VK_F16 = 0x7F VK_F17 = 0x80 VK_F18 = 0x81 VK_F19 = 0x82 VK_F20 = 0x83 VK_F21 = 0x84 VK_F22 = 0x85 VK_F23 = 0x86 VK_F24 = 0x87 VK_NUM_LOCK = 0x90 VK_SCROLL = 0x91 VK_LSHIFT = 0xA0 VK_RSHIFT = 0xA1 VK_LCONTROL = 0xA2 VK_RCONTROL = 0xA3 VK_LMENU = 0xA4 VK_RMENU = 0xA5 VK_numlock = 0x90 VK_scrolllock = 0x91 VK_lshift = 0xA0 VK_rshift = 0xA1 VK_lctrl = 0xA2 VK_rctrl = 0xA3 VK_lalt = 0xA4 VK_ralt = 0xA5 VK_BROWSER_BACK = 0xA6 VK_BROWSER_FORWARD = 0xA7 VK_BROWSER_REFRESH = 0xA8 VK_BROWSER_STOP = 0xA9 VK_BROWSER_SEARCH = 0xAA VK_BROWSER_FAVORITES = 0xAB VK_BROWSER_HOME = 0xAC VK_VOLUME_MUTE = 0xAD VK_VOLUME_DOWN = 0xAE VK_VOLUME_UP = 0xAF VK_MEDIA_NEXT_TRACK = 0xB0 VK_MEDIA_PREV_TRACK = 0xB1 VK_MEDIA_STOP = 0xB2 VK_MEDIA_PLAY_PAUSE = 0xB3 VK_LAUNCH_MAIL = 0xB4 VK_LAUNCH_MEDIA_SELECT = 0xB5 VK_LAUNCH_APP1 = 0xB6 VK_LAUNCH_APP2 = 0xB7 VK_PROCESSKEY = 0xE5 VK_PACKET = 0xE7 VK_ATTN = 0xF6 VK_CRSEL = 0xF7 VK_EXSEL = 0xF8 VK_EREOF = 0xF9 VK_PLAY = 0xFA VK_ZOOM = 0xFB VK_NONAME = 0xFC VK_PA1 = 0xFD VK_OEM_CLEAR = 0xFE @classmethod def getName(cls, cid): return cls._names.get(cid, None) VirtualKeyCodes.initialize() elif sys.platform.startswith('linux'): class VirtualKeyCodes(Constants): @classmethod def getName(cls, cid): return cls._names.get(cid, None) VirtualKeyCodes.initialize() elif sys.platform == 'darwin': class AnsiKeyCodes(Constants): ANSI_Equal = 0x18 ANSI_Minus = 0x1B ANSI_RightBracket = 0x1E ANSI_LeftBracket = 0x21 ANSI_Quote = 0x27 ANSI_Semicolon = 0x29 ANSI_Backslash = 0x2A ANSI_Comma = 0x2B ANSI_Slash = 0x2C ANSI_Period = 0x2F ANSI_Grave = 0x32 ANSI_KeypadDecimal = 0x41 ANSI_KeypadMultiply = 0x43 ANSI_KeypadPlus = 0x45 ANSI_KeypadClear = 0x47 ANSI_KeypadDivide = 0x4B ANSI_KeypadEnter = 0x4C ANSI_KeypadMinus = 0x4E ANSI_KeypadEquals = 0x51 ANSI_Keypad0 = 0x52 ANSI_Keypad1 = 0x53 ANSI_Keypad2 = 0x54 ANSI_Keypad3 = 0x55 ANSI_Keypad4 = 0x56 ANSI_Keypad5 = 0x57 ANSI_Keypad6 = 0x58 ANSI_Keypad7 = 0x59 ANSI_Keypad8 = 0x5B ANSI_Keypad9 = 0x5C @classmethod def getName(cls, cid): return cls._names.get(cid, None) AnsiKeyCodes.initialize() AnsiKeyCodes._keys.remove(AnsiKeyCodes.getID('UNDEFINED')) class UnicodeChars(Constants): VK_RETURN = 0x0003 RETURN = 0x000D VK_DELETE = 0x007F # "Delete" TAB = 0x0009 # "Tab" ESCAPE = 0x001b # "Escape" UP = 0xf700 # "Up" DOWN = 0xF701 # "Down" LEFT = 0xF702 # "Left" RIGHT = 0xF703 # "Right" F1 = 0xF704 # "F1" F2 = 0xF705 # "F2" F3 = 0xF706 # "F3" F4 = 0xF707 # "F4" F5 = 0xF708 # "F5" F6 = 0xF709 # "F6" F7 = 0xF70A # "F7" F8 = 0xF70B # "F8" F9 = 0xF70C # "F9" F10 = 0xF70D # "F10" F11 = 0xF70E # "F11" F12 = 0xF70F # "F12" F13 = 0xF710 # "F13" F14 = 0xF711 # "F14" F15 = 0xF712 # "F15" F16 = 0xF713 # "F16" F17 = 0xF714 # "F17" F18 = 0xF715 # "F18" F19 = 0xF716 # "F19" F20 = 0xF717 # "F20" F21 = 0xF718 # "F21" F22 = 0xF719 # "F22" F23 = 0xF71A # "F23" F24 = 0xF71B # "F24" F25 = 0xF71C # "F25" F26 = 0xF71D # "F26" F27 = 0xF71E # "F27" F28 = 0xF71F # "F28" F29 = 0xF720 # "F29" F30 = 0xF721 # "F30" F31 = 0xF722 # "F31" F32 = 0xF723 # "F32" F33 = 0xF724 # "F33" F34 = 0xF725 # "F34" F35 = 0xF726 # "F35" INSERT = 0xF727 # "Insert" DELETE = 0xF728 # "Delete" HOME = 0xF729 # "Home" BEGIN = 0xF72A # "Begin" END = 0xF72B # "End" PAGE_UP = 0xF72C # "PageUp" PAGE_DOWN = 0xF72D # "PageDown" PRINT_SCREEN = 0xF72E # "PrintScreen" SCROLL_LOCK = 0xF72F # "ScrollLock" PAUSE = 0xF730 # "Pause" SYSREQ = 0xF731 # "SysReq" BREAK = 0xF732 # "Break" RESET = 0xF733 # "Reset" STOP = 0xF734 # "Stop" MENU = 0xF735 # "Menu" VK_MENU = 0x0010 # Menu key on non-apple US keyboards USER = 0xF736 # "User" SYSTEM = 0xF737 # "System" PRINT = 0xF738 # "Print" CLEAR_LINE = 0xF739 # "ClearLine" CLEAR = 0xF73A # "ClearDisplay" INSERT_LINE = 0xF73B # "InsertLine" DELETE_LINE = 0xF73C # "DeleteLine" INSERT_CHAR = 0xF73D # "InsertChar" DELETE_CHAR = 0xF73E # "DeleteChar" PREV = 0xF73F # "Prev" NEXT = 0xF740 # "Next" SELECT = 0xF741 # "Select" EXECUTE = 0xF742 # "Execute" UNDO = 0xF743 # "Undo" REDO = 0xF744 # "Redo" FIND = 0xF745 # "Find" HELP = 0xF746 # "Help" MODE = 0xF747 # "ModeSwitch" SHIFT = 0x21E7 # Unicode UPWARDS WHITE ARROW CONTROL = 0x2303 # Unicode UP ARROWHEAD OPTION = 0x2325 # Unicode OPTION KEY COMMAND = 0x2318 # Unicode PLACE OF INTEREST SIGN # Unicode LOWER RIGHT PENCIL; actually pointed left until Mac OS X 10.3 PENCIL_RIGHT = 0x270E # Unicode LOWER LEFT PENCIL; available in Mac OS X 10.3 and later PENCIL_LEFT = 0xF802 CHECK = 0x2713 # Unicode CHECK MARK DIAMOND = 0x25C6 # Unicode BLACK DIAMOND BULLET = 0x2022 # Unicode BULLET APPLE_LOGO = 0xF8FF # Unicode APPLE LOGO @classmethod def getName(cls, cid): return cls._names.get(cid, None) UnicodeChars.initialize() UnicodeChars._keys.remove(UnicodeChars.getID('UNDEFINED')) class VirtualKeyCodes(Constants): F1 = 145 # Keycode on Apple wireless kb F2 = 144 # Keycode on Apple wireless kb F3 = 160 # Keycode on Apple wireless kb F4 = 131 # Keycode on Apple wireless kb VK_ISO_SECTION = 0x0A VK_JIS_YEN = 0x5D VK_JIS_UNDERSCORE = 0x5E VK_JIS_KEYPAD_COMMA = 0x5F VK_JIS_EISU = 0x66 VK_JIS_KANA = 0x68 VK_RETURN = 0x24 VK_TAB = 0x30 VK_SPACE = 0x31 VK_DELETE = 0x33 VK_ESCAPE = 0x35 VK_COMMAND = 0x37 VK_SHIFT = 0x38 VK_CAPS_LOCK = 0x39 VK_OPTION = 0x3A VK_CONTROL = 0x3B VK_SHIFT_RIGHT = 0x3C VK_OPTION_RIGHT = 0x3D VK_CONTROL_RIGHT = 0x3E VK_FUNCTION = 0x3F VK_F17 = 0x40 VK_VOLUME_UP = 0x48 VK_VOLUME_DOWN = 0x49 VK_VOLUME_MUTE = 0x4A VK_F18 = 0x4F VK_F19 = 0x50 VK_F20 = 0x5A VK_F5 = 0x60 VK_F6 = 0x61 VK_F7 = 0x62 VK_F3 = 0x63 VK_F8 = 0x64 VK_F9 = 0x65 VK_F11 = 0x67 VK_F13 = 0x69 VK_F16 = 0x6A VK_F14 = 0x6B VK_F10 = 0x6D VK_MENU = 0x6E VK_F12 = 0x6F VK_F15 = 0x71 VK_HELP = 0x72 VK_HOME = 0x73 VK_PAGE_UP = 0x74 VK_DEL = 0x75 VK_F4 = 0x76 VK_END = 0x77 VK_F2 = 0x78 VK_PAGE_DOWN = 0x79 VK_LEFT = 0x7B VK_UP = 0x7E VK_RIGHT = 0x7C VK_DOWN = 0x7D VK_F1 = 0x7A KEY_EQUAL = 24 KEY_MINUS = 27 KEY_RIGHT_SQUARE_BRACKET = 30 KEY_LEFT_SQUARE_BRACKET = 33 KEY_RETURN = 36 KEY_SINGLE_QUOTE = 39 KEY_SEMICOLAN = 41 KEY_BACKSLASH = 42 KEY_COMMA = 43 KEY_FORWARD_SLASH = 44 KEY_PERIOD = 47 KEY_TAB = 48 KEY_SPACE = 49 KEY_LEFT_SINGLE_QUOTE = 50 KEY_DELETE = 51 KEY_ENTER = 52 KEY_ESCAPE = 53 KEYPAD_PERIOD = 65 KEYPAD_MULTIPLY = 67 KEYPAD_PLUS = 69 KEYPAD_CLEAR = 71 KEYPAD_DIVIDE = 75 KEYPAD_ENTER = 76 # numberpad on full kbd KEYPAD_EQUALS = 78 KEYPAD_EQUAL = 81 KEYPAD_0 = 82 KEYPAD_1 = 83 KEYPAD_2 = 84 KEYPAD_3 = 85 KEYPAD_4 = 86 KEYPAD_5 = 87 KEYPAD_6 = 88 KEYPAD_7 = 89 KEYPAD_8 = 91 KEYPAD_9 = 92 KEY_F5 = 96 KEY_F6 = 97 KEY_F7 = 98 KEY_F3 = 99 KEY_F8 = 100 KEY_F9 = 101 KEY_F11 = 103 KEY_F13 = 105 KEY_F14 = 107 KEY_F10 = 109 KEY_F12 = 111 KEY_F15 = 113 KEY_HELP = 114 KEY_HOME = 115 KEY_PGUP = 116 KEY_DELETE = 117 KEY_F4 = 118 KEY_END = 119 KEY_F2 = 120 KEY_PGDN = 121 KEY_F1 = 122 KEY_LEFT = 123 KEY_RIGHT = 124 KEY_DOWN = 125 KEY_UP = 126 @classmethod def getName(cls, cid): return cls._names.get(cid, None) VirtualKeyCodes.initialize() VirtualKeyCodes._keys.remove(VirtualKeyCodes.getID('UNDEFINED')) class ModifierKeyCodes(Constants): _mod_names = [ 'lctrl', 'rctrl', 'lshift', 'rshift', 'lalt', 'ralt', 'lcmd', 'rcmd', 'capslock', 'MOD_SHIFT', 'MOD_ALT', 'MOD_CTRL', 'MOD_CMD', 'numlock', 'function', 'modhelp', 'scrolllock'] lctrl = 1 rctrl = 2 lshift = 4 rshift = 8 lalt = 16 ralt = 32 lcmd = 64 rcmd = 128 capslock = 256 MOD_SHIFT = 512 MOD_ALT = 1024 MOD_CTRL = 2048 MOD_CMD = 4096 numlock = 8192 function = 16384 modhelp = 32768 scrolllock = modhelp * 2 ModifierKeyCodes.initialize() ModifierKeyCodes._keys.remove(ModifierKeyCodes.getID('UNDEFINED')) class KeyboardConstants(Constants): """Stores internally used mappings between OS and iohub keyboard key constants.""" _virtualKeyCodes = VirtualKeyCodes() if sys.platform == 'win32': _asciiKeyCodes = AsciiConstants() if sys.platform == 'darwin': _unicodeChars = UnicodeChars() _ansiKeyCodes = AnsiKeyCodes() _modifierCodes = ModifierKeyCodes() @classmethod def getName(cls, cid): return cls._names.get(cid, None) @classmethod def _getKeyName(cls, keyEvent): vcode_name = KeyboardConstants._virtualKeyCodes.getName( keyEvent.KeyID) if vcode_name: if vcode_name.startswith('VK_NUMPAD'): return 'num_%s' % (vcode_name[9:].lower()) return vcode_name[3:].lower() else: phkey = keyEvent.Key.lower() if phkey.startswith('numpad'): phkey = 'num_%s' % (phkey.Key[6:]) return phkey @classmethod def _getKeyNameAndModsForEvent(cls, keyEvent): return cls._getKeyName( keyEvent), cls.getModifiersForEvent(keyEvent) @classmethod def getModifiersForEvent(cls, event): return cls._modifierCodes2Labels(event.Modifiers) @classmethod def _modifierCodes2Labels(cls, mods): if mods == 0: return [] modconstants = cls._modifierCodes modNameList = [] for k in modconstants._keys: mc = modconstants._names[k] if mods & k == k: modNameList.append(mc) mods = mods - k if mods == 0: return modNameList return modNameList KeyboardConstants.initialize() class EyeTrackerConstants(Constants): # Sample Filter Levels FILTER_LEVEL_OFF = 0 FILTER_OFF = 0 FILTER_LEVEL_1 = 1 FILTER_LEVEL_2 = 2 FILTER_LEVEL_3 = 3 FILTER_LEVEL_4 = 4 FILTER_LEVEL_5 = 5 FILTER_ON = 9 # Sample Filter Types FILTER_FILE = 10 FILTER_NET = 11 FILTER_ONLINE = 11 FILTER_SERIAL = 12 FILTER_ANALOG = 13 FILTER_ALL = 14 # Eye Type Constants LEFT_EYE = 21 RIGHT_EYE = 22 SIMULATED_MONOCULAR = 23 MONOCULAR = 24 BINOCULAR = 26 BINOCULAR_AVERAGED = 27 BINOCULAR_CUSTOM = 28 SIMULATED_BINOCULAR = 29 # Calibration / Validation Related Constants # Target Point Count NO_POINTS = 40 ONE_POINT = 41 TWO_POINTS = 42 THREE_POINTS = 43 FOUR_POINTS = 44 FIVE_POINTS = 45 SEVEN_POINTS = 47 EIGHT_POINTS = 48 NINE_POINTS = 49 THIRTEEN_POINTS = 53 SIXTEEN_POINTS = 56 TWENTYFIVE_POINTS = 65 CUSTOM_POINTS = 69 # Pattern Dimensionality Types CALIBRATION_HORZ_1D = 130 CALIBRATION_VERT_1D = 131 CALIBRATION_2D = 132 CALIBRATION_3D = 133 # Target Pacing Types AUTO_CALIBRATION_PACING = 90 MANUAL_CALIBRATION_PACING = 91 # Target Shape Types CIRCLE_TARGET = 121 CROSSHAIR_TARGET = 122 IMAGE_TARGET = 123 MOVIE_TARGET = 124 # System Setup Method Initial State Constants DEFAULT_SETUP_PROCEDURE = 100 TRACKER_FEEDBACK_STATE = 101 CALIBRATION_STATE = 102 VALIDATION_STATE = 103 DRIFT_CORRECTION_STATE = 104 # Pupil Measure Type Constants PUPIL_AREA = 70 PUPIL_DIAMETER = 71 PUPIL_WIDTH = 72 PUPIL_HEIGHT = 73 PUPIL_MAJOR_AXIS = 74 PUPIL_MINOR_AXIS = 75 PUPIL_RADIUS = 76 PUPIL_DIAMETER_MM = 77 PUPIL_WIDTH_MM = 78 PUPIL_HEIGHT_MM = 79 PUPIL_MAJOR_AXIS_MM = 80 PUPIL_MINOR_AXIS_MM = 81 PUPIL_RADIUS_MM = 82 # Video Based Eye Tracking Algorithm Constants PUPIL_CR_TRACKING = 140 PUPIL_ONLY_TRACKING = 141 ELLIPSE_FIT = 146 CIRCLE_FIT = 147 CENTROID_FIT = 148 # Eye Tracker Interface Return Code Constants EYETRACKER_OK = 200 # EYETRACKER_ERROR deprecated for EYETRACKER_UNDEFINED_ERROR EYETRACKER_ERROR = 201 EYETRACKER_UNDEFINED_ERROR = 201 # FUNCTIONALITY_NOT_SUPPORTED deprecated for # EYETRACKER_INTERFACE_METHOD_NOT_SUPPORTED FUNCTIONALITY_NOT_SUPPORTED = 202 EYETRACKER_INTERFACE_METHOD_NOT_SUPPORTED = 202 EYETRACKER_CALIBRATION_ERROR = 203 EYETRACKER_VALIDATION_ERROR = 204 EYETRACKER_SETUP_ABORTED = 205 EYETRACKER_NOT_CONNECTED = 206 EYETRACKER_MODEL_NOT_SUPPORTED = 207 EYETRACKER_RECEIVED_INVALID_INPUT = 208 EyeTrackerConstants.initialize() # XInput Gamepad related class XInputBatteryTypeConstants(Constants): # The device is not connected. BATTERY_TYPE_DISCONNECTED = 0x00 # The device is a wired device and does not have a battery. BATTERY_TYPE_WIRED = 0x01 # The device has an alkaline battery. BATTERY_TYPE_ALKALINE = 0x02 # The device has a nickel metal hydride battery. BATTERY_TYPE_NIMH = 0x03 # The device has an unknown battery type. BATTERY_TYPE_UNKNOWN = 0xFF XInputBatteryTypeConstants.initialize() try: XInputBatteryTypeConstants._keys.remove( XInputBatteryTypeConstants.getID('UNDEFINED')) except Exception: # pylint: disable=broad-except pass class XInputBatteryLevelConstants(Constants): # BatteryLevels BATTERY_LEVEL_EMPTY = 0x00 BATTERY_LEVEL_LOW = 0x01 BATTERY_LEVEL_MEDIUM = 0x02 BATTERY_LEVEL_FULL = 0x03 XInputBatteryLevelConstants.initialize() try: XInputBatteryLevelConstants._keys.remove( XInputBatteryLevelConstants.getID('UNDEFINED')) except Exception: # pylint: disable=broad-except pass class XInputCapabilitiesConstants(Constants): UNDEFINED = 9999999 # Device Type XBOX360_GAMEPAD = 0x01 OTHER_XINPUT_GAMEPAD = 0x0 # subtype is defined as 0x01 in xinput.h, redining so no conflicts XINPUT_GAMEPAD = 0x08 XINPUT_UNKNOWN_SUBTYPE = 0x06 XInputCapabilitiesConstants.initialize() try: XInputCapabilitiesConstants._keys.remove( XInputCapabilitiesConstants.getID('UNDEFINED')) except Exception: # pylint: disable=broad-except pass class XInputGamePadConstants(Constants): DPAD_UP = 0x0001 DPAD_DOWN = 0x0002 DPAD_LEFT = 0x0004 DPAD_RIGHT = 0x0008 START = 0x0010 BACK = 0x0020 LEFT_THUMB = 0x0040 RIGHT_THUMB = 0x0080 LEFT_SHOULDER = 0x0100 RIGHT_SHOULDER = 0x0200 A = 0x1000 B = 0x2000 X = 0x4000 Y = 0x8000 _batteryTypes = XInputBatteryTypeConstants() _batteryLevels = XInputBatteryLevelConstants() _capabilities = XInputCapabilitiesConstants() XInputGamePadConstants.initialize() try: XInputGamePadConstants._keys.remove( XInputGamePadConstants.getID('UNDEFINED')) except Exception: # pylint: disable=broad-except pass # pylint: enable=protected-access
30,618
Python
.py
1,007
22.722939
89
0.593744
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,652
__init__.py
psychopy_psychopy/psychopy/iohub/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import sys import platform from .errors import print2err, printExceptionDetailsToStdErr from .util import module_directory if sys.platform == 'darwin': import objc # pylint: disable=import-error EXP_SCRIPT_DIRECTORY = '' def _localFunc(): return None IOHUB_DIRECTORY = module_directory(_localFunc) try: import tables _DATA_STORE_AVAILABLE = True except ModuleNotFoundError: print2err('WARNING: pytables package not found. ', 'ioHub hdf5 datastore functionality will be disabled.') _DATA_STORE_AVAILABLE = False except ImportError: print2err('WARNING: pytables package failed to load. ', 'ioHub hdf5 datastore functionality will be disabled.') _DATA_STORE_AVAILABLE = False except Exception: printExceptionDetailsToStdErr() from psychopy.iohub.constants import EventConstants, KeyboardConstants, MouseConstants lazyImports = """ from psychopy.iohub.client.connect import launchHubServer from psychopy.iohub.devices.computer import Computer from psychopy.iohub.client.eyetracker.validation import ValidationProcedure """ try: from psychopy.contrib.lazy_import import lazy_import lazy_import(globals(), lazyImports) except Exception: exec(lazyImports)
1,467
Python
.py
39
34.487179
86
0.781228
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,653
server.py
psychopy_psychopy/psychopy/iohub/server.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import importlib import os import sys import inspect from operator import itemgetter from collections import deque, OrderedDict import msgpack import gevent from gevent.server import DatagramServer from gevent import Greenlet import numpy try: import msgpack_numpy msgpack_numpy.patch() except ImportError: pass from . import IOHUB_DIRECTORY, EXP_SCRIPT_DIRECTORY, _DATA_STORE_AVAILABLE from .errors import print2err, printExceptionDetailsToStdErr, ioHubError from .net import MAX_PACKET_SIZE from .util import convertCamelToSnake, win32MessagePump from .util import yload, yLoader from .constants import DeviceConstants, EventConstants from .devices import DeviceEvent, import_device, importDeviceModule from .devices import Computer from .devices.deviceConfigValidation import validateDeviceConfiguration getTime = Computer.getTime syncClock = Computer.syncClock # pylint: disable=protected-access # pylint: disable=broad-except def convertByteStrings(rdict): if rdict is None or len(rdict)==0: return rdict result = dict() for k, i in rdict.items(): if isinstance(k, bytes): k = k.decode('utf-8') if isinstance(i, bytes): i = i.decode('utf-8') result[k] = i return result class udpServer(DatagramServer): client_proc_init_req = None def __init__(self, ioHubServer, address): self.iohub = ioHubServer self.feed = None self._running = True self.iohub.log('ioHub Server configuring msgpack...') self.coder = msgpack self.packer = msgpack.Packer() self.pack = self.packer.pack self.unpacker = msgpack.Unpacker(use_list=True) self.unpack = self.unpacker.unpack self.feed = self.unpacker.feed self.multipacket_reads = 0 DatagramServer.__init__(self, address) def handle(self, request, replyTo): if self._running is False: return False self.feed(request) if self.multipacket_reads > 0: # Multi packet request handling... self.multipacket_reads -= 1 if self.multipacket_reads > 0: # If reading part of multi packet request, just return and wait for next part of request return False request = self.unpack() if request[0] == 'IOHUB_MULTIPACKET_REQUEST': # setup multi packet request read self.multipacket_reads = request[1] return False else: self.multipacket_reads = 0 request_type = request.pop(0) if not isinstance(request_type, str): request_type = str(request_type, 'utf-8') # convert bytes to string for compatibility if request_type == 'SYNC_REQ': self.sendResponse(['SYNC_REPLY', getTime()], replyTo) return True elif request_type == 'PING': _ = request.pop(0) #client time msg_id = request.pop(0) payload = request.pop(0) ctime = getTime() self.sendResponse(['PING_BACK', ctime, msg_id, payload, replyTo], replyTo) return True elif request_type == 'GET_EVENTS': return self.handleGetEvents(replyTo) elif request_type == 'EXP_DEVICE': return self.handleExperimentDeviceRequest(request, replyTo) elif request_type == 'CUSTOM_TASK': return self.handleCustomTaskRequest(request, replyTo) elif request_type == 'RPC': callable_name = request.pop(0) args = None kwargs = None if len(request) == 1: args = request.pop(0) if len(request) == 1: kwargs = request.pop(0) result = None try: if isinstance(callable_name, bytes): callable_name = callable_name.decode('utf-8') result = getattr(self, callable_name) except Exception: print2err('RPC_ATTRIBUTE_ERROR') printExceptionDetailsToStdErr() self.sendResponse('RPC_ATTRIBUTE_ERROR', replyTo) return False if result and callable(result): funcPtr = result nargs = [] if args: for a in args: if isinstance(a, bytes): nargs.append(a.decode('utf-8')) else: nargs.append(a) args = nargs try: if args is None and kwargs is None: result = funcPtr() elif args and kwargs: result = funcPtr(*args, **convertByteStrings(kwargs)) elif args and not kwargs: result = funcPtr(*args) elif not args and kwargs: result = funcPtr(**convertByteStrings(kwargs)) edata = ('RPC_RESULT', callable_name, result) self.sendResponse(edata, replyTo) return True except Exception: print2err('RPC_RUNTIME_ERROR') printExceptionDetailsToStdErr() self.sendResponse('RPC_RUNTIME_ERROR', replyTo) return False else: print2err('RPC_NOT_CALLABLE_ERROR') printExceptionDetailsToStdErr() self.sendResponse('RPC_NOT_CALLABLE_ERROR', replyTo) return False elif request_type == 'GET_IOHUB_STATUS': self.sendResponse((request_type, self.iohub.getStatus()), replyTo) return True elif request_type == 'STOP_IOHUB_SERVER': self.shutDown() else: print2err('RPC_NOT_CALLABLE_ERROR') printExceptionDetailsToStdErr() self.sendResponse('RPC_NOT_CALLABLE_ERROR', replyTo) return False def handleCustomTaskRequest(self, request, replyTo): custom_tasks = self.iohub.custom_tasks subtype = request.pop(0) tasklet_label = request.pop(0) print2err('REQUEST: {}'.format(request)) if subtype == 'START': import importlib try: print2err('EXP_SCRIPT_DIRECTORY: ', EXP_SCRIPT_DIRECTORY) task_class_path = request.pop(0) if EXP_SCRIPT_DIRECTORY not in sys.path: sys.path.append(EXP_SCRIPT_DIRECTORY) mod_name, class_name = task_class_path.rsplit('.', 1) mod = importlib.import_module(mod_name) task_cls = getattr(mod, class_name) if custom_tasks.get(tasklet_label): custom_tasks.get(tasklet_label).stop() del custom_tasks[tasklet_label] class_kwargs = {} if len(request): class_kwargs = request.pop(0) custom_tasks[tasklet_label] = task_cls(**convertByteStrings(class_kwargs)) custom_tasks[tasklet_label].start() except Exception: print2err( 'ioHub Start CustomTask Error: could not load ' 'TASK START function: ', task_class_path) printExceptionDetailsToStdErr() print2err('Received CUSTOM TASK START: {}'.format(request)) elif subtype == 'STOP': tcls = custom_tasks.get(tasklet_label) if tcls: tcls.stop() del custom_tasks[tasklet_label] print2err('Received CUSTOM TASK STOP: {}'.format(request)) else: print2err( 'Received UNKNOWN CUSTOM TASK SUBTYPE: {}'.format(subtype)) edata = ('CUSTOM_TASK_REPLY', request) self.sendResponse(edata, replyTo) def handleGetEvents(self, replyTo): try: self.iohub.processDeviceEvents() currentEvents = list(self.iohub.eventBuffer) self.iohub.eventBuffer.clear() if len(currentEvents) > 0: currentEvents = sorted( currentEvents, key=itemgetter( DeviceEvent.EVENT_HUB_TIME_INDEX)) self.sendResponse( ('GET_EVENTS_RESULT', currentEvents), replyTo) else: self.sendResponse(('GET_EVENTS_RESULT', None), replyTo) return True except Exception: print2err('IOHUB_GET_EVENTS_ERROR') printExceptionDetailsToStdErr() self.sendResponse('IOHUB_GET_EVENTS_ERROR', replyTo) return False def handleExperimentDeviceRequest(self, request, replyTo): request_type = request.pop(0) if not isinstance(request_type, str): request_type = str(request_type, 'utf-8') # convert bytes to string for compatibility io_dev_dict = ioServer.deviceDict if request_type == 'EVENT_TX': exp_events = request.pop(0) exp_dev_cb = io_dev_dict['Experiment']._nativeEventCallback for eventAsTuple in exp_events: exp_dev_cb(eventAsTuple) self.sendResponse(('EVENT_TX_RESULT', len(exp_events)), replyTo) return True elif request_type == 'DEV_RPC': dclass = request.pop(0) if not isinstance(dclass, str): dclass = str(dclass, 'utf-8') dmethod = request.pop(0) if not isinstance(dmethod, str): dmethod = str(dmethod, 'utf-8') args = None kwargs = None if len(request) == 1: args = request[0] elif len(request) == 2: args = request[0] kwargs = request[1] if len(kwargs) == 0: kwargs = None dev = None if dclass.find('.') > 0: for dname, dev in ioServer.deviceDict.items(): if dname.endswith(dclass): dev = ioServer.deviceDict.get(dname, None) break else: dev = ioServer.deviceDict.get(dclass, None) if dev is None: print2err('IOHUB_DEVICE_ERROR') printExceptionDetailsToStdErr() self.sendResponse('IOHUB_DEVICE_ERROR', replyTo) return False try: method = getattr(dev, dmethod) except Exception: print2err('IOHUB_DEVICE_METHOD_ERROR') printExceptionDetailsToStdErr() self.sendResponse('IOHUB_DEVICE_METHOD_ERROR', replyTo) return False result = [] try: if args and kwargs: result = method(*args, **convertByteStrings(kwargs)) elif args: result = method(*args) elif kwargs: result = method(**convertByteStrings(kwargs)) else: result = method() #print2err("DEV_RPC_RESULT: ", result) self.sendResponse(('DEV_RPC_RESULT', result), replyTo) return True except Exception: print2err('RPC_DEVICE_RUNTIME_ERROR') printExceptionDetailsToStdErr() self.sendResponse('RPC_DEVICE_RUNTIME_ERROR', replyTo) return False elif request_type == 'GET_DEVICE_LIST': try: dev_list = [] for d in self.iohub.devices: dev_list.append((d.name, d.__class__.__name__)) self.sendResponse( ('GET_DEV_LIST_RESULT', len(dev_list), dev_list), replyTo) return True except Exception: print2err('RPC_DEVICE_RUNTIME_ERROR') printExceptionDetailsToStdErr() self.sendResponse('RPC_DEVICE_RUNTIME_ERROR', replyTo) return False elif request_type == 'GET_DEV_INTERFACE': dclass = request.pop(0) if not isinstance(dclass, str): dclass = str(dclass, 'utf-8') data = None if dclass in ['EyeTracker', 'DAQ']: for dname, hdevice in ioServer.deviceDict.items(): if dname.endswith(dclass): data = hdevice._getRPCInterface() break else: dev = ioServer.deviceDict.get(dclass, None) if dev: data = dev._getRPCInterface() if data: self.sendResponse(('GET_DEV_INTERFACE', data), replyTo) return True else: print2err('GET_DEV_INTERFACE_ERROR: ', '_getRPCInterface returned: ', data) self.sendResponse('GET_DEV_INTERFACE_ERROR', replyTo) return False elif request_type == 'ADD_DEVICE': cls_name = request.pop(0) dev_cfg = request.pop(1) data = self.iohub.createNewMonitoredDevice(cls_name, dev_cfg) if data: self.sendResponse(('ADD_DEVICE', data), replyTo) return True else: print2err('ADD_DEVICE_ERROR: createNewMonitoredDevice ', 'returned: ', data) self.sendResponse('ADD_DEVICE_ERROR', replyTo) return False else: print2err('DEVICE_RPC_TYPE_NOT_SUPPORTED_ERROR: ', 'Unknown Request Type: ', request_type) self.sendResponse('DEVICE_RPC_TYPE_NOT_SUPPORTED_ERROR', replyTo) return False def sendResponse(self, data, address): reply_data_sz = -1 max_pkt_sz = int(MAX_PACKET_SIZE / 2 - 20) pkt_cnt = -1 p = si = -1 try: reply_data = self.pack(data) reply_data_sz = len(reply_data) if reply_data_sz >= max_pkt_sz: pkt_cnt = int(reply_data_sz // max_pkt_sz) + 1 mpr_payload = ('IOHUB_MULTIPACKET_RESPONSE', pkt_cnt) self.sendResponse(mpr_payload, address) gevent.sleep(0.0001) for p in range(pkt_cnt - 1): si = p*max_pkt_sz self.socket.sendto(reply_data[si:si+max_pkt_sz], address) # macOS hangs if we do not sleep gevent between each msg packet gevent.sleep(0.0001) si = (p+1)*max_pkt_sz self.socket.sendto(reply_data[si:reply_data_sz], address) else: self.socket.sendto(reply_data, address) except Exception: print2err('=============================') print2err('Error trying to send data to experiment process:') print2err('max_pkt_sz: ', max_pkt_sz) print2err('reply_data_sz: ', reply_data_sz) print2err('pkt_cnt: ', pkt_cnt) print2err('packet index, byte index: ', p, si) printExceptionDetailsToStdErr() print2err('=============================') pktdata = self.pack('IOHUB_SERVER_RESPONSE_ERROR') self.socket.sendto(pktdata, address) def setExperimentInfo(self, exp_info_list): self.iohub.experimentInfoList = exp_info_list dsfile = self.iohub.dsfile if dsfile: exp_id = dsfile.createOrUpdateExperimentEntry(exp_info_list) self.iohub._experiment_id = exp_id self.iohub.log('Current Experiment ID: {}'.format(exp_id)) return exp_id return False def checkIfSessionCodeExists(self, sessionCode): try: dsfile = self.iohub.dsfile if dsfile: return dsfile.checkIfSessionCodeExists(sessionCode) return False except Exception: printExceptionDetailsToStdErr() def registerWindowHandles(self, *win_hwhds): if self.iohub: for wh in win_hwhds: if wh['handle'] not in self.iohub._psychopy_windows.keys(): self.iohub._psychopy_windows[wh['handle']] = wh wh['size'] = numpy.asarray(wh['size']) wh['pos'] = numpy.asarray(wh['pos']) if wh['monitor']: from psychopy import monitors monitor = wh['monitor'] monitor['monitor'] = monitors.Monitor('{}'.format(wh['handle'])) monitor['monitor'].setDistance(monitor['distance']) monitor['monitor'].setWidth(monitor['width']) monitor['monitor'].setSizePix(monitor['resolution']) self.iohub.log('Registered Win: {}'.format(wh)) def unregisterWindowHandles(self, *win_hwhds): if self.iohub: for wh in win_hwhds: if wh in self.iohub._psychopy_windows.keys(): del self.iohub._psychopy_windows[wh] self.iohub.log('Removed Win: {}'.format(wh)) def updateWindowPos(self, win_hwhd, pos): """ Update stored psychopy window position. :param win_hwhd: :param pos: :return: """ winfo = self.iohub._psychopy_windows.get(win_hwhd) if winfo: winfo['pos'] = pos self.iohub.log('Update Win: {}'.format(winfo)) else: print2err('warning: win_hwhd {} not registered with iohub server.'.format(win_hwhd)) self.iohub.log('updateWindowPos warning: win_hwhd {} not registered with iohub server.'.format(win_hwhd)) def createExperimentSessionEntry(self, sessionInfoDict): sessionInfoDict = convertByteStrings(sessionInfoDict) self.iohub.sessionInfoDict = sessionInfoDict dsfile = self.iohub.dsfile if dsfile: sess_id = dsfile.createExperimentSessionEntry(sessionInfoDict) self.iohub._session_id = sess_id self.iohub.log('Current Session ID: %d' % (self.iohub._session_id)) return sess_id return False def initConditionVariableTable(self, exp_id, sess_id, numpy_dtype): dsfile = self.iohub.dsfile if dsfile: output = [] for a in numpy_dtype: if isinstance(a[1], str): output.append(tuple(a)) else: temp = [a[0], []] for i in a[1]: temp[1].append(tuple(i)) output.append(tuple(temp)) return dsfile.initConditionVariableTable(exp_id, sess_id, output) return False def extendConditionVariableTable(self, exp_id, sess_id, data): dsfile = self.iohub.dsfile if dsfile: return dsfile.extendConditionVariableTable(exp_id, sess_id, data) return False def clearEventBuffer(self, clear_device_level_buffers=False): """ :param clear_device_level_buffers: :return: """ self.iohub.clearEventBuffer() if clear_device_level_buffers is True: for device in self.iohub.devices: try: device.clearEvents(call_proc_events=False) except Exception: pass @staticmethod def getTime(): """See Computer.getTime documentation, where current process will be the ioHub Server process.""" return getTime() @staticmethod def syncClock(params): """ Sync parameters between Computer.global_clock and a given dict. Parameters ---------- params : dict Dict of attributes and values to apply to the computer's global clock. See `psychopy.clock.MonotonicClock` for what attributes to include. """ return syncClock(params) @staticmethod def setPriority(level='normal', disable_gc=False): """See Computer.setPriority documentation, where current process will be the ioHub Server process.""" return Computer.setPriority(level, disable_gc) @staticmethod def getPriority(): """See Computer.getPriority documentation, where current process will be the ioHub Server process.""" return Computer.getPriority() @staticmethod def getProcessAffinity(): return Computer.getCurrentProcessAffinity() @staticmethod def setProcessAffinity(processorList): return Computer.setCurrentProcessAffinity(processorList) def flushIODataStoreFile(self): dsfile = self.iohub.dsfile if dsfile: dsfile.emrtFile.flush() return True return False def shutDown(self): try: self.setPriority('normal') self.iohub.shutdown() self._running = False self.stop() except Exception: print2err('Error in ioSever.shutdown():') printExceptionDetailsToStdErr() sys.exit(1) class DeviceMonitor(Greenlet): def __init__(self, device, sleep_interval): Greenlet.__init__(self) self.device = device self.sleep_interval = sleep_interval self.running = False def _run(self): self.running = True ctime = Computer.getTime while self.running is True: stime = ctime() self.device._poll() i = self.sleep_interval - (ctime() - stime) gevent.sleep(max(0,i)) def __del__(self): self.device = None class ioServer(): eventBuffer = None deviceDict = {} _logMessageBuffer = deque(maxlen=128) _psychopy_windows = {} status = 'OFFLINE' def __init__(self, rootScriptPathDir, config=None): self._session_id = None self._experiment_id = None self.log('Server Time Offset: {0}'.format( Computer.global_clock.getLastResetTime())) self._hookManager = None self.dsfile = None self.config = config self.devices = [] self.deviceMonitors = [] self.custom_tasks = OrderedDict() self.sessionInfoDict = None self.experimentInfoList = None self.filterLookupByInput = {} self.filterLookupByOutput = {} self.filterLookupByName = {} self._hookDevice = None self._all_dev_conf_errors = [] ebuf_sz = config.get('global_event_buffer', 2048) ioServer.eventBuffer = deque(maxlen=ebuf_sz) self._running = True # start UDP service self.udpService = udpServer(self, ':%d' % config.get('udp_port', 9000)) self._initDataStore(config, rootScriptPathDir) self._addDevices(config) self._addPubSubListeners() def _initDataStore(self, config, script_dir): try: # initial dataStore setup if 'data_store' in config and _DATA_STORE_AVAILABLE: ds_conf = config.get('data_store') def_ds_conf_path = os.path.join(IOHUB_DIRECTORY, 'datastore', 'default_datastore.yaml') _, def_ds_conf = yload(open(def_ds_conf_path, 'r'), Loader=yLoader).popitem() for dkey, dvalue in def_ds_conf.items(): if dkey not in ds_conf: ds_conf[dkey] = dvalue if ds_conf.get('enable', True): ds_dir = script_dir hdf_name = ds_conf.get('filename', 'events') + '.hdf5' hdf_parent_folder = ds_conf.get('parent_dir', '.') if os.path.isabs(hdf_parent_folder): ds_dir = hdf_parent_folder else: ds_dir = os.path.abspath(script_dir) ds_dir = os.path.normpath(os.path.join(ds_dir, hdf_parent_folder)) if not os.path.exists(ds_dir): os.makedirs(ds_dir) self.createDataStoreFile(hdf_name, ds_dir, 'a', ds_conf) except Exception: print2err('Error during ioDataStore creation....') printExceptionDetailsToStdErr() def _addDevices(self, config): # built device list and config from initial yaml config settings try: for iodevice in config.get('monitor_devices', ()): for dev_cls_name, dev_conf in iodevice.items(): self.createNewMonitoredDevice(dev_cls_name, dev_conf) except Exception: print2err('Error during device creation ....') printExceptionDetailsToStdErr() def _addPubSubListeners(self): # Add PubSub device listeners to other event types try: for d in self.devices: if d.__class__.__name__ == 'EventPublisher': monitored_event_ids = d._event_listeners.keys() for eid in monitored_event_ids: evt_cls = EventConstants.getClass(eid) evt_dev_cls = evt_cls.PARENT_DEVICE for ed in self.devices: if ed.__class__ == evt_dev_cls: ed._addEventListener(d, [eid, ]) break except Exception: print2err('Error PubSub Device listener association ....') printExceptionDetailsToStdErr() def processDeviceConfigDictionary(self, dev_mod_path, dev_cls_name, dev_conf, def_dev_conf): for dparam, dvalue in def_dev_conf.items(): if dparam in dev_conf: if isinstance(dvalue, (dict, OrderedDict)): self.processDeviceConfigDictionary(None, None, dev_conf.get(dparam), dvalue) elif dparam not in dev_conf: if isinstance(dvalue, (dict, OrderedDict)): sub_param = dict() self.processDeviceConfigDictionary(None, None, sub_param, dvalue) dev_conf[dparam] = sub_param else: dev_conf[dparam] = dvalue # Start device config verification. if dev_mod_path and dev_cls_name: dev_conf_errors = validateDeviceConfiguration(dev_mod_path, dev_cls_name, dev_conf) for err_type, err_list in dev_conf_errors.items(): if len(err_list) > 0: device_errors = self._all_dev_conf_errors.get(dev_mod_path, {}) device_errors[err_type] = err_list self._all_dev_conf_errors[dev_mod_path] = device_errors def pumpMsgTasklet(self, sleep_interval): while self._running: stime = Computer.getTime() try: win32MessagePump() except KeyboardInterrupt: self._running = False break dur = sleep_interval - (Computer.getTime() - stime) gevent.sleep(max(0.0, dur)) def createNewMonitoredDevice(self, dev_cls_name, dev_conf): self._all_dev_conf_errors = dict() try: dinstance = None dconf = None devt_ids = None devt_classes = None dev_data = self.addDeviceToMonitor(dev_cls_name, dev_conf) if dev_data: dinstance, dconf, devt_ids, devt_classes = dev_data DeviceConstants.addClassMapping(dinstance.__class__) EventConstants.addClassMappings(devt_ids, devt_classes) else: print2err('## Device was not started by the ioHub Server: ', dev_cls_name) raise ioHubError('Device config validation failed') except Exception: print2err('Error during device creation ....') printExceptionDetailsToStdErr() raise ioHubError('Error during device creation ....') # Update DataStore Structure if required. if _DATA_STORE_AVAILABLE: try: if self.dsfile is not None: self.dsfile.updateDataStoreStructure(dinstance, devt_classes) except Exception: print2err('Error updating data store for device addition:', dinstance, devt_ids) printExceptionDetailsToStdErr() self.log('Adding ioServer and DataStore event listeners......') # add event listeners for saving events if _DATA_STORE_AVAILABLE and self.dsfile is not None: dcls_name = dinstance.__class__.__name__ if dconf['save_events']: dinstance._addEventListener(self.dsfile, devt_ids) lstr = 'Added Device DS Listener: {}, {}'.format(dcls_name, devt_ids) self.log(lstr) else: self.log('DS Disabled for Device: %s'%(dcls_name)) else: self.log('DataStore Not Enabled. No events will be saved.') # Add Device Monitor for Keyboard or Mouse device type deviceDict = ioServer.deviceDict iohub = self hookManager = self._hookManager if dev_cls_name in ('Mouse', 'Keyboard'): if Computer.platform == 'win32': try: import pyHook except ImportError: import pyWinhook as pyHook if hookManager is None: iohub.log('Creating pyHook HookManager....') hookManager = self._hookManager = pyHook.HookManager() hookManager.keyboard_hook = False if dev_cls_name == 'Mouse': if hookManager.mouse_hook is False: dmouse = deviceDict['Mouse'] hookManager.MouseAll = dmouse._nativeEventCallback hookManager.HookMouse() elif dev_cls_name == 'Keyboard': if hookManager.keyboard_hook is False: dkeyboard = deviceDict['Keyboard'] hookManager.KeyAll = dkeyboard._nativeEventCallback hookManager.HookKeyboard() elif Computer.platform.startswith('linux'): from .devices import pyXHook if hookManager is None: log_evt = self.config.get('log_raw_kb_mouse_events', False) self._hookManager = pyXHook.HookManager(log_evt) hookManager = self._hookManager hookManager._mouseHooked = False hookManager._keyboardHooked = False if dev_cls_name == 'Keyboard': if hookManager._keyboardHooked is False: hookManager.HookKeyboard() kbcb_func = deviceDict['Keyboard']._nativeEventCallback hookManager.KeyDown = kbcb_func hookManager.KeyUp = kbcb_func hookManager._keyboardHooked = True elif dev_cls_name == 'Mouse': if hookManager._mouseHooked is False: hookManager.HookMouse() mcb_func = deviceDict['Mouse']._nativeEventCallback hookManager.MouseAllButtonsDown = mcb_func hookManager.MouseAllButtonsUp = mcb_func hookManager.MouseAllMotion = mcb_func hookManager._mouseHooked = True if hookManager._running is False: hookManager.start() else: # OSX if self._hookDevice is None: self._hookDevice = [] if dev_cls_name not in self._hookDevice: msgpump_interval = self.config.get('msgpump_interval', 0.001) if dev_cls_name == 'Mouse': dmouse = deviceDict['Mouse'] self.deviceMonitors.append(DeviceMonitor(dmouse, msgpump_interval)) dmouse._CGEventTapEnable(dmouse._tap, True) self._hookDevice.append('Mouse') if dev_cls_name == 'Keyboard': dkeyboard = deviceDict['Keyboard'] kbHookMonitor = DeviceMonitor(dkeyboard, 0.001) self.deviceMonitors.append(kbHookMonitor) dkeyboard._CGEventTapEnable(dkeyboard._tap, True) self._hookDevice.append('Keyboard') return [dev_cls_name, dconf['name'], dinstance._getRPCInterface()] def addDeviceToMonitor(self, dev_cls_name, dev_conf): dev_cls_name = str(dev_cls_name) self.log('Handling Device: %s' % (dev_cls_name,)) DeviceClass = None cls_name_start = dev_cls_name.rfind('.') # define subdirectory to look in iohub_submod = 'psychopy.iohub.' iohub_submod_len = len(iohub_submod) dev_mod_pth = iohub_submod + 'devices.' if cls_name_start > 0: dev_mod_pth += dev_cls_name[:cls_name_start].lower() dev_cls_name = dev_cls_name[cls_name_start + 1:] else: dev_mod_pth += dev_cls_name.lower() # convert subdirectory to path dev_mod = importDeviceModule(dev_mod_pth) dev_file_pth = os.path.dirname(dev_mod.__file__) # get config from path dev_conf_pth = os.path.join(dev_file_pth, 'default_%s.yaml' % (dev_cls_name.lower())) self.log('Loading Device Defaults file: %s' % (dev_cls_name,)) # Load config, try first from the usual location. If the file isn't # present, look at the directory the device interface class is located # in. This additional step is required for devices which are offloaded # to plugins. try: _dconf = yload(open(dev_conf_pth, 'r'), Loader=yLoader) except FileNotFoundError: # Look for the file using an alternative method, this may be due to # file being located in a plugin directory, for now only the # EyeTracker device is offloaded to plugins. if dev_cls_name.endswith('EyeTracker'): # Get the path from the object handles which reference the # file in the plugin directory dev_conf_pth = os.path.dirname( inspect.getfile(dev_mod.EyeTracker)) dev_conf_pth = os.path.join( dev_conf_pth, 'default_%s.yaml' % (dev_cls_name.lower())) with open(dev_conf_pth, 'r') as conf_file: _dconf = yload(conf_file, Loader=yLoader) else: print2err( 'ERROR: Device Defaults file not found: %s' % ( dev_cls_name,)) return None _, def_dev_conf = _dconf.popitem() self.processDeviceConfigDictionary(dev_mod_pth, dev_cls_name, dev_conf, def_dev_conf) if dev_mod_pth in self._all_dev_conf_errors: # Complete device config verification. print2err('ERROR: DEVICE CONFIG ERRORS FOUND! ', 'IOHUB NOT LOADING DEVICE: ', dev_mod_pth) dev_conf_errors = self._all_dev_conf_errors[dev_mod_pth] for err_type, errors in dev_conf_errors.items(): print2err('%s count %d:' % (err_type, len(errors))) for error in errors: print2err('\t{0}'.format(error)) print2err('\n') return None DeviceClass, dev_cls_name, evt_classes = import_device(dev_mod_pth, dev_cls_name) deviceDict = ioServer.deviceDict if dev_conf.get('enable', True): self.log('Searching Device Path: %s' % (dev_cls_name,)) self.log('Creating Device: %s' % (dev_cls_name,)) # print2err("Creating Device: %s"%(device_class_name,)) if DeviceClass._iohub_server is None: DeviceClass._iohub_server = self if dev_cls_name != 'Display': if DeviceClass._display_device is None: DeviceClass._display_device = deviceDict['Display'] dev_instance = DeviceClass(dconfig=dev_conf) self.devices.append(dev_instance) deviceDict[dev_cls_name] = dev_instance self.log('Device Instance Created: %s' % (dev_cls_name,)) if 'device_timer' in dev_conf: interval = dev_conf['device_timer'].get('interval', 0.001) dPoller = DeviceMonitor(dev_instance, interval) self.deviceMonitors.append(dPoller) ltxt = '%s timer period: %.3f' % (dev_cls_name, interval) self.log(ltxt) monitor_evt_ids = [] monitor_evt_list = dev_conf.get('monitor_event_types', []) if isinstance(monitor_evt_list, (list, tuple)): for evt_name in monitor_evt_list: evt_cls_name = convertCamelToSnake(evt_name[:-5], False) event_id = getattr(EventConstants, evt_cls_name) monitor_evt_ids.append(event_id) self.log('{0} Monitoring Events: {1}'.format(dev_cls_name, monitor_evt_ids)) # add event listeners for streaming events if dev_conf.get('stream_events') is True: self.log('%s: Streaming Events are Enabled.' % dev_cls_name) # add listener for global event queue dev_instance._addEventListener(self, monitor_evt_ids) self.log('ioServer Event Listener: {}'.format(monitor_evt_ids)) # add listener for device event queue dev_instance._addEventListener(dev_instance, monitor_evt_ids) self.log('{} Event Listener: {}'.format(dev_cls_name, monitor_evt_ids)) return dev_instance, dev_conf, monitor_evt_ids, evt_classes def log(self, text, level=None): try: log_time = getTime() exp = self.deviceDict.get('Experiment', None) if exp and self._session_id and self._experiment_id: while len(self._logMessageBuffer): lm = self._logMessageBuffer.popleft() exp.log(*lm) exp.log(text, level, log_time) else: self._logMessageBuffer.append((text, level, log_time)) except Exception: printExceptionDetailsToStdErr() def createDataStoreFile(self, fname, fpath, fmode, iohub_settings): if _DATA_STORE_AVAILABLE: from .datastore import DataStoreFile self.closeDataStoreFile() self.dsfile = DataStoreFile(fname, fpath, fmode, iohub_settings) def closeDataStoreFile(self): if self.dsfile: pytablesfile = self.dsfile self.dsfile = None pytablesfile.flush() pytablesfile.close() def processEventsTasklet(self, sleep_interval): while self._running: stime = Computer.getTime() self.processDeviceEvents() dur = sleep_interval - (Computer.getTime() - stime) gevent.sleep(max(0, dur)) def processDeviceEvents(self): for device in self.devices: evt = [] try: events = device._getNativeEventBuffer() while events: evt = device._getIOHubEventObject(events.popleft()) if evt: etype = evt[DeviceEvent.EVENT_TYPE_ID_INDEX] for l in device._getEventListeners(etype): l._handleEvent(evt) filtered_events = [] for efilter in device._filters.values(): filtered_events.extend(efilter._removeOutputEvents()) for evt in filtered_events: etype = evt[DeviceEvent.EVENT_TYPE_ID_INDEX] for l in device._getEventListeners(etype): l._handleEvent(evt) except Exception: print2err('Error in processDeviceEvents: ', device, ' : ', len(events)) if evt: etype = evt[DeviceEvent.EVENT_TYPE_ID_INDEX] ename = EventConstants.getName(etype) print2err('Event type ID: ', etype, ' : ', ename) printExceptionDetailsToStdErr() print2err('--------------------------------------') def _handleEvent(self, event): self.eventBuffer.append(event) def clearEventBuffer(self, call_proc_events=True): if call_proc_events is True: self.processDeviceEvents() l = len(self.eventBuffer) self.eventBuffer.clear() return l def checkForPsychopyProcess(self, sleep_interval): while self._running: if Computer.psychopy_process: if Computer.psychopy_process.is_running() is False: Computer.psychopy_process = None self.shutdown() break else: gevent.sleep(sleep_interval) @classmethod def getStatus(cls): return cls.status @classmethod def setStatus(cls, s): cls.status = s return s def shutdown(self): try: self._running = False if Computer.platform.startswith('linux'): if self._hookManager: self._hookManager.cancel() elif Computer.platform == 'win32': del self._hookManager # if self._hookManager: # self._hookManager.UnhookMouse() # self._hookManager.UnhookKeyboard() while self.deviceMonitors: self.deviceMonitors.pop(0).running = False if self.eventBuffer: self.clearEventBuffer() self.closeDataStoreFile() while self.devices: self.devices.pop(0)._close() except Exception: print2err('Error in ioSever.shutdown():') printExceptionDetailsToStdErr() def __del__(self): self.shutdown() # pylint: enable=protected-access # pylint: enable=broad-except
43,732
Python
.py
957
31.264368
117
0.548115
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,654
keyboard.py
psychopy_psychopy/psychopy/iohub/client/keyboard.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from collections import deque import time from ..client import ioHubDeviceView, ioEvent, DeviceRPC from ..devices import DeviceEvent, Computer from ..util import win32MessagePump from ..devices.keyboard import KeyboardInputEvent from ..constants import EventConstants, KeyboardConstants # pylint: disable=protected-access getTime = Computer.getTime kb_cls_attr_names = KeyboardInputEvent.CLASS_ATTRIBUTE_NAMES kb_mod_codes2labels = KeyboardConstants._modifierCodes2Labels class KeyboardEvent(ioEvent): """ Base class for KeyboardPress and KeyboardRelease events. Note that keyboard events can be compared using a single character basestring. For example:: kb_evts = keyboard.getKeys(['a','b','c']) for event in kb_evts: if event.key == 'b' or event.char == 'b': return True return False can be written as: return 'b' in keyboard.getKeys() """ _attrib_index = dict() _attrib_index['key'] = kb_cls_attr_names.index('key') _attrib_index['char'] = kb_cls_attr_names.index('char') _attrib_index['modifiers'] = kb_cls_attr_names.index('modifiers') def __init__(self, ioe_array): super(KeyboardEvent, self).__init__(ioe_array) for aname, aindex, in list(self._attrib_index.items()): setattr(self, '_%s' % aname, ioe_array[aindex]) self._modifiers = kb_mod_codes2labels(self._modifiers) @property def key(self): return self._key @property def char(self): """The unicode value of the keyboard event, if available. This field is only populated when the keyboard event results in a character that could be printable. :return: unicode, '' if no char value is available for the event. """ return self._char @property def modifiers(self): """ A list of any modifier keys that were pressed when this keyboard event occurred. Each element of the list contains a keyboard modifier string constant. Possible values are: * 'lctrl', 'rctrl' * 'lshift', 'rshift' * 'lalt', 'ralt' (labelled as 'option' keys on Apple Keyboards) * 'lcmd', 'rcmd' (map to the 'windows' key(s) on Windows keyboards) * 'menu' * 'capslock' * 'numlock' * 'function' (OS X only) * 'modhelp' (OS X only) If no modifiers were active when the event occurred, an empty list is returned. :return: tuple """ return self._modifiers def __str__(self): pstr = ioEvent.__str__(self) return '{}, key: {} char: {}, modifiers: {}'.format(pstr, self.key, self.char, self.modifiers) def __eq__(self, v): if isinstance(v, KeyboardEvent): return self.key == v.key return self.key == v def __ne__(self, v): return not self.__eq__(v) class KeyboardPress(KeyboardEvent): """An iohub Keyboard device key press event.""" def __init__(self, ioe_array): super(KeyboardPress, self).__init__(ioe_array) class KeyboardRelease(KeyboardEvent): """An iohub Keyboard device key release event.""" _attrib_index = dict(KeyboardEvent._attrib_index) _attrib_index['duration'] = kb_cls_attr_names.index('duration') _attrib_index['press_event_id'] = kb_cls_attr_names.index('press_event_id') def __init__(self, ioe_array): super(KeyboardRelease, self).__init__(ioe_array) # self._duration = ioe_array[self._attrib_index['duration']] # self._press_event_id = ioe_array[self._attrib_index['press_event_id']] @property def duration(self): """The duration (in seconds) of the key press. This is calculated by subtracting the current event.time from the associated keypress.time. If no matching keypress event was reported prior to this event, then 0.0 is returned. This can happen, for example, when the key was pressed prior to psychopy starting to monitor the device. This condition can also happen when keyboard.reset() method is called between the press and release event times. :return: float """ return self._duration @property def pressEventID(self): """The event.id of the associated press event. The key press id is 0 if no associated KeyboardPress event was found. See the duration property documentation for details on when this can occur. :return: unsigned int """ return self._press_event_id def __str__(self): return '%s, duration: %.3f press_event_id: %d' % ( KeyboardEvent.__str__(self), self.duration, self.pressEventID) class Keyboard(ioHubDeviceView): """The Keyboard device provides access to KeyboardPress and KeyboardRelease events as well as the current keyboard state. Examples: A. Print all keyboard events received for 5 seconds:: from psychopy.iohub import launchHubServer from psychopy.core import getTime # Start the ioHub process. 'io' can now be used during the # experiment to access iohub devices and read iohub device events. io = launchHubServer() keyboard = io.devices.keyboard # Check for and print any Keyboard events received for 5 seconds. stime = getTime() while getTime()-stime < 5.0: for e in keyboard.getEvents(): print(e) # Stop the ioHub Server io.quit() B. Wait for a keyboard press event (max of 5 seconds):: from psychopy.iohub import launchHubServer from psychopy.core import getTime # Start the ioHub process. 'io' can now be used during the # experiment to access iohub devices and read iohub device events. io = launchHubServer() keyboard = io.devices.keyboard # Wait for a key keypress event ( max wait of 5 seconds ) presses = keyboard.waitForPresses(maxWait=5.0) print(presses) # Stop the ioHub Server io.quit() """ KEY_PRESS = EventConstants.KEYBOARD_PRESS KEY_RELEASE = EventConstants.KEYBOARD_RELEASE _type2class = {KEY_PRESS: KeyboardPress, KEY_RELEASE: KeyboardRelease} def __init__(self, ioclient, dev_cls_name, dev_config): super(Keyboard, self).__init__(ioclient, 'client.Keyboard', dev_cls_name, dev_config) self.clock = Computer.global_clock self._events = dict() self._reporting = self.isReportingEvents() self._pressed_keys = {} self._device_config = dev_config self._event_buffer_length = dev_config.get('event_buffer_length') self._clearEventsRPC = DeviceRPC(self.hubClient._sendToHubServer, self.device_class, 'clearEvents') def _clearLocalEvents(self, event_type=None): for etype, elist in list(self._events.items()): if event_type is None: elist.clear() elif event_type == etype: elist.clear() def _syncDeviceState(self): """An optimized iohub server request that receives all device state and event information in one response. :return: None """ kb_state = self.getCurrentDeviceState() events = {int(k): v for k, v in list(kb_state.get('events').items())} pressed_keys = {int(k): v for k, v in list(kb_state.get('pressed_keys', {}).items())} self._reporting = kb_state.get('reporting_events') self._pressed_keys.clear() akeyix = KeyboardEvent._attrib_index['key'] iotimeix = DeviceEvent.EVENT_HUB_TIME_INDEX for _, (key_array, _) in pressed_keys.items(): self._pressed_keys[key_array[akeyix]] = key_array[iotimeix] for etype, event_arrays in events.items(): ddeque = deque(maxlen=self._event_buffer_length) evts = [self._type2class[etype](e) for e in event_arrays] self._events.setdefault(etype, ddeque).extend(evts) @property def state(self): """ Returns all currently pressed keys as a dictionary of key : time values. The key is taken from the originating press event .key field. The time value is time of the key press event. Note that any pressed, or active, modifier keys are included in the return value. :return: dict """ self._syncDeviceState() self._pressed_keys = {keys: vals for keys, vals in self._pressed_keys.items()} return self._pressed_keys @property def reporting(self): """Specifies if the keyboard device is reporting / recording events. * True: keyboard events are being reported. * False: keyboard events are not being reported. By default, the Keyboard starts reporting events automatically when the ioHub process is started and continues to do so until the process is stopped. This property can be used to read or set the device reporting state:: # Read the reporting state of the keyboard. is_reporting_keyboard_event = keyboard.reporting # Stop the keyboard from reporting any new events. keyboard.reporting = False """ return self._reporting @reporting.setter def reporting(self, r): """Sets the state of keyboard event reporting / recording.""" self._reporting = self.enableEventReporting(r) return self._reporting def clearEvents(self, event_type=None, filter_id=None): self._clearLocalEvents(event_type) return self._clearEventsRPC(event_type=event_type, filter_id=filter_id) def getKeys(self, keys=None, chars=None, ignoreKeys=None, mods=None, duration=None, etype=None, clear=True): """ Return a list of any KeyboardPress or KeyboardRelease events that have occurred since the last time either: * this method was called with the kwarg clear=True (default) * the keyboard.clear() method was called. Other than the 'clear' kwarg, any kwargs that are not None or an empty list are used to filter the possible events that can be returned. If multiple filter criteria are provided, only events that match **all** specified criteria are returned. If no KeyboardEvent's are found that match the filtering criteria, an empty tuple is returned. Returned events are sorted by time. :param keys: Include events where .key in keys. :param chars: Include events where .char in chars. :param ignoreKeys: Ignore events where .key in ignoreKeys. :param mods: Include events where .modifiers include >=1 mods element. :param duration: Include KeyboardRelease events where .duration > duration or .duration < -(duration). :param etype: Include events that match etype of Keyboard.KEY_PRESS or Keyboard.KEY_RELEASE. :param clear: True (default) = clear returned events from event buffer, False = leave the keyboard event buffer unchanged. :return: tuple of KeyboardEvent instances, or () """ self._syncDeviceState() ecount = 0 for elist in list(self._events.values()): ecount += len(elist) if ecount == 0: return [] def filterEvent(e): r1 = (keys is None or e.key in keys) and ( ignoreKeys is None or e.key not in ignoreKeys) r2 = (chars is None or e.char in chars) r3 = True if duration is not None: r3 = (duration // abs(duration) * e.duration) >= duration r4 = True if mods: r4 = len([m for m in mods if m in e.modifiers]) > 0 return r1 and r2 and r3 and r4 press_evt = [] release_evt = [] if etype is None or etype == Keyboard.KEY_PRESS: press_evt = [ e for e in self._events.get( Keyboard.KEY_PRESS, []) if filterEvent(e)] if etype is None or etype == Keyboard.KEY_RELEASE: release_evt = [ e for e in self._events.get( Keyboard.KEY_RELEASE, []) if filterEvent(e)] return_events = sorted(press_evt + release_evt, key=lambda x: x.time) if clear is True: for e in return_events: self._events[e._type].remove(e) return return_events def getPresses(self, keys=None, chars=None, ignoreKeys=None, mods=None, clear=True): """See the getKeys() method documentation. This method is identical, but only returns KeyboardPress events. """ return self.getKeys( keys=keys, chars=chars, ignoreKeys=ignoreKeys, mods=mods, duration=None, etype=self.KEY_PRESS, clear=clear ) def getReleases(self, keys=None, chars=None, ignoreKeys=None, mods=None, duration=None, clear=True): """See the getKeys() method documentation. This method is identical, but only returns KeyboardRelease events. """ return self.getKeys( keys=keys, chars=chars, ignoreKeys=ignoreKeys, mods=mods, duration=duration, etype=self.KEY_RELEASE, clear=clear ) def waitForKeys(self, maxWait=None, keys=None, chars=None, mods=None, duration=None, etype=None, clear=True, checkInterval=0.002): """Blocks experiment execution until at least one matching KeyboardEvent occurs, or until maxWait seconds has passed since the method was called. Keyboard events are filtered the same way as in the getKeys() method. As soon as at least one matching KeyboardEvent occurs prior to maxWait, the matching events are returned as a tuple. Returned events are sorted by time. :param maxWait: Maximum seconds method waits for >=1 matching event. If <=0.0, method functions the same as getKeys(). If None, the methods blocks indefinitely. :param keys: Include events where .key in keys. :param chars: Include events where .char in chars. :param mods: Include events where .modifiers include >=1 mods element. :param duration: Include KeyboardRelease events where .duration > duration or .duration < -(duration). :param etype: Include events that match etype of Keyboard.KEY_PRESS or Keyboard.KEY_RELEASE. :param clear: True (default) = clear returned events from event buffer, False = leave the keyboard event buffer unchanged. :param checkInterval: The time between geyKeys() calls while waiting. The method sleeps between geyKeys() calls, up until checkInterval*2.0 sec prior to the maxWait. After that time, keyboard events are constantly checked until the method times out. :return: tuple of KeyboardEvent instances, or () """ start_time = getTime() if maxWait is None: maxWait = 60000.0 timeout = start_time + maxWait key = [] def pumpKeys(): key = self.getKeys( keys=keys, chars=chars, mods=mods, duration=duration, etype=etype, clear=clear ) if key: return key win32MessagePump() return key # Don't wait if maxWait is <= 0 if maxWait <= 0: key = pumpKeys() return key while getTime() < (timeout - checkInterval * 2): # Pump events on pyglet windows if they exist ltime = getTime() key = pumpKeys() if key: return key sleep_dur = max(checkInterval - (getTime() - ltime), 0.0001) time.sleep(sleep_dur) while getTime() < timeout: key = pumpKeys() if key: return key return key def waitForPresses(self, maxWait=None, keys=None, chars=None, mods=None, duration=None, clear=True, checkInterval=0.002): """See the waitForKeys() method documentation. This method is identical, but only returns KeyboardPress events. """ return self.waitForKeys( maxWait=maxWait, keys=keys, chars=chars, mods=mods, duration=duration, etype=Keyboard.KEY_PRESS, # used this instead of `self.KEY_PRESS` clear=clear, checkInterval=checkInterval ) def waitForReleases(self, maxWait=None, keys=None, chars=None, mods=None, duration=None, clear=True, checkInterval=0.002): """See the waitForKeys() method documentation. This method is identical, but only returns KeyboardRelease events. """ return self.waitForKeys( maxWait=maxWait, keys=keys, chars=chars, mods=mods, duration=duration, etype=Keyboard.KEY_RELEASE, # used this instead of `self.KEY_RLEASE` clear=clear, checkInterval=checkInterval )
18,266
Python
.py
402
34.634328
93
0.609641
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,655
connect.py
psychopy_psychopy/psychopy/iohub/client/connect.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import os from .. import _DATA_STORE_AVAILABLE, IOHUB_DIRECTORY from . import ioHubConnection from ..util import yload, yLoader, readConfig from psychopy import logging def launchHubServer(**kwargs): """ Starts the ioHub Server subprocess, and return a :class:`psychopy.iohub.client.ioHubConnection` object that is used to access enabled iohub device's events, get events, and control the ioHub process during the experiment. By default (no kwargs specified), the ioHub server does not create an ioHub HDF5 file, events are available to the experiment program at runtime. The following Devices are enabled by default: - Keyboard: named 'keyboard', with runtime event reporting enabled. - Mouse: named 'mouse', with runtime event reporting enabled. - Monitor: named 'monitor'. - Experiment: named 'experiment'. To customize how the ioHub Server is initialized when started, use one or more of the following keyword arguments when calling the function: Parameters ----------- experiment_code : str, <= 256 char If experiment_code is provided, an ioHub HDF5 file will be created for the session. session_code : str, <= 256 char When specified, used as the name of the ioHub HDF5 file created for the session. experiment_info : dict Can be used to save the following experiment metadata fields: code (<=256 chars), title (<=256 chars), description (<=4096 chars), version (<=32 chars) session_info : dict Can be used to save the following session metadata fields: code (<=256 chars), name (<=256 chars), comments (<=4096 chars), user_variables (dict) datastore_name : str Used to provide an ioHub HDF5 file name different than the session_code. window : :class:`psychopy.visual.Window` The psychoPy experiment window being used. Information like display size, viewing distance, coord / color type is used to update the ioHub Display device. iohub_config_name : str Specifies the name of the iohub_config.yaml file that contains the ioHub Device list to be used by the ioHub Server. i.e. the 'device_list' section of the yaml file. iohub.device.path : str Add an ioHub Device by using the device class path as the key, and the device's configuration in a dict value. psychopy_monitor : (deprecated) The path to a Monitor Center config file Examples: A. Wait for the 'q' key to be pressed:: from psychopy.iohub.client import launchHubServer # Start the ioHub process. 'io' can now be used during the # experiment to access iohub devices and read iohub device events. io=launchHubServer() print("Press any Key to Exit Example.....") # Wait until a keyboard event occurs keys = io.devices.keyboard.waitForKeys(keys=['q',]) print("Key press detected: {}".format(keys)) print("Exiting experiment....") # Stop the ioHub Server io.quit() Please see the psychopy/demos/coder/iohub/launchHub.py demo for examples of different ways to use the launchHubServer function. """ # if already running, return extant connection object if ioHubConnection.ACTIVE_CONNECTION is not None: return ioHubConnection.ACTIVE_CONNECTION # otherwise, make a new one experiment_code = kwargs.get('experiment_code', None) if experiment_code: del kwargs['experiment_code'] experiment_info = kwargs.get('experiment_info') if experiment_info: del kwargs['experiment_info'] for k, v in list(experiment_info.items()): if k in ['code', 'title', 'description', 'version']: experiment_info[k] = u"{}".format(v) if experiment_info.get('code'): experiment_code = experiment_info['code'] elif experiment_code: experiment_info['code'] = experiment_code elif experiment_code: experiment_info = dict(code=experiment_code) session_code = kwargs.get('session_code', None) if session_code: del kwargs['session_code'] session_info = kwargs.get('session_info') if session_info: del kwargs['session_info'] for k, v in list(session_info.items()): if k in ['code', 'name', 'comments']: session_info[k] = u"{}".format(v) elif k == 'user_variables': session_info[k] = v if session_info.get('code'): session_code = session_info['code'] elif session_code: session_info['code'] = session_code elif session_code: session_info = dict(code=session_code) else: session_info = {} if experiment_code and not session_code: # this means we should auto_generate a session code import datetime dtstr = datetime.datetime.now().strftime('%d_%m_%Y_%H_%M') session_info['code'] = session_code = u"S_{0}".format(dtstr) datastore_name = None if _DATA_STORE_AVAILABLE is True: datastore_name = kwargs.get('datastore_name') if datastore_name: del kwargs['datastore_name'] elif session_code: datastore_name = session_code monitor_devices_config = None iohub_conf_file_name = kwargs.get('iohub_config_name') if iohub_conf_file_name: # Load the specified iohub configuration file, # converting it to apython dict. with open(iohub_conf_file_name, 'r') as iohub_conf_file: _temp_conf_read = yload(iohub_conf_file, Loader=yLoader) monitor_devices_config = _temp_conf_read.get('monitor_devices') del kwargs['iohub_config_name'] device_dict = {} if monitor_devices_config: device_dict = monitor_devices_config if isinstance(device_dict, (list, tuple)): tempdict_ = {} for ddict in device_dict: tempdict_[list(ddict.keys())[0]] = list(ddict.values())[0] device_dict = tempdict_ # PsychoPy Window & Monitor integration # Get default iohub display config settings for experiment display_config = device_dict.get('Display', {}) if display_config: del device_dict['Display'] # Check for a psychopy_monitor_name name monitor_name = kwargs.get('psychopy_monitor_name', kwargs.get('monitor_name')) if monitor_name: if kwargs.get('psychopy_monitor_name'): del kwargs['psychopy_monitor_name'] else: del kwargs['monitor_name'] window = kwargs.get('window') if window: kwargs['window'] = None del kwargs['window'] # PsychoPy Window has been provided, so read all info needed for iohub Display from Window if window.units: display_config['reporting_unit_type'] = window.units if window.colorSpace: display_config['color_space'] = window.colorSpace display_config['device_number'] = window.screen if window.monitor.name == "__blank__": logging.warning("launchHubServer: window.monitor.name is '__blank__'. " "Create the PsychoPy window with a valid Monitor name.") elif window.monitor.name: display_config['psychopy_monitor_name'] = window.monitor.name display_config['override_using_psycho_settings'] = True if not window._isFullScr: logging.warning("launchHubServer: If using the iohub mouse or eyetracker devices, fullScr should be True.") elif monitor_name: display_config['psychopy_monitor_name'] = monitor_name display_config['override_using_psycho_settings'] = True logging.warning("launchHubServer: Use of psychopy_monitor_name is deprecated. " "Please use window= and provide a psychopy window that has a .monitor.") device_dict.update(kwargs) device_list = [] def isFunction(func): import types return isinstance(func, types.FunctionType) def func2str(func): return '%s.%s' % (func.__module__, func.__name__) def configfuncs2str(config): for key, val in list(config.items()): if isinstance(val, dict): configfuncs2str(val) if isFunction(val): config[key] = func2str(val) configfuncs2str(device_dict) # Add Display device as first in list of devices to be sent to iohub device_list.append(dict(Display=display_config)) # Ensure a Experiment, Keyboard, and Mouse Devices have been defined. # If not, create them. check_for_devs = ['Experiment', 'Keyboard', 'Mouse'] for adev_name in check_for_devs: if adev_name not in device_dict: device_list.append({adev_name: {}}) else: device_list.append({adev_name: device_dict[adev_name]}) del device_dict[adev_name] iohub_config = dict() def_ioconf = readConfig(os.path.join(IOHUB_DIRECTORY, u'default_config.yaml')) # Add remaining defined devices to the device list. for class_name, device_config in device_dict.items(): if class_name in def_ioconf: # not a device, a top level iohub config param iohub_config[class_name] = device_config else: device_list.append({class_name: device_config}) # Create an ioHub configuration dictionary. iohub_config['monitor_devices'] = device_list if _DATA_STORE_AVAILABLE and (datastore_name or session_code): # If datastore_name kwarg or experiment code has been provided, # then enable saving of device events to the iohub datastore hdf5 file. # If datastore_name kwarg was provided, it is used for the hdf5 file # name, otherwise the session code is used. This avoids different # experiments / sessions running in the same directory from using # the same hdf5 file name. if datastore_name is None: datastore_name = session_code parent_dir, datastore_name = os.path.split(datastore_name) iohub_config['data_store'] = dict(enable=True, filename=datastore_name, experiment_info=experiment_info, session_info=session_info) if parent_dir: iohub_config['data_store']['parent_dir'] = parent_dir return ioHubConnection(iohub_config)
10,784
Python
.py
220
40.009091
119
0.652265
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,656
__init__.py
psychopy_psychopy/psychopy/iohub/client/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import os import sys import time import subprocess import json import signal from weakref import proxy import psutil try: import psychopy.logging as psycho_logging except ImportError: psycho_logging = None from ..lazy_import import lazy_import from .. import IOHUB_DIRECTORY from ..util import yload, yLoader from ..errors import print2err, ioHubError, printExceptionDetailsToStdErr from ..util import isIterable, updateDict, win32MessagePump from ..devices import DeviceEvent, import_device from ..devices.computer import Computer from ..devices.experiment import MessageEvent, LogEvent from ..constants import DeviceConstants, EventConstants from psychopy import constants getTime = Computer.getTime _currentSessionInfo = None def windowInfoDict(win): windict = dict(handle=win._hw_handle, pos=win.pos, size=win.size, units=win.units, useRetina=win.useRetina, monitor=None) if win.monitor: windict['monitor'] = dict(resolution=win.monitor.getSizePix(), width=win.monitor.getWidth(), distance=win.monitor.getDistance()) return windict def getFullClassName(klass): module = klass.__module__ if module == 'builtins': return klass.__qualname__ # avoid outputs like 'builtins.str' return module + '.' + klass.__qualname__ class DeviceRPC(): ''' ioHubDeviceView creates an RPC interface with the iohub server. Each iohub device method exposed by an ioHubDeviceView is represented by an associated DeviceRPC instance. ''' _log_time_index = DeviceEvent.EVENT_HUB_TIME_INDEX _log_text_index = LogEvent.CLASS_ATTRIBUTE_NAMES.index('text') _log_level_index = LogEvent.CLASS_ATTRIBUTE_NAMES.index('log_level') def __init__(self, sendToHub, device_class, method_name): self.device_class = device_class self.method_name = method_name self.sendToHub = sendToHub @staticmethod def _returnarg(a): # pragma: no cover return a def __call__(self, *args, **kwargs): # Send the device method call request to the ioHub Server and wait # for the method return value sent back from the ioHub Server. r = self.sendToHub(('EXP_DEVICE', 'DEV_RPC', self.device_class, self.method_name, args, kwargs)) if r is None: # print("r is None:",('EXP_DEVICE', 'DEV_RPC', self.device_class, # self.method_name, args, kwargs)) return None r = r[1:] if len(r) == 1: r = r[0] if self.method_name != 'getEvents': return r # The result of a call to an iohub Device getEvents() method # gets some special handling, converting the returned events # into the desired object type, etc... asType = 'namedtuple' if 'asType' in kwargs: asType = kwargs['asType'] elif 'as_type' in kwargs: asType = kwargs['as_type'] conversionMethod = self._returnarg if asType == 'dict': conversionMethod = ioHubConnection.eventListToDict elif asType == 'object': conversionMethod = ioHubConnection.eventListToObject elif asType == 'namedtuple': conversionMethod = ioHubConnection.eventListToNamedTuple if self.device_class != 'Experiment': return [conversionMethod(el) for el in r] EVT_TYPE_IX = DeviceEvent.EVENT_TYPE_ID_INDEX LOG_EVT = LogEvent.EVENT_TYPE_ID toBeLogged = [el for el in r if el[EVT_TYPE_IX] == LOG_EVT] for l in toBeLogged: r.remove(l) if psycho_logging: ltime = l[self._log_time_index] ltext = l[self._log_text_index] llevel = l[self._log_level_index] psycho_logging.log(ltext, llevel, ltime) return [conversionMethod(el) for el in r] # pylint: disable=protected-access class ioHubDeviceView(): """ ioHubDeviceView is used as a client / PsychoPy process side representation of an ioHub device that is actually running on the separate iohub process. An ioHubDeviceView instance allows the PsychoPy script process to call public iohub device methods as if the device method calls were being made locally. The ioHubConnection class creates an ioHubDeviceView instance for each ioHub device being run during the experiment. ioHubDeviceView instances are never created directly by a user script, they are created for you by the ioHubConnection class when it connects to the ioHub Process. """ def __init__(self, hubClient, device_class_path, device_class_name, device_config): self.hubClient = hubClient self.name = device_config.get('name', device_class_name.lower()) self.device_class = device_class_name self.device_class_path=device_class_path rpc_request = ('EXP_DEVICE', 'GET_DEV_INTERFACE', device_class_name) r = self.hubClient._sendToHubServer(rpc_request) self._methods = r[1] def __getattr__(self, name): if name in self._methods: r = DeviceRPC(self.hubClient._sendToHubServer, self.device_class, name) return r raise AttributeError(self, name) def getName(self): """ Gets the name given to the device in the ioHub configuration file. ( the device: name: property ) Args: None Returns: (str): the user defined label / name of the device """ return self.name def getIOHubDeviceClass(self, full=False): """ Gets the ioHub Device class associated with the oHubDeviceView. This is specified for a device in the ioHub configuration file. ( the device: device_class: property ) :param full: Returns: (class): ioHub Device class associated with this ioHubDeviceView """ if full: return self.device_class_path return self.device_class def getDeviceInterface(self): """getDeviceInterface returns a list containing the names of all methods that are callable for the ioHubDeviceView object. Only public methods are included in the interface. Any method beginning with a '_' is not included. Args: None Returns: (tuple): list of method names in the ioHubDeviceView interface. """ return self._methods # pylint: enable=protected-access class ioHubDevices(): """ Provides .name access to the ioHub device's created when the ioHub Server is started. Each iohub device is accessible via a dynamically created attribute of this class, the name of which is defined by the device configuration 'name' setting. Each device attribute is an instance of the ioHubDeviceView class. A user script never creates an instance of this class directly, access is provided via the ioHubConnection.devices attribute. """ def __init__(self, hubClient): self.hubClient = hubClient self._devicesByName = dict() def addDevice(self, name, d): setattr(self, name, d) self._devicesByName[name] = d def getDevice(self, name): return self._devicesByName.get(name) def getAll(self): return self._devicesByName.values() def getNames(self): return self._devicesByName.keys() class ioHubConnection(): """ioHubConnection is responsible for creating, sending requests to, and reading replies from the ioHub Process. This class is also used to shut down and disconnect the ioHub Server process. The ioHubConnection class is also used as the interface to any ioHub Device instances that have been created so that events from the device can be monitored. These device objects can be accessed via the ioHubConnection .devices attribute, providing 'dot name' access to enabled devices. Alternatively, the .getDevice(name) method can be used and will return None if the device name specified does not exist. Using the .devices attribute is handy if you know the name of the device to be accessed and you are sure it is actually enabled on the ioHub Process. An example of accessing a device using the .devices attribute:: # get the Mouse device, named mouse mouse=hub.devices.mouse mouse_position = mouse.getPosition() print('mouse position: ', mouse_position) # Returns something like: # >> mouse position: [-211.0, 371.0] """ ACTIVE_CONNECTION = None def __init__(self, ioHubConfig=None, ioHubConfigAbsPath=None): if ioHubConfig: if not isinstance(ioHubConfig, dict): raise ioHubError( 'The provided ioHub Configuration is not a dictionary.', ioHubConfig) if ioHubConnection.ACTIVE_CONNECTION is not None: raise RuntimeError('An existing ioHubConnection is already open. Use ' 'iohub.client.ioHubConnection.getActiveConnection() ' 'to access it; or use ' 'iohub.ioHubConnection.getActiveConnection().quit() ' 'to close it.') Computer.psychopy_process = psutil.Process() # udp port setup self.udp_client = None # the dynamically generated object that contains an attribute for # each device registered for monitoring with the ioHub server so # that devices can be accessed experiment process side by device name. self.devices = ioHubDevices(self) # A circular buffer used to hold events retrieved from self.getEvents() # during self.wait() periods. self.allEvents = [] self.experimentID = None self.experimentSessionID = None self._experimentMetaData = None self._sessionMetaData = None self._server_process = None self._iohub_server_config = None self._shutdown_attempted = False self._cv_order = None self._message_cache = [] self.iohub_status = self._startServer(ioHubConfig, ioHubConfigAbsPath) if self.iohub_status != 'OK': raise RuntimeError('Error starting ioHub server: {}'.format(self.iohub_status)) @classmethod def getActiveConnection(cls): return cls.ACTIVE_CONNECTION def getDevice(self, deviceName): """ Returns the ioHubDeviceView that has a matching name (based on the device : name property specified in the ioHub_config.yaml for the experiment). If no device with the given name is found, None is returned. Example, accessing a Keyboard device that was named 'kb' :: keyboard = self.getDevice('kb') kb_events= keyboard.getEvent() This is the same as using the 'natural naming' approach supported by the .devices attribute, i.e:: keyboard = self.devices.kb kb_events= keyboard.getEvent() However the advantage of using getDevice(device_name) is that an exception is not created if you provide an invalid device name, or if the device is not enabled on the ioHub server; None is returned instead. Args: deviceName (str): Name given to the ioHub Device to be returned Returns: The ioHubDeviceView instance for deviceName. """ return self.devices.getDevice(deviceName) def getEvents(self, device_label=None, as_type='namedtuple'): """Retrieve any events that have been collected by the ioHub Process from monitored devices since the last call to getEvents() or clearEvents(). By default all events for all monitored devices are returned, with each event being represented as a namedtuple of all event attributes. When events are retrieved from an event buffer, they are removed from that buffer as well. If events are only needed from one device instead of all devices, providing a valid device name as the device_label argument will result in only events from that device being returned. Events can be received in one of several object types by providing the optional as_type property to the method. Valid values for as_type are the following str values: * 'list': Each event is a list of ordered attributes. * 'namedtuple': Each event is converted to a namedtuple object. * 'dict': Each event converted to a dict object. * 'object': Each event is converted to a DeviceEvent subclass based on the event's type. Args: device_label (str): Name of device to retrieve events for. If None ( the default ) returns device events from all devices. as_type (str): Returned event object type. Default: 'namedtuple'. Returns: tuple: List of event objects; object type controlled by 'as_type'. """ r = None if device_label is None: events = self._sendToHubServer(('GET_EVENTS',))[1] if events is None: r = self.allEvents else: self.allEvents.extend(events) r = self.allEvents self.allEvents = [] else: r = self.devices.getDevice(device_label).getEvents() if r: if as_type == 'list': return r conversionMethod = None if as_type == 'namedtuple': conversionMethod = self.eventListToNamedTuple elif as_type == 'dict': conversionMethod = self.eventListToDict elif as_type == 'object': conversionMethod = self.eventListToObject if conversionMethod: return [conversionMethod(el) for el in r] return r return [] def clearEvents(self, device_label='all'): """Clears unread events from the ioHub Server's Event Buffer(s) so that unneeded events are not discarded. If device_label is 'all', ( the default ), then events from both the ioHub *Global Event Buffer* and all *Device Event Buffer's* are cleared. If device_label is None then all events in the ioHub *Global Event Buffer* are cleared, but the *Device Event Buffers* are unaffected. If device_label is a str giving a valid device name, then that *Device Event Buffer* is cleared, but the *Global Event Buffer* is not affected. Args: device_label (str): device name, 'all', or None Returns: None """ if device_label and isinstance(device_label, str): device_label = device_label.lower() if device_label == 'all': self.allEvents = [] self._sendToHubServer(('RPC', 'clearEventBuffer', [True, ])) try: self.getDevice('keyboard')._clearLocalEvents() except: pass else: d = self.devices.getDevice(device_label) if d: d.clearEvents() elif device_label in [None, '', False]: self.allEvents = [] self._sendToHubServer(('RPC', 'clearEventBuffer', [False, ])) try: self.getDevice('keyboard')._clearLocalEvents() except: pass else: raise ValueError( 'Invalid device_label value: {}'.format(device_label)) def sendMessageEvent(self, text, category='', offset=0.0, sec_time=None): """ Create and send an Experiment MessageEvent to the ioHub Server for storage in the ioDataStore hdf5 file. Args: text (str): The text message for the message event. 128 char max. category (str): A str grouping code for the message. Optional. 32 char max. offset (float): Optional sec.msec offset applied to the message event time stamp. Default 0. sec_time (float): Absolute sec.msec time stamp for the message in. If not provided, or None, then the MessageEvent is time stamped when this method is called using the global timer (core.getTime()). """ self.cacheMessageEvent(text, category, offset, sec_time) self._sendToHubServer(('EXP_DEVICE', 'EVENT_TX', self._message_cache)) self._message_cache = [] def cacheMessageEvent(self, text, category='', offset=0.0, sec_time=None): """ Create an Experiment MessageEvent and store in local cache. Message must be sent before it is saved to hdf5 file. Args: text (str): The text message for the message event. 128 char max. category (str): A str grouping code for the message. Optional. 32 char max. offset (float): Optional sec.msec offset applied to the message event time stamp. Default 0. sec_time (float): Absolute sec.msec time stamp for the message in. If not provided, or None, then the MessageEvent is time stamped when this method is called using the global timer (core.getTime()). """ self._message_cache.append(MessageEvent._createAsList(text, # pylint: disable=protected-access category=category, msg_offset=offset, sec_time=sec_time)) def sendMessageEvents(self, messageList=[]): if messageList: self.cacheMessageEvents(messageList) if self._message_cache: self._sendToHubServer(('EXP_DEVICE', 'EVENT_TX', self._message_cache)) self._message_cache = [] def cacheMessageEvents(self, messageList): for m in messageList: self._message_cache.append(MessageEvent._createAsList(**m)) def getHubServerConfig(self): """Returns a dict containing the current ioHub Server configuration. Args: None Returns: dict: ioHub Server configuration. """ return self._iohub_server_config def getSessionID(self): return self.experimentSessionID def getSessionMetaData(self): """Returns a dict representing the experiment session data that is being used for the current ioHub Experiment Session. Changing values in the dict has no effect on the session data that has already been saved to the ioHub DataStore. Args: None Returns: dict: Experiment Session metadata saved to the ioHub DataStore. None if the ioHub DataStore is not enabled. """ return self._sessionMetaData def getExperimentID(self): return self.experimentID def getExperimentMetaData(self): """Returns a dict representing the experiment data that is being used for the current ioHub Experiment. Args: None Returns: dict: Experiment metadata saved to the ioHub DataStore. None if the ioHub DataStore is not enabled. """ return self._experimentMetaData def wait(self, delay, check_hub_interval=0.02): # TODO: Integrate iohub event collection done in this version of wait # with psychopy wait() and deprecate this method. """Pause the experiment script execution for delay seconds. time.sleep() is used for delays > 0.02 sec (20 msec) During the wait period, events are received from iohub every 'check_hub_interval' seconds, being buffered so they can be accessed after the wait duration. This is done for two reasons: * The iohub server's global and device level event buffers do not start to drop events if one of the (circular) event buffers becomes full during the wait duration. * The number of events in the iohub process event buffers does not becaome too large, which could result in a longer than normal getEvents() call time. Args: delay (float): The sec.msec delay until method returns. check_hub_interval (float): The sec.msec interval between calls to io.getEvents() during the delay period. Returns: float: The actual duration of the delay in sec.msec format. """ stime = Computer.getTime() targetEndTime = stime + delay if check_hub_interval < 0: check_hub_interval = 0 if check_hub_interval > 0: remainingSec = targetEndTime - Computer.getTime() while remainingSec > check_hub_interval+0.025: time.sleep(check_hub_interval) events = self.getEvents() if events: self.allEvents.extend(events) # Call win32MessagePump so PsychoPy Windows do not become # 'unresponsive' if delay is long. win32MessagePump() remainingSec = targetEndTime - Computer.getTime() time.sleep(max(0.0, targetEndTime - Computer.getTime() - 0.02)) while (targetEndTime - Computer.getTime()) > 0.0: pass return Computer.getTime() - stime def createTrialHandlerRecordTable(self, trials, cv_order=None): """ Create a condition variable table in the ioHub data file based on the a psychopy TrialHandler. By doing so, the iohub data file can contain the DV and IV values used for each trial of an experiment session, along with all the iohub device events recorded by iohub during the session. Example psychopy code usage:: # Load a trial handler and # create an associated table in the iohub data file # from psychopy.data import TrialHandler, importConditions exp_conditions=importConditions('trial_conditions.xlsx') trials = TrialHandler(exp_conditions, 1) # Inform the ioHub server about the TrialHandler # io.createTrialHandlerRecordTable(trials) # Read a row of the trial handler for # each trial of your experiment # for trial in trials: # do whatever... # During the trial, trial variable values can be updated # trial['TRIAL_START']=flip_time # At the end of each trial, before getting # the next trial handler row, send the trial # variable states to iohub so they can be stored for future # reference. # io.addTrialHandlerRecord(trial) """ trial = trials.trialList[0] self._cv_order = cv_order if cv_order is None: self._cv_order = trial.keys() trial_condition_types = [] for cond_name in self._cv_order: cond_val = trial[cond_name] if isinstance(cond_val, str): numpy_dtype = (cond_name, 'S', 256) elif isinstance(cond_val, int): numpy_dtype = (cond_name, 'i8') elif isinstance(cond_val, float): numpy_dtype = (cond_name, 'f8') else: numpy_dtype = (cond_name, 'S', 256) trial_condition_types.append(numpy_dtype) # pylint: disable=protected-access cvt_rpc = ('RPC', 'initConditionVariableTable', (self.experimentID, self.experimentSessionID, trial_condition_types)) r = self._sendToHubServer(cvt_rpc) return r[2] def addTrialHandlerRecord(self, cv_row): """Adds the values from a TriaHandler row / record to the iohub data file for future data analysis use. :param cv_row: :return: None """ data = [] if isinstance(cv_row, (list, tuple)): data = list(cv_row) elif self._cv_order: for cv_name in self._cv_order: data.append(cv_row[cv_name]) else: data = list(cv_row.values()) for i, d in enumerate(data): if isinstance(d, str): data[i] = d.encode('utf-8') cvt_rpc = ('RPC', 'extendConditionVariableTable', (self.experimentID, self.experimentSessionID, data)) r = self._sendToHubServer(cvt_rpc) return r[2] def registerWindowHandles(self, *winHandles): """ Sends 1 - n Window handles to iohub so it can determine if kb or mouse events were targeted at a psychopy window or other window. """ r = self._sendToHubServer(('RPC', 'registerWindowHandles', winHandles)) return r[2] def unregisterWindowHandles(self, *winHandles): """ Sends 1 - n Window handles to iohub so it can determine if kb or mouse events were targeted at a psychopy window or other window. """ r = self._sendToHubServer( ('RPC', 'unregisterWindowHandles', winHandles)) return r[2] def updateWindowPos(self, win, x, y): r = self._sendToHubServer(('RPC', 'updateWindowPos', (win._hw_handle, (x, y)))) return r[2] def getTime(self): """ **Deprecated Method:** Use Computer.getTime instead. Remains here for testing time bases between processes only. """ return self._sendToHubServer(('RPC', 'getTime'))[2] def syncClock(self, clock): """ Synchronise ioHub's internal clock with a given instance of MonotonicClock. """ params = { '_timeAtLastReset': clock._timeAtLastReset, '_epochTimeAtLastReset': clock._epochTimeAtLastReset, 'format': clock.format, } if isinstance(params['format'], type): params['format'] = params['format'].__name__ # sync clock in this process for key, value in params.items(): setattr(Computer.global_clock, key, value) # sync clock in server process return self._sendToHubServer(('RPC', 'syncClock', (params,))) def setPriority(self, level='normal', disable_gc=False): """See Computer.setPriority documentation, where current process will be the iohub process.""" return self._sendToHubServer(('RPC', 'setPriority', [level, disable_gc]))[2] def getPriority(self): """See Computer.getPriority documentation, where current process will be the iohub process.""" return self._sendToHubServer(('RPC', 'getPriority'))[2] def getProcessAffinity(self): """ Returns the current **ioHub Process** affinity setting, as a list of 'processor' id's (from 0 to getSystemProcessorCount()-1). A Process's Affinity determines which CPU's or CPU cores a process can run on. By default the ioHub Process can run on any CPU or CPU core. This method is not supported on OS X at this time. Args: None Returns: list: A list of integer values between 0 and Computer.getSystemProcessorCount()-1, where values in the list indicate processing unit indexes that the ioHub process is able to run on. """ r = self._sendToHubServer(('RPC', 'getProcessAffinity')) return r[2] def setProcessAffinity(self, processor_list): """ Sets the **ioHub Process** Affinity based on the value of processor_list. A Process's Affinity determines which CPU's or CPU cores a process can run on. By default the ioHub Process can run on any CPU or CPU core. The processor_list argument must be a list of 'processor' id's; integers in the range of 0 to Computer.processing_unit_count-1, representing the processing unit indexes that the ioHub Server should be allowed to run on. If processor_list is given as an empty list, the ioHub Process will be able to run on any processing unit on the computer. This method is not supported on OS X at this time. Args: processor_list (list): A list of integer values between 0 and Computer.processing_unit_count-1, where values in the list indicate processing unit indexes that the ioHub process is able to run on. Returns: None """ r = self._sendToHubServer( ('RPC', 'setProcessAffinity', processor_list)) return r[2] def addDeviceToMonitor(self, device_class, device_config=None): """ Normally this method should not be used, as all devices should be specified when the iohub server is being started. Adds a device to the ioHub Server for event monitoring during the experiment. Adding a device to the iohub server after it has been started can take 10'2 to 100's of msec to perform on the ioHub server (depending on the device type). When the device is being added, events from existing devices can not be monitored. Args: device_class (str): The iohub class name of the device being added. device_config (dict): The device configuration settings to be set. Device settings not provided in device_config will be set to the default values specified by the device. Returns: DeviceView Instance: The PsychoPy Process's view of the ioHub Device created that was created, as would be returned if a device was accessed using the .devices attribute or the .getDeviceByLabel() method. """ if device_config is None: device_config = {} drpc = ('EXP_DEVICE', 'ADD_DEVICE', device_class, device_config) r = self._sendToHubServer(drpc) device_class_name, dev_name, _ = r[2] return self._addDeviceView(dev_name, device_class_name) def flushDataStoreFile(self): """Manually tell the iohub datastore to flush any events it has buffered in memory to disk. Any cached message events are sent to the iohub server before flushing the iohub datastore. Args: None Returns: None """ self.sendMessageEvents() r = self._sendToHubServer(('RPC', 'flushIODataStoreFile')) return r def startCustomTasklet(self, task_name, task_class_path, **class_kwargs): """ Instruct the iohub server to start running a custom tasklet given by task_class_path. It is important that the custom task does not block for any significant amount of time, or the processing of events by the iohub server will be negatively effected. See the customtask.py demo for an example of how to make a long running task not block the rest of the iohub server. """ class_kwargs.setdefault('name', task_name) r = self._sendToHubServer(('CUSTOM_TASK', 'START', task_name, task_class_path, class_kwargs)) return r def stopCustomTasklet(self, task_name): """ Instruct the iohub server to stop the custom task that was previously started by calling self.startCustomTasklet(....). task_name identifies which custom task should be stopped and must match the task_name of a previously started custom task. """ r = self._sendToHubServer(('CUSTOM_TASK', 'STOP', task_name)) return r def shutdown(self): """Tells the ioHub Server to close all ioHub Devices, the ioDataStore, and the connection monitor between the PsychoPy and ioHub Processes. Then end the server process itself. Args: None Returns: None """ self._shutDownServer() def quit(self): """Same as the shutdown() method, but has same name as PsychoPy core.quit() so maybe easier to remember.""" self.shutdown() # Private Methods..... def _startServer(self, ioHubConfig=None, ioHubConfigAbsPath=None): """Starts the ioHub Process, storing it's process id, and creating the experiment side device representation for IPC access to public device methods.""" experiment_info = None session_info = None hub_defaults_config = {} rootScriptPath = os.path.dirname(sys.argv[0]) if len(rootScriptPath)<=1: rootScriptPath = os.path.abspath(".") # >>>>> Load / Create / Update iohub config file..... cfpath = os.path.join(IOHUB_DIRECTORY, 'default_config.yaml') with open(cfpath, 'r') as config_file: hub_defaults_config = yload(config_file, Loader=yLoader) if ioHubConfigAbsPath is None and ioHubConfig is None: ioHubConfig = dict(monitor_devices=[dict(Keyboard={}), dict(Display={}), dict(Mouse={})]) elif ioHubConfig is not None and ioHubConfigAbsPath is None: if 'monitor_devices' not in ioHubConfig: raise KeyError("ioHubConfig must be provided with " "'monitor_devices' key:value.") if 'data_store' in ioHubConfig: iods = ioHubConfig['data_store'] if 'experiment_info' in iods and 'session_info' in iods: experiment_info = iods['experiment_info'] session_info = iods['session_info'] else: raise KeyError("ERROR: ioHubConfig:ioDataStore must " "contain both a 'experiment_info' and a " "'session_info' entry.") elif ioHubConfigAbsPath is not None and ioHubConfig is None: with open(ioHubConfigAbsPath, 'r') as config_file: ioHubConfig = yload(config_file, Loader=yLoader) else: raise ValueError('Both a ioHubConfig dict object AND a path to an ' 'ioHubConfig file can not be provided.') if ioHubConfig: updateDict(ioHubConfig, hub_defaults_config) if ioHubConfig and ioHubConfigAbsPath is None: if isinstance(ioHubConfig.get('monitor_devices'), dict): # short hand device spec is being used. Convert dict of # devices in a list of device dicts. devs = ioHubConfig.get('monitor_devices') devsList = [{dname: dc} for dname, dc in devs.items()] ioHubConfig['monitor_devices'] = devsList import tempfile with tempfile.NamedTemporaryFile(mode='w', suffix='iohub', delete=False) as tfile: tfile.write(json.dumps(ioHubConfig)) ioHubConfigAbsPath = os.path.abspath(tfile.name) # <<<<< Finished Load / Create / Update iohub config file. self._iohub_server_config = ioHubConfig if sys.platform == 'darwin': self._osxKillAndFreePort() # >>>> Start iohub subprocess run_script = os.path.join(IOHUB_DIRECTORY, 'start_iohub_process.py') subprocessArgList = [sys.executable, run_script, '%.6f' % Computer.global_clock.getLastResetTime(), rootScriptPath, ioHubConfigAbsPath, "{}".format(Computer.current_process.pid)] # To enable coverage in the iohub process, set the iohub\default_config # setting 'coverage_env_var' to the name of the coverage # config file that exists in the psychopy\iohub site-packages folder. # For example: # coverage_env_var: .coveragerc # # If coverage_env_var is None or the file is not found, # coverage of ioHub Server process is disabled. coverage_env_var = self._iohub_server_config.get('coverage_env_var') envars = dict(os.environ) if coverage_env_var not in [None, 'None']: coverage_env_var = "{}".format(coverage_env_var) cov_config_path = os.path.join(IOHUB_DIRECTORY, coverage_env_var) if os.path.exists(cov_config_path): print("Coverage enabled for ioHub Server Process.") else: print("ioHub Process Coverage conf file not found: %s", cov_config_path) envars['COVERAGE_PROCESS_START'] = coverage_env_var self._server_process = subprocess.Popen(subprocessArgList, env=envars, cwd=IOHUB_DIRECTORY, # set sub process stderr to be stdout so PsychoPy Runner # shows errors from iohub stderr=subprocess.STDOUT, ) # Get iohub server pid and psutil process object # for affinity and process priority setting. Computer.iohub_process_id = self._server_process.pid Computer.iohub_process = psutil.Process(self._server_process.pid) # >>>>> Create open UDP port to ioHub Server server_udp_port = self._iohub_server_config.get('udp_port', 9000) from ..net import UDPClientConnection # initially open with a timeout so macOS does not hang. self.udp_client = UDPClientConnection(remote_port=server_udp_port, timeout=0.1) # If ioHub server does not respond correctly, # terminate process and exit the program. if self._waitForServerInit() is False: self._server_process.terminate() return "ioHub startup failed." # close and reopen blocking version of socket self.udp_client.close() self.udp_client = UDPClientConnection(remote_port=server_udp_port) # <<<<< Done Creating open UDP port to ioHub Server # <<<<< Done starting iohub subprocess ioHubConnection.ACTIVE_CONNECTION = proxy(self) # Send iohub server any existing open psychopy window handles. try: from psychopy.visual import window window.IOHUB_ACTIVE = True if window.openWindows: whs = [] # pylint: disable=protected-access for w in window.openWindows: winfo = windowInfoDict(w()) whs.append(winfo) w().backend.onMoveCallback = self.updateWindowPos self.registerWindowHandles(*whs) except ImportError: pass # Sending experiment_info if available..... if experiment_info: self._sendExperimentInfo(experiment_info) # Sending session_info if available..... if session_info: # print 'Sending session_info: {0}'.format(session_info) self._sendSessionInfo(session_info) # >>>> Creating client side iohub device wrappers... self._createDeviceList(ioHubConfig['monitor_devices']) return 'OK' def _waitForServerInit(self): # >>>> Wait for iohub server ready signal .... hubonline = False # timeout if ioServer does not reply in 30 seconds timeout_duration = self._iohub_server_config.get('start_process_timeout', 30.0) timeout_time = Computer.getTime() + timeout_duration while hubonline is False and Computer.getTime() < timeout_time: r = self._sendToHubServer(['GET_IOHUB_STATUS', ]) if r: hubonline = r[1] == 'RUNNING' time.sleep(0.1) return hubonline # # <<<< Finished wait for iohub server ready signal .... def _createDeviceList(self, monitor_devices_config): """Create client side iohub device views. """ # get the list of devices registered with the ioHub for device_config_dict in monitor_devices_config: device_class_name = list(device_config_dict.keys())[0] device_config = list(device_config_dict.values())[0] if device_config.get('enable', True) is True: try: self._addDeviceView(device_class_name, device_config) except Exception: # pylint: disable=broad-except print2err('_createDeviceList: Error adding class. ') printExceptionDetailsToStdErr() def _addDeviceView(self, dev_cls_name, dev_config): """Add an iohub device view to self.devices""" try: name = dev_config.get('name', dev_cls_name.lower()) dev_cls_name = "{}".format(dev_cls_name) dev_name = dev_cls_name.lower() cls_name_start = dev_name.rfind('.') dev_mod_pth = 'psychopy.iohub.devices.' if cls_name_start > 0: dev_mod_pth2 = dev_name[:cls_name_start] dev_mod_pth = '{0}{1}'.format(dev_mod_pth, dev_mod_pth2) dev_cls_name = dev_cls_name[cls_name_start + 1:] else: dev_mod_pth = '{0}{1}'.format(dev_mod_pth, dev_name) # try to import EyeTracker class from given path try: dev_import_result = import_device(dev_mod_pth, dev_cls_name) except ModuleNotFoundError: # if not found, try importing from root (may have entry point) dev_import_result = import_device("psychopy.iohub.devices", dev_cls_name) dev_cls, dev_cls_name, evt_cls_list = dev_import_result DeviceConstants.addClassMapping(dev_cls) device_event_ids = [] for ev in list(evt_cls_list.values()): if ev.EVENT_TYPE_ID: device_event_ids.append(ev.EVENT_TYPE_ID) EventConstants.addClassMappings(device_event_ids, evt_cls_list) name_start = name.rfind('.') if name_start > 0: name = name[name_start + 1:] from .. import client as iohubclientmod local_class = None local_module = getattr(iohubclientmod, dev_cls_name.lower(), False) if local_module: # need to touch local_module since it was lazy loaded # pylint: disable=exec-used exec('import psychopy.iohub.client.{}'.format(dev_cls_name.lower())) local_class = getattr(local_module, dev_cls_name, False) if local_class: d = local_class(self, dev_cls_name, dev_config) else: d = ioHubDeviceView(self, dev_mod_pth + "." + dev_cls_name, dev_cls_name, dev_config) self.devices.addDevice(name, d) return d except Exception: # pylint: disable=broad-except print2err('_addDeviceView: Error adding class. ') printExceptionDetailsToStdErr() return None def _convertDict(self, d): r = {} for k, v in d.items(): if isinstance(v, bytes): v = str(v, 'utf-8') elif isinstance(v, list) or isinstance(v, tuple): v = self._convertList(v) elif isinstance(v, dict): v = self._convertDict(v) if isinstance(k, bytes): k = str(k, 'utf-8') r[k]=v return r def _convertList(self, l): r = [] for i in l: if isinstance(i, bytes): r.append(str(i, 'utf-8')) elif isinstance(i, list) or isinstance(i, tuple): r.append(self._convertList(i)) elif isinstance(i, dict): r.append(self._convertDict(i)) else: r.append(i) return r def _sendToHubServer(self, tx_data): """General purpose local <-> iohub server process UDP based request - reply code. The method blocks until the request is fulfilled and and a response is received from the ioHub server. Args: tx_data (tuple): data to send to iohub server Return (object): response from the ioHub Server process. """ try: # send request to host, return is # bytes sent. #print("SEND:",tx_data) self.udp_client.sendTo(tx_data) except Exception as e: # pylint: disable=broad-except import traceback traceback.print_exc() self.shutdown() raise e result = None try: # wait for response from ioHub server, which will be the # result data and iohub server address (ip4,port). result = self.udp_client.receive() if result: result, _ = result #print("RESULT:",result) except Exception as e: # pylint: disable=broad-except import traceback traceback.print_exc() self.shutdown() raise e # check if the reply is an error or not. If it is, raise the error. # TODO: This is not really working as planned, in part because iohub # server does not consistently return error responses when needed errorReply = self._isErrorReply(result) if errorReply: raise ioHubError(result) # Otherwise return the result if result is not None: # Use recursive conversion funcs if isinstance(result, list) or isinstance(result, tuple): result = self._convertList(result) elif isinstance(result, dict): result = self._convertDict(result) return result def _sendExperimentInfo(self, experimentInfoDict): """Sends the experiment info from the experiment config file to the ioHub Server, which passes it to the ioDataStore, determines if the experiment already exists in the hdf5 file based on 'experiment_code', and returns a new or existing experiment ID based on that criteria. """ fieldOrder = (('experiment_id', 0), ('code', ''), ('title', ''), ('description', ''), ('version', '')) values = [] for key, defaultValue in fieldOrder: if key in experimentInfoDict: values.append(experimentInfoDict[key]) else: values.append(defaultValue) experimentInfoDict[key] = defaultValue r = self._sendToHubServer(('RPC', 'setExperimentInfo', (values,))) self.experimentID = r[2] experimentInfoDict['experiment_id'] = self.experimentID self._experimentMetaData = experimentInfoDict return r[2] def _sendSessionInfo(self, sess_info): """Sends the experiment session info from the experiment config file and the values entered into the session dialog to the ioHub Server, which passes it to the ioDataStore. The dataStore determines if the session already exists in the experiment file based on 'session_code', and returns a new session ID if session_code is not in use by the experiment. """ if self.experimentID is None: raise RuntimeError("Experiment ID must be set by calling" " _sendExperimentInfo before calling" " _sendSessionInfo.") if 'code' not in sess_info: raise ValueError("Code must be provided in sessionInfoDict" " ( StringCol(24) ).") if 'name' not in sess_info: sess_info['name'] = '' if 'comments' not in sess_info: sess_info['comments'] = '' if 'user_variables' not in sess_info: sess_info['user_variables'] = {} org_sess_info = sess_info['user_variables'] sess_info['user_variables'] = json.dumps(sess_info['user_variables']) r = self._sendToHubServer(('RPC', 'createExperimentSessionEntry', (sess_info,)) ) self.experimentSessionID = r[2] sess_info['user_variables'] = org_sess_info sess_info['session_id'] = self.experimentSessionID self._sessionMetaData = sess_info return sess_info['session_id'] @staticmethod def eventListToObject(evt_data): """Convert an ioHub event currently in list value format into the correct ioHub.devices.DeviceEvent subclass for the given event type.""" evt_type = evt_data[DeviceEvent.EVENT_TYPE_ID_INDEX] return EventConstants.getClass(evt_type).createEventAsClass(evt_data) @staticmethod def eventListToDict(evt_data): """Convert an ioHub event currently in list value format into the event as a dictionary of attribute name, attribute values.""" if isinstance(evt_data, dict): return evt_data etype = evt_data[DeviceEvent.EVENT_TYPE_ID_INDEX] return EventConstants.getClass(etype).createEventAsDict(evt_data) @staticmethod def eventListToNamedTuple(evt_data): """Convert an ioHub event currently in list value format into the namedtuple format for an event.""" if not isinstance(evt_data, list): return evt_data etype = evt_data[DeviceEvent.EVENT_TYPE_ID_INDEX] return EventConstants.getClass(etype).createEventAsNamedTuple(evt_data) # client utility methods. def _getDeviceList(self): r = self._sendToHubServer(('EXP_DEVICE', 'GET_DEVICE_LIST')) return r[2] def _shutDownServer(self): if self._shutdown_attempted is False: # send any cached experiment messages self.sendMessageEvents() try: from psychopy.visual import window window.IOHUB_ACTIVE = False except ImportError: pass self._shutdown_attempted = True TimeoutError = psutil.TimeoutExpired try: if self.udp_client: # if it isn't already garbage-collected self.udp_client.sendTo(('STOP_IOHUB_SERVER',)) self.udp_client.close() if Computer.iohub_process: # This wait() used to have timeout=5, removing it to allow # sufficient time for all iohub devices to be closed. r = Computer.iohub_process.wait() print('ioHub Server Process Completed With Code: ', r) except TimeoutError: print('Warning: TimeoutExpired, Killing ioHub Server process.') Computer.iohub_process.kill() except Exception: # pylint: disable=broad-except print("Warning: Unhandled Exception. " "Killing ioHub Server process.") if Computer.iohub_process: Computer.iohub_process.kill() printExceptionDetailsToStdErr() finally: ioHubConnection.ACTIVE_CONNECTION = None self._server_process = None Computer.iohub_process_id = None Computer.iohub_process = None return True @staticmethod def _isErrorReply(data): """ Check if an iohub server reply contains an error that should be raised by the local process. """ # is it an ioHub error object? if isinstance(data, ioHubError): return True if isIterable(data) and len(data) > 0: d0 = data[0] if isIterable(d0): return False else: if isinstance(d0, str) and d0.find('ERROR') >= 0: return data return False else: return data #'Invalid Response Received from ioHub Server' def _osxKillAndFreePort(self): server_udp_port = self._iohub_server_config.get('udp_port', 9000) p = subprocess.Popen(['lsof', '-i:%d'%server_udp_port, '-P'], stdout=subprocess.PIPE, encoding='utf-8') lines = p.communicate()[0] for line in lines.splitlines(): if line.startswith('Python'): PID, userID = line.split()[1:3] # could verify same userID as current user, probably not needed os.kill(int(PID), signal.SIGKILL) print('Called os.kill(int(PID),signal.SIGKILL): ', PID, userID) def __del__(self): try: self._shutDownServer() ioHubConnection.ACTIVE_CONNECTION = None except Exception: # pylint: disable=broad-except pass ############################################################################## class ioEvent(): """ Parent class for all events generated by a psychopy.iohub.client Device wrapper. """ _attrib_index = dict() _attrib_index['id'] = DeviceEvent.EVENT_ID_INDEX _attrib_index['time'] = DeviceEvent.EVENT_HUB_TIME_INDEX _attrib_index['type'] = DeviceEvent.EVENT_TYPE_ID_INDEX def __init__(self, ioe_array, device=None): self._time = ioe_array[ioEvent._attrib_index['time']] self._id = ioe_array[ioEvent._attrib_index['id']] self._type = ioe_array[ioEvent._attrib_index['type']] self._device = device @property def device(self): """ The ioHubDeviceView that is associated with the event, i.e. the iohub device view for the device that generated the event. :return: ioHubDeviceView """ return self._device @property def time(self): """ The time stamp of the event. Uses the same time base that is used by psychopy.core.getTime() :return: float """ return self._time @property def id(self): """The unique id for the event; in some cases used to track associated events. :return: int """ return self._id @property def type(self): """The event type string constant. :return: str """ return EventConstants.getName(self._type) @property def dict(self): d = {} for k in self._attrib_index: d[k] = getattr(self, k) return d def __str__(self): return 'time: %.3f, type: %s, id: %d' % (self.time, self.type, self.id) _lazyImports = """ from psychopy.iohub.client.connect import launchHubServer from psychopy.iohub.client import keyboard from psychopy.iohub.client import wintab """ try: lazy_import(globals(), _lazyImports) except Exception as e: #pylint: disable=broad-except print2err('lazy_import Exception:', e) exec(_lazyImports) #pylint: disable=exec-used
56,879
Python
.py
1,209
35.159636
104
0.601438
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,657
wintab.py
psychopy_psychopy/psychopy/iohub/client/wintab.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from collections import deque import math import numpy as np from . import ioHubDeviceView, ioEvent, DeviceRPC from ..devices import Computer from ..devices.wintab import WintabSampleEvent from ..constants import EventConstants if Computer.platform == 'win32': import win32api FRAC = LOWORD = win32api.LOWORD INT = HIWORD = win32api.HIWORD else: FRAC = lambda x: x & 0x0000ffff INT = lambda x: x >> 16 def FIX_DOUBLE(x): return INT(x) + FRAC(x) / 65536.0 # ### Patch psychopy.platform_specific.sendStayAwake ### so that it does not cause psychopy window to consume ### events needed by iohub.devices.wintab. # def _noOpFunc(): pass from psychopy import platform_specific _sendStayAwake = platform_specific.sendStayAwake platform_specific.sendStayAwake=_noOpFunc _sendStayAwake() print(">> iohub.wintab device patching platform_specific.sendStayAwake.") # TabletPen Device and Events Types class PenSampleEvent(ioEvent): """Represents a tablet pen position / pressure event.""" STATES = dict() STATES[1] = 'FIRST_ENTER' STATES[2] = 'FIRST_HOVER' STATES[4] = 'HOVERING' STATES[8] = 'FIRST_PRESS' STATES[16] = 'PRESSED' wtsample_attrib_names = WintabSampleEvent.CLASS_ATTRIBUTE_NAMES _attrib_index = dict() _attrib_index['x'] = wtsample_attrib_names.index('x') _attrib_index['y'] = wtsample_attrib_names.index('y') _attrib_index['z'] = wtsample_attrib_names.index('z') _attrib_index['buttons'] = wtsample_attrib_names.index('buttons') _attrib_index['pressure'] = wtsample_attrib_names.index('pressure') _attrib_index['altitude'] = wtsample_attrib_names.index('orient_altitude') _attrib_index['azimuth'] = wtsample_attrib_names.index('orient_azimuth') _attrib_index['status'] = wtsample_attrib_names.index('status') def __init__(self, ioe_array, device): super(PenSampleEvent, self).__init__(ioe_array, device) for efname, efvalue in list(PenSampleEvent._attrib_index.items()): if efvalue >= 0: setattr(self, '_' + efname, ioe_array[efvalue]) self._velocity = 0.0 self._acceleration = 0.0 @property def x(self): return self._x @property def y(self): return self._y @property def z(self): return self._z def getPixPos(self, win): sw, sh = win.winHandle.width, win.winHandle.height return (int(self._x / self.device.axis['x']['range'] * sw - sw / 2), int(self._y / self.device.axis['y']['range'] * sh - sh / 2)) def getNormPos(self): return (-1.0 + (self._x / self.device.axis['x']['range']) * 2.0, -1.0 + (self._y / self.device.axis['y']['range']) * 2.0) @property def pressure(self): return self._pressure @property def altitude(self): return self._altitude @property def azimuth(self): return self._azimuth @property def buttons(self): return self._buttons @property def status(self): return [v for k, v in list(self.STATES.items()) if self._status & k == k] @property def tilt(self): """Get the pen horizontal & vertical tilt for the sample. horizontal tilt (azimuth) vertical tilt (altitude) """ axis = self.device.axis altitude_axis = axis['orient_altitude'] azimuth_axis = axis['orient_azimuth'] if altitude_axis['supported'] and azimuth_axis['supported']: tilt1 = altitude_axis['adjust'] tilt1 -= abs(self.altitude) / altitude_axis['factor'] #/* adjust azimuth */ tilt2 = float(self.azimuth / azimuth_axis['factor']) return tilt1, tilt2 return 0, 0 @property def velocity(self): """Returns the calculated x, y, and xy velocity for the current sample. :return: (float, float, float) """ return self._velocity @property def acceleration(self): """Returns the calculated x, y, and xy acceleration for the current sample. :return: (float, float, float) """ return self._acceleration @property def accelleration(self): # deprecated, use acceleration instead return self._acceleration @velocity.setter def velocity(self, v): """Returns the calculated x, y, and xy velocity for the current sample. :return: (float, float, float) """ self._velocity = v @acceleration.setter def acceleration(self, a): """Returns the calculated x, y, and xy acceleration for the current sample. :return: (float, float, float) """ self._acceleration = a @accelleration.setter def accelleration(self, a): # deprecated, use acceleration instead self._acceleration = a def __str__(self): sargs = [ioEvent.__str__(self), self.x, self.y, self.z, self.pressure, self.tilt] return '{}, x,y,z: {}, {}, {} pressure: {}, tilt: {}'.format(*sargs) class PenEnterRegionEvent(ioEvent): """Occurs when Stylus enters the tablet region.""" def __init__(self, ioe_array, device): super(PenEnterRegionEvent, self).__init__(ioe_array, device) class PenLeaveRegionEvent(ioEvent): """Occurs when Stylus leaves the tablet region.""" def __init__(self, ioe_array, device): super(PenLeaveRegionEvent, self).__init__(ioe_array, device) class Wintab(ioHubDeviceView): """The Wintab device provides access to PenSampleEvent events.""" SAMPLE = EventConstants.WINTAB_SAMPLE ENTER = EventConstants.WINTAB_ENTER_REGION LEAVE = EventConstants.WINTAB_LEAVE_REGION _type2class = {SAMPLE: PenSampleEvent, ENTER: PenEnterRegionEvent, LEAVE: PenLeaveRegionEvent} def __init__(self, ioclient, dev_cls_name, dev_config): super(Wintab, self).__init__(ioclient, 'client.Wintab', dev_cls_name, dev_config) self._prev_sample = None self._events = dict() self._reporting = False self._device_config = dev_config self._event_buffer_length = dev_config.get('event_buffer_length') self._clearEventsRPC = DeviceRPC(self.hubClient._sendToHubServer, self.device_class, 'clearEvents') self._context = {'Context': {'status': 'Device not Initialized'}} self._axis = {'Axis': {'status': 'Device not Initialized'}} self._hw_model = {'ModelInfo': {'status': 'Device not Initialized'}} if self.getInterfaceStatus() == 'HW_OK': wthw = self.getHardwareConfig() self._context = wthw['Context'] self._axis = wthw['Axis'] self._hw_model = wthw['ModelInfo'] # Add extra axis info for axis in list(self._axis.values()): axis['range'] = axis['max'] - axis['min'] axis['supported'] = axis['range'] != 0 # Add tilt related calc constants to orient_azimuth # and orient_altitude axis # azi_axis = self._axis['orient_azimuth'] alt_axis = self._axis['orient_altitude'] if azi_axis['supported'] and alt_axis['supported']: azi_axis['factor'] = FIX_DOUBLE(azi_axis['resolution']) azi_axis['factor'] = azi_axis['factor'] / (2 * math.pi) # convert altitude resolution to double alt_axis['factor'] = FIX_DOUBLE(alt_axis['resolution']) # adjust for maximum value at vertical alt_axis['adjust'] = alt_axis['max'] / alt_axis['factor'] def _calculateVelAccel(self, s): curr_samp = self._type2class[self.SAMPLE](s, self) if 'FIRST_ENTER' in curr_samp.status: self._prev_sample = None prev_samp = self._prev_sample if prev_samp: try: dx = curr_samp.x - prev_samp.x dy = curr_samp.y - prev_samp.y dt = (curr_samp.time - prev_samp.time) if dt <= 0: print( 'Warning: dt == 0: {}, {}, {}'.format( dt, curr_samp.time, prev_samp.time)) curr_samp.velocity = (0, 0, 0) curr_samp.acceleration = (0, 0, 0) else: cvx = dx / dt cvy = dy / dt cvxy = np.sqrt(dx * dx + dy * dy) / dt curr_samp.velocity = cvx, cvy, cvxy pvx, pvy, _ = prev_samp.velocity if prev_samp.velocity != (0, 0, 0): dx = cvx - pvx dy = cvy - pvy cax = dx / dt cay = dy / dt cayx = np.sqrt(dx * dx + dy * dy) / dt curr_samp.acceleration = cax, cay, cayx else: curr_samp.acceleration = (0, 0, 0) except ZeroDivisionError: print("ERROR: wintab._calculateVelAccel ZeroDivisionError " "occurred. prevId: %d, currentId: %d" % (curr_samp.id, prev_samp.id)) curr_samp.velocity = (0, 0, 0) curr_samp.acceleration = (0, 0, 0) except Exception as e: #pylint: disable=broad-except print("ERROR: wintab._calculateVelAccel error [%s] occurred." "prevId: %d, currentId: %d" % (str(e), curr_samp.id, prev_samp.id)) curr_samp.velocity = (0, 0, 0) curr_samp.acceleration = (0, 0, 0) else: curr_samp.velocity = (0, 0, 0) curr_samp.acceleration = (0, 0, 0) self._prev_sample = curr_samp return curr_samp def _syncDeviceState(self): """An optimized iohub server request that receives all device state and event information in one response. :return: None """ kb_state = self.getCurrentDeviceState() self._reporting = kb_state.get('reporting_events') for etype, event_arrays in list(kb_state.get('events').items()): etype = int(etype) ddeque = deque(maxlen=self._event_buffer_length) et_queue = self._events.setdefault(etype, ddeque) if etype == self.SAMPLE: for s in event_arrays: et_queue.append(self._calculateVelAccel(s)) else: for evt in event_arrays: et_queue.append(self._type2class[etype](evt, self)) @property def reporting(self): """Specifies if the device is reporting / recording events. * True: events are being reported. * False: events are not being reported. """ return self._reporting @reporting.setter def reporting(self, r): """Sets the state of keyboard event reporting / recording.""" if r is True: self._prev_sample = None self._reporting = self.enableEventReporting(r) return self._reporting @property def axis(self): return self._axis @property def context(self): return self._context @property def model(self): return self._hw_model def clearEvents(self, event_type=None, filter_id=None): result = self._clearEventsRPC(event_type=event_type, filter_id=filter_id) for etype, elist in list(self._events.items()): if event_type is None or event_type == etype: elist.clear() return result def getSamples(self, clear=True): """ Return a list of any Tablet sample events that have occurred since the last time either: * this method was called with the kwarg clear=True (default) * the tablet.clear() method was called. """ self._syncDeviceState() return_events = [e for e in self._events.get(self.SAMPLE, [])] if return_events and clear is True: self._events.get(self.SAMPLE).clear() return sorted(return_events, key=lambda x: x.time) def getEnters(self, clear=True): self._syncDeviceState() return_events = [e for e in self._events.get(self.ENTER, [])] if return_events and clear is True: self._events.get(self.ENTER).clear() return sorted(return_events, key=lambda x: x.time) def getLeaves(self, clear=True): self._syncDeviceState() return_events = [e for e in self._events.get(self.LEAVE, [])] if return_events and clear is True: self._events.get(self.LEAVE).clear() return sorted(return_events, key=lambda x: x.time)
13,202
Python
.py
309
32.601942
89
0.584841
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,658
__init__.py
psychopy_psychopy/psychopy/iohub/client/eyetracker/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL).
211
Python
.py
4
52
85
0.745192
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,659
procedure.py
psychopy_psychopy/psychopy/iohub/client/eyetracker/validation/procedure.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). """ Eye Tracker Validation procedure using the ioHub common eye tracker interface. To use the validation process from within a Coder script: * Create a target stim * Create a list of validation target positions. Use the `PositionGrid` class to help create a target position list. * Create a ValidationProcedure class instance, providing the target stim and position list and other arguments to define details of the validation procedure. * Use `ValidationProcedure.run()` to perform the validation routine. * Use `ValidationProcedure.getValidationResults()` to access information about each target position displayed and the events collected during the each target validation period. See demos/coder/iohub/eyetracking/validation.py for a complete example. """ from weakref import proxy import numpy as np from time import sleep import os import sys from matplotlib import pyplot as pl from psychopy import visual from psychopy.iohub.util import win32MessagePump, normjoin from psychopy.iohub.constants import EventConstants from psychopy.iohub.client import ioHubConnection, Computer from psychopy.tools.monitorunittools import convertToPix from psychopy.tools.monitorunittools import pix2deg, deg2pix from psychopy.iohub.client.eyetracker.validation import PositionGrid, Trigger, KeyboardTrigger, TimeTrigger getTime = Computer.getTime class TargetStim: def __init__(self, win, radius=None, fillcolor=None, edgecolor=None, edgewidth=None, dotcolor=None, dotradius=None, units=None, colorspace=None, opacity=1.0, contrast=1.0): """ TargetStim is a 'doughnut' style target graphic used during the validation procedure. :param win: Window being used for validation. :param radius: The outer radius of the target. :param fillcolor: The color used to fill the target body. :param edgecolor: The color for the edge around the target. :param edgewidth: The thickness of the target outer edge (always in pixels). :param dotcolor: The color of the central target dot. :param dotradius: The radius to use for the target dot. :param units: The psychopy unit type of any size values. :param colorspace: The psychopy color space of any colors. :param opacity: The transparency of the target (0.0 - 1.0). :param contrast: The contrast of the target stim. """ from weakref import proxy self.win = proxy(win) self.stim = [] self._radius = radius outer = visual.Circle(self.win, radius=radius, fillColor=fillcolor, lineColor=edgecolor, lineWidth=edgewidth, edges=32, units=units, colorSpace=colorspace, opacity=opacity, contrast=contrast, interpolate=True, autoLog=False) self.stim.append(outer) if dotcolor and dotcolor != fillcolor: centerdot = visual.Circle(self.win, radius=dotradius, fillColor=dotcolor, lineColor=dotcolor, lineWidth=0.0, edges=32, interpolate=True, units=units, colorSpace=colorspace, opacity=opacity, contrast=contrast, autoLog=False) self.stim.append(centerdot) def setPos(self, pos): """ Set the center position of the target stim. Used during validation procedure to change target position. """ for s in self.stim: s.setPos(pos) @property def pos(self): return self.stim[0].pos @pos.setter def pos(self, value): self.setPos(value) @property def radius(self): return self._radius @radius.setter def radius(self, r): self._radius = self.stim[0].radius = r def setSize(self, s): """ Update the size of the target stim. """ self.stim[0].radius = s/2 def getSize(self): """ Get the size of the target stim. """ return self.stim[0].radius*2 def draw(self): """ Draw the Target stim. """ for s in self.stim: s.draw() def contains(self, p): """ Is point p contained within the Target Stim? :param p: x, y position in stim units :return: bool: True: p is within the stim """ return self.stim[0].contains(p) @property def innerRadius(self): try: return self.stim[1].radius except: return self.stim[0].radius def create3PointGrid(): io = ioHubConnection.getActiveConnection() if io is None: raise RuntimeError("iohub must be running.") l, t, r, b = io.devices.display.getCoordBounds() return [(0.0, (t-b)/4), (-(r-l)/4, -(t-b)/4), ((r-l)/4, -(t-b)/4)] def create5PointGrid(): io = ioHubConnection.getActiveConnection() if io is None: raise RuntimeError("iohub must be running.") four_point = PositionGrid(io.devices.display.getCoordBounds(), (2, 2), scale=0.85).getPositions() return [(0.0, 0.0),] + four_point def create9PointGrid(): io = ioHubConnection.getActiveConnection() if io is None: raise RuntimeError("iohub must be running.") return PositionGrid(io.devices.display.getCoordBounds(), (3, 3), scale=0.85, firstposindex=4) def create13PointGrid(): io = ioHubConnection.getActiveConnection() if io is None: raise RuntimeError("iohub must be running.") nine_point = create9PointGrid().getPositions() four_point = PositionGrid(io.devices.display.getCoordBounds(), (2, 2), scale=0.5).getPositions() thirteen_point = nine_point + four_point return thirteen_point def create17PointGrid(): io = ioHubConnection.getActiveConnection() if io is None: raise RuntimeError("iohub must be running.") sixteen_pos = PositionGrid(io.devices.display.getCoordBounds(), (4, 4), scale=0.85).getPositions() return [(0.0, 0.0), ] + sixteen_pos class ValidationProcedure: def __init__(self, win=None, # psychopy window target=None, # target stim positions=None, # string constant or list of points randomize_positions=True, # boolean expand_scale=None, # float target_duration=None, # float target_delay=None, # float enable_position_animation=True, color_space=None, # None == use window color space unit_type=None, # None == use window unit type (may need to enforce this for Validation) progress_on_key=" ", # str or None gaze_cursor=None, # None, color, or a stim object with setPos() text_color=None, show_results_screen=True, # bool save_results_screen=False, # bool # args not used by Builder at this time contract_target=True, accuracy_period_start=0.550, accuracy_period_stop=.150, show_intro_screen=False, intro_text='Ready to Start Validation Procedure.', results_in_degrees=False, terminate_key="escape", toggle_gaze_cursor_key="g"): """ ValidationProcedure is used to test the gaze accuracy of a calibrated eye tracking system. Once a ValidationProcedure class instance has been created, call the `.run()` method to start the validation process, which consists of the following steps: 1) (Optionally) Display an Introduction screen. A 'space' key press is used to start target presentation. 2) Displaying the validation target at each position being validated. Target progression from one position to the next is controlled by the specified `triggers`, defaulting to a 'space' key press. The target graphics can simply jump from one position to the next, or optional target_animation settings can be used to have the target move across the screen from one point to the next and / or expand / contract at each target location. 3) (Optionally) Display a Results screen. The Results screen shows each target position, the position of each sample used for the accuracy calculation, and some validation result statistics. Data collected during the validation target sequence is used to calculate accuracy information for each target position presented. The raw data as well as the computed accuracy stats is available via the `.getValidationResults()` method. To make the validation output consistent across iohub common eye tracker implementations, validation is performed on monocular eye data. If binocular eye samples are being recorded, the average of the left and right eye positions is used for each gaze sample. See the validation.py demo in demos.coder.iohub.eyetracking for a demo. TODO: Update param list docs :param win: PsychoPy window to use for validation. Must be full screen. :param target: Stimulus to use as validation target. If None, default `TargetStim` is used. :param positions: Positions to validate. Provide list of x,y pairs, or use a `PositionGrid` class. :param target_animation: :param randomize_positions: bool: Randomize target positions before presentation. :param show_intro_screen: bool: Display a validation procedure Introduction screen. :param intro_text: Introduction screen text. :param show_results_screen: bool: Display a validation procedure Results screen. :param results_in_degrees: bool: Convert results to visual degrees. :param save_results_screen: bool: Save results screen as image. :param terminate_key: Key that will end the validation procedure. Default is 'escape'. :param toggle_gaze_cursor_key: Key to toggle gaze cursor visibility (hidden to start). Default is key is 'g'. :param accuracy_period_start: Time prior to target trigger to use as start of period for valid samples. :param accuracy_period_stop: Time prior to target trigger to use as end of period for valid samples. :param triggers: Target progression triggers. Default is 'space' key press. :param storeeventsfor: iohub devices that events should be stored for. """ self.terminate_key = terminate_key self.toggle_gaze_cursor_key = toggle_gaze_cursor_key self.io = ioHubConnection.getActiveConnection() if isinstance(positions, str): # position set constant, THREE_POINTS, FIVE_POINTS, NINE_POINTS, THIRTEEN_POINTS, SEVENTEEN_POINTS if positions == 'THREE_POINTS': positions = create3PointGrid() elif positions == 'FIVE_POINTS': positions = create5PointGrid() elif positions == 'NINE_POINTS': positions = create9PointGrid() elif positions == 'THIRTEEN_POINTS': positions = create13PointGrid() elif positions == 'SEVENTEEN_POINTS': positions = create17PointGrid() else: raise ValueError("Unsupported positions string constant: [{}]".format(positions)) if isinstance(positions, (list, tuple)): positions = PositionGrid(posList=positions, firstposindex=0, repeatFirstPos=False) self.positions = positions self.randomize_positions = randomize_positions if self.randomize_positions: self.positions.randomize() self.win = proxy(win) target_animation = {} target_animation['enable'] = enable_position_animation target_animation['targetdelay'] = target_delay target_animation['targetduration'] = target_duration target_animation['expandedscale'] = expand_scale target_animation['contracttarget'] = contract_target self.animation_params = target_animation self.accuracy_period_start = accuracy_period_start self.accuracy_period_stop = accuracy_period_stop self.show_intro_screen = show_intro_screen self.intro_text = intro_text self.intro_text_stim = None self.show_results_screen = show_results_screen self.results_in_degrees = results_in_degrees self.save_results_screen = save_results_screen self._validation_results = None self.text_color = text_color self.text_color_space = color_space if text_color is None or text_color == 'auto': # If no calibration text color provided, base it on the window background color from psychopy.iohub.util import complement sbcolor = win.color from psychopy.colors import Color tcolor_obj = Color(sbcolor, win.colorSpace) self.text_color = complement(*tcolor_obj.rgb255) self.text_color_space = 'rgb255' storeeventsfor = [self.io.devices.keyboard, self.io.devices.tracker, self.io.devices.experiment] trig_list = [] if progress_on_key: if isinstance(progress_on_key, (list, tuple)): for k in progress_on_key: trig_list.append(KeyboardTrigger(k, on_press=True)) else: trig_list.append(KeyboardTrigger(progress_on_key, on_press=True)) elif target_duration: trig_list.append(TimeTrigger(start_time=None, delay=target_duration),) triggers = Trigger.getTriggersFrom(trig_list) # Create the ValidationTargetRenderer instance; used to control the sequential # presentation of the target at each of the grid positions. self.targetsequence = ValidationTargetRenderer(win, target=target, positions=self.positions, triggers=triggers, storeeventsfor=storeeventsfor, terminate_key=terminate_key, gaze_cursor_key=toggle_gaze_cursor_key, gaze_cursor=gaze_cursor, color_space=color_space, unit_type=unit_type) def run(self): """ Run the validation procedure, returning after the full validation process is complete, including: a) display of an instruction screen b) display of the target position sequence used for validation data collection. c) display of a validation accuracy results plot. """ keyboard = self.io.devices.keyboard if self.show_intro_screen: # Display Validation Intro Screen self.showIntroScreen() if self.terminate_key and self.terminate_key in keyboard.waitForReleases(keys=[' ', 'space',self.terminate_key]): print("Escape key pressed. Exiting validation") self._validation_results = None return # Perform Validation..... terminate = not self.targetsequence.display(**self.animation_params) if terminate: print("Escape key pressed. Exiting validation") self._validation_results = None return self.io.clearEvents('all') self._createValidationResults() if self.show_results_screen: self.showResultsScreen() kb_presses = keyboard.waitForPresses(keys=['space',' ', self.terminate_key, self.targetsequence.gaze_cursor_key]) while 'space' not in kb_presses and ' ' not in kb_presses: if self.targetsequence.gaze_cursor_key in kb_presses: self.targetsequence.display_gaze = not self.targetsequence.display_gaze self.showResultsScreen() if self.terminate_key in kb_presses: print("Escape key pressed. Exiting validation") break kb_presses = keyboard.waitForPresses(keys=['space', ' ', self.terminate_key, self.targetsequence.gaze_cursor_key]) return self._validation_results def showResultsScreen(self): self.drawResultScreen() ftime = self.win.flip() if self.save_results_screen: self.win.getMovieFrame() self.win.saveMovieFrames(self._generateImageName()) return ftime def showIntroScreen(self): text = self.intro_text + '\nPress SPACE to Start....' textpos = (0, 0) if self.intro_text_stim: self.intro_text_stim.setText(text) self.intro_text_stim.setPos(textpos) else: self.intro_text_stim = visual.TextStim(self.win, text=text, pos=textpos, height=30, color=self.text_color, colorSpace=self.text_color_space, opacity=1.0, contrast=1.0, units='pix', ori=0.0, antialias=True, bold=False, italic=False, anchorHoriz='center', anchorVert='center', wrapWidth=self.win.size[0] * .8) self.intro_text_stim.draw() self.win.flip() return self.win.flip() @property def results(self): """ See getValidationResults(). :return: """ return self._validation_results def getValidationResults(self): """ Return the validation results dict for the last validation run. If a validation as not yet been run(), None is returned. Validation results are provided separately for each target position and include: a) An array of the samples used for the accuracy calculation. The samples used are selected using the following criteria: i) Only samples where the target was stationary and not expanding or contracting are selected. ii) Samples are selected that fall between: start_time_filter = last_sample_time - accuracy_period_start and end_time_filter = last_sample_time - accuracy_period_end Therefore, the duration of the selected sample period is: selection_period_dur = end_time_filter - start_time_filter iii) Sample that contain missing / invalid position data are removed, providing the final set of samples used for accuracy calculations. The min, max, and mean values from each set of selected samples is calculated. b) The x and y error of sampled gaze position relative to the current target position. This data is in the same units as is used by the validation window. c) The xy distance error from the from each eye's gaze position to the target position. This is also calculated as an average of both eyes when binocular data is available. The data is unsigned, providing the absolute distance from gaze to target positions Validation Results Dict Structure ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ {'display_bounds': [-1.0, 1.0, 1.0, -1.0], 'display_pix': array([1920, 1080]), 'display_units': 'norm', 'max_error': 2.3668638421479, 'mean_error': 0.9012516727129639, 'min_error': 0.0, 'passed': True, 'position_count': 9, 'positions_failed_processing': 0, 'reporting_unit_type': 'degree', 'target_positions': [array([0., 0.]), array([0.85, 0.85]), array([-0.85, 0. ]), array([0.85, 0. ]), array([ 0.85, -0.85]), array([-0.85, 0.85]), array([-0.85, -0.85]), array([0. , 0.85]), array([ 0. , -0.85])], 'position_results': [{'index': 0, 'calculation_status': 'PASSED', 'target_position': array([0., 0.]), 'sample_time_range': [4.774341499977744, 6.8343414999777], 'filter_samples_time_range': [6.2843414999777005, 6.6843414999777], 'min_error': 0.0, 'max_error': 0.7484680652684592, 'mean_error': 0.39518431321527914, 'stdev_error': 0.24438398690651483, 'valid_filtered_sample_perc': 1.0, }, # Validation results dict is given for each target position # .... ] } :return: validation results dict. """ return self._validation_results def _createValidationResults(self): """ Create validation results dict and save validation analysis info as experiment messages to the iohub .hdf5 file. :return: dict """ self._validation_results = None sample_array = self.targetsequence.getSampleMessageData() target_positions_used = self.targetsequence.positions.getPositions() if self.results_in_degrees: for postdat in sample_array: postdat['targ_pos_x'], postdat['targ_pos_y'] = toDeg(self.win, *toPix(self.win, postdat['targ_pos_x'], postdat['targ_pos_y'])) binoc_sample_types = [EventConstants.BINOCULAR_EYE_SAMPLE, EventConstants.GAZEPOINT_SAMPLE] if self.targetsequence.sample_type in binoc_sample_types: postdat['left_eye_x'], postdat['left_eye_y'] = toDeg(self.win, *toPix(self.win, postdat['left_eye_x'], postdat['left_eye_y'])) postdat['right_eye_x'], postdat['right_eye_y'] = toDeg(self.win, *toPix(self.win, postdat['right_eye_x'], postdat['right_eye_y'])) else: postdat['eye_x'], postdat['eye_y'] = toDeg(self.win, *toPix(self.win, postdat['eye_x'], postdat['eye_y'])) min_error = 100000.0 max_error = 0.0 summed_error = 0.0 point_count = 0 self.io.sendMessageEvent('Results', 'VALIDATION') results = dict(display_units=self.win.units, display_bounds=self.positions.bounds, display_pix=self.win.size, position_count=len(sample_array), target_positions=target_positions_used) for k, v in results.items(): self.io.sendMessageEvent('{}: {}'.format(k, v), 'VALIDATION') results['position_results'] = [] results['positions_failed_processing'] = 0 for pindex, samplesforpos in enumerate(sample_array): self.io.sendMessageEvent('Target Position Results: {0}'.format(pindex), 'VALIDATION') stationary_samples = samplesforpos[samplesforpos['targ_state'] == self.targetsequence.TARGET_STATIONARY] if len(stationary_samples): last_stime = stationary_samples[-1]['eye_time'] first_stime = stationary_samples[0]['eye_time'] filter_stime = last_stime - self.accuracy_period_start filter_etime = last_stime - self.accuracy_period_stop all_samples_in_period = stationary_samples[stationary_samples['eye_time'] >= filter_stime] all_samples_in_period = all_samples_in_period[all_samples_in_period['eye_time'] < filter_etime] good_samples_in_period = all_samples_in_period[all_samples_in_period['eye_status'] == 0] all_samples_count = all_samples_in_period.shape[0] good_sample_count = good_samples_in_period.shape[0] try: good_sample_ratio = good_sample_count / float(all_samples_count) except ZeroDivisionError: good_sample_ratio = 0 else: all_samples_in_period = [] good_samples_in_period = [] good_sample_ratio = 0 # Dictionary of the different levels of samples selected during filtering # for valid samples to use in accuracy calculations. sample_msg_data_filtering = dict(all_samples=samplesforpos, # All samples from target period. # Sample during stationary period at end of target # presentation display. stationary_samples=stationary_samples, # Samples that occurred within the # defined time selection period. time_filtered_samples=all_samples_in_period, # Samples from the selection period that # do not have missing data used_samples=good_samples_in_period) position_results = dict(index=pindex, target_position=target_positions_used[pindex], sample_time_range=[first_stime, last_stime], filter_samples_time_range=[filter_stime, filter_etime], valid_filtered_sample_perc=good_sample_ratio) for k, v in position_results.items(): self.io.sendMessageEvent('{}: {}'.format(k, v), 'VALIDATION') position_results['sample_from_filter_stages'] = sample_msg_data_filtering position_results2 = dict() if int(good_sample_ratio * 100) == 0: position_results2['calculation_status'] = 'FAILED' results['positions_failed_processing'] += 1 else: target_x = good_samples_in_period[:]['targ_pos_x'] target_y = good_samples_in_period[:]['targ_pos_y'] binoc_sample_types = [EventConstants.BINOCULAR_EYE_SAMPLE, EventConstants.GAZEPOINT_SAMPLE] if self.targetsequence.sample_type in binoc_sample_types: left_x = good_samples_in_period[:]['left_eye_x'] left_y = good_samples_in_period[:]['left_eye_y'] left_error_x = target_x - left_x left_error_y = target_y - left_y left_error_xy = np.hypot(left_error_x, left_error_y) right_x = good_samples_in_period[:]['right_eye_x'] right_y = good_samples_in_period[:]['right_eye_y'] right_error_x = target_x - right_x right_error_y = target_y - right_y right_error_xy = np.hypot(right_error_x, right_error_y) lr_error = (right_error_xy + left_error_xy) / 2.0 lr_error_max = lr_error.max() lr_error_min = lr_error.min() lr_error_mean = lr_error.mean() lr_error_std = np.std(lr_error) min_error = min(min_error, lr_error_min) max_error = max(max_error, lr_error_max) summed_error += lr_error_mean point_count += 1.0 else: eye_x = good_samples_in_period[:]['eye_x'] eye_y = good_samples_in_period[:]['eye_y'] error_x = target_x - eye_x error_y = target_y - eye_y error_xy = np.hypot(error_x, error_y) lr_error = error_xy lr_error_max = lr_error.max() lr_error_min = lr_error.min() lr_error_mean = lr_error.mean() lr_error_std = np.std(lr_error) min_error = min(min_error, lr_error_min) max_error = max(max_error, lr_error_max) summed_error += lr_error_mean point_count += 1.0 position_results2['calculation_status'] = 'PASSED' position_results2['min_error'] = lr_error_min position_results2['max_error'] = lr_error_max position_results2['mean_error'] = lr_error_mean position_results2['stdev_error'] = lr_error_std for k, v in position_results2.items(): self.io.sendMessageEvent('{}: {}'.format(k, v), 'VALIDATION') position_results[k] = v results['position_results'].append(position_results) self.io.sendMessageEvent('Done Target Position Results : {0}'.format(pindex), 'VALIDATION') unit_type = self.win.units if self.results_in_degrees: unit_type = 'degree' if point_count >= 1: mean_error = summed_error / point_count else: min_error = max_error = mean_error = 0.0 err_results = dict(reporting_unit_type=unit_type, min_error=min_error, max_error=max_error, mean_error=mean_error, passed=results['positions_failed_processing'] == 0, positions_failed_processing=results['positions_failed_processing']) for k, v in err_results.items(): self.io.sendMessageEvent('{}: {}'.format(k, v), 'VALIDATION') results[k] = v self.io.sendMessageEvent('Validation Report Complete', 'VALIDATION') self._validation_results = results return self._validation_results def _generateImageName(self): import datetime file_name = 'validation_' + datetime.datetime.now().strftime('%d_%m_%Y_%H_%M') + '.png' #if self.save_results_screen: # return normjoin(self.save_results_screen, file_name) rootScriptPath = os.path.dirname(sys.argv[0]) return normjoin(rootScriptPath, file_name) def drawResultScreen(self): """ Draw validation results screen. :return: """ results = self.getValidationResults() for tp in self.positions.getPositions(): self.targetsequence.target.pos = tp self.targetsequence.target.draw() title_txt = 'Validation Results\nMin: %.4f, Max: %.4f,' \ ' Mean %.4f (%s units)' % (results['min_error'], results['max_error'], results['mean_error'], results['reporting_unit_type']) title_stim = visual.TextStim(self.win, text=title_txt, height=24, pos=(0.0, (self.win.size[1] / 2.0) * .95), color=self.text_color, colorSpace=self.text_color_space, units='pix', antialias=True, anchorVert='center', anchorHoriz='center', wrapWidth=self.win.size[0] * .8) title_stim.draw() exit_text = visual.TextStim(self.win, text='Press SPACE to continue.', opacity=1.0, units='pix', height=None, pos=(0.0, -(self.win.size[1] / 2.0) * .95), color=self.text_color, colorSpace=self.text_color_space, antialias=True, bold=True, anchorVert='center', anchorHoriz='center', wrapWidth=self.win.size[0] * .8) exit_text.draw() color_list = pl.cm.tab20b(np.linspace(0, 1, (len(results['position_results'])))) # draw eye samples ci = 0 for position_results in results['position_results']: color = color_list[ci] * 2.0 - 1.0 utype = 'pix' target_x, target_y = position_results['target_position'] sample_gfx_radius = deg2pix(0.33, self.win.monitor, correctFlat=False) if self.results_in_degrees: sample_gfx_radius = 0.33 utype='deg' sample_gfx = visual.Circle(self.win, radius=sample_gfx_radius, fillColor=color, lineColor=[1, 1, 1], lineWidth=1, edges=64, units=utype, colorSpace='rgb', opacity=0.66, interpolate=True, autoLog=False) if position_results['calculation_status'] == 'FAILED': position_txt = "Failed" txt_bold = True position_txt_color = "red" else: samples = position_results['sample_from_filter_stages']['used_samples'] binoc_sample_types = [EventConstants.BINOCULAR_EYE_SAMPLE, EventConstants.GAZEPOINT_SAMPLE] if self.targetsequence.sample_type in binoc_sample_types: gaze_x = (samples[:]['left_eye_x'] + samples[:]['right_eye_x']) / 2.0 gaze_y = (samples[:]['left_eye_y'] + samples[:]['right_eye_y']) / 2.0 else: gaze_x = samples[:]['eye_x'] gaze_y = samples[:]['eye_y'] for i in range(len(gaze_x)): if self.results_in_degrees: g_pos = gaze_x[i], gaze_y[i] else: g_pos = toPix(self.win, gaze_x[i], gaze_y[i]) g_pos = g_pos[0][0], g_pos[1][0] sample_gfx.pos = g_pos sample_gfx.draw() txt_bold = False position_txt = "Gaze Error:\nMin: %.4f\nMax: %.4f\n" \ "Avg: %.4f\nStdev: %.4f" % (position_results['min_error'], position_results['max_error'], position_results['mean_error'], position_results['stdev_error']) position_txt_color = "green" if self.targetsequence.display_gaze: text_pix_pos = toPix(self.win, target_x, target_y) text_pix_pos = text_pix_pos[0][0], text_pix_pos[1][0] target_text_stim = visual.TextStim(self.win, text=position_txt, units='pix', pos=text_pix_pos, height=21, color=position_txt_color, antialias=True, bold=txt_bold, anchorVert='center', anchorHoriz='center') target_text_stim.draw() ci += 1 class ValidationTargetRenderer: TARGET_STATIONARY = 1 TARGET_MOVING = 2 TARGET_EXPANDING = 4 TARGET_CONTRACTING = 8 # Experiment Message text field types and tokens message_types = dict(BEGIN_SEQUENCE=('BEGIN_SEQUENCE', '', int), DONE_SEQUENCE=('DONE_SEQUENCE', '', int), NEXT_POS_TRIG=('NEXT_POS_TRIG', '', int, float), START_DRAW=('START_DRAW', ',', int, float, float, float, float), SYNCTIME=('SYNCTIME', ',', int, float, float, float, float), EXPAND_SIZE=('EXPAND_SIZE', '', float, float), CONTRACT_SIZE=('CONTRACT_SIZE', '', float, float), POS_UPDATE=('POS_UPDATE', ',', float, float), TARGET_POS=('TARGET_POS', ',', float, float)) max_msg_type_length = max([len(s) for s in message_types.keys()]) binocular_sample_message_element = [('targ_pos_ix', int), ('last_msg_time', np.float64), ('last_msg_type', str, max_msg_type_length), ('next_msg_time', np.float64), ('next_msg_type', str, max_msg_type_length), ('targ_pos_x', np.float64), ('targ_pos_y', np.float64), ('targ_state', int), ('eye_time', np.float64), ('eye_status', int), ('left_eye_x', np.float64), ('left_eye_y', np.float64), ('left_pupil_size', np.float64), ('right_eye_x', np.float64), ('right_eye_y', np.float64), ('right_pupil_size', np.float64)] monocular_sample_message_element = [('targ_pos_ix', int), ('last_msg_time', np.float64), ('last_msg_type', str, max_msg_type_length), ('next_msg_time', np.float64), ('next_msg_type', str, max_msg_type_length), ('targ_pos_x', np.float64), ('targ_pos_y', np.float64), ('targ_state', int), ('eye_time', np.float64), ('eye_status', int), ('eye_x', np.float64), ('eye_y', np.float64), ('pupil_size', np.float64)] def __init__(self, win, target, positions, storeeventsfor=[], triggers=None, msgcategory='', io=None, terminate_key='escape', gaze_cursor_key='g', gaze_cursor=None, color_space=None, unit_type=None): """ ValidationTargetRenderer is an internal class used by `ValidationProcedure`. psychopy.iohub.client.eyetracker.validation.Trigger based classes are used to define the criteria used to start displaying the next target position graphics. By providing a set of DeviceEventTriggers, complex criteria for target position pacing can be defined. iohub devices can be provided in the storeeventsfor keyword argument. Events which occur during each target position presentation period are stored and are available at the end of the display() period, grouped by position index and device event types. :param win: :param target: :param positions: :param storeeventsfor: :param triggers: :param msgcategory: :param io: """ self.terminate_key = terminate_key self.gaze_cursor_key = gaze_cursor_key self.display_gaze = False self.gaze_cursor = None if isinstance(gaze_cursor, (str, list, tuple)): gc_size = deg2pix(3.0, win.monitor, correctFlat=False) self.gaze_cursor = visual.GratingStim(win, tex=None, mask='gauss', pos=(0, 0), size=(gc_size, gc_size), color=gaze_cursor, colorSpace=color_space, units='pix', opacity=0.8) elif gaze_cursor and hasattr(gaze_cursor, 'setPos'): self.gaze_cursor = gaze_cursor else: raise ValueError("Gaze Cursor must be a color value or visual stim type.") self._terminate_requested = False self.win = proxy(win) self.target = target self.positions = positions self.storeevents = storeeventsfor self.msgcategory = msgcategory if io is None: io = ioHubConnection.getActiveConnection() self.io = io self._keyboard = self.io.devices.keyboard # If storeevents is True, targetdata will be a list of dict's. # Each dict, among other things, contains all ioHub events that occurred # from when a target was first presented at a position, to when the # the wait period completed for that position. # self.targetdata = [] self.triggers = triggers def _draw(self): """ Draw the target stim. """ self.target.draw() if self.gaze_cursor and self.display_gaze: gpos = self.io.devices.tracker.getLastGazePosition() valid_gaze_pos = isinstance(gpos, (tuple, list)) if valid_gaze_pos: pix_pos = toPix(self.win, *gpos) pix_pos = pix_pos[0][0], pix_pos[1][0] self.gaze_cursor.setPos(pix_pos) self.gaze_cursor.draw() def _animateTarget(self, topos, frompos, **kwargs): """ Any logic related to drawing the target at the new screen position, including any intermediate animation effects, is done here. Return the flip time when the target was first drawn at the newpos location. """ io = self.io # Target position animation phase animate_position = kwargs.get('enable') targetdelay = kwargs.get('targetdelay') if frompos is not None: if animate_position: start_time = getTime() while (getTime() - start_time) <= targetdelay: t = (getTime()-start_time) / targetdelay v1 = frompos v2 = topos t = 60.0 * ((1.0 / 10.0) * t ** 5 - (1.0 / 4.0) * t ** 4 + (1.0 / 6.0) * t ** 3) moveTo = ((1.0 - t) * v1[0] + t * v2[0], (1.0 - t) * v1[1] + t * v2[1]) self.target.pos = moveTo self._draw() fliptime = self.win.flip() io.sendMessageEvent('POS_UPDATE %.4f,%.4f' % (moveTo[0], moveTo[1]), self.msgcategory, sec_time=fliptime) self._addDeviceEvents() if self._terminate_requested: return 0 else: # No target animation, so just show cleared screen # for targetdelay seconds fliptime = self.win.flip(clearBuffer=True) while getTime() < fliptime+targetdelay: self._addDeviceEvents() if self._terminate_requested: return 0 self.target.pos = topos self._draw() fliptime = self.win.flip() io.sendMessageEvent('TARGET_POS %.4f,%.4f' % (topos[0], topos[1]), self.msgcategory, sec_time=fliptime) self._addDeviceEvents() # Target expand / contract phase expandedscale = kwargs.get('expandedscale') targetduration = kwargs.get('targetduration') contract_target = kwargs.get('contracttarget') initialradius = self.target.radius expand_duration = None contract_duration = None if contract_target and expandedscale and expandedscale > 1.0: # both expand and contract expand_duration = contract_duration = targetduration / 2 elif contract_target: # contract only expand_duration = None contract_duration = targetduration elif expandedscale and expandedscale > 1.0: # contract only expand_duration = targetduration contract_duration = None if expand_duration: expandedradius = self.target.radius * expandedscale starttime = getTime() expandedtime = fliptime + expand_duration while fliptime < expandedtime: mu = (fliptime - starttime) / expand_duration cradius = initialradius * (1.0 - mu) + expandedradius * mu self.target.radius = cradius self._draw() fliptime = self.win.flip() io.sendMessageEvent('EXPAND_SIZE %.4f %.4f' % (cradius, initialradius), self.msgcategory, sec_time=fliptime) self._addDeviceEvents() if self._terminate_requested: return 0 if contract_duration: starttime = getTime() contractedtime = fliptime + contract_duration start_radius = self.target.radius try: stop_radius = self.target.innerRadius except: stop_radius = start_radius/2 print("Warning: validation target has no .innerRadius property.") while fliptime < contractedtime: mu = (fliptime - starttime) / contract_duration cradius = start_radius * (1.0 - mu) + stop_radius * mu self.target.radius = cradius self._draw() fliptime = self.win.flip() io.sendMessageEvent('CONTRACT_SIZE %.4f %.4f' % (cradius, initialradius), self.msgcategory, sec_time=fliptime) self._addDeviceEvents() if self._terminate_requested: return 0 return fliptime def moveTo(self, topos, frompos, **kwargs): """ Indicates that the target should be moved frompos to topos. If a PositionGrid has been provided, moveTo should not be called directly. Instead, use the display() method to start the full target position presentation sequence. """ io = self.io fpx, fpy = -1, -1 if frompos is not None: fpx, fpy = frompos[0], frompos[1] io.sendMessageEvent('START_DRAW %d %.4f,%.4f %.4f,%.4f' % (self.positions.posIndex, fpx, fpy, topos[0], topos[1]), self.msgcategory) fliptime = self._animateTarget(topos, frompos, **kwargs) io.sendMessageEvent('SYNCTIME %d %.4f,%.4f %.4f,%.4f' % (self.positions.posIndex, fpx, fpy, topos[0], topos[1]), self.msgcategory, sec_time=fliptime) # wait for trigger to fire last_pump_time = fliptime trig_fired = self._hasTriggerFired(start_time=fliptime) while not trig_fired: if getTime() - last_pump_time >= 0.250: win32MessagePump() last_pump_time = getTime() if self.display_gaze: self._draw() self.win.flip() else: sleep(0.001) if self._checkForTerminate(): return self._checkForToggleGaze() trig_fired = self._hasTriggerFired(start_time=fliptime) def _hasTriggerFired(self, **kwargs): """ Used internally to know when one of the triggers has occurred and the target should move to the next target position. """ # wait for trigger to fire triggered = None for trig in self.triggers: if trig.triggered(**kwargs): triggered = trig self._addDeviceEvents(trig.clearEventHistory(True)) if triggered: break if triggered: # by default, assume it was a timer trigger,so use 255 as 'event type' event_type_id = 255 trig_evt = triggered.getTriggeringEvent() if hasattr(trig_evt, 'type'): # actually it was a device event trigger event_type_id = trig_evt.type # get time trigger of trigger event event_time = triggered.getTriggeringTime() self.io.sendMessageEvent('NEXT_POS_TRIG %d %.3f' % (event_type_id, event_time), self.msgcategory) for trig in self.triggers: trig.resetTrigger() return triggered def _initTargetData(self, frompos, topos): """ Internally used to create the data structure used to store position information and events which occurred during each target position period. """ if self.storeevents: deviceevents = {} for device in self.storeevents: deviceevents[device] = [] self.targetdata.append(dict(frompos=frompos, topos=topos, events=deviceevents)) def _addDeviceEvents(self, device_event_dict={}): if self._checkForTerminate(): return self._checkForToggleGaze() dev_event_buffer = self.targetdata[-1]['events'] for dev, dev_events in dev_event_buffer.items(): if dev in device_event_dict: dev_events.extend(device_event_dict[dev]) else: dev_events.extend(dev.getEvents()) def _checkForTerminate(self): keys = self._keyboard.getEvents(EventConstants.KEYBOARD_PRESS, clearEvents=False) for k in keys: if k.key == self.terminate_key: self._terminate_requested = True break return self._terminate_requested def _checkForToggleGaze(self): keys = self._keyboard.getEvents(EventConstants.KEYBOARD_PRESS, clearEvents=False) for k in keys: if k.key == self.gaze_cursor_key: # get (clear) the event so it does not trigger multiple times. self._keyboard.getEvents(EventConstants.KEYBOARD_PRESS, clearEvents=True) self.display_gaze = not self.display_gaze self._draw() self.win.flip() return self.display_gaze return self.display_gaze def display(self, **kwargs): """ Display the target at each point in the position grid, performing target animation if requested. The target then holds position until one of the specified triggers occurs, resulting in the target moving to the next position in the positiongrid. To setup target animation between grid positions, the following keyword arguments are supported. If an option is not specified, the animation related to it is not performed. Note that target expansion and contraction change the target stimulus outer diameter only. The edge thickness and central dot radius do not change. When this method returns, the target has been displayed at all positions. Data collected for each position period can be accessed via the targetdata attribute. """ del self.targetdata[:] prevpos = None io = self.io io.clearEvents('all') io.sendMessageEvent('BEGIN_SEQUENCE {0}'.format(len(self.positions.positions)), self.msgcategory) turn_rec_off = [] for d in self.storeevents: if not d.isReportingEvents(): d.enableEventReporting(True) turn_rec_off.append(d) sleep(0.025) initialsize=self.target.radius for pos in self.positions: self._initTargetData(prevpos, pos) self._addDeviceEvents() if self._terminate_requested: break self.target.radius = initialsize self.moveTo(pos, prevpos, **kwargs) prevpos = pos self._addDeviceEvents() if self._terminate_requested: break self.target.radius = initialsize for d in turn_rec_off: d.enableEventReporting(False) if self._terminate_requested: io.sendMessageEvent('VALIDATION TERMINATED BY USER', self.msgcategory) return False io.sendMessageEvent('DONE_SEQUENCE {0}'.format(len(self.positions.positions)), self.msgcategory) sleep(0.025) self._addDeviceEvents() io.clearEvents('all') return True def _processMessageEvents(self): self.target_pos_msgs = [] self.saved_pos_samples = [] for pd in self.targetdata: events = pd.get('events') # create a dict of device labels as keys, device events as value devlabel_events = {} for k, v in events.items(): devlabel_events[k.getName()] = v samples = devlabel_events.get('tracker', []) # remove any eyetracker events that are not samples samples = [s for s in samples if s.type in (EventConstants.BINOCULAR_EYE_SAMPLE, EventConstants.MONOCULAR_EYE_SAMPLE, EventConstants.GAZEPOINT_SAMPLE)] self.saved_pos_samples.append(samples) self.sample_type = self.saved_pos_samples[0][0].type if self.sample_type == EventConstants.MONOCULAR_EYE_SAMPLE: self.sample_msg_dtype = self.monocular_sample_message_element else: self.sample_msg_dtype = self.binocular_sample_message_element messages = devlabel_events.get('experiment', []) msg_lists = [] for m in messages: temp = m.text.strip().split() msg_type = self.message_types.get(temp[0]) if msg_type: current_msg = [m.time, m.category] if msg_type[1] == ',': for t in temp: current_msg.extend(t.split(',')) else: current_msg.extend(temp) for mi, dtype in enumerate(msg_type[2:]): current_msg[mi + 3] = dtype(current_msg[mi + 3]) msg_lists.append(current_msg) if msg_lists[0][2] == 'NEXT_POS_TRIG': # handle case where the trigger msg from the previous target # message was not read until the start of the next pos. # In which case, move msg to end of previous targ pos msgs npm = msg_lists.pop(0) self.target_pos_msgs[-1].append(npm) self.target_pos_msgs.append(msg_lists) for i in range(len(self.target_pos_msgs)): self.target_pos_msgs[i] = np.asarray(self.target_pos_msgs[i], dtype=object) return self.target_pos_msgs def getSampleMessageData(self): """ Return a list of numpy ndarrays, each containing joined eye sample and previous / next experiment message data for the sample's time. """ # preprocess message events self._processMessageEvents() # inline func to return sample field array based on sample namedtup def getSampleData(s): sampledata = [s.time, s.status] binoc_sample_types = [EventConstants.BINOCULAR_EYE_SAMPLE, EventConstants.GAZEPOINT_SAMPLE] if s.type in binoc_sample_types: sampledata.extend((s.left_gaze_x, s.left_gaze_y, s.left_pupil_measure1, s.right_gaze_x, s.right_gaze_y, s.right_pupil_measure1)) return sampledata sampledata.extend((s.gaze_x, s.gaze_y, s.pupil_measure1)) return sampledata current_target_pos = -1.0, -1.0 current_targ_state = 0 target_pos_samples = [] for pindex, samples in enumerate(self.saved_pos_samples): last_msg, messages = self.target_pos_msgs[pindex][0], self.target_pos_msgs[pindex][1:] samplesforposition = [] pos_sample_count = len(samples) si = 0 for current_msg in messages: last_msg_time = last_msg[0] last_msg_type = last_msg[2] if last_msg_type == 'START_DRAW': if not current_targ_state & self.TARGET_STATIONARY: current_targ_state += self.TARGET_STATIONARY current_targ_state -= current_targ_state & self.TARGET_MOVING current_targ_state -= current_targ_state & self.TARGET_EXPANDING current_targ_state -= current_targ_state & self.TARGET_CONTRACTING elif last_msg_type == 'EXPAND_SIZE': if not current_targ_state & self.TARGET_EXPANDING: current_targ_state += self.TARGET_EXPANDING current_targ_state -= current_targ_state & self.TARGET_CONTRACTING elif last_msg_type == 'CONTRACT_SIZE': if not current_targ_state & self.TARGET_CONTRACTING: current_targ_state += self.TARGET_CONTRACTING current_targ_state -= current_targ_state & self.TARGET_EXPANDING elif last_msg_type == 'TARGET_POS': current_target_pos = float(last_msg[3]), float(last_msg[4]) current_targ_state -= current_targ_state & self.TARGET_MOVING if not current_targ_state & self.TARGET_STATIONARY: current_targ_state += self.TARGET_STATIONARY elif last_msg_type == 'POS_UPDATE': current_target_pos = float(last_msg[3]), float(last_msg[4]) if not current_targ_state & self.TARGET_MOVING: current_targ_state += self.TARGET_MOVING current_targ_state -= current_targ_state & self.TARGET_STATIONARY elif last_msg_type == 'SYNCTIME': if not current_targ_state & self.TARGET_STATIONARY: current_targ_state += self.TARGET_STATIONARY current_targ_state -= current_targ_state & self.TARGET_MOVING current_targ_state -= current_targ_state & self.TARGET_EXPANDING current_targ_state -= current_targ_state & self.TARGET_CONTRACTING current_target_pos = float(last_msg[6]), float(last_msg[7]) while si < pos_sample_count: sample = samples[si] if last_msg_time <= sample.time < current_msg[0]: sarray = [pindex, last_msg_time, last_msg_type, current_msg[0], current_msg[2], current_target_pos[0], current_target_pos[1], current_targ_state] sarray.extend(getSampleData(sample)) sndarray = np.asarray(tuple(sarray), dtype=self.sample_msg_dtype) samplesforposition.append(sndarray) si += 1 elif sample.time >= current_msg[0]: break else: si += 1 last_msg = current_msg possamples = np.asanyarray(samplesforposition) target_pos_samples.append(possamples) # So we now have a list len == number target positions. Each element # of the list is a list of all eye sample / message data for a # target position. Each element of the data list for a single target # position is itself a list that that contains combined info about # an eye sample and message info valid for when the sample time was. return np.asanyarray(target_pos_samples, dtype=object) def toPix(win, x, y): """Returns the stim's position in pixels, based on its pos, units, and win. """ try: xy = np.zeros((len(x), 2)) except TypeError: xy = np.zeros((1, 2)) xy[:, 0] = x xy[:, 1] = y r = convertToPix(np.asarray((0, 0)), xy, win.units, win) return r[:, 0], r[:, 1] def toDeg(win, x, y): try: xy = np.zeros((len(x), 2)) except TypeError: xy = np.zeros((1, 2)) xy[:, 0] = x xy[:, 1] = y r = pix2deg(xy, win.monitor, correctFlat=False) return r[:, 0], r[:, 1]
60,791
Python
.py
1,117
38.961504
136
0.564161
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,660
trigger.py
psychopy_psychopy/psychopy/iohub/client/eyetracker/validation/trigger.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from psychopy import core from psychopy.iohub.constants import EventConstants from psychopy.iohub.client import ioHubConnection getTime = core.getTime class Trigger: io = None def __init__(self, trigger_function=lambda a, b, c: True, user_kwargs={}, repeat_count=0): Trigger.io = ioHubConnection.getActiveConnection() self.trigger_function = trigger_function self.user_kwargs = user_kwargs self._last_triggered_event = None self._last_triggered_time = None self.repeat_count = repeat_count self.triggered_count = 0 def triggered(self, **kwargs): if 0 <= self.repeat_count < self.triggered_count: return False return True def getTriggeringEvent(self): return self._last_triggered_event def getTriggeringTime(self): return self._last_triggered_time def getTriggeredStateCallback(self): return self.trigger_function, self.user_kwargs def resetLastTriggeredInfo(self): self._last_triggered_event = None self._last_triggered_time = None def resetTrigger(self): self.resetLastTriggeredInfo() self.triggered_count = 0 @classmethod def getEventBuffer(cls, copy=False): return {} @classmethod def clearEventHistory(cls, returncopy=False): if returncopy: return {} @classmethod def getTriggersFrom(cls, triggers): """ Returns a list of Trigger instances generated based on the contents of the input triggers. :param triggers: :return: """ # Handle different valid trigger object types if isinstance(triggers, (list, tuple)): # Support is provided for a list of Trigger objects or a list of # strings. t1 = triggers[0] if isinstance(t1, str): # triggers is a list of strings, so try and create a list of # DeviceEventTrigger's using keyboard device, KEYBOARD_RELEASE # event type, and the triggers list elements each as the # event.key. kbtriggers = [] for c in triggers: kbtriggers.append(KeyboardTrigger(c, on_press=False)) trig_list = kbtriggers else: # Assume triggers is a list of Trigger objects trig_list = triggers elif isinstance(triggers, (int, float)): # triggers is a number, so assume a TimeTrigger is wanted where # the delay == triggers. start time will be the fliptime of the # last update for drawing to the new target position. trig_list = (TimeTrigger(start_time=None, delay=triggers),) elif isinstance(triggers, str): # triggers is a string, so try and create a # DeviceEventTrigger using keyboard device, KEYBOARD_RELEASE # event type, and triggers as the event.key. trig_list = [KeyboardTrigger(triggers, on_press=False), ] elif isinstance(triggers, Trigger): # A single Trigger object was provided trig_list = (triggers,) else: raise ValueError('The triggers kwarg could not be understood as a valid triggers input value.') return trig_list class TimeTrigger(Trigger): """ A TimeTrigger associates a delay from the provided start_time parameter to when the classes triggered() method returns True. start_time and delay can be sec.msec float, or a callable object (that takes no parameters). """ def __init__(self, start_time, delay, repeat_count=0, trigger_function=lambda a, b, c: True, user_kwargs={}): Trigger.io = ioHubConnection.getActiveConnection() Trigger.__init__(self, trigger_function, user_kwargs, repeat_count) self._start_time = start_time if start_time is None or not callable(start_time): def startTimeFunc(): if self._start_time is None: self._start_time = getTime() return self._start_time self.startTime = startTimeFunc else: self.startTime = start_time self.delay = delay if not callable(delay): def delayFunc(): return delay self.delay = delayFunc def triggered(self, **kwargs): if Trigger.triggered(self) is False: return False if self.startTime is None: start_time = kwargs.get('start_time') else: start_time = self.startTime() if self.delay is None: delay = kwargs.get('delay') else: delay = self.delay() ct = getTime() if ct - start_time >= delay: self._last_triggered_time = ct self._last_triggered_event = ct self.triggered_count += 1 return True return False def resetTrigger(self): self.resetLastTriggeredInfo() self.triggered_count = 0 self._start_time = None class DeviceEventTrigger(Trigger): """ A DeviceEventTrigger associates a set of conditions for a DeviceEvent that must be met before the classes triggered() method returns True. """ _lastEventsByDevice = dict() def __init__(self, device, event_type, event_attribute_conditions={}, repeat_count=-1, trigger_function=lambda a, b, c: True, user_kwargs={}): Trigger.io = ioHubConnection.getActiveConnection() Trigger.__init__(self, trigger_function, user_kwargs, repeat_count) self.device = device self.event_type = event_type self.event_attribute_conditions = event_attribute_conditions def triggered(self, **kwargs): if Trigger.triggered(self) is False: return False events = self.device.getEvents() if events is None: events = [] if self.device in self._lastEventsByDevice: self._lastEventsByDevice[self.device].extend(events) else: self._lastEventsByDevice[self.device] = events unhandledEvents = self._lastEventsByDevice.get(self.device, []) for event in unhandledEvents: foundEvent = True if event.type != self.event_type: foundEvent = False else: for (attrname, conds) in self.event_attribute_conditions.items(): if isinstance(conds, (list, tuple)) and getattr(event, attrname) in conds: # event_value is a list or tuple of possible values # that are OK pass elif getattr(event, attrname) is conds or getattr(event, attrname) == conds: # event_value is a single value pass else: foundEvent = False if foundEvent is True: self._last_triggered_time = getTime() self._last_triggered_event = event self.triggered_count += 1 return True return False @classmethod def getEventBuffer(cls, copy=False): if copy: return dict(cls._lastEventsByDevice) return cls._lastEventsByDevice @classmethod def clearEventHistory(cls, returncopy=False): eventbuffer = None if returncopy: eventbuffer = dict(cls._lastEventsByDevice) cls._lastEventsByDevice.clear() return eventbuffer def resetLastTriggeredInfo(self): Trigger.resetLastTriggeredInfo(self) if self.device in self._lastEventsByDevice: del self._lastEventsByDevice[self.device] class KeyboardTrigger(DeviceEventTrigger): def __init__(self, key, on_press=False): Trigger.io = ioHubConnection.getActiveConnection() if on_press: etype = EventConstants.KEYBOARD_PRESS else: etype = EventConstants.KEYBOARD_RELEASE DeviceEventTrigger.__init__(self, self.io.devices.keyboard, event_type=etype, event_attribute_conditions={'key': key})
8,491
Python
.py
199
32.090452
113
0.61738
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,661
__init__.py
psychopy_psychopy/psychopy/iohub/client/eyetracker/validation/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from .posgrid import PositionGrid from .trigger import Trigger, KeyboardTrigger, DeviceEventTrigger, TimeTrigger from .procedure import TargetStim, ValidationProcedure
380
Python
.py
7
53.285714
85
0.80429
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,662
posgrid.py
psychopy_psychopy/psychopy/iohub/client/eyetracker/validation/posgrid.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import numpy as np from psychopy.iohub.client import ioHubConnection class PositionGrid: def __init__(self, bounds=None, shape=None, # Defines the number of columns and rows of # positions needed. If shape is an array of # two elements, it defines the col,row shape # for position layout. Position count will # equal rows*cols. If shape is a single # int, the position grid col,row shape will # be shape x shape. posCount=None, # Defines the number of positions to create # without any col,row position constraint. leftMargin=None, # Specify the minimum valid horz position. rightMargin=None, # Limit horz positions to be < max horz # position minus rightMargin. topMargin=None, # Limit vert positions to be < max vert # position minus topMargin. bottomMargin=None, # Specify the minimum valid vert position. scale=1.0, # Scale can be one or two numbers, each # between 0.0 and 1.0. If a tuple is # provided, it represents the horz, vert # scale to be applied to window width, # height. If a single number is # given, the same scale will be applied to # both window width and height. The scaled # window size is centered on the original # window size to define valid position area. posList=None, # Provide an existing list of (x,y) # positions. If posList is provided, the # shape, posCount, margin and scale arg's # are ignored. noiseStd=None, # Add a random shift to each position based # on a normal distribution with mean = 0.0 # and sigma equal to noiseStd. Specify # value based on units being used. firstposindex=0, # Specify which position in the position # list should be displayed first. This # position is not effected by randomization. repeatFirstPos=False # If the first position in the list should # be provided as the last position as well, # set to True. In this case, the number of # positions returned will be position # count + 1. False indicated the first # position should not be repeated. ): """ PositionGrid provides a flexible way to generate a set of x,y position values within the boundaries of the psychopy window object provided. The class provides a set of arguments that represent commonly needed constraints when creating a target position list, supporting a variety of position arrangements. PositionGrid supports the len() function, and returns the number of positions generated based on the supplied parameters. If repeatFirstPos is true, len(posgrid) == number of unique positions + 1 (a repeat of the first position value). PositionGrid is a generator, so the normal way to access the positions from the class is to use a for loop or with statement: posgrid = PositionGrid(....) for pos in posgrid: # do something cool with the pos print(pos) :param bounds: :param shape: :param posCount: :param leftMargin: :param rightMargin: :param topMargin: :param bottomMargin: :param scale: :param posList: :param noiseStd: :param firstposindex: :param repeatFirstPos: """ self.posIndex = 0 self.positions = None self.posOffsets = None self.bounds = bounds if self.bounds is None: self.bounds = ioHubConnection.getActiveConnection().devices.display.getCoordBounds() winSize = self.bounds[2] - self.bounds[0], self.bounds[3] - self.bounds[1] self.firstposindex = firstposindex self.repeatfirstpos = repeatFirstPos self.horzStd, self.vertStd = None, None if noiseStd: if hasattr(noiseStd, '__len__'): self.horzStd, self.vertStd = noiseStd else: self.horzStd, self.vertStd = noiseStd, noiseStd horzScale, vertScale = None, None if scale: if hasattr(scale, '__len__'): horzScale, vertScale = scale else: horzScale, vertScale = scale, scale rowCount, colCount = None, None if shape: if hasattr(shape, '__len__'): colCount, rowCount = shape else: rowCount, colCount = shape, shape if posList: # User has provided the target positions, use posList to set # self.positions as array of x,y pairs. if len(posList) == 2 and len(posList[0]) != 2 and len(posList[0]) == len(posList[1]): # positions were provided in ((x1,x2,..,xn),(y1,y2,..,yn)) # format self.positions = np.column_stack((posList[0], posList[1])) elif len(posList[0]) == 2: self.positions = np.asarray(posList) else: raise ValueError('PositionGrid posList kwarg must be in ((x1,y1),(x2,y2),..,(xn,yn))' ' or ((x1,x2,..,xn),(y1,y2,..,yn)) format') if self.positions is None and (posCount or (rowCount and colCount)): # Auto generate position list based on criteria # provided. if winSize is not None: pixw, pixh = winSize xmin = 0.0 xmax = 1.0 ymin = 0.0 ymax = 1.0 if leftMargin: if leftMargin < pixw: xmin = leftMargin / pixw else: raise ValueError('PositionGrid leftMargin kwarg must be < winSize[0]') if rightMargin: if rightMargin < pixw: xmax = 1.0 - rightMargin / pixw else: raise ValueError('PositionGrid rightMargin kwarg must be < winSize[0]') if topMargin: if topMargin < pixh: ymax = 1.0 - topMargin / pixh else: raise ValueError('PositionGrid topMargin kwarg must be < winSize[1]') if bottomMargin: if bottomMargin < pixh: ymin = bottomMargin / pixh else: raise ValueError('PositionGrid bottomMargin kwarg must be < winSize[1]') if horzScale: if 0.0 < horzScale <= 1.0: xmin += (1.0 - horzScale) / 2.0 xmax -= (1.0 - horzScale) / 2.0 else: raise ValueError('PositionGrid horzScale kwarg must be 0.0 > horzScale <= 1.0') if vertScale: if 0.0 < vertScale <= 1.0: ymin += (1.0 - vertScale) / 2.0 ymax -= (1.0 - vertScale) / 2.0 else: raise ValueError('PositionGrid vertScale kwarg must be 0.0 > vertScale <= 1.0') if posCount: colCount = int(np.sqrt(posCount)) rowCount = colCount xps = np.random.uniform(xmin, xmax, colCount) * pixw - pixw / 2.0 yps = np.random.uniform(ymin, ymax, rowCount) * pixh - pixh / 2.0 else: xps = np.linspace(xmin, xmax, colCount) * pixw - pixw / 2.0 yps = np.linspace(ymin, ymax, rowCount) * pixh - pixh / 2.0 xps, yps = np.meshgrid(xps, yps) self.positions = np.column_stack((xps.flatten(), yps.flatten())) else: raise ValueError('PositionGrid posCount kwarg also requires winSize to be provided.') if self.positions is None: raise AttributeError('PositionGrid is unable to generate positions based on the provided kwargs.') if self.firstposindex and self.firstposindex > 0: fpos = self.positions[self.firstposindex] self.positions = np.delete(self.positions, self.firstposindex, 0) self.positions = np.insert(self.positions, 0, fpos, 0) self._generatePosOffsets() def __len__(self): if self.repeatfirstpos: return len(self.positions) + 1 else: return len(self.positions) def randomize(self): """ Randomize the positions within the position list. If a first position index was been provided, randomization only occurs for positions[1:]. This can be called multiple times if the same position list is being used repeatedly and a random presentation order is needed. Each time randomize() is called, if noiseStd is != 0, a new set of normally distributed offsets are created for the target positions. """ if self.firstposindex is None: np.random.shuffle(self.positions) else: firstpos = self.positions[0] self.positions = np.delete(self.positions, 0, 0) np.random.shuffle(self.positions) self.positions = np.insert(self.positions, 0, firstpos, 0) self._generatePosOffsets() def _generatePosOffsets(self): """Create a new set of position displayment 'noise' based on the noiseStd value given when the object was initialized.""" horzPosOffsetList = np.zeros((len(self), 1)) if self.horzStd: horzPosOffsetList = np.random.normal(0.0, self.horzStd, len(self)) vertPosOffsetList = np.zeros((len(self), 1)) if self.vertStd: vertPosOffsetList = np.random.normal(0.0, self.vertStd, len(self)) self.posOffsets = np.column_stack((vertPosOffsetList, horzPosOffsetList)) def __iter__(self): return self # Python 3 compatibility def __next__(self): return self.next() def next(self): """Returns the next position in the list. Usually this method is not called directly. Instead, positions are accessed by iterating over the PositionGrid object. pos = PositionGrid(....) for p in pos: # do something cool with it pass """ if self.posIndex < len(self.positions): pos = self.positions[self.posIndex] + self.posOffsets[self.posIndex] self.posIndex = self.posIndex + 1 return pos elif self.repeatfirstpos and self.posIndex == len(self.positions): pos = self.positions[0] + self.posOffsets[0] self.posIndex = self.posIndex + 1 return pos else: self.posIndex = 0 raise StopIteration() def getPositions(self): return [p for p in self]
11,618
Python
.py
238
34.941176
110
0.564439
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,663
util.py
psychopy_psychopy/psychopy/iohub/datastore/util.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import numbers # numbers.Integral is like (int, long) but supports Py3 import os from collections import namedtuple import json import numpy from ..errors import print2err from packaging.version import Version import tables if Version(tables.__version__) < Version('3'): from tables import openFile as open_file walk_groups = "walkGroups" list_nodes = "listNodes" get_node = "getNode" read_where = "readWhere" else: from tables import open_file walk_groups = "walk_groups" list_nodes = "list_nodes" get_node = "get_node" read_where = "read_where" _hubFiles = [] def openHubFile(filepath, filename, mode): """ Open an HDF5 DataStore file and register it so that it is closed even on interpreter crash. """ global _hubFiles hubFile = open_file(os.path.join(filepath, filename), mode) _hubFiles.append(hubFile) return hubFile def displayDataFileSelectionDialog(starting_dir=None, prompt="Select a ioHub HDF5 File", allowed="HDF5 Files (*.hdf5)"): """ Shows a FileDialog and lets you select a .hdf5 file to open for processing. """ from psychopy.gui.qtgui import fileOpenDlg filePath = fileOpenDlg(tryFilePath=starting_dir, prompt=prompt, allowed=allowed) if filePath is None: return None return filePath def displayEventTableSelectionDialog(title, list_label, list_values, default='Select'): from psychopy import gui if default not in list_values: list_values.insert(0, default) else: list_values.remove(list_values) list_values.insert(0, default) selection_dict = {list_label: list_values} dlg_info = dict(selection_dict) infoDlg = gui.DlgFromDict(dictionary=dlg_info, title=title) if not infoDlg.OK: return None while list(dlg_info.values())[0] == default and infoDlg.OK: dlg_info = dict(selection_dict) infoDlg = gui.DlgFromDict(dictionary=dlg_info, title=title) if not infoDlg.OK: return None return list(dlg_info.values())[0] def getEyeSampleTypesInFile(hdf5FilePath): """ Return the eye sample type(s) saved in the hdf5 file located in hdf5FilePath. If no eye samples have been saved to the file return []. Possible return list values are defined in psychopy.iohub.constants.EYE_SAMPLE_TYPES. :param returnType: (type) :return: (list) """ dpath, dfile = os.path.split(hdf5FilePath) datafile = ExperimentDataAccessUtility(dpath, dfile) result = datafile.getAvailableEyeSampleTypes() datafile.close() return result def saveEventReport(hdf5FilePath=None, eventType=None, eventFields=[], useConditionsTable=False, usePsychopyDataFile=None, columnNames=[], trialStart=None, trialStop=None, timeMargins=(0.0, 0.0) ): """ Save a tab delimited event report from an iohub .hdf5 data file. Events can optionally be split into groups using either a Psychopy .csv data file (usePsychopyDataFile), iohub experiment message events, or the hdf5 condition variables table (useConditionsTable=True). If usePsychopyDataFile is True, trialStart and trialStop must be provided, or a dialog will prompt the user to select a column from the Psychopy .cvs file. The column must have a float or int data type. Each non nan / None row will be used to split events. If usePsychopyDataFile and useConditionsTable are False and trialStart and trialStop are provided as text, events are split based on the time of iohub Experiment Message events that match the trialStart and trialStop text. :param hdf5FilePath: (str or None) :param eventType: (str or None) :param eventFields: (list) :param useConditionsTable: (bool) :param usePsychopyDataFile: (bool) :param columnNames: (list) :param trialStart: (str or None) :param trialStop: (str or None) :param timeMargins: ([float, float] or None) :return: """ # Select the hdf5 file to process. if usePsychopyDataFile is True and useConditionsTable is True: raise RuntimeError("saveEventReport: useConditionsTable and usePsychopyDataFile can both not be True") if not hdf5FilePath: selectedFilePath = displayDataFileSelectionDialog(os.getcwd()) if selectedFilePath: hdf5FilePath = selectedFilePath[0] if not hdf5FilePath: raise RuntimeError("Warning: saveEventReport requires hdf5FilePath. No report saved.") dpath, dfile = os.path.split(hdf5FilePath) datafile = ExperimentDataAccessUtility(dpath, dfile) if not eventType: # Get a dict of all event types -> DataStore table info for the selected DataStore file. eventTableMappings = datafile.getEventMappingInformation() # Get event tables that have data... events_with_data = datafile.getEventsByType() # Select which event table to output eventNameList = [] for event_id in list(events_with_data.keys()): eventNameList.append(eventTableMappings[event_id].class_name.decode('utf-8')) eventType = displayEventTableSelectionDialog("Select Event Type to Save", "Event Type:", eventNameList) if eventType is None: datafile.close() raise RuntimeError("saveEventReport requires eventType. No report saved.") #print("getAvailableEyeSampleTypes: ", datafile.getAvailableEyeSampleTypes()) # Get the event table to generate report for event_table = datafile.getEventTable(eventType) if not eventFields: # If no event fields were specified, report (almost) all event fields. eventFields = [c for c in event_table.colnames if c not in ['experiment_id', 'session_id', 'device_id', 'type', 'filter_id']] trial_times = [] column_names = [] psychoResults = None psychopyDataFile = None if usePsychopyDataFile is True: psychopyDataFile = hdf5FilePath[:-4] + 'csv' if not os.path.isfile(psychopyDataFile): datafile.close() raise RuntimeError("saveEventReport: Could not find .csv file: %s" % psychopyDataFile) import pandas psychoResults = pandas.read_csv(psychopyDataFile, delimiter=",", encoding='utf-8') if trialStart is None or trialStop is None: # get list of possible column names from columnNames = [] for columnName in psychoResults.columns: if columnName.endswith('.started') or columnName.endswith('.stopped'): if psychoResults[columnName].dtype in [float, int]: columnNames.append(columnName) if trialStart is None: trialStart = displayEventTableSelectionDialog("Select Event Grouping Start Time Column", "Columns", list(columnNames)) if trialStop is None: trialStop = displayEventTableSelectionDialog("Select Event Grouping End Time Column", "Columns", [cn for cn in columnNames if cn != trialStart]) print('trialStop:', trialStop) if trialStart and trialStop: if trialStart not in psychoResults.columns: datafile.close() raise ValueError("saveEventReport trialStart column not found in psychopyDataFile: %s" % trialStart) if trialStop not in psychoResults.columns: datafile.close() raise ValueError("saveEventReport trialStop column not found in psychopyDataFile: %s" % trialStop) for t_ix, r in psychoResults.iterrows(): if r[trialStart] != 'None' and r[trialStop] != 'None' and pandas.notna(r[trialStart]) and pandas.notna( r[trialStop]): trial_times.append([t_ix, r[trialStart] - timeMargins[0], r[trialStop] + timeMargins[1]]) else: datafile.close() raise ValueError("saveEventReport trialStart and trialStop must be specified when using psychopyDataFile.") cvTable = None if useConditionsTable is True: # Use hdf5 conditions table columns 'trialStart' and 'trialStop' to group events if trialStart is None or trialStop is None: # If either trialStart and trialStop are None, display selection dialogs try: cvColumnNames = datafile.getConditionVariableNames()[2:] except Exception as e: #datastore Conditions table must not exist datafile.close() raise RuntimeError("saveEventReport: Error calling datafile.getConditionVariableNames().\n{}".format(e)) if trialStart is None: trialStart = displayEventTableSelectionDialog("Select Event Grouping Start Time Column", "Columns", list(cvColumnNames)) if trialStop is None: trialStop = displayEventTableSelectionDialog("Select Event Grouping End Time Column", "Columns", [cn for cn in cvColumnNames if cn != trialStart]) if trialStart is None or trialStop is None: datafile.close() raise ValueError("saveEventReport: trialStart and trialStop must be specified " "when useConditionsTable is True.") if trialStart not in cvColumnNames: datafile.close() raise ValueError("saveEventReport:" " trialStart column not found in trial condition variables table: %s" % trialStart) if trialStop not in cvColumnNames: datafile.close() raise ValueError("saveEventReport:" " trialStop column not found in trial condition variables table: %s" % trialStop) cvTable = datafile.getConditionVariablesTable() for t_ix, r in enumerate(cvTable): trial_times.append([t_ix, r[trialStart] - timeMargins[0], r[trialStop] + timeMargins[1]]) if useConditionsTable is False and psychoResults is None and trialStart and trialStop: # Create a table of trial_index, trial_start_time, trial_end_time for each trial by # getting the time of 'TRIAL_START' and 'TRIAL_END' experiment messages. mgs_table = datafile.getEventTable('MessageEvent') trial_start_msgs = mgs_table.where('text == b"%s"' % trialStart) for mix, msg in enumerate(trial_start_msgs): trial_times.append([mix + 1, msg['time'] - timeMargins[0], 0]) trial_end_msgs = mgs_table.where('text == b"%s"' % trialStop) for mix, msg in enumerate(trial_end_msgs): trial_times[mix][2] = msg['time'] + timeMargins[1] del mgs_table elif trialStart is None and trialStop is None: # do not split events into trial groupings pass elif trialStart is None or trialStop is None: datafile.close() raise RuntimeError("Warning: saveEventReport requires trialStart and trialStop to be strings or both None." " No report saved.") if eventType == 'MessageEvent': # Sort experiment messages by time since they may not be ordered chronologically. event_table = event_table.read() event_table.sort(order='time') ecount = 0 # Open a file to save the tab delimited output to. output_file_name = os.path.join(dpath, "%s.%s.txt" % (dfile[:-5], eventType)) with open(output_file_name, 'w') as output_file: # Save header row to file if trial_times: if useConditionsTable: cvtColumnNames = datafile.getConditionVariableNames()[2:] if columnNames: for cname in columnNames: if cname not in cvtColumnNames: datafile.close() raise ValueError("saveEventReport: .hdf5 conditions table column '%s' not found." % cname) column_names = list(columnNames) + eventFields else: column_names = list(cvtColumnNames) + eventFields columnNames = list(cvtColumnNames) elif hasattr(psychoResults, 'columns'): if columnNames: for cname in columnNames: if cname not in psychoResults.columns: datafile.close() raise ValueError( "saveEventReport: psychopyDataFileColumn '%s' not found in .csv file." % cname) column_names = list(columnNames) + eventFields else: column_names = list(psychoResults.columns) + eventFields columnNames = list(psychoResults.columns) else: column_names = ['TRIAL_INDEX', trialStart, trialStop] + eventFields else: column_names = eventFields output_file.write('\t'.join(column_names)) output_file.write('\n') event_groupings = [] if trial_times: # Split events into trials for tindex, tstart, tstop in trial_times: if eventType == 'MessageEvent': event_groupings.append(event_table[(event_table['time'] >= tstart) & (event_table['time'] <= tstop)]) else: event_groupings.append(event_table.where("(time >= %f) & (time <= %f)" % (tstart, tstop))) else: # Report events without splitting them into trials if eventType == 'MessageEvent': event_groupings.append(event_table) else: event_groupings.append(event_table.iterrows()) # Save a row for each event within the trial period for tid, trial_events in enumerate(event_groupings): for event in trial_events: event_data = [] for c in eventFields: cv = event[c] if type(cv) == numpy.bytes_: cv = event[c].decode('utf-8') if type(cv) == str and len(cv) == 0: cv = '.' event_data.append(str(cv)) if trial_times: tindex, tstart, tstop = trial_times[tid] if useConditionsTable: cvRow=cvTable.read(tindex, tindex+1) cvrowdat = [cvRow[c][0] for c in columnNames] for ri, cv in enumerate(cvrowdat): if type(cv) == numpy.bytes_: cvrowdat[ri] = cvrowdat[ri].decode('utf-8') else: cvrowdat[ri] = str(cvrowdat[ri]) if type(cv) == str and len(cv) == 0: cvrowdat[ri] = '.' output_file.write('\t'.join(cvrowdat + event_data)) elif hasattr(psychoResults, 'columns'): drow = psychoResults.iloc[tindex] prowdat = [str(drow[c]) for c in columnNames] output_file.write('\t'.join(prowdat + event_data)) else: output_file.write('\t'.join([str(tindex), str(tstart), str(tstop)] + event_data)) else: output_file.write('\t'.join(event_data)) output_file.write('\n') ecount += 1 # Done report creation, close input file datafile.close() return output_file_name, ecount ########### Experiment / Experiment Session Based Data Access ################# class ExperimentDataAccessUtility: """The ExperimentDataAccessUtility provides a simple, high level, way to access data saved in an ioHub DataStore HDF5 file. Data access is done by providing information at an experiment and session level, as well as specifying the ioHub Event types you want to retrieve data for. An instance of the ExperimentDataAccessUtility class is created by providing the location and name of the file to read, as well as any session code filtering you want applied to the retrieved datasets. Args: hdfFilePath (str): The path of the directory the DataStore HDF5 file is in. hdfFileName (str): The name of the DataStore HDF5 file. experimentCode (str): If multi-experiment support is enabled for the DataStore file, this argument can be used to specify what experiment data to load based on the experiment_code given. NOTE: Multi-experiment data file support is not well tested and should not be used at this point. sessionCodes (str or list): The experiment session code to filter data by. If a list of codes is given, then all codes in the list will be used. Returns: object: the created instance of the ExperimentDataAccessUtility, ready to get your data! """ def __init__(self, hdfFilePath, hdfFileName, experimentCode=None, sessionCodes=[], mode='r'): """An instance of the ExperimentDataAccessUtility class is created by providing the location and name of the file to read, as well as any session code filtering you want applied to the retrieved datasets. Args: hdfFilePath (str): The path of the directory the DataStore HDF5 file is in. hdfFileName (str): The name of the DataStore HDF5 file. experimentCode (str): If multi-experiment support is enabled for the DataStore file, this argument can be used to specify what experiment data to load based on the experiment_code given. NOTE: Multi-experiment data file support is not well tested and should not be used at this point. sessionCodes (str or list): The experiment session code to filter data by. If a list of codes is given, then all codes in the list will be used. Returns: object: the created instance of the ExperimentDataAccessUtility, ready to get your data! """ self.hdfFilePath = hdfFilePath self.hdfFileName = hdfFileName self.mode = mode self.hdfFile = None self._experimentCode = experimentCode self._sessionCodes = sessionCodes self._lastWhereClause = None try: self.hdfFile = openHubFile(hdfFilePath, hdfFileName, mode) except Exception as e: raise ExperimentDataAccessException(e) self.getExperimentMetaData() def printTableStructure(self, tableName): """Print to stdout the current structure and content statistics of the specified DataStore table. To print out the complete structure of the DataStore file, including the name of all available tables, see the printHubFileStructure method. Args: tableName (str): The DataStore table name to print metadata information out for. """ if self.hdfFile: hubFile = self.hdfFile for group in getattr(hubFile, walk_groups)("/"): for table in getattr(hubFile, list_nodes)(group, classname='Table'): if table.name == tableName: print('------------------') print('Path:', table) print('Table name:', table.name) print('Number of rows in table:', table.nrows) print('Number of cols in table:', len(table.colnames)) print('Attribute name := type, shape:') for name in table.colnames: print('\t', name, ':= %s, %s' % (table.coldtypes[name], table.coldtypes[name].shape)) print('------------------') return def printHubFileStructure(self): """Print to stdout the current global structure of the loaded DataStore File.""" if self.hdfFile: print(self.hdfFile) def getExperimentMetaData(self): """Returns the metadata for the experiment the datStore file is for. **Docstr TBC.** """ if self.hdfFile: expcols = self.hdfFile.root.data_collection.experiment_meta_data.colnames if 'sessions' not in expcols: expcols.append('sessions') ExperimentMetaDataInstance = namedtuple( 'ExperimentMetaDataInstance', expcols) experiments = [] for e in self.hdfFile.root.data_collection.experiment_meta_data: self._experimentID = e['experiment_id'] a_exp = list(e[:]) a_exp.append(self.getSessionMetaData()) experiments.append(ExperimentMetaDataInstance(*a_exp)) return experiments def getSessionMetaData(self, sessions=None): """ Returns the metadata associated with the experiment session codes in use. **Docstr TBC.** """ if self.hdfFile: if sessions is None: sessions = [] sessionCodes = self._sessionCodes sesscols = self.hdfFile.root.data_collection.session_meta_data.colnames SessionMetaDataInstance = namedtuple('SessionMetaDataInstance', sesscols) for r in self.hdfFile.root.data_collection.session_meta_data: if (len(sessionCodes) == 0 or r['code'] in sessionCodes) and r['experiment_id'] == self._experimentID: rcpy = list(r[:]) rcpy[-1] = json.loads(rcpy[-1]) sessions.append(SessionMetaDataInstance(*rcpy)) return sessions def getTableForPath(self, path): """ Given a valid table path within the DataStore file, return the accociated table. """ getattr(self.hdfFile, get_node)(path) def getEventTable(self, event_type): """ Returns the DataStore table that contains events of the specified type. **Docstr TBC.** """ if self.hdfFile: klassTables = self.hdfFile.root.class_table_mapping event_column = None event_value = None if isinstance(event_type, str): if event_type.find('Event') >= 0: event_column = 'class_name' event_value = event_type else: event_value = '' tokens = event_type.split('_') for t in tokens: event_value += t[0].upper() + t[1:].lower() event_value = event_type + 'Event' elif isinstance(event_type, numbers.Integral): event_column = 'class_id' event_value = event_type else: print2err( 'getEventTable error: event_type argument must be a string or and int') return None result = [] where_cls = '(%s == b"%s") & (class_type_id == 1)' % (event_column, event_value) for row in klassTables.where(where_cls): result.append(row.fetch_all_fields()) if len(result) == 0: return None if len(result) != 1: print2err('event_type_id passed to getEventAttribute can only return one row from CLASS_MAPPINGS.') return None tablePathString = result[0][3] if isinstance(tablePathString, bytes): tablePathString = tablePathString.decode('utf-8') return getattr(self.hdfFile, get_node)(tablePathString) return None def getEventMappingInformation(self): """Returns details on how ioHub Event Types are mapped to tables within the given DataStore file.""" if self.hdfFile: eventMappings = dict() class_2_table = self.hdfFile.root.class_table_mapping EventTableMapping = namedtuple( 'EventTableMapping', self.hdfFile.root.class_table_mapping.colnames) for row in class_2_table[:]: eventMappings[row['class_id']] = EventTableMapping(*row) return eventMappings return None def getEventsByType(self, condition_str=None): """Returns a dict of all event tables within the DataStore file that have at least one event instance saved. Keys are Event Type constants, as specified by iohub.EventConstants. Each value is a row iterator for events of that type. """ eventTableMappings = self.getEventMappingInformation() if eventTableMappings: events_by_type = dict() getNode = getattr(self.hdfFile, get_node) for event_type_id, event_mapping_info in eventTableMappings.items(): try: cond = '(type == %d)' % (event_type_id) if condition_str: cond += ' & ' + condition_str et_path = event_mapping_info.table_path if isinstance(et_path, bytes): et_path = et_path.decode('utf-8') events_by_type[event_type_id] = next(getNode(et_path).where(cond)) except StopIteration: pass return events_by_type return None def getAvailableEyeSampleTypes(self, returnType=str): """ Return the eye sample type(s) saved to the current hdf5 file. If no eye samples have been saved to the file return []. Possible return list values are defined in psychopy.iohub.constants.EYE_SAMPLE_TYPES. :param returnType: (type) :return: (list) """ from psychopy.iohub.constants import EYE_SAMPLE_TYPES if returnType == int: return [etype for etype in self.getEventsByType() if etype in EYE_SAMPLE_TYPES] if returnType == str: eventTableMappings = self.getEventMappingInformation() sampleTypes = [etype for etype in self.getEventsByType() if etype in EYE_SAMPLE_TYPES] eventList = [] for event_id in sampleTypes: eventList.append(eventTableMappings[event_id].class_name.decode('utf-8')) return eventList raise RuntimeError("getAvailableEyeSampleTypes returnType arg must be set to either int or str type.") def getConditionVariablesTable(self): """ **Docstr TBC.** """ cv_group = self.hdfFile.root.data_collection.condition_variables ecv = 'EXP_CV_%d' % (self._experimentID,) if ecv in cv_group._v_leaves: return cv_group._v_leaves[ecv] return None def getConditionVariableNames(self): """ **Docstr TBC.** """ cv_group = self.hdfFile.root.data_collection.condition_variables ecv = "EXP_CV_%d" % (self._experimentID,) if ecv in cv_group._v_leaves: ecvTable = cv_group._v_leaves[ecv] return ecvTable.colnames return None def getConditionVariables(self, filter=None): """ **Docstr TBC.** """ if filter is None: session_ids = [] for s in self.getExperimentMetaData()[0].sessions: session_ids.append(s.session_id) filter = dict(SESSION_ID=(' in ', session_ids)) ConditionSetInstance = None for conditionVarName, conditionVarComparitor in filter.items(): avComparison, value = conditionVarComparitor cv_group = self.hdfFile.root.data_collection.condition_variables cvrows = [] ecv = "EXP_CV_%d" % (self._experimentID,) if ecv in cv_group._v_leaves: ecvTable = cv_group._v_leaves[ecv] if ConditionSetInstance is None: colnam = ecvTable.colnames ConditionSetInstance = namedtuple('ConditionSetInstance', colnam) cvrows.extend( [ ConditionSetInstance( * r[:]) for r in ecvTable if all( [ eval( '{0} {1} {2}'.format( r[conditionVarName], conditionVarComparitor[0], conditionVarComparitor[1])) for conditionVarName, conditionVarComparitor in filter.items()])]) return cvrows def getValuesForVariables(self, cv, value, cvNames): """ **Docstr TBC.** """ if isinstance(value, (list, tuple)): resolvedValues = [] for v in value: if isinstance(value, str) and value.startswith('@') and value.endswith('@'): value = value[1:-1] if value in cvNames: resolvedValues.append(getattr(cv, v)) else: raise ExperimentDataAccessException('getEventAttributeValues: {0} is not a valid attribute ' 'name in {1}'.format(v, cvNames)) elif isinstance(value, str): resolvedValues.append(value) return resolvedValues elif isinstance(value, str) and value.startswith('@') and value.endswith('@'): value = value[1:-1] if value in cvNames: return getattr(cv, value) else: raise ExperimentDataAccessException('getEventAttributeValues: {0} is not a valid attribute name' ' in {1}'.format(value, cvNames)) else: raise ExperimentDataAccessException('Unhandled value type !: {0} is not a valid type for value ' '{1}'.format(type(value), value)) def getEventAttributeValues(self, event_type_id, event_attribute_names, filter_id=None, conditionVariablesFilter=None, startConditions=None, endConditions=None): """ **Docstr TBC.** Args: event_type_id event_attribute_names filter_id conditionVariablesFilter startConditions endConditions Returns: Values for the specified event type and event attribute columns which match the provided experiment condition variable filter, starting condition filer, and ending condition filter criteria. """ if self.hdfFile: klassTables = self.hdfFile.root.class_table_mapping deviceEventTable = None result = [row.fetch_all_fields() for row in klassTables.where('(class_id == %d) &' ' (class_type_id == 1)' % (event_type_id))] if len(result) != 1: raise ExperimentDataAccessException("event_type_id returned > 1 row from CLASS_MAPPINGS.") tablePathString = result[0][3] if isinstance(tablePathString, bytes): tablePathString = tablePathString.decode('utf-8') deviceEventTable = getattr(self.hdfFile, get_node)(tablePathString) for ename in event_attribute_names: if ename not in deviceEventTable.colnames: raise ExperimentDataAccessException('getEventAttribute: %s does not have a column named %s' % (deviceEventTable.title, event_attribute_names)) resultSetList = [] csier = list(event_attribute_names) csier.append('query_string') csier.append('condition_set') EventAttributeResults = namedtuple('EventAttributeResults', csier) if deviceEventTable is not None: if not isinstance(event_attribute_names, (list, tuple)): event_attribute_names = [event_attribute_names, ] filteredConditionVariableList = None if conditionVariablesFilter is None: filteredConditionVariableList = self.getConditionVariables() else: filteredConditionVariableList = self.getConditionVariables(conditionVariablesFilter) cvNames = self.getConditionVariableNames() # no further where clause building needed; get reseults and # return if startConditions is None and endConditions is None: for cv in filteredConditionVariableList: wclause = '( experiment_id == {0} ) & ( SESSION_ID == {1} )'.format(self._experimentID, cv.SESSION_ID) wclause += ' & ( type == {0} ) '.format(event_type_id) if filter_id is not None: wclause += '& ( filter_id == {0} ) '.format(filter_id) resultSetList.append([]) for ename in event_attribute_names: resultSetList[-1].append(getattr(deviceEventTable, read_where)(wclause, field=ename)) resultSetList[-1].append(wclause) resultSetList[-1].append(cv) eventAttributeResults = EventAttributeResults(*resultSetList[-1]) resultSetList[-1] = eventAttributeResults return resultSetList # start or end conditions exist.... for cv in filteredConditionVariableList: resultSetList.append([]) wclause = '( experiment_id == {0} ) & ( session_id == {1} )'.format(self._experimentID, cv.SESSION_ID) wclause += ' & ( type == {0} ) '.format(event_type_id) if filter_id is not None: wclause += '& ( filter_id == {0} ) '.format(filter_id) # start Conditions need to be added to where clause if startConditions is not None: wclause += '& (' for conditionAttributeName, conditionAttributeComparitor in startConditions.items(): avComparison, value = conditionAttributeComparitor value = self.getValuesForVariables(cv, value, cvNames) wclause += ' ( {0} {1} {2} ) & '.format(conditionAttributeName, avComparison, value) wclause = wclause[:-3] wclause += ' ) ' # end Conditions need to be added to where clause if endConditions is not None: wclause += ' & (' for conditionAttributeName, conditionAttributeComparitor in endConditions.items(): avComparison, value = conditionAttributeComparitor value = self.getValuesForVariables(cv, value, cvNames) wclause += ' ( {0} {1} {2} ) & '.format(conditionAttributeName, avComparison, value) wclause = wclause[:-3] wclause += ' ) ' for ename in event_attribute_names: resultSetList[-1].append(getattr(deviceEventTable, read_where)(wclause, field=ename)) resultSetList[-1].append(wclause) resultSetList[-1].append(cv) eventAttributeResults = EventAttributeResults(*resultSetList[-1]) resultSetList[-1] = eventAttributeResults return resultSetList return None def getEventIterator(self, event_type): """ **Docstr TBC.** Args: event_type Returns: (iterator): An iterator providing access to each matching event as a numpy recarray. """ return self.getEventTable(event_type).iterrows() def close(self): """Close the ExperimentDataAccessUtility and associated DataStore File.""" global _hubFiles if self.hdfFile in _hubFiles: _hubFiles.remove(self.hdfFile) self.hdfFile.close() self.experimentCodes = None self.hdfFilePath = None self.hdfFileName = None self.mode = None self.hdfFile = None def __del__(self): try: self.close() except Exception: pass class ExperimentDataAccessException(Exception): pass
37,743
Python
.py
717
38.34728
296
0.587119
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,664
__init__.py
psychopy_psychopy/psychopy/iohub/datastore/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import os import atexit import numpy as np from packaging.version import Version from ..server import DeviceEvent from ..constants import EventConstants from ..errors import ioHubError, printExceptionDetailsToStdErr, print2err import tables from tables import parameters, StringCol, UInt32Col, UInt16Col, NoSuchNodeError if Version(tables.__version__) < Version('3'): from tables import openFile as open_file create_table = "createTable" create_group = "createGroup" f_get_child = "_f_getChild" else: from tables import open_file create_table = "create_table" create_group = "create_group" _f_get_child = "_f_get_child" parameters.MAX_NUMEXPR_THREADS = None """The maximum number of threads that PyTables should use internally in Numexpr. If `None`, it is automatically set to the number of cores in your machine.""" parameters.MAX_BLOSC_THREADS = None """The maximum number of threads that PyTables should use internally in Blosc. If `None`, it is automatically set to the number of cores in your machine.""" DATA_FILE_TITLE = "ioHub DataStore - Experiment Data File." FILE_VERSION = '0.9.1.2' SCHEMA_AUTHORS = 'Sol Simpson' SCHEMA_MODIFIED_DATE = 'October 27, 2021' class DataStoreFile(): def __init__(self, fileName, folderPath, fmode='a', iohub_settings=None): self.fileName = fileName self.folderPath = folderPath self.filePath = os.path.join(folderPath, fileName) if iohub_settings.get('multiple_sessions', False) is False: fmode = 'w' self.settings = iohub_settings self.active_experiment_id = None self.active_session_id = None self.flushCounter = self.settings.get('flush_interval', 32) self._eventCounter = 0 self.TABLES = dict() self._eventGroupMappings = dict() self.emrtFile = open_file(self.filePath, mode=fmode) atexit.register(close_open_data_files, False) if len(self.emrtFile.title) == 0: self.buildOutTemplate() self.flush() else: self.loadTableMappings() def loadTableMappings(self): # create meta-data tables self.TABLES['EXPERIMENT_METADETA'] = self.emrtFile.root.data_collection.experiment_meta_data self.TABLES['SESSION_METADETA'] = self.emrtFile.root.data_collection.session_meta_data self.TABLES['CLASS_TABLE_MAPPINGS'] = self.emrtFile.root.class_table_mapping def buildOutTemplate(self): self.emrtFile.title = DATA_FILE_TITLE self.emrtFile.FILE_VERSION = FILE_VERSION self.emrtFile.SCHEMA_DESIGNER = SCHEMA_AUTHORS self.emrtFile.SCHEMA_MODIFIED = SCHEMA_MODIFIED_DATE create_group_func = getattr(self.emrtFile, create_group) create_table_func = getattr(self.emrtFile, create_table) # CREATE GROUPS self.TABLES['CLASS_TABLE_MAPPINGS'] = create_table_func(self.emrtFile.root, 'class_table_mapping', ClassTableMappings, title='ioHub DeviceEvent Class to ' 'DataStore Table Mappings.') create_group_func(self.emrtFile.root, 'data_collection', title='Data collected using ioHub.') self.flush() create_group_func(self.emrtFile.root.data_collection, 'events', title='Events collected using ioHub.') create_group_func(self.emrtFile.root.data_collection, 'condition_variables', title="Experiment Condition " "Variable Data.") self.flush() self.TABLES['EXPERIMENT_METADETA'] = create_table_func(self.emrtFile.root.data_collection, 'experiment_meta_data', ExperimentMetaData, title='Experiment Metadata.') self.TABLES['SESSION_METADETA'] = create_table_func(self.emrtFile.root.data_collection, 'session_meta_data', SessionMetaData, title='Session Metadata.') self.flush() create_group_func(self.emrtFile.root.data_collection.events, 'experiment', title='Experiment Device Events.') create_group_func(self.emrtFile.root.data_collection.events, 'keyboard', title='Keyboard Device Events.') create_group_func(self.emrtFile.root.data_collection.events, 'mouse', title='Mouse Device Events.') create_group_func(self.emrtFile.root.data_collection.events, 'wintab', title='Wintab Device Events.') create_group_func(self.emrtFile.root.data_collection.events, 'eyetracker', title='EyeTracker Device Events.') create_group_func(self.emrtFile.root.data_collection.events, 'serial', title='Serial Interface Events.') create_group_func(self.emrtFile.root.data_collection.events, 'pstbox', title='Serial Pstbox Device Events.') self.flush() @staticmethod def eventTableLabel2ClassName(event_table_label): tokens = str(event_table_label[0] + event_table_label[1:].lower() + 'Event').split('_') return ''.join([t[0].upper() + t[1:] for t in tokens]) def groupNodeForEvent(self, event_cls): evt_group_label = event_cls.PARENT_DEVICE.DEVICE_TYPE_STRING.lower() datevts_node = self.emrtFile.root.data_collection.events try: # If group for event table already exists return it.... return datevts_node._f_get_child(evt_group_label) except tables.NoSuchNodeError: # Create the group node for the event.... egtitle = "%s%s Device Events." % (evt_group_label[0].upper(), evt_group_label[1:]) self.emrtFile.createGroup(datevts_node, evt_group_label, title=egtitle) return datevts_node._f_get_child(evt_group_label) def updateDataStoreStructure(self, device_instance, event_class_dict): dfilter = tables.Filters(complevel=0, complib='zlib', shuffle=False, fletcher32=False) for event_cls_name, event_cls in event_class_dict.items(): if event_cls.IOHUB_DATA_TABLE: table_label = event_cls.IOHUB_DATA_TABLE if table_label not in self.TABLES: try: tc_name = self.eventTableLabel2ClassName(table_label) create_table_func = getattr(self.emrtFile, create_table) dc_name = device_instance.__class__.__name__ self.TABLES[table_label] = create_table_func(self.groupNodeForEvent(event_cls), tc_name, event_cls.NUMPY_DTYPE, title='%s Data' % dc_name, filters=dfilter.copy()) self.flush() except tables.NodeError: self.TABLES[table_label] = self.groupNodeForEvent(event_cls)._f_get_child(tc_name) except Exception as e: print2err('---------------ERROR------------------') print2err('Exception %s in iohub.datastore.updateDataStoreStructure:' % (e.__class__.__name__)) print2err('\tevent_cls: {0}'.format(event_cls)) print2err('\tevent_cls_name: {0}'.format(event_cls_name)) print2err('\tevent_table_label: {0}'.format(table_label)) print2err('\teventTable2ClassName: {0}'.format(tc_name)) print2err('\tgroupNodeForEvent(event_cls): {0}'.format(self.groupNodeForEvent(event_cls))) print2err('\nException:') printExceptionDetailsToStdErr() print2err('--------------------------------------') if table_label in self.TABLES: self.addClassMapping(event_cls, self.TABLES[table_label]) else: print2err('---- IOHUB.DATASTORE CANNOT ADD CLASS MAPPING ----') print2err('\t** TABLES missing key: {0}'.format(table_label)) print2err('\tevent_cls: {0}'.format(event_cls)) print2err('\tevent_cls_name: {0}'.format(event_cls_name)) print2err('\teventTableLabel2ClassName: {0}'.format(self.eventTableLabel2ClassName(table_label))) print2err('----------------------------------------------') def addClassMapping(self, ioClass, ctable): cmtable = self.TABLES['CLASS_TABLE_MAPPINGS'] names = [x['class_id'] for x in cmtable.where('(class_id == %d)' % ioClass.EVENT_TYPE_ID)] if len(names) == 0: trow = cmtable.row trow['class_id'] = ioClass.EVENT_TYPE_ID trow['class_type_id'] = 1 # Device or Event etc. trow['class_name'] = ioClass.__name__ trow['table_path'] = ctable._v_pathname trow.append() self.flush() def createOrUpdateExperimentEntry(self, experimentInfoList): experiment_metadata = self.TABLES['EXPERIMENT_METADETA'] result = [row for row in experiment_metadata.iterrows() if row['code'] == experimentInfoList[1]] if len(result) > 0: result = result[0] self.active_experiment_id = result['experiment_id'] return self.active_experiment_id max_id = 0 id_col = experiment_metadata.col('experiment_id') if len(id_col) > 0: max_id = np.amax(id_col) self.active_experiment_id = max_id + 1 experimentInfoList[0] = self.active_experiment_id experiment_metadata.append([tuple(experimentInfoList), ]) self.flush() return self.active_experiment_id def createExperimentSessionEntry(self, sessionInfoDict): session_metadata = self.TABLES['SESSION_METADETA'] max_id = 0 id_col = session_metadata.col('session_id') if len(id_col) > 0: max_id = np.amax(id_col) self.active_session_id = int(max_id + 1) values = (self.active_session_id, self.active_experiment_id, sessionInfoDict['code'], sessionInfoDict['name'], sessionInfoDict['comments'], sessionInfoDict['user_variables']) session_metadata.append([values, ]) self.flush() return self.active_session_id def initConditionVariableTable( self, experiment_id, session_id, np_dtype): expcv_table = None exp_session = [('EXPERIMENT_ID', 'i4'), ('SESSION_ID', 'i4')] exp_session.extend(np_dtype) np_dtype = [] for npctype in exp_session: if isinstance(npctype[0], str): nv = [str(npctype[0]), ] nv.extend(npctype[1:]) np_dtype.append(tuple(nv)) else: np_dtype.append(npctype) np_dtype2 = [] for adtype in np_dtype: adtype2 = [] for a in adtype: if isinstance(a, bytes): a = str(a, 'utf-8') adtype2.append(a) np_dtype2.append(tuple(adtype2)) np_dtype = np_dtype2 self._EXP_COND_DTYPE = np.dtype(np_dtype) try: expCondTableName = "EXP_CV_%d" % (experiment_id) experimentConditionVariableTable = getattr(self.emrtFile.root.data_collection.condition_variables, _f_get_child)(expCondTableName) self.TABLES['EXP_CV'] = experimentConditionVariableTable except NoSuchNodeError: try: experimentConditionVariableTable = getattr(self.emrtFile, create_table)( self.emrtFile.root.data_collection.condition_variables, expCondTableName, self._EXP_COND_DTYPE, title='Condition Variable Values for Experiment ID %d' % experiment_id) self.TABLES['EXP_CV'] = experimentConditionVariableTable self.emrtFile.flush() except Exception: printExceptionDetailsToStdErr() return False except Exception: print2err('Error getting expcv_table for experiment %d, table name: %s' % (experiment_id, expCondTableName)) printExceptionDetailsToStdErr() return False self._activeRunTimeConditionVariableTable = expcv_table return True def extendConditionVariableTable(self, experiment_id, session_id, data): if self._EXP_COND_DTYPE is None: return False if self.emrtFile and 'EXP_CV' in self.TABLES: temp = [experiment_id, session_id] temp.extend(data) data = temp try: etable = self.TABLES['EXP_CV'] for i, d in enumerate(data): if isinstance(d, (list, tuple)): data[i] = tuple(d) np_array = np.array([tuple(data), ], dtype=self._EXP_COND_DTYPE) etable.append(np_array) self.bufferedFlush() return True except Exception: printExceptionDetailsToStdErr() return False def checkForExperimentAndSessionIDs(self, event=None): if self.active_experiment_id is None or self.active_session_id is None: exp_id = self.active_experiment_id if exp_id is None: exp_id = 0 sess_id = self.active_session_id if sess_id is None: sess_id = 0 return False return True def checkIfSessionCodeExists(self, sessionCode): if self.emrtFile: wclause = 'experiment_id == %d' % (self.active_experiment_id,) sessionsForExperiment = self.emrtFile.root.data_collection.session_meta_data.where(wclause) sessionCodeMatch = [sess for sess in sessionsForExperiment if sess['code'] == sessionCode] if len(sessionCodeMatch) > 0: return True return False def _handleEvent(self, event): try: if self.checkForExperimentAndSessionIDs(event) is False: return False etype = event[DeviceEvent.EVENT_TYPE_ID_INDEX] eventClass = EventConstants.getClass(etype) etable = self.TABLES[eventClass.IOHUB_DATA_TABLE] event[DeviceEvent.EVENT_EXPERIMENT_ID_INDEX] = self.active_experiment_id event[DeviceEvent.EVENT_SESSION_ID_INDEX] = self.active_session_id np_array = np.array([tuple(event), ], dtype=eventClass.NUMPY_DTYPE) etable.append(np_array) self.bufferedFlush() except Exception: print2err("Error saving event: ", event) printExceptionDetailsToStdErr() def _handleEvents(self, events): try: if self.checkForExperimentAndSessionIDs(len(events)) is False: return False event = events[0] etype = event[DeviceEvent.EVENT_TYPE_ID_INDEX] eventClass = EventConstants.getClass(etype) etable = self.TABLES[eventClass.IOHUB_DATA_TABLE] np_events = [] for event in events: event[DeviceEvent.EVENT_EXPERIMENT_ID_INDEX] = self.active_experiment_id event[DeviceEvent.EVENT_SESSION_ID_INDEX] = self.active_session_id np_events.append(tuple(event)) np_array = np.array(np_events, dtype=eventClass.NUMPY_DTYPE) etable.append(np_array) self.bufferedFlush(len(np_events)) except ioHubError as e: print2err(e) except Exception: printExceptionDetailsToStdErr() def bufferedFlush(self, eventCount=1): """ If flushCounter threshold is >=0 then do some checks. If it is < 0, then flush only occurs when command is sent to ioHub, so do nothing here. """ if self.flushCounter >= 0: if self.flushCounter == 0: self.flush() return True if self.flushCounter <= self._eventCounter: self.flush() self._eventCounter = 0 return True self._eventCounter += eventCount return False def flush(self): try: if self.emrtFile: self.emrtFile.flush() except tables.ClosedFileError: pass except Exception: printExceptionDetailsToStdErr() def close(self): self.flush() self._activeRunTimeConditionVariableTable = None self.emrtFile.close() def __del__(self): try: self.close() except Exception: pass ## -------------------- Utility Functions ------------------------ ## def close_open_data_files(verbose): open_files = tables.file._open_files clall = hasattr(open_files, 'close_all') if clall: open_files.close_all() else: are_open_files = len(open_files) > 0 if verbose and are_open_files: print2err('Closing remaining open data files:') for fileh in open_files: if verbose: print2err('%s...' % (open_files[fileh].filename,)) open_files[fileh].close() if verbose: print2err('done') registered_close_open_data_files = True atexit.register(close_open_data_files, False) ## ---------------------- Pytable Definitions ------------------- ## class ClassTableMappings(tables.IsDescription): class_id = UInt32Col(pos=1) class_type_id = UInt32Col(pos=2) # Device or Event etc. class_name = StringCol(32, pos=3) table_path = StringCol(128, pos=4) class ExperimentMetaData(tables.IsDescription): experiment_id = UInt32Col(pos=1) code = StringCol(256, pos=2) title = StringCol(256, pos=3) description = StringCol(4096, pos=4) version = StringCol(32, pos=5) class SessionMetaData(tables.IsDescription): session_id = UInt32Col(pos=1) experiment_id = UInt32Col(pos=2) code = StringCol(256, pos=3) name = StringCol(256, pos=4) comments = StringCol(4096, pos=5) user_variables = StringCol(16384, pos=6) # Holds json encoded version of user variable dict for session
18,898
Python
.py
371
38.250674
120
0.595699
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,665
computer.py
psychopy_psychopy/psychopy/iohub/devices/computer.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import gc import sys import psutil from ..errors import print2err from psychopy import clock REALTIME_PRIORITY_CLASS = -18 HIGH_PRIORITY_CLASS = -10 class Computer(): """Computer provides access to OS and Process level functionality: * Read the current time in sec.msec format. The time base used is shared by the ioHub and PsychoPy processes. * Access the iohub and psychopy psutil.Process objects * Get / set process priority and affinity. * Read system memory and CPU usage Computer contains only static methods and class attributes. Therefore all supported functionality can be accessed directly from the Computer class itself; an instance of the class never needs to be created. """ #: Access to the psutil.Process class for the current system Process. current_process = psutil.Process() #: The psutil Process object for the ioHub Process. iohub_process = None #: If Computer class is on the iohub server process, psychopy_process is #: the psychopy process created from the pid passed to iohub on startup. #: The iohub server checks that this process exists #: (server.checkForPsychopyProcess()) and shuts down if it does not. psychopy_process = None #: The OS process ID of the ioHub Process. iohub_process_id = None #: True if the current process is the ioHub Server Process. False if the #: current process is the Experiment Runtime Process. is_iohub_process = False #: global_clock is used as the common time base for all devices #: and between the ioHub Server and Experiment Runtime Process. Do not #: access this class directly, instead use the Computer.getTime() #: and associated method name alias's to actually get the current ioHub # time. global_clock = clock.monotonicClock #: The name of the current operating system Python is running on. platform = sys.platform #: Python Env. bits: 32 or 64. Note that when a #: Python 32 bit runtime is used a 64 bit OS sysbits will equal 32. pybits = 32 + int(sys.maxsize > 2 ** 32) * 32 try: #: Attribute representing the number of *processing units* available on #: the current computer. This includes cpu's, cpu cores, and hyperthreads. #: #: processing_unit_count = num_cpus * cores_per_cpu * num_hyperthreads #: #: where: #: * num_cpus: Number of CPU chips on the motherboard #: (usually 1 now). #: * cores_per_cpu: Number of processing cores per CPU (2,4 is common) #: * num_hyperthreads: Hyper-threaded cores = 2, otherwise 1. processing_unit_count = psutil.cpu_count() #: The number of cpu cores available on the computer. #: Hyperthreads are NOT included. core_count = psutil.cpu_count(False) #hyperthreads not included except AttributeError: # psutil might be too old (cpu_count added in 2.0) import multiprocessing processing_unit_count = multiprocessing.cpu_count() core_count = None # but not used anyway try: #: Process priority when first started. If process is set to #: high priority, this value is used when the process is set back to #: normal priority. _process_original_nice_value=psutil.Process().nice() # used on linux. except TypeError: # on older versions of psutil (in ubuntu 14.04) nice is attr not call _process_original_nice_value=psutil.Process().nice #: True if the current process is currently in high or real-time #: priority mode (enabled by calling Computer.setPriority()). in_high_priority_mode = False def __init__(self): print2err('WARNING: Computer is a static class, ' 'no need to create an instance. just use Computer.xxxxxx') @staticmethod def getPriority(): """Returns the current processes priority as a string. This method is not supported on OS X. :return: 'normal', 'high', or 'realtime' """ proc_priority = Computer.current_process.nice() if Computer.platform == 'win32': if proc_priority == psutil.HIGH_PRIORITY_CLASS: return 'high' if proc_priority == psutil.REALTIME_PRIORITY_CLASS: return 'realtime' if proc_priority == psutil.NORMAL_PRIORITY_CLASS: return 'normal' else: if proc_priority <= REALTIME_PRIORITY_CLASS: return 'realtime' if proc_priority <= HIGH_PRIORITY_CLASS: return 'high' if proc_priority == Computer._process_original_nice_value: return 'normal' return proc_priority @staticmethod def _setProcessPriority(process, nice_val, disable_gc): org_nice_val = Computer._process_original_nice_value try: process.nice(nice_val) Computer.in_high_priority_mode = nice_val != org_nice_val if disable_gc: gc.disable() else: gc.enable() return True except psutil.AccessDenied: print2err('WARNING: Could not set process {} priority ' 'to {}'.format(process.pid, nice_val)) return False @staticmethod def setPriority(level='normal', disable_gc=False): """ Attempts to change the current processes priority based on level. Supported levels are: * 'normal': sets the current process priority to NORMAL_PRIORITY_CLASS on Windows, or to the processes original nice value on Linux. * 'high': sets the current process priority to HIGH_PRIORITY_CLASS on Windows, or to a nice value of -10 value on Linux. * 'realtime': sets the current process priority to REALTIME_PRIORITY_CLASS on Windows, or to a nice value of -18 value on Linux. If level is 'normal', Python GC is also enabled. If level is 'high' or 'realtime', and disable_gc is True, then the Python garbage collection (GC) thread is suspended. This method is not supported on OS X. :return: Priority level of process when method returns. """ level = level.lower() current_process = Computer.current_process nice_val = Computer._process_original_nice_value if level == 'normal': disable_gc = False elif level == 'high': nice_val = HIGH_PRIORITY_CLASS if Computer.platform == 'win32': nice_val = psutil.HIGH_PRIORITY_CLASS elif level.lower() == 'realtime': nice_val = REALTIME_PRIORITY_CLASS if Computer.platform == 'win32': nice_val = psutil.REALTIME_PRIORITY_CLASS Computer._setProcessPriority(current_process, nice_val, disable_gc) return Computer.getPriority() @staticmethod def getProcessingUnitCount(): """ Return the number of *processing units* available on the current computer. Processing Units include: cpu's, cpu cores, and hyper threads. Notes: * processing_unit_count = num_cpus*num_cores_per_cpu*num_hyperthreads. * For single core CPU's, num_cores_per_cpu = 1. * For CPU's that do not support hyperthreading, num_hyperthreads = 1, otherwise num_hyperthreads = 2. Args: None Returns: int: the number of processing units on the computer. """ return Computer.processing_unit_count @staticmethod def getProcessAffinities(): """Retrieve the current PsychoPy Process affinity list and ioHub Process affinity list. For example, on a 2 core CPU with hyper-threading, the possible 'processor' list would be [0,1,2,3], and by default both the PsychoPy and ioHub Processes can run on any of these 'processors', so:: psychoCPUs,ioHubCPUS=Computer.getProcessAffinities() print psychoCPUs,ioHubCPUS >> [0,1,2,3], [0,1,2,3] If Computer.setProcessAffinities was used to set the PsychoPy Process to core 1 (index 0 and 1) and the ioHub Process to core 2 (index 2 and 3), with each using both hyper threads of the given core, the set call would look like:: Computer.setProcessAffinities([0,1],[2,3]) psychoCPUs,ioHubCPUS=Computer.getProcessAffinities() print psychoCPUs,ioHubCPUS >> [0,1], [2,3] If the ioHub is not being used (i.e self.hub is None), then only the PsychoPy Process affinity list will be returned and None will be returned for the ioHub Process affinity:: psychoCPUs,ioHubCPUS=Computer.getProcessAffinities() print psychoCPUs,ioHubCPUS >> [0,1,2,3], None **But in this case, why are you using the ioHub package at all? ;)** This method is not supported on OS X. Args: None Returns: (list,list) Tuple of two lists: PsychoPy Process affinity ID list and ioHub Process affinity ID list. """ curproc_affinity = Computer.current_process.cpu_affinity() iohproc_affinity = Computer.iohub_process.cpu_affinity() return curproc_affinity, iohproc_affinity @staticmethod def setProcessAffinities(experimentProcessorList, ioHubProcessorList): """Sets the processor affinity for the PsychoPy Process and the ioHub Process. For example, on a 2 core CPU with hyper-threading, the possible 'processor' list would be [0,1,2,3], and by default both the experiment and ioHub server processes can run on any of these 'processors', so to have both processes have all processors available (which is the default), you would call:: Computer.setProcessAffinities([0,1,2,3], [0,1,2,3]) # check the process affinities psychoCPUs,ioHubCPUS=Computer.getProcessAffinities() print psychoCPUs,ioHubCPUS >> [0,1,2,3], [0,1,2,3] based on the above CPU example. If setProcessAffinities was used to set the experiment process to core 1 (index 0,1) and the ioHub server process to core 2 (index 2,3), with each using both hyper threads of the given core, the set call would look like:: Computer.setProcessAffinities([0,1],[2,3]) # check the process affinities psychoCPUs,ioHubCPUS=Computer.getProcessAffinities() print psychoCPUs,ioHubCPUS >> [0,1], [2,3] Args: experimentProcessorList (list): list of int processor ID's to set the PsychoPy Process affinity to. An empty list means all processors. ioHubProcessorList (list): list of int processor ID's to set the ioHub Process affinity to. An empty list means all processors. Returns: None """ Computer.current_process.cpu_affinity(experimentProcessorList) Computer.iohub_process.cpu_affinity(ioHubProcessorList) @staticmethod def autoAssignAffinities(): """Auto sets the PsychoPy Process and ioHub Process affinities based on some very simple logic. It is not known at this time if the implementation of this method makes any sense in terms of actually improving performance. Field tests and feedback will need to occur, based on which the algorithm can be improved. Currently: * If the system is detected to have 1 processing unit, or greater than 8 processing units, nothing is done by the method. * For a system that has two processing units, the PsychoPy Process is assigned to index 0, ioHub Process assigned to 1. * For a system that has four processing units, the PsychoPy Process is assigned to index's 0,1 and the ioHub Process assigned to 2,3. * For a system that has eight processing units, the PsychoPy Process is assigned to index 2,3, ioHub Process assigned to 4,5. All other processes running on the OS are attempted to be assigned to indexes 0,1,6,7. Args: None Returns: None """ cpu_count = Computer.processing_unit_count if cpu_count == 2: # print 'Assigning experiment process to CPU 0, ioHubServer process # to CPU 1' Computer.setProcessAffinities([0, ], [1, ]) elif cpu_count == 4: # print 'Assigning experiment process to CPU 0,1, ioHubServer # process to CPU 2,3' Computer.setProcessAffinities([0, 1], [2, 3]) elif cpu_count == 8: # print 'Assigning experiment process to CPU 2,3, ioHubServer # process to CPU 4,5, attempting to assign all others to 0,1,6,7' Computer.setProcessAffinities([2, 3], [4, 5]) Computer.setAllOtherProcessesAffinity( [0, 1, 6, 7], [Computer.currentProcessID, Computer.iohub_process_id]) else: print('autoAssignAffinities does not support %d processors.' % ( cpu_count,)) @staticmethod def getCurrentProcessAffinity(): """ Returns a list of 'processor' ID's (from 0 to Computer.processing_unit_count-1) that the current (calling) process is able to run on. Args: None Returns: None """ return Computer.current_process.cpu_affinity() @staticmethod def setCurrentProcessAffinity(processorList): """ Sets the list of 'processor' ID's (from 0 to Computer.processing_unit_count-1) that the current (calling) process should only be allowed to run on. Args: processorList (list): list of int processor ID's to set the current Process affinity to. An empty list means all processors. Returns: None """ return Computer.current_process.cpu_affinity(processorList) @staticmethod def setProcessAffinityByID(process_id, processor_list): """ Sets the list of 'processor' ID's (from 0 to Computer.processing_unit_count-1) that the process with the provided OS Process ID is able to run on. Args: processID (int): The system process ID that the affinity should be set for. processorList (list): list of int processor ID's to set process with the given processID too. An empty list means all processors. Returns: None """ p = psutil.Process(process_id) return p.cpu_affinity(processor_list) @staticmethod def getProcessAffinityByID(process_id): """ Returns a list of 'processor' ID's (from 0 to Computer.processing_unit_count-1) that the process with the provided processID is able to run on. Args: processID (int): The system process ID that the affinity should be set for. Returns: processorList (list): list of int processor ID's to set process with the given processID too. An empty list means all processors. """ p = psutil.Process(process_id) return p.cpu_affinity() @staticmethod def setAllOtherProcessesAffinity( processor_list, exclude_process_id_list=[]): """ Sets the affinity for all OS Processes other than those specified in the exclude_process_id_list, to the processing unit indexes specified in processor_list. Valid values in the processor_list are between 0 to Computer.processing_unit_count-1. exclude_process_id_list should be a list of OS Process ID integers, or an empty list (indicating to set the affiinty to all processing units). Note that the OS may not allow the calling process to set the affinity of every other process running on the system. For example, some system level processing can not have their affinity set by a user level application. However, in general, many processes can have their affinity set by another user process. Args: processor_list (list): list of int processor ID's to set all OS Processes to. An empty list means all processors. exclude_process_id_list (list): A list of process ID's that should not have their process affinity settings changed. Returns: None """ for p in psutil.pids(): if p not in exclude_process_id_list: try: psutil.Process(p).cpu_affinity(processor_list) except Exception: pass @staticmethod def getProcessFromName(pnames, id_only=False): procs = [] if isinstance(pnames, str): pnames = [pnames, ] for p in psutil.process_iter(): if p.name() in pnames: if id_only: procs.append(p.pid) else: procs.append(p) return procs @staticmethod def getTime(): """ Returns the current sec.msec-msec time of the system. The underlying timer that is used is based on OS and Python version. Three requirements exist for the ioHub time base implementation: * The Python interpreter does not apply an offset to the times returned based on when the timer module being used was loaded or when the timer function first called was first called. * The timer implementation used must be monotonic and report elapsed time between calls, 'not' CPU usage time. * The timer implementation must provide a resolution of 50 usec or better. Given the above requirements, ioHub selects a timer implementation as follows: * On Windows, the Windows Query Performance Counter API is used using ctypes access. * On other OS's, if the Python version being used is 2.6 or lower, time.time is used. For Python 2.7 and above, the timeit.default_timer function is used. Args: None Returns: None """ return Computer.global_clock.getTime() @staticmethod def syncClock(params): """ Sync parameters between Computer.global_clock and a given dict. Parameters ---------- params : dict Dict of attributes and values to apply to the computer's global clock. See `psychopy.clock.MonotonicClock` for what attributes to include. """ for key, value in params.items(): setattr(Computer.global_clock, key, value) @staticmethod def getPhysicalSystemMemoryInfo(): """Return a class containing information about current memory usage. Args: None Returns: vmem: (total=long, available=long, percent=float, used=long, free=long) Where: * vmem.total: the total amount of memory in bytes. * vmem.available: the available amount of memory in bytes. * vmem.percent: the percent of memory in use by the system. * vmem.used: the used amount of memory in bytes. * vmem.free: the amount of memory that is free in bytes.On Windows, this is the same as vmem.available. """ m = psutil.virtual_memory() return m @staticmethod def getCPUTimeInfo(percpu=False): """Return a float representing the current CPU utilization as a percentage. Args: percpu (bool): If True, a list of cputimes objects is returned, one for each processing unit for the computer. If False, only a single cputimes object is returned. Returns: object: (user=float, system=float, idle=float) """ return psutil.cpu_times_percent(percpu=percpu) @staticmethod def getCurrentProcess(): """Get the current / Local process. On Windows and Linux, this is a psutil.Process class instance. Args: None Returns: object: Process object for the current system process. """ return Computer.current_process @staticmethod def getIoHubProcess(): """Get the ioHub Process. On Windows and Linux, this is a psutil.Process class instance. Args: None Returns: object: Process object for the ioHub Process. """ return Computer.iohub_process
21,326
Python
.py
479
34.807933
86
0.637917
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,666
pyXHook.py
psychopy_psychopy/psychopy/iohub/devices/pyXHook.py
# pyxhook -- an extension to emulate some of the PyHook library on linux. # # Copyright (C) 2008 Tim Alexander <dragonfyre13@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Thanks to Alex Badea <vamposdecampos@gmail.com> for writing the Record # demo for the xlib libraries. It helped me immensely working with these # in this library. # # Thanks to the python-xlib team. This wouldn't have been possible without # your code. # # This requires: # at least python-xlib 1.4 # xwindows must have the "record" extension present, and active. # # This file has now been somewhat extensively modified by # Daniel Folkinshteyn <nanotube@users.sf.net> # So if there are any bugs, they are probably my fault. :) # # January 2013: File modified by # Sol Simpson (sol@isolver-software.com), with some cleanup done and # modifications made so it integrated with the ioHub module more effecively # ( but therefore making this version not useful for general application usage) # # March, 2013: -Fixed an existing bug that caused capslock not to have an effect, # -Added tracking of what keys are pressed and how many auto repeat # press events each has received. # April, 2013: - Modified to directly return ioHub device event arrays # - optimized keysym lookup by loading into a dict cache # - started adding support for reporting unicode keys import threading import unicodedata import ctypes as ct from Xlib import X, display from Xlib.ext import record from Xlib.protocol import rq from . import xlib as _xlib from .computer import Computer from ..constants import EventConstants, MouseConstants, ModifierKeyCodes from ..errors import print2err jdumps = lambda x: str(x) try: import ujson jdumps = ujson.dumps except Exception: import json jdumps = json.dumps getTime = Computer.getTime ####################################################################### ########################START CLASS DEF################################ ####################################################################### def event2json(event): """ Instance Variable: KeyButtonPointerEvent time The server X time when this event was generated. Instance Variable: KeyButtonPointerEvent root The root window which the source window is an inferior of. Instance Variable: KeyButtonPointerEvent window The window the event is reported on. Instance Variable: KeyButtonPointerEvent same_screen Set to 1 if window is on the same screen as root, 0 otherwise. Instance Variable: KeyButtonPointerEvent child If the source window is an inferior of window, child is set to the child of window that is the ancestor of (or is) the source window. Otherwise it is set to X.NONE. Instance Variable: KeyButtonPointerEvent root_x Instance Variable: KeyButtonPointerEvent root_y The pointer coordinates at the time of the event, relative to the root window. Instance Variable: KeyButtonPointerEvent event_x Instance Variable: KeyButtonPointerEvent event_y The pointer coordinates at the time of the event, relative to window. If window is not on the same screen as root, these are set to 0. Instance Variable: KeyButtonPointerEvent state The logical state of the button and modifier keys just before the event. Instance Variable: KeyButtonPointerEvent detail For KeyPress and KeyRelease, this is the keycode of the event key. For ButtonPress and ButtonRelease, this is the button of the event. For MotionNotify, this is either X.NotifyNormal or X.NotifyHint. """ return jdumps(dict(type=event.type, send_event=event.send_event, time=event.time, root=str(event.root), window=str(event.window), same_screen=event.same_screen, child=str(event.child), root_x=event.root_x, root_y=event.root_y, event_x=event.event_x, event_y=event.event_y, state=event.state, detail=event.detail)) # xlib modifier constants to iohub str constants key_mappings = {'num_lock': 'numlock', 'caps_lock': 'capslock', 'scroll_lock': 'scrolllock', 'shift_l': 'lshift', 'shift_r': 'rshift', 'alt_l': 'lalt', 'alt_r': 'ralt', 'control_l': 'lctrl', 'control_r': 'rctrl', 'super_l': 'lcmd', 'super_r': 'rcmd' } class HookManager(threading.Thread): """Creates a separate thread that starts the Xlib Record functionality, capturing keyboard and mouse events and transmitting them to the associated callback functions set.""" DEVICE_TIME_TO_SECONDS = 0.001 evt_types = [ X.KeyRelease, X.KeyPress, X.ButtonRelease, X.ButtonPress, X.MotionNotify] def __init__(self, log_event_details=False): threading.Thread.__init__(self) self.finished = threading.Event() self._running = False self.log_events = log_event_details self.log_events_file = None # Give these some initial values self.mouse_position_x = 0 self.mouse_position_y = 0 # Assign default function actions (do nothing). self.KeyDown = lambda x: True self.KeyUp = lambda x: True self.MouseAllButtonsDown = lambda x: True self.MouseAllButtonsUp = lambda x: True self.MouseAllMotion = lambda x: True self.contextEventMask = [X.KeyPress, X.MotionNotify] # Used to hold any keys currently pressed and the repeat count # of each key. self.key_states = dict() self.contextEventMask = [X.KeyPress, X.MotionNotify] # Hook to our display. self.local_dpy = display.Display() self.record_dpy = display.Display() self.ioHubMouseButtonMapping = {1: 'MOUSE_BUTTON_LEFT', 2: 'MOUSE_BUTTON_MIDDLE', 3: 'MOUSE_BUTTON_RIGHT' } self.pressedMouseButtons = 0 self.scroll_y = 0 # Direct xlib ctypes wrapping for better / faster keyboard event -> key, # char field mapping. self._xlib = _xlib self._xdisplay = _xlib.XOpenDisplay(None) self._xroot = _xlib.XDefaultRootWindow(self._xdisplay) self._keysym = _xlib.KeySym() self._compose = _xlib.XComposeStatus() self._tmp_compose = _xlib.XComposeStatus() self._revert = ct.c_int(0) self._charbuf = (ct.c_char * 17)() self._cwin = _xlib.Window() self._revert_to_return = ct.c_int() self._xkey_evt = _xlib.XKeyEvent() self._xkey_evt.serial = 1 # not known, make it up. self._xkey_evt.send_event = 0 self._xkey_evt.subwindow = 0 self._xkey_evt.display = self._xdisplay self._xkey_evt.root = self._xroot # ', Window), self._xkey_evt.subwindow = 0 # ', Window) def run(self): self._running = True # Check if the extension is present if not self.record_dpy.has_extension('RECORD'): print2err( 'RECORD extension not found. ioHub can not use python Xlib. Exiting....') return False # Create a recording context; we only want key and mouse events self.ctx = self.record_dpy.record_create_context( 0, [record.AllClients], [{ 'core_requests': (0, 0), 'core_replies': (0, 0), 'ext_requests': (0, 0, 0, 0), 'ext_replies': (0, 0, 0, 0), 'delivered_events': (0, 0), # (X.KeyPress, X.ButtonPress), 'device_events': tuple(self.contextEventMask), 'errors': (0, 0), 'client_started': False, 'client_died': False, }]) if self.log_events: import datetime cdate = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M') with open('x11_events_{0}.log'.format(cdate), 'w') as self.log_events_file: # Enable the context; this only returns after a call to record_disable_context, # while calling the callback function in the meantime self.record_dpy.record_enable_context( self.ctx, self.processevents) # Finally free the context self.record_dpy.record_free_context(self.ctx) else: self.record_dpy.record_enable_context(self.ctx, self.processevents) # Finally free the context self.record_dpy.record_free_context(self.ctx) def cancel(self): self.finished.set() self._running = False self.local_dpy.record_disable_context(self.ctx) self.local_dpy.flush() try: self._xlib.XCloseDisplay(self._xdisplay) self._xlib = None except AttributeError: pass def printevent(self, event): print2err(event) def HookKeyboard(self): pass def HookMouse(self): pass def updateKeysPressedState(self, key_str, pressed_event): keyautocount = self.key_states.setdefault(key_str, -1) if pressed_event: self.key_states[key_str] = keyautocount + 1 else: del self.key_states[key_str] return self.key_states def isKeyPressed(self, key_str_id): """Returns 0 if key is not pressed, otherwise a. positive int, representing the auto repeat count ( return val - 1) of key press events that have occurred for the key. """ return self.key_states.get(key_str_id, 0) def getPressedKeys(self, repeatCounts=False): """ If repeatCounts == False (default), returns a list of all the key symbol strings currently pressed. If repeatCounts == True, returns the dict of key sybol strs, pressedCount. """ if repeatCounts: return self.key_states return list(self.key_states.keys()) def processevents(self, reply): logged_time = getTime() if reply.category != record.FromServer: return if reply.client_swapped: print2err( 'pyXlib: * received swapped protocol data, cowardly ignored') return if not len(reply.data):# or ord(reply.data[0]) < 2: # not an event return data = reply.data while len(data): event, data = rq.EventField(None).parse_binary_value( data, self.record_dpy.display, None, None) if self.log_events_file and event.type in self.evt_types: self.log_events_file.write(event2json(event) + '\n') event.iohub_logged_time = logged_time if event.type == X.KeyPress: hookevent = self.makekeyhookevent(event) self.KeyDown(hookevent) elif event.type == X.KeyRelease: hookevent = self.makekeyhookevent(event) self.KeyUp(hookevent) elif event.type == X.ButtonPress: hookevent = self.buttonpressevent(event) self.MouseAllButtonsDown(hookevent) elif event.type == X.ButtonRelease and event.detail not in (4, 5): # 1 mouse wheel scroll event was generating a button press # and a button release event for each single scroll, so allow # wheel scroll events through for buttonpressevent, but not for # buttonreleaseevent so 1 scroll action causes 1 scroll event. hookevent = self.buttonreleaseevent(event) self.MouseAllButtonsUp(hookevent) elif event.type == X.MotionNotify: # use mouse moves to record mouse position, since press and release events # do not give mouse position info (event.root_x and event.root_y have # bogus info). hookevent = self.mousemoveevent(event) self.MouseAllMotion(hookevent) def buttonpressevent(self, event): r = self.makemousehookevent(event) return r def buttonreleaseevent(self, event): r = self.makemousehookevent(event) return r def mousemoveevent(self, event): self.mouse_position_x = event.root_x self.mouse_position_y = event.root_y r = self.makemousehookevent(event) return r def getKeyChar(self, kb_event): keycode = kb_event.detail # get char string for keyboard event. _xlib.XGetInputFocus( self._xdisplay, ct.byref( self._cwin), ct.byref( self._revert_to_return)) self._xkey_evt.window = self._cwin self._xkey_evt.type = kb_event.type # >>> How many of these event fields really need to be filled in for XLookupString to work? self._xkey_evt.time = kb_event.time # ', Time), self._xkey_evt.x = kb_event.event_x # ', c_int), self._xkey_evt.y = kb_event.event_y # ', c_int), self._xkey_evt.x_root = kb_event.root_x # ', c_int), self._xkey_evt.y_root = kb_event.root_y # ', c_int), self._xkey_evt.state = kb_event.state # ', c_uint), self._xkey_evt.keycode = keycode # ', c_uint), self._xkey_evt.same_screen = kb_event.same_screen # ', c_int), # <<< count = _xlib.XLookupString( ct.byref( self._xkey_evt), self._charbuf, 16, ct.byref( self._keysym), ct.byref( self._compose)) char = '' ucat = '' if count > 0: char = u'' + self._charbuf[0:count].decode('utf-8') ucat = unicodedata.category(char) char = char.encode('utf-8') # special char char handling # Setting count == 0 makes key use XKeysymToString return value. if ucat.lower() == 'cc': if char == '\r': char = '\n' count = 0 elif char == '\t': count = 0 elif char != '\n': char = '' count = 0 # Get key value keysym = _xlib.XKeycodeToKeysym(self._xdisplay, keycode, 0) key = _xlib.XKeysymToString(keysym) if isinstance(key, bytes): key = key.decode('utf-8') if isinstance(char, bytes): char = char.decode('utf-8') if key: key = key.lower() if key and key.startswith('kp_'): key = 'num_%s' % (key[3:]) elif key in key_mappings: key = key_mappings[key] elif count > 0: self._xkey_evt.state = 0 count = _xlib.XLookupString( ct.byref( self._xkey_evt), self._charbuf, 16, ct.byref( self._keysym), ct.byref( self._tmp_compose)) key = '' if count > 0: key = u'' + self._charbuf[0:count].decode('utf-8') key = key.encode('utf-8') else: key = '' return keycode, keysym, key, char def makekeyhookevent(self, event): """Creates a ioHub keyboard event in list format, completing as much as possible from within pyXHook.""" key_code, keysym, key, char = self.getKeyChar(event) event_type_id = EventConstants.KEYBOARD_PRESS is_pressed_key = event.type == X.KeyPress if not is_pressed_key: is_pressed_key = False event_type_id = EventConstants.KEYBOARD_RELEASE pressed_keys = self.updateKeysPressedState(key, is_pressed_key) auto_repeat_count = pressed_keys.get(key, 0) mod_mask = event.state modifier_key_state = 0 # Update currently active modifiers (modifier_key_state) # if mod_mask & 2 == 2: # capslock is active: modifier_key_state += ModifierKeyCodes.capslock if mod_mask & 16 == 16: # numlock is active: modifier_key_state += ModifierKeyCodes.numlock for pk in pressed_keys: if pk not in ['capslock', 'numlock']: is_mod_id = ModifierKeyCodes.getID(pk) if is_mod_id: modifier_key_state += is_mod_id # return event to iohub return [[0, 0, 0, # device id (not currently used) 0, # to be assigned by ioHub server# Device._getNextEventID(), event_type_id, event.time * self.DEVICE_TIME_TO_SECONDS, event.iohub_logged_time, event.iohub_logged_time, 0.0, # confidence interval not set for keyboard or mouse devices. 0.0, # delay not set for keyboard or mouse devices. 0, # filter level not used auto_repeat_count, # auto_repeat key_code, # scan / Keycode of event. keysym, # KeyID / VK code for key pressed 0, # unicode value for char, otherwise, 0 key, # psychpy key event val modifier_key_state, # The logical state of the button and modifier keys just # before the event. int(self._cwin.value), char, # utf-8 encoded char or label for the key. (depending on # whether it is a visible char or not) 0.0, 0 ], ] def makemousehookevent(self, event): """Creates an incomplete ioHub keyboard event in list format. It is incomplete as some of the elements of the array are filled in by the ioHub server when it receives the events. For event attributes see: http://python-xlib.sourceforge.net/doc/html/python-xlib_13.html time The server X time when this event was generated. root The root window which the source window is an inferior of. window The window the event is reported on. same_screen Set to 1 if window is on the same screen as root, 0 otherwise. child If the source window is an inferior of window, child is set to the child of window that is the ancestor of (or is) the source window. Otherwise it is set to X.NONE. root_x root_y The pointer coordinates at the time of the event, relative to the root window. event_x event_y The pointer coordinates at the time of the event, relative to window. If window is not on the same screen as root, these are set to 0. state The logical state of the button and modifier keys just before the event. detail For KeyPress and KeyRelease, this is the keycode of the event key. For ButtonPress and ButtonRelease, this is the button of the event. For MotionNotify, this is either X.NotifyNormal or X.NotifyHint. """ px, py = event.root_x, event.root_y event_type_id = 0 event_state = [] event_detail = [] dy = 0 _xlib.XGetInputFocus( self._xdisplay, ct.byref( self._cwin), ct.byref( self._revert_to_return)) if event.type == 6: if event.state < 128: event_type_id = EventConstants.MOUSE_MOVE else: event_type_id = EventConstants.MOUSE_DRAG if event.type in [4, 5]: if event.type == 5: event_type_id = EventConstants.MOUSE_BUTTON_RELEASE elif event.type == 4: event_type_id = EventConstants.MOUSE_BUTTON_PRESS if event.detail == 4 and event.type == 4: event_type_id = EventConstants.MOUSE_SCROLL self.scroll_y += 1 dy = 1 elif event.detail == 5 and event.type == 4: event_type_id = EventConstants.MOUSE_SCROLL self.scroll_y -= 1 dy = -1 if event.state & 1 == 1: event_state.append('SHIFT') if event.state & 4 == 4: event_state.append('ALT') if event.state & 64 == 64: event_state.append('WIN_MENU') if event.state & 8 == 8: event_state.append('CTRL') event_state.append('MOUSE_BUTTON_LEFT') if event.state & 512 == 512: event_state.append('MOUSE_BUTTON_MIDDLE') if event.state & 1024 == 1024: event_state.append('MOUSE_BUTTON_RIGHT') if event.detail == 1: event_detail.append('MOUSE_BUTTON_LEFT') if event.detail == 2: event_detail.append('MOUSE_BUTTON_MIDDLE') if event.detail == 3: event_detail.append('MOUSE_BUTTON_RIGHT') # TODO implement mouse event to display index detection display_index = 0 currentButton = 0 pressed = 0 currentButtonID = 0 if event.type in [ 4, 5] and event_type_id != EventConstants.MOUSE_SCROLL: currentButton = self.ioHubMouseButtonMapping.get(event.detail) currentButtonID = MouseConstants.getID(currentButton) pressed = event.type == 4 if pressed is True: self.pressedMouseButtons += currentButtonID else: self.pressedMouseButtons -= currentButtonID return [[0, 0, 0, # device id (not currently used) 0, # to be assigned by ioHub server# Device._getNextEventID(), event_type_id, event.time * self.DEVICE_TIME_TO_SECONDS, event.iohub_logged_time, event.iohub_logged_time, 0.0, # confidence interval not set for keyboard or mouse devices. 0.0, # delay not set for keyboard or mouse devices. 0, # filter level not used display_index, # event.DisplayIndex, pressed, currentButtonID, self.pressedMouseButtons, px, # mouse x pos py, # mouse y post 0, # scroll_dx not supported 0, # scroll_x dy, self.scroll_y, 0, # mod state, filled in when event received by iohub int(self._cwin.value)], ] # TO DO: Implement multimonitor location based on mouse location support. # Currently always uses monitor index 0 # # #######################################################################
24,090
Python
.py
542
33.280443
172
0.578525
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,667
deviceConfigValidation.py
psychopy_psychopy/psychopy/iohub/devices/deviceConfigValidation.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import importlib import socket import os import numbers # numbers.Integral is like (int, long) but supports Py3 from psychopy import colors from psychopy.iohub.devices import importDeviceModule from psychopy.tools import arraytools from ..util import yload, yLoader, module_directory, getSupportedConfigSettings from ..errors import print2err # Takes a device configuration yaml dict and processes it based on the devices # support_settings_values.yaml (which must be in the same directory as the # Device class) to ensure all entries for the device setting are valid values. class ValidationError(Exception): """Base class for exceptions in this module.""" pass class BooleanValueError(ValidationError): """Exception raised for errors when a bool was expected for the settings parameter value. Attributes: device_config_setting_name -- The name of the Device configuration parameter that has the error. value_given -- the value read from the experiment configuration file. msg -- explanation of the error """ def __init__(self, device_param_name, value_given): self.msg = 'A bool value is required for the given Device configuration parameter' self.device_config_param_name = device_param_name self.value_given = value_given def __str__(self): return '\n{0}:\n\tmsg: {1}\n\tparam_name: {2}\n\tvalue: {3}\n'.format( self.__class__.__name__, self.msg, self.device_config_param_name, self.value_given) class StringValueError(ValidationError): """Exception raised for errors when a str was expected for the settings parameter value. Attributes: device_config_param_name -- The name of the Device configuration parameter that has the error. value_given -- the value read from the experiment configuration file. device_config_param_constraints -- the set of constraints that apply to the parameter. msg -- explanation of the error """ def __init__( self, device_config_param_name, value_given, device_config_param_constraints): self.msg = 'A str value is required for the given Device configuration parameter that meets the specified constraints' self.device_config_param_name = device_config_param_name self.value_given = value_given self.device_config_param_constraints = device_config_param_constraints def __str__(self): return '\n{0}:\n\tmsg: {1}\n\tparam_name: {2}\n\tvalue: {3}\n'.format( self.__class__.__name__, self.msg, self.device_config_param_name, self.value_given) class FloatValueError(ValidationError): """Exception raised for errors when a float was expected for the settings parameter value. Attributes: device_config_param_name -- The name of the Device configuration parameter that has the error. value_given -- the value read from the experiment configuration file. device_config_param_constraints -- the set of constraints that apply to the parameter. msg -- explanation of the error """ def __init__( self, device_config_param_name, value_given, device_config_param_constraints): self.msg = 'A float value is required for the given Device configuration parameter that meets the specified constraints' self.device_config_param_name = device_config_param_name self.value_given = value_given self.device_config_param_constraints = device_config_param_constraints def __str__(self): return '\n{0}:\n\tmsg: {1}\n\tparam_name: {2}\n\tvalue: {3}\n'.format( self.__class__.__name__, self.msg, self.device_config_param_name, self.value_given) class IntValueError(ValidationError): """Exception raised for errors when an int was expected for the settings parameter value. Attributes: device_config_param_name -- The name of the Device configuration parameter that has the error. value_given -- the value read from the experiment configuration file. device_config_param_constraints -- the set of constraints that apply to the parameter. msg -- explanation of the error """ def __init__( self, device_config_param_name, value_given, device_config_param_constraints): self.msg = 'An int value is required for the given Device configuration parameter that meets the specified constraints' self.device_config_param_name = device_config_param_name self.value_given = value_given self.device_config_param_constraints = device_config_param_constraints def __str__(self): return '\n{0}:\n\tmsg: {1}\n\tparam_name: {2}\n\tvalue: {3}\n'.format( self.__class__.__name__, self.msg, self.device_config_param_name, self.value_given) class NumberValueError(ValidationError): """Exception raised for errors when an int OR float was expected for the settings parameter value. Attributes: device_config_param_name -- The name of the Device configuration parameter that has the error. value_given -- the value read from the experiment configuration file. device_config_param_constraints -- the set of constraints that apply to the parameter. msg -- explanation of the error """ def __init__( self, device_config_param_name, value_given, device_config_param_constraints): self.msg = 'An int or float value is required for the given Device configuration parameter that meets the specified constraints' self.device_config_param_name = device_config_param_name self.value_given = value_given self.device_config_param_constraints = device_config_param_constraints def __str__(self): return '\n{0}:\n\tmsg: {1}\n\tparam_name: {2}\n\tvalue: {3}\n'.format( self.__class__.__name__, self.msg, self.device_config_param_name, self.value_given) class IpValueError(ValidationError): """Exception raised for errors when an IP address was expected for the settings parameter value. Attributes: device_config_param_name -- The name of the Device configuration parameter that has the error. value_given -- the value read from the experiment configuration file. msg -- explanation of the error """ def __init__(self, device_config_param_name, value_given): self.msg = 'An IP address value is required for the given Device configuration parameter.' self.device_config_param_name = device_config_param_name self.value_given = value_given def __str__(self): return '\n{0}:\n\tmsg: {1}\n\tparam_name: {2}\n\tvalue: {3}\n'.format( self.__class__.__name__, self.msg, self.device_config_param_name, self.value_given) class ColorValueError(ValidationError): """Exception raised for errors when a color was expected for the settings parameter value. Attributes: device_config_param_name -- The name of the Device configuration parameter that has the error. value_given -- the value read from the experiment configuration file. msg -- explanation of the error """ def __init__(self, device_config_param_name, value_given): self.msg = 'A color value is required for the given Device configuration parameter.' self.device_config_param_name = device_config_param_name self.value_given = value_given def __str__(self): return '\n{0}:\n\tmsg: {1}\n\tparam_name: {2}\n\tvalue: {3}\n'.format( self.__class__.__name__, self.msg, self.device_config_param_name, self.value_given) class DateStringValueError(ValidationError): """Exception raised for errors when a date string was expected for the settings parameter value. Attributes: device_config_param_name -- The name of the Device configuration parameter that has the error. value_given -- the value read from the experiment configuration file. msg -- explanation of the error """ def __init__(self, device_config_param_name, value_given): self.msg = 'A date string value is required for the given Device configuration parameter.' self.device_config_param_name = device_config_param_name self.value_given = value_given def __str__(self): return '\n{0}:\n\tmsg: {1}\n\tparam_name: {2}\n\tvalue: {3}\n'.format( self.__class__.__name__, self.msg, self.device_config_param_name, self.value_given) class NonSupportedValueError(ValidationError): """Exception raised when the configuration value provided does not match one of the possible valid Device configuration parameter values. Attributes: device_config_setting_name -- The name of the Device configuration parameter that has the error. value_given -- the value read from the experiment configuration file. valid_values -- the valid options for the configuration setting. msg -- explanation of the error """ def __init__(self, device_param_name, value_given, valid_values): self.msg = 'A the provided value is not supported for the given Device configuration parameter' self.device_config_param_name = device_param_name self.value_given = value_given self.valid_values = valid_values def __str__(self): return '\n{0}:\n\tmsg: {1}\n\tparam_name: {2}\n\tvalue: {3}\n\tconstraints: {4}'.format( self.__class__.__name__, self.msg, self.device_config_param_name, self.value_given, self.valid_values) MIN_VALID_STR_LENGTH = 1 MAX_VALID_STR_LENGTH = 1024 MIN_VALID_FLOAT_VALUE = 0.0 MAX_VALID_FLOAT_VALUE = 1000000.0 MIN_VALID_INT_VALUE = 0 MAX_VALID_INT_VALUE = 1000000 def is_sequence(arg): return hasattr(arg, "__getitem__") or hasattr(arg, "__iter__") def isValidColor(config_param_name, color, constraints): """ Return color if it is a valid psychopy color (regardless of color space) , otherwise raise error. Color value can be in hex, name, rgb, rgb255 format. """ if isinstance(color, str): if color[0] == '#' or color[0:2].lower() == '0x': rgb255color = colors.hex2rgb255(color) if rgb255color is not None: return color else: raise ColorValueError(config_param_name, color) if color.lower() in colors.colorNames.keys(): return color else: raise ColorValueError(config_param_name, color) if isinstance(color, (float, int)) or (is_sequence(color) and len(color) == 3): colorarray = arraytools.val2array(color, length=3) if colorarray is not None: return color else: raise ColorValueError(config_param_name, color) raise ColorValueError(config_param_name, color) def isValidString(config_param_name, value, constraints): if isinstance(value, str): if value == constraints: # static string return value constraints.setdefault('min_length', MIN_VALID_STR_LENGTH) constraints.setdefault('max_length', MAX_VALID_STR_LENGTH) constraints.setdefault('first_char_alpha', False) min_length = int(constraints.get('min_length')) max_length = int(constraints.get('max_length')) first_char_alpha = bool(constraints.get('first_char_alpha')) if len(value) >= min_length: if len(value) <= max_length: if first_char_alpha is True and value[0].isalpha() is False: raise StringValueError( config_param_name, value, constraints) else: return value elif int(constraints.get('min_length')) == 0 and value is None: return value raise StringValueError(config_param_name, value, constraints) def isValidFloat(config_param_name, value, constraints): if isinstance(value, float): constraints.setdefault('min', MIN_VALID_FLOAT_VALUE) constraints.setdefault('max', MAX_VALID_FLOAT_VALUE) minv = float(constraints.get('min')) maxv = float(constraints.get('max')) if value >= minv: if value <= maxv: return value raise FloatValueError(config_param_name, value, constraints) def isValidInt(config_param_name, value, constraints): if isinstance(value, numbers.Integral): constraints.setdefault('min', MIN_VALID_INT_VALUE) constraints.setdefault('max', MAX_VALID_INT_VALUE) minv = int(constraints.get('min')) maxv = int(constraints.get('max')) if value >= minv: if value <= maxv: return value raise IntValueError(config_param_name, value, constraints) def isBool(config_param_name, value, valid_value): try: value = bool(value) return value except Exception: raise BooleanValueError(config_param_name, value) def isValidIpAddress(config_param_name, value, valid_value): try: socket.inet_aton(value) return value except Exception: raise IpValueError(config_param_name, value) def isValidList(config_param_name, value, constraints): try: min_length = constraints.get('min_length', 1) max_length = constraints.get('max_length', 128) if min_length == 0 and value is None or value == 'None': return value valid_values = constraints.get('valid_values', []) if len(valid_values) == 0: return value if not isinstance(value, (list, tuple)): if value not in valid_values: raise NonSupportedValueError( config_param_name, value, constraints) elif min_length in [0, 1]: return value current_length = len(value) if current_length < min_length or current_length > max_length: raise NonSupportedValueError(config_param_name, value, constraints) for v in value: if v not in valid_values: raise NonSupportedValueError(config_param_name, v, valid_values) return value except Exception: raise NonSupportedValueError(config_param_name, value, constraints) def isValueValid(config_param_name, value, valid_values): if isinstance(value, (list, tuple)): for v in value: if v not in valid_values: raise NonSupportedValueError(config_param_name, value, valid_values) elif value not in valid_values: raise NonSupportedValueError(config_param_name, value, valid_values) return value CONFIG_VALIDATION_KEY_WORD_MAPPINGS = dict( IOHUB_STRING=isValidString, IOHUB_BOOL=isBool, IOHUB_FLOAT=isValidFloat, IOHUB_INT=isValidInt, IOHUB_LIST=isValidList, IOHUB_COLOR=isValidColor, IOHUB_IP_ADDRESS_V4=isValidIpAddress) ############################################### _current_dir = module_directory(isValidString) def buildConfigParamValidatorMapping( device_setting_validation_dict, param_validation_func_mapping, parent_name): for param_name, param_config in device_setting_validation_dict.items(): current_param_path = None if parent_name is None: current_param_path = param_name else: current_param_path = '%s.%s' % (parent_name, param_name) keyword_validator_function = None if isinstance(param_name, str): keyword_validator_function = CONFIG_VALIDATION_KEY_WORD_MAPPINGS.get( param_name, None) if keyword_validator_function: param_validation_func_mapping[ parent_name] = keyword_validator_function, param_config #print2err('ADDED MAPPING1: ', current_param_path, " ", isValueValid, " ", param_config) elif isinstance(param_config, str): keyword_validator_function = CONFIG_VALIDATION_KEY_WORD_MAPPINGS.get( param_config, None) if keyword_validator_function: param_validation_func_mapping[ current_param_path] = keyword_validator_function, {} #print2err('ADDED MAPPING2: ', current_param_path, " ", isValueValid, " ", param_config) else: param_validation_func_mapping[ current_param_path] = isValueValid, [param_config, ] #print2err('ADDED MAPPING3: ', current_param_path, " ", isValueValid, " ", param_config) elif isinstance(param_config, dict): buildConfigParamValidatorMapping( param_config, param_validation_func_mapping, current_param_path) elif isinstance(param_config, (list, tuple)): param_validation_func_mapping[ current_param_path] = isValueValid, param_config #print2err('ADDED MAPPING4: ', current_param_path, " ", isValueValid, " ", param_config) else: param_validation_func_mapping[ current_param_path] = isValueValid, [param_config, ] #print2err('ADDED MAPPING5: ', current_param_path, " ", isValueValid, " ", param_config) def validateConfigDictToFuncMapping( param_validation_func_mapping, current_device_config, parent_param_path): validation_results = dict(errors=[], not_found=[]) for config_param, config_value in current_device_config.items(): if parent_param_path is None: current_param_path = config_param else: current_param_path = '%s.%s' % (parent_param_path, config_param) param_validation = param_validation_func_mapping.get( current_param_path, None) if param_validation: param_validation_func, constraints = param_validation try: param_value = param_validation_func( current_param_path, config_value, constraints) current_device_config[config_param] = param_value # print2err("PARAM {0}, VALUE {1} is VALID.".format(current_param_path,param_value)) except ValidationError: validation_results['errors'].append( (config_param, config_value)) #print2err("Device Config Validation Error: param: {0}, value: {1}\nError: {2}".format(config_param,config_value,e)) elif isinstance(config_value, dict): validateConfigDictToFuncMapping( param_validation_func_mapping, config_value, current_param_path) else: validation_results['not_found'].append( (config_param, config_value)) return validation_results def validateDeviceConfiguration( relative_module_path, device_class_name, current_device_config): """Validate the device configuration settings provided. """ validation_module = importDeviceModule(relative_module_path) validation_file_path = getSupportedConfigSettings(validation_module) # use a default config if we can't get the YAML file if not os.path.exists(validation_file_path): validation_file_path = os.path.join( _current_dir, relative_module_path[len('psychopy.iohub.devices.'):].replace( '.', os.path.sep), 'supported_config_settings.yaml') device_settings_validation_dict = yload( open(validation_file_path, 'r'), Loader=yLoader) device_settings_validation_dict = device_settings_validation_dict[ list(device_settings_validation_dict.keys())[0]] param_validation_func_mapping = dict() parent_config_param_path = None buildConfigParamValidatorMapping( device_settings_validation_dict, param_validation_func_mapping, parent_config_param_path) validation_results = validateConfigDictToFuncMapping( param_validation_func_mapping, current_device_config, None) return validation_results
20,488
Python
.py
412
40.873786
136
0.661993
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,668
xlib.py
psychopy_psychopy/psychopy/iohub/devices/xlib.py
''' Copied from pyglet 1.2 lib/x11 Wrapper for X11 Generated with: tools/genwrappers.py xlib Do not modify this file. ''' __docformat__ = 'restructuredtext' __version__ = '$Id$' import ctypes from ctypes import * import pyglet.lib _lib = pyglet.lib.load_library('X11') _int_types = (c_int16, c_int32) if hasattr(ctypes, 'c_int64'): # Some builds of ctypes apparently do not have c_int64 # defined; it's a pretty good bet that these builds do not # have 64-bit pointers. _int_types += (ctypes.c_int64,) for t in _int_types: if sizeof(t) == sizeof(c_size_t): c_ptrdiff_t = t class c_void(Structure): # c_void_p is a buggy return type, converting to int, so # POINTER(None) == c_void_p is actually written as # POINTER(c_void), so it can be treated as a real pointer. _fields_ = [('dummy', c_int)] XlibSpecificationRelease = 6 # /usr/include/X11/Xlib.h:39 X_PROTOCOL = 11 # /usr/include/X11/X.h:53 X_PROTOCOL_REVISION = 0 # /usr/include/X11/X.h:54 XID = c_ulong # /usr/include/X11/X.h:66 Mask = c_ulong # /usr/include/X11/X.h:70 Atom = c_ulong # /usr/include/X11/X.h:74 VisualID = c_ulong # /usr/include/X11/X.h:76 Time = c_ulong # /usr/include/X11/X.h:77 Window = XID # /usr/include/X11/X.h:96 Drawable = XID # /usr/include/X11/X.h:97 Font = XID # /usr/include/X11/X.h:100 Pixmap = XID # /usr/include/X11/X.h:102 Cursor = XID # /usr/include/X11/X.h:103 Colormap = XID # /usr/include/X11/X.h:104 GContext = XID # /usr/include/X11/X.h:105 KeySym = XID # /usr/include/X11/X.h:106 KeyCode = c_ubyte # /usr/include/X11/X.h:108 None_ = 0 # /usr/include/X11/X.h:115 ParentRelative = 1 # /usr/include/X11/X.h:118 CopyFromParent = 0 # /usr/include/X11/X.h:121 PointerWindow = 0 # /usr/include/X11/X.h:126 InputFocus = 1 # /usr/include/X11/X.h:127 PointerRoot = 1 # /usr/include/X11/X.h:129 AnyPropertyType = 0 # /usr/include/X11/X.h:131 AnyKey = 0 # /usr/include/X11/X.h:133 AnyButton = 0 # /usr/include/X11/X.h:135 AllTemporary = 0 # /usr/include/X11/X.h:137 CurrentTime = 0 # /usr/include/X11/X.h:139 NoSymbol = 0 # /usr/include/X11/X.h:141 NoEventMask = 0 # /usr/include/X11/X.h:150 KeyPressMask = 1 # /usr/include/X11/X.h:151 KeyReleaseMask = 2 # /usr/include/X11/X.h:152 ButtonPressMask = 4 # /usr/include/X11/X.h:153 ButtonReleaseMask = 8 # /usr/include/X11/X.h:154 EnterWindowMask = 16 # /usr/include/X11/X.h:155 LeaveWindowMask = 32 # /usr/include/X11/X.h:156 PointerMotionMask = 64 # /usr/include/X11/X.h:157 PointerMotionHintMask = 128 # /usr/include/X11/X.h:158 Button1MotionMask = 256 # /usr/include/X11/X.h:159 Button2MotionMask = 512 # /usr/include/X11/X.h:160 Button3MotionMask = 1024 # /usr/include/X11/X.h:161 Button4MotionMask = 2048 # /usr/include/X11/X.h:162 Button5MotionMask = 4096 # /usr/include/X11/X.h:163 ButtonMotionMask = 8192 # /usr/include/X11/X.h:164 KeymapStateMask = 16384 # /usr/include/X11/X.h:165 ExposureMask = 32768 # /usr/include/X11/X.h:166 VisibilityChangeMask = 65536 # /usr/include/X11/X.h:167 StructureNotifyMask = 131072 # /usr/include/X11/X.h:168 ResizeRedirectMask = 262144 # /usr/include/X11/X.h:169 SubstructureNotifyMask = 524288 # /usr/include/X11/X.h:170 SubstructureRedirectMask = 1048576 # /usr/include/X11/X.h:171 FocusChangeMask = 2097152 # /usr/include/X11/X.h:172 PropertyChangeMask = 4194304 # /usr/include/X11/X.h:173 ColormapChangeMask = 8388608 # /usr/include/X11/X.h:174 OwnerGrabButtonMask = 16777216 # /usr/include/X11/X.h:175 KeyPress = 2 # /usr/include/X11/X.h:181 KeyRelease = 3 # /usr/include/X11/X.h:182 ButtonPress = 4 # /usr/include/X11/X.h:183 ButtonRelease = 5 # /usr/include/X11/X.h:184 MotionNotify = 6 # /usr/include/X11/X.h:185 EnterNotify = 7 # /usr/include/X11/X.h:186 LeaveNotify = 8 # /usr/include/X11/X.h:187 FocusIn = 9 # /usr/include/X11/X.h:188 FocusOut = 10 # /usr/include/X11/X.h:189 KeymapNotify = 11 # /usr/include/X11/X.h:190 Expose = 12 # /usr/include/X11/X.h:191 GraphicsExpose = 13 # /usr/include/X11/X.h:192 NoExpose = 14 # /usr/include/X11/X.h:193 VisibilityNotify = 15 # /usr/include/X11/X.h:194 CreateNotify = 16 # /usr/include/X11/X.h:195 DestroyNotify = 17 # /usr/include/X11/X.h:196 UnmapNotify = 18 # /usr/include/X11/X.h:197 MapNotify = 19 # /usr/include/X11/X.h:198 MapRequest = 20 # /usr/include/X11/X.h:199 ReparentNotify = 21 # /usr/include/X11/X.h:200 ConfigureNotify = 22 # /usr/include/X11/X.h:201 ConfigureRequest = 23 # /usr/include/X11/X.h:202 GravityNotify = 24 # /usr/include/X11/X.h:203 ResizeRequest = 25 # /usr/include/X11/X.h:204 CirculateNotify = 26 # /usr/include/X11/X.h:205 CirculateRequest = 27 # /usr/include/X11/X.h:206 PropertyNotify = 28 # /usr/include/X11/X.h:207 SelectionClear = 29 # /usr/include/X11/X.h:208 SelectionRequest = 30 # /usr/include/X11/X.h:209 SelectionNotify = 31 # /usr/include/X11/X.h:210 ColormapNotify = 32 # /usr/include/X11/X.h:211 ClientMessage = 33 # /usr/include/X11/X.h:212 MappingNotify = 34 # /usr/include/X11/X.h:213 GenericEvent = 35 # /usr/include/X11/X.h:214 LASTEvent = 36 # /usr/include/X11/X.h:215 ShiftMask = 1 # /usr/include/X11/X.h:221 LockMask = 2 # /usr/include/X11/X.h:222 ControlMask = 4 # /usr/include/X11/X.h:223 Mod1Mask = 8 # /usr/include/X11/X.h:224 Mod2Mask = 16 # /usr/include/X11/X.h:225 Mod3Mask = 32 # /usr/include/X11/X.h:226 Mod4Mask = 64 # /usr/include/X11/X.h:227 Mod5Mask = 128 # /usr/include/X11/X.h:228 ShiftMapIndex = 0 # /usr/include/X11/X.h:233 LockMapIndex = 1 # /usr/include/X11/X.h:234 ControlMapIndex = 2 # /usr/include/X11/X.h:235 Mod1MapIndex = 3 # /usr/include/X11/X.h:236 Mod2MapIndex = 4 # /usr/include/X11/X.h:237 Mod3MapIndex = 5 # /usr/include/X11/X.h:238 Mod4MapIndex = 6 # /usr/include/X11/X.h:239 Mod5MapIndex = 7 # /usr/include/X11/X.h:240 Button1Mask = 256 # /usr/include/X11/X.h:246 Button2Mask = 512 # /usr/include/X11/X.h:247 Button3Mask = 1024 # /usr/include/X11/X.h:248 Button4Mask = 2048 # /usr/include/X11/X.h:249 Button5Mask = 4096 # /usr/include/X11/X.h:250 AnyModifier = 32768 # /usr/include/X11/X.h:252 Button1 = 1 # /usr/include/X11/X.h:259 Button2 = 2 # /usr/include/X11/X.h:260 Button3 = 3 # /usr/include/X11/X.h:261 Button4 = 4 # /usr/include/X11/X.h:262 Button5 = 5 # /usr/include/X11/X.h:263 NotifyNormal = 0 # /usr/include/X11/X.h:267 NotifyGrab = 1 # /usr/include/X11/X.h:268 NotifyUngrab = 2 # /usr/include/X11/X.h:269 NotifyWhileGrabbed = 3 # /usr/include/X11/X.h:270 NotifyHint = 1 # /usr/include/X11/X.h:272 NotifyAncestor = 0 # /usr/include/X11/X.h:276 NotifyVirtual = 1 # /usr/include/X11/X.h:277 NotifyInferior = 2 # /usr/include/X11/X.h:278 NotifyNonlinear = 3 # /usr/include/X11/X.h:279 NotifyNonlinearVirtual = 4 # /usr/include/X11/X.h:280 NotifyPointer = 5 # /usr/include/X11/X.h:281 NotifyPointerRoot = 6 # /usr/include/X11/X.h:282 NotifyDetailNone = 7 # /usr/include/X11/X.h:283 VisibilityUnobscured = 0 # /usr/include/X11/X.h:287 VisibilityPartiallyObscured = 1 # /usr/include/X11/X.h:288 VisibilityFullyObscured = 2 # /usr/include/X11/X.h:289 PlaceOnTop = 0 # /usr/include/X11/X.h:293 PlaceOnBottom = 1 # /usr/include/X11/X.h:294 FamilyInternet = 0 # /usr/include/X11/X.h:298 FamilyDECnet = 1 # /usr/include/X11/X.h:299 FamilyChaos = 2 # /usr/include/X11/X.h:300 FamilyInternet6 = 6 # /usr/include/X11/X.h:301 FamilyServerInterpreted = 5 # /usr/include/X11/X.h:304 PropertyNewValue = 0 # /usr/include/X11/X.h:308 PropertyDelete = 1 # /usr/include/X11/X.h:309 ColormapUninstalled = 0 # /usr/include/X11/X.h:313 ColormapInstalled = 1 # /usr/include/X11/X.h:314 GrabModeSync = 0 # /usr/include/X11/X.h:318 GrabModeAsync = 1 # /usr/include/X11/X.h:319 GrabSuccess = 0 # /usr/include/X11/X.h:323 AlreadyGrabbed = 1 # /usr/include/X11/X.h:324 GrabInvalidTime = 2 # /usr/include/X11/X.h:325 GrabNotViewable = 3 # /usr/include/X11/X.h:326 GrabFrozen = 4 # /usr/include/X11/X.h:327 AsyncPointer = 0 # /usr/include/X11/X.h:331 SyncPointer = 1 # /usr/include/X11/X.h:332 ReplayPointer = 2 # /usr/include/X11/X.h:333 AsyncKeyboard = 3 # /usr/include/X11/X.h:334 SyncKeyboard = 4 # /usr/include/X11/X.h:335 ReplayKeyboard = 5 # /usr/include/X11/X.h:336 AsyncBoth = 6 # /usr/include/X11/X.h:337 SyncBoth = 7 # /usr/include/X11/X.h:338 RevertToParent = 2 # /usr/include/X11/X.h:344 Success = 0 # /usr/include/X11/X.h:350 BadRequest = 1 # /usr/include/X11/X.h:351 BadValue = 2 # /usr/include/X11/X.h:352 BadWindow = 3 # /usr/include/X11/X.h:353 BadPixmap = 4 # /usr/include/X11/X.h:354 BadAtom = 5 # /usr/include/X11/X.h:355 BadCursor = 6 # /usr/include/X11/X.h:356 BadFont = 7 # /usr/include/X11/X.h:357 BadMatch = 8 # /usr/include/X11/X.h:358 BadDrawable = 9 # /usr/include/X11/X.h:359 BadAccess = 10 # /usr/include/X11/X.h:360 BadAlloc = 11 # /usr/include/X11/X.h:369 BadColor = 12 # /usr/include/X11/X.h:370 BadGC = 13 # /usr/include/X11/X.h:371 BadIDChoice = 14 # /usr/include/X11/X.h:372 BadName = 15 # /usr/include/X11/X.h:373 BadLength = 16 # /usr/include/X11/X.h:374 BadImplementation = 17 # /usr/include/X11/X.h:375 FirstExtensionError = 128 # /usr/include/X11/X.h:377 LastExtensionError = 255 # /usr/include/X11/X.h:378 InputOutput = 1 # /usr/include/X11/X.h:387 InputOnly = 2 # /usr/include/X11/X.h:388 CWBackPixmap = 1 # /usr/include/X11/X.h:392 CWBackPixel = 2 # /usr/include/X11/X.h:393 CWBorderPixmap = 4 # /usr/include/X11/X.h:394 CWBorderPixel = 8 # /usr/include/X11/X.h:395 CWBitGravity = 16 # /usr/include/X11/X.h:396 CWWinGravity = 32 # /usr/include/X11/X.h:397 CWBackingStore = 64 # /usr/include/X11/X.h:398 CWBackingPlanes = 128 # /usr/include/X11/X.h:399 CWBackingPixel = 256 # /usr/include/X11/X.h:400 CWOverrideRedirect = 512 # /usr/include/X11/X.h:401 CWSaveUnder = 1024 # /usr/include/X11/X.h:402 CWEventMask = 2048 # /usr/include/X11/X.h:403 CWDontPropagate = 4096 # /usr/include/X11/X.h:404 CWColormap = 8192 # /usr/include/X11/X.h:405 CWCursor = 16384 # /usr/include/X11/X.h:406 CWX = 1 # /usr/include/X11/X.h:410 CWY = 2 # /usr/include/X11/X.h:411 CWWidth = 4 # /usr/include/X11/X.h:412 CWHeight = 8 # /usr/include/X11/X.h:413 CWBorderWidth = 16 # /usr/include/X11/X.h:414 CWSibling = 32 # /usr/include/X11/X.h:415 CWStackMode = 64 # /usr/include/X11/X.h:416 ForgetGravity = 0 # /usr/include/X11/X.h:421 NorthWestGravity = 1 # /usr/include/X11/X.h:422 NorthGravity = 2 # /usr/include/X11/X.h:423 NorthEastGravity = 3 # /usr/include/X11/X.h:424 WestGravity = 4 # /usr/include/X11/X.h:425 CenterGravity = 5 # /usr/include/X11/X.h:426 EastGravity = 6 # /usr/include/X11/X.h:427 SouthWestGravity = 7 # /usr/include/X11/X.h:428 SouthGravity = 8 # /usr/include/X11/X.h:429 SouthEastGravity = 9 # /usr/include/X11/X.h:430 StaticGravity = 10 # /usr/include/X11/X.h:431 UnmapGravity = 0 # /usr/include/X11/X.h:435 NotUseful = 0 # /usr/include/X11/X.h:439 WhenMapped = 1 # /usr/include/X11/X.h:440 Always = 2 # /usr/include/X11/X.h:441 IsUnmapped = 0 # /usr/include/X11/X.h:445 IsUnviewable = 1 # /usr/include/X11/X.h:446 IsViewable = 2 # /usr/include/X11/X.h:447 SetModeInsert = 0 # /usr/include/X11/X.h:451 SetModeDelete = 1 # /usr/include/X11/X.h:452 DestroyAll = 0 # /usr/include/X11/X.h:456 RetainPermanent = 1 # /usr/include/X11/X.h:457 RetainTemporary = 2 # /usr/include/X11/X.h:458 Above = 0 # /usr/include/X11/X.h:462 Below = 1 # /usr/include/X11/X.h:463 TopIf = 2 # /usr/include/X11/X.h:464 BottomIf = 3 # /usr/include/X11/X.h:465 Opposite = 4 # /usr/include/X11/X.h:466 RaiseLowest = 0 # /usr/include/X11/X.h:470 LowerHighest = 1 # /usr/include/X11/X.h:471 PropModeReplace = 0 # /usr/include/X11/X.h:475 PropModePrepend = 1 # /usr/include/X11/X.h:476 PropModeAppend = 2 # /usr/include/X11/X.h:477 GXclear = 0 # /usr/include/X11/X.h:485 GXand = 1 # /usr/include/X11/X.h:486 GXandReverse = 2 # /usr/include/X11/X.h:487 GXcopy = 3 # /usr/include/X11/X.h:488 GXandInverted = 4 # /usr/include/X11/X.h:489 GXnoop = 5 # /usr/include/X11/X.h:490 GXxor = 6 # /usr/include/X11/X.h:491 GXor = 7 # /usr/include/X11/X.h:492 GXnor = 8 # /usr/include/X11/X.h:493 GXequiv = 9 # /usr/include/X11/X.h:494 GXinvert = 10 # /usr/include/X11/X.h:495 GXorReverse = 11 # /usr/include/X11/X.h:496 GXcopyInverted = 12 # /usr/include/X11/X.h:497 GXorInverted = 13 # /usr/include/X11/X.h:498 GXnand = 14 # /usr/include/X11/X.h:499 GXset = 15 # /usr/include/X11/X.h:500 LineSolid = 0 # /usr/include/X11/X.h:504 LineOnOffDash = 1 # /usr/include/X11/X.h:505 LineDoubleDash = 2 # /usr/include/X11/X.h:506 CapNotLast = 0 # /usr/include/X11/X.h:510 CapButt = 1 # /usr/include/X11/X.h:511 CapRound = 2 # /usr/include/X11/X.h:512 CapProjecting = 3 # /usr/include/X11/X.h:513 JoinMiter = 0 # /usr/include/X11/X.h:517 JoinRound = 1 # /usr/include/X11/X.h:518 JoinBevel = 2 # /usr/include/X11/X.h:519 FillSolid = 0 # /usr/include/X11/X.h:523 FillTiled = 1 # /usr/include/X11/X.h:524 FillStippled = 2 # /usr/include/X11/X.h:525 FillOpaqueStippled = 3 # /usr/include/X11/X.h:526 EvenOddRule = 0 # /usr/include/X11/X.h:530 WindingRule = 1 # /usr/include/X11/X.h:531 ClipByChildren = 0 # /usr/include/X11/X.h:535 IncludeInferiors = 1 # /usr/include/X11/X.h:536 Unsorted = 0 # /usr/include/X11/X.h:540 YSorted = 1 # /usr/include/X11/X.h:541 YXSorted = 2 # /usr/include/X11/X.h:542 YXBanded = 3 # /usr/include/X11/X.h:543 CoordModeOrigin = 0 # /usr/include/X11/X.h:547 CoordModePrevious = 1 # /usr/include/X11/X.h:548 Complex = 0 # /usr/include/X11/X.h:552 Nonconvex = 1 # /usr/include/X11/X.h:553 Convex = 2 # /usr/include/X11/X.h:554 ArcChord = 0 # /usr/include/X11/X.h:558 ArcPieSlice = 1 # /usr/include/X11/X.h:559 GCFunction = 1 # /usr/include/X11/X.h:564 GCPlaneMask = 2 # /usr/include/X11/X.h:565 GCForeground = 4 # /usr/include/X11/X.h:566 GCBackground = 8 # /usr/include/X11/X.h:567 GCLineWidth = 16 # /usr/include/X11/X.h:568 GCLineStyle = 32 # /usr/include/X11/X.h:569 GCCapStyle = 64 # /usr/include/X11/X.h:570 GCJoinStyle = 128 # /usr/include/X11/X.h:571 GCFillStyle = 256 # /usr/include/X11/X.h:572 GCFillRule = 512 # /usr/include/X11/X.h:573 GCTile = 1024 # /usr/include/X11/X.h:574 GCStipple = 2048 # /usr/include/X11/X.h:575 GCTileStipXOrigin = 4096 # /usr/include/X11/X.h:576 GCTileStipYOrigin = 8192 # /usr/include/X11/X.h:577 GCFont = 16384 # /usr/include/X11/X.h:578 GCSubwindowMode = 32768 # /usr/include/X11/X.h:579 GCGraphicsExposures = 65536 # /usr/include/X11/X.h:580 GCClipXOrigin = 131072 # /usr/include/X11/X.h:581 GCClipYOrigin = 262144 # /usr/include/X11/X.h:582 GCClipMask = 524288 # /usr/include/X11/X.h:583 GCDashOffset = 1048576 # /usr/include/X11/X.h:584 GCDashList = 2097152 # /usr/include/X11/X.h:585 GCArcMode = 4194304 # /usr/include/X11/X.h:586 GCLastBit = 22 # /usr/include/X11/X.h:588 FontLeftToRight = 0 # /usr/include/X11/X.h:595 FontRightToLeft = 1 # /usr/include/X11/X.h:596 FontChange = 255 # /usr/include/X11/X.h:598 XYBitmap = 0 # /usr/include/X11/X.h:606 XYPixmap = 1 # /usr/include/X11/X.h:607 ZPixmap = 2 # /usr/include/X11/X.h:608 AllocNone = 0 # /usr/include/X11/X.h:616 AllocAll = 1 # /usr/include/X11/X.h:617 DoRed = 1 # /usr/include/X11/X.h:622 DoGreen = 2 # /usr/include/X11/X.h:623 DoBlue = 4 # /usr/include/X11/X.h:624 CursorShape = 0 # /usr/include/X11/X.h:632 TileShape = 1 # /usr/include/X11/X.h:633 StippleShape = 2 # /usr/include/X11/X.h:634 AutoRepeatModeOff = 0 # /usr/include/X11/X.h:640 AutoRepeatModeOn = 1 # /usr/include/X11/X.h:641 AutoRepeatModeDefault = 2 # /usr/include/X11/X.h:642 LedModeOff = 0 # /usr/include/X11/X.h:644 LedModeOn = 1 # /usr/include/X11/X.h:645 KBKeyClickPercent = 1 # /usr/include/X11/X.h:649 KBBellPercent = 2 # /usr/include/X11/X.h:650 KBBellPitch = 4 # /usr/include/X11/X.h:651 KBBellDuration = 8 # /usr/include/X11/X.h:652 KBLed = 16 # /usr/include/X11/X.h:653 KBLedMode = 32 # /usr/include/X11/X.h:654 KBKey = 64 # /usr/include/X11/X.h:655 KBAutoRepeatMode = 128 # /usr/include/X11/X.h:656 MappingSuccess = 0 # /usr/include/X11/X.h:658 MappingBusy = 1 # /usr/include/X11/X.h:659 MappingFailed = 2 # /usr/include/X11/X.h:660 MappingModifier = 0 # /usr/include/X11/X.h:662 MappingKeyboard = 1 # /usr/include/X11/X.h:663 MappingPointer = 2 # /usr/include/X11/X.h:664 DontPreferBlanking = 0 # /usr/include/X11/X.h:670 PreferBlanking = 1 # /usr/include/X11/X.h:671 DefaultBlanking = 2 # /usr/include/X11/X.h:672 DisableScreenSaver = 0 # /usr/include/X11/X.h:674 DisableScreenInterval = 0 # /usr/include/X11/X.h:675 DontAllowExposures = 0 # /usr/include/X11/X.h:677 AllowExposures = 1 # /usr/include/X11/X.h:678 DefaultExposures = 2 # /usr/include/X11/X.h:679 ScreenSaverReset = 0 # /usr/include/X11/X.h:683 ScreenSaverActive = 1 # /usr/include/X11/X.h:684 HostInsert = 0 # /usr/include/X11/X.h:692 HostDelete = 1 # /usr/include/X11/X.h:693 EnableAccess = 1 # /usr/include/X11/X.h:697 DisableAccess = 0 # /usr/include/X11/X.h:698 StaticGray = 0 # /usr/include/X11/X.h:704 GrayScale = 1 # /usr/include/X11/X.h:705 StaticColor = 2 # /usr/include/X11/X.h:706 PseudoColor = 3 # /usr/include/X11/X.h:707 TrueColor = 4 # /usr/include/X11/X.h:708 DirectColor = 5 # /usr/include/X11/X.h:709 LSBFirst = 0 # /usr/include/X11/X.h:714 MSBFirst = 1 # /usr/include/X11/X.h:715 # /usr/include/X11/Xlib.h:73 _Xmblen = _lib._Xmblen _Xmblen.restype = c_int _Xmblen.argtypes = [c_char_p, c_int] X_HAVE_UTF8_STRING = 1 # /usr/include/X11/Xlib.h:85 XPointer = c_char_p # /usr/include/X11/Xlib.h:87 Bool = c_int # /usr/include/X11/Xlib.h:89 Status = c_int # /usr/include/X11/Xlib.h:90 True_ = 1 # /usr/include/X11/Xlib.h:91 False_ = 0 # /usr/include/X11/Xlib.h:92 QueuedAlready = 0 # /usr/include/X11/Xlib.h:94 QueuedAfterReading = 1 # /usr/include/X11/Xlib.h:95 QueuedAfterFlush = 2 # /usr/include/X11/Xlib.h:96 class struct__XExtData(Structure): __slots__ = [ 'number', 'next', 'free_private', 'private_data', ] struct__XExtData._fields_ = [ ('number', c_int), ('next', POINTER(struct__XExtData)), ('free_private', POINTER(CFUNCTYPE(c_int, POINTER(struct__XExtData)))), ('private_data', XPointer), ] XExtData = struct__XExtData # /usr/include/X11/Xlib.h:166 class struct_anon_15(Structure): __slots__ = [ 'extension', 'major_opcode', 'first_event', 'first_error', ] struct_anon_15._fields_ = [ ('extension', c_int), ('major_opcode', c_int), ('first_event', c_int), ('first_error', c_int), ] XExtCodes = struct_anon_15 # /usr/include/X11/Xlib.h:176 class struct_anon_16(Structure): __slots__ = [ 'depth', 'bits_per_pixel', 'scanline_pad', ] struct_anon_16._fields_ = [ ('depth', c_int), ('bits_per_pixel', c_int), ('scanline_pad', c_int), ] XPixmapFormatValues = struct_anon_16 # /usr/include/X11/Xlib.h:186 class struct_anon_17(Structure): __slots__ = [ 'function', 'plane_mask', 'foreground', 'background', 'line_width', 'line_style', 'cap_style', 'join_style', 'fill_style', 'fill_rule', 'arc_mode', 'tile', 'stipple', 'ts_x_origin', 'ts_y_origin', 'font', 'subwindow_mode', 'graphics_exposures', 'clip_x_origin', 'clip_y_origin', 'clip_mask', 'dash_offset', 'dashes', ] struct_anon_17._fields_ = [ ('function', c_int), ('plane_mask', c_ulong), ('foreground', c_ulong), ('background', c_ulong), ('line_width', c_int), ('line_style', c_int), ('cap_style', c_int), ('join_style', c_int), ('fill_style', c_int), ('fill_rule', c_int), ('arc_mode', c_int), ('tile', Pixmap), ('stipple', Pixmap), ('ts_x_origin', c_int), ('ts_y_origin', c_int), ('font', Font), ('subwindow_mode', c_int), ('graphics_exposures', c_int), ('clip_x_origin', c_int), ('clip_y_origin', c_int), ('clip_mask', Pixmap), ('dash_offset', c_int), ('dashes', c_char), ] XGCValues = struct_anon_17 # /usr/include/X11/Xlib.h:218 class struct__XGC(Structure): __slots__ = [ ] struct__XGC._fields_ = [ ('_opaque_struct', c_int) ] class struct__XGC(Structure): __slots__ = [ ] struct__XGC._fields_ = [ ('_opaque_struct', c_int) ] GC = POINTER(struct__XGC) # /usr/include/X11/Xlib.h:233 class struct_anon_18(Structure): __slots__ = [ 'ext_data', 'visualid', 'class', 'red_mask', 'green_mask', 'blue_mask', 'bits_per_rgb', 'map_entries', ] struct_anon_18._fields_ = [ ('ext_data', POINTER(XExtData)), ('visualid', VisualID), ('class', c_int), ('red_mask', c_ulong), ('green_mask', c_ulong), ('blue_mask', c_ulong), ('bits_per_rgb', c_int), ('map_entries', c_int), ] Visual = struct_anon_18 # /usr/include/X11/Xlib.h:249 class struct_anon_19(Structure): __slots__ = [ 'depth', 'nvisuals', 'visuals', ] struct_anon_19._fields_ = [ ('depth', c_int), ('nvisuals', c_int), ('visuals', POINTER(Visual)), ] Depth = struct_anon_19 # /usr/include/X11/Xlib.h:258 class struct_anon_20(Structure): __slots__ = [ 'ext_data', 'display', 'root', 'width', 'height', 'mwidth', 'mheight', 'ndepths', 'depths', 'root_depth', 'root_visual', 'default_gc', 'cmap', 'white_pixel', 'black_pixel', 'max_maps', 'min_maps', 'backing_store', 'save_unders', 'root_input_mask', ] class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] struct_anon_20._fields_ = [ ('ext_data', POINTER(XExtData)), ('display', POINTER(struct__XDisplay)), ('root', Window), ('width', c_int), ('height', c_int), ('mwidth', c_int), ('mheight', c_int), ('ndepths', c_int), ('depths', POINTER(Depth)), ('root_depth', c_int), ('root_visual', POINTER(Visual)), ('default_gc', GC), ('cmap', Colormap), ('white_pixel', c_ulong), ('black_pixel', c_ulong), ('max_maps', c_int), ('min_maps', c_int), ('backing_store', c_int), ('save_unders', c_int), ('root_input_mask', c_long), ] Screen = struct_anon_20 # /usr/include/X11/Xlib.h:286 class struct_anon_21(Structure): __slots__ = [ 'ext_data', 'depth', 'bits_per_pixel', 'scanline_pad', ] struct_anon_21._fields_ = [ ('ext_data', POINTER(XExtData)), ('depth', c_int), ('bits_per_pixel', c_int), ('scanline_pad', c_int), ] ScreenFormat = struct_anon_21 # /usr/include/X11/Xlib.h:296 class struct_anon_22(Structure): __slots__ = [ 'background_pixmap', 'background_pixel', 'border_pixmap', 'border_pixel', 'bit_gravity', 'win_gravity', 'backing_store', 'backing_planes', 'backing_pixel', 'save_under', 'event_mask', 'do_not_propagate_mask', 'override_redirect', 'colormap', 'cursor', ] struct_anon_22._fields_ = [ ('background_pixmap', Pixmap), ('background_pixel', c_ulong), ('border_pixmap', Pixmap), ('border_pixel', c_ulong), ('bit_gravity', c_int), ('win_gravity', c_int), ('backing_store', c_int), ('backing_planes', c_ulong), ('backing_pixel', c_ulong), ('save_under', c_int), ('event_mask', c_long), ('do_not_propagate_mask', c_long), ('override_redirect', c_int), ('colormap', Colormap), ('cursor', Cursor), ] XSetWindowAttributes = struct_anon_22 # /usr/include/X11/Xlib.h:317 class struct_anon_23(Structure): __slots__ = [ 'x', 'y', 'width', 'height', 'border_width', 'depth', 'visual', 'root', 'class', 'bit_gravity', 'win_gravity', 'backing_store', 'backing_planes', 'backing_pixel', 'save_under', 'colormap', 'map_installed', 'map_state', 'all_event_masks', 'your_event_mask', 'do_not_propagate_mask', 'override_redirect', 'screen', ] struct_anon_23._fields_ = [ ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('border_width', c_int), ('depth', c_int), ('visual', POINTER(Visual)), ('root', Window), ('class', c_int), ('bit_gravity', c_int), ('win_gravity', c_int), ('backing_store', c_int), ('backing_planes', c_ulong), ('backing_pixel', c_ulong), ('save_under', c_int), ('colormap', Colormap), ('map_installed', c_int), ('map_state', c_int), ('all_event_masks', c_long), ('your_event_mask', c_long), ('do_not_propagate_mask', c_long), ('override_redirect', c_int), ('screen', POINTER(Screen)), ] XWindowAttributes = struct_anon_23 # /usr/include/X11/Xlib.h:345 class struct_anon_24(Structure): __slots__ = [ 'family', 'length', 'address', ] struct_anon_24._fields_ = [ ('family', c_int), ('length', c_int), ('address', c_char_p), ] XHostAddress = struct_anon_24 # /usr/include/X11/Xlib.h:356 class struct_anon_25(Structure): __slots__ = [ 'typelength', 'valuelength', 'type', 'value', ] struct_anon_25._fields_ = [ ('typelength', c_int), ('valuelength', c_int), ('type', c_char_p), ('value', c_char_p), ] XServerInterpretedAddress = struct_anon_25 # /usr/include/X11/Xlib.h:366 class struct__XImage(Structure): __slots__ = [ 'width', 'height', 'xoffset', 'format', 'data', 'byte_order', 'bitmap_unit', 'bitmap_bit_order', 'bitmap_pad', 'depth', 'bytes_per_line', 'bits_per_pixel', 'red_mask', 'green_mask', 'blue_mask', 'obdata', 'f', ] class struct_funcs(Structure): __slots__ = [ 'create_image', 'destroy_image', 'get_pixel', 'put_pixel', 'sub_image', 'add_pixel', ] class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] struct_funcs._fields_ = [ ('create_image', POINTER( CFUNCTYPE( POINTER(struct__XImage), POINTER(struct__XDisplay), POINTER(Visual), c_uint, c_int, c_int, c_char_p, c_uint, c_uint, c_int, c_int))), ('destroy_image', POINTER( CFUNCTYPE( c_int, POINTER(struct__XImage)))), ('get_pixel', POINTER( CFUNCTYPE( c_ulong, POINTER(struct__XImage), c_int, c_int))), ('put_pixel', POINTER( CFUNCTYPE( c_int, POINTER(struct__XImage), c_int, c_int, c_ulong))), ('sub_image', POINTER( CFUNCTYPE( POINTER(struct__XImage), POINTER(struct__XImage), c_int, c_int, c_uint, c_uint))), ('add_pixel', POINTER( CFUNCTYPE( c_int, POINTER(struct__XImage), c_long))), ] struct__XImage._fields_ = [ ('width', c_int), ('height', c_int), ('xoffset', c_int), ('format', c_int), ('data', c_char_p), ('byte_order', c_int), ('bitmap_unit', c_int), ('bitmap_bit_order', c_int), ('bitmap_pad', c_int), ('depth', c_int), ('bytes_per_line', c_int), ('bits_per_pixel', c_int), ('red_mask', c_ulong), ('green_mask', c_ulong), ('blue_mask', c_ulong), ('obdata', XPointer), ('f', struct_funcs), ] XImage = struct__XImage # /usr/include/X11/Xlib.h:405 class struct_anon_26(Structure): __slots__ = [ 'x', 'y', 'width', 'height', 'border_width', 'sibling', 'stack_mode', ] struct_anon_26._fields_ = [ ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('border_width', c_int), ('sibling', Window), ('stack_mode', c_int), ] XWindowChanges = struct_anon_26 # /usr/include/X11/Xlib.h:416 class struct_anon_27(Structure): __slots__ = [ 'pixel', 'red', 'green', 'blue', 'flags', 'pad', ] struct_anon_27._fields_ = [ ('pixel', c_ulong), ('red', c_ushort), ('green', c_ushort), ('blue', c_ushort), ('flags', c_char), ('pad', c_char), ] XColor = struct_anon_27 # /usr/include/X11/Xlib.h:426 class struct_anon_28(Structure): __slots__ = [ 'x1', 'y1', 'x2', 'y2', ] struct_anon_28._fields_ = [ ('x1', c_short), ('y1', c_short), ('x2', c_short), ('y2', c_short), ] XSegment = struct_anon_28 # /usr/include/X11/Xlib.h:435 class struct_anon_29(Structure): __slots__ = [ 'x', 'y', ] struct_anon_29._fields_ = [ ('x', c_short), ('y', c_short), ] XPoint = struct_anon_29 # /usr/include/X11/Xlib.h:439 class struct_anon_30(Structure): __slots__ = [ 'x', 'y', 'width', 'height', ] struct_anon_30._fields_ = [ ('x', c_short), ('y', c_short), ('width', c_ushort), ('height', c_ushort), ] XRectangle = struct_anon_30 # /usr/include/X11/Xlib.h:444 class struct_anon_31(Structure): __slots__ = [ 'x', 'y', 'width', 'height', 'angle1', 'angle2', ] struct_anon_31._fields_ = [ ('x', c_short), ('y', c_short), ('width', c_ushort), ('height', c_ushort), ('angle1', c_short), ('angle2', c_short), ] XArc = struct_anon_31 # /usr/include/X11/Xlib.h:450 class struct_anon_32(Structure): __slots__ = [ 'key_click_percent', 'bell_percent', 'bell_pitch', 'bell_duration', 'led', 'led_mode', 'key', 'auto_repeat_mode', ] struct_anon_32._fields_ = [ ('key_click_percent', c_int), ('bell_percent', c_int), ('bell_pitch', c_int), ('bell_duration', c_int), ('led', c_int), ('led_mode', c_int), ('key', c_int), ('auto_repeat_mode', c_int), ] XKeyboardControl = struct_anon_32 # /usr/include/X11/Xlib.h:464 class struct_anon_33(Structure): __slots__ = [ 'key_click_percent', 'bell_percent', 'bell_pitch', 'bell_duration', 'led_mask', 'global_auto_repeat', 'auto_repeats', ] struct_anon_33._fields_ = [ ('key_click_percent', c_int), ('bell_percent', c_int), ('bell_pitch', c_uint), ('bell_duration', c_uint), ('led_mask', c_ulong), ('global_auto_repeat', c_int), ('auto_repeats', c_char * 32), ] XKeyboardState = struct_anon_33 # /usr/include/X11/Xlib.h:475 class struct_anon_34(Structure): __slots__ = [ 'time', 'x', 'y', ] struct_anon_34._fields_ = [ ('time', Time), ('x', c_short), ('y', c_short), ] XTimeCoord = struct_anon_34 # /usr/include/X11/Xlib.h:482 class struct_anon_35(Structure): __slots__ = [ 'max_keypermod', 'modifiermap', ] struct_anon_35._fields_ = [ ('max_keypermod', c_int), ('modifiermap', POINTER(KeyCode)), ] XModifierKeymap = struct_anon_35 # /usr/include/X11/Xlib.h:489 class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] Display = struct__XDisplay # /usr/include/X11/Xlib.h:498 class struct_anon_36(Structure): __slots__ = [ 'ext_data', 'private1', 'fd', 'private2', 'proto_major_version', 'proto_minor_version', 'vendor', 'private3', 'private4', 'private5', 'private6', 'resource_alloc', 'byte_order', 'bitmap_unit', 'bitmap_pad', 'bitmap_bit_order', 'nformats', 'pixmap_format', 'private8', 'release', 'private9', 'private10', 'qlen', 'last_request_read', 'request', 'private11', 'private12', 'private13', 'private14', 'max_request_size', 'db', 'private15', 'display_name', 'default_screen', 'nscreens', 'screens', 'motion_buffer', 'private16', 'min_keycode', 'max_keycode', 'private17', 'private18', 'private19', 'xdefaults', ] class struct__XPrivate(Structure): __slots__ = [ ] struct__XPrivate._fields_ = [ ('_opaque_struct', c_int) ] class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] class struct__XPrivate(Structure): __slots__ = [ ] struct__XPrivate._fields_ = [ ('_opaque_struct', c_int) ] class struct__XPrivate(Structure): __slots__ = [ ] struct__XPrivate._fields_ = [ ('_opaque_struct', c_int) ] class struct__XrmHashBucketRec(Structure): __slots__ = [ ] struct__XrmHashBucketRec._fields_ = [ ('_opaque_struct', c_int) ] class struct__XDisplay(Structure): __slots__ = [ ] struct__XDisplay._fields_ = [ ('_opaque_struct', c_int) ] struct_anon_36._fields_ = [ ('ext_data', POINTER(XExtData)), ('private1', POINTER(struct__XPrivate)), ('fd', c_int), ('private2', c_int), ('proto_major_version', c_int), ('proto_minor_version', c_int), ('vendor', c_char_p), ('private3', XID), ('private4', XID), ('private5', XID), ('private6', c_int), ('resource_alloc', POINTER(CFUNCTYPE(XID, POINTER(struct__XDisplay)))), ('byte_order', c_int), ('bitmap_unit', c_int), ('bitmap_pad', c_int), ('bitmap_bit_order', c_int), ('nformats', c_int), ('pixmap_format', POINTER(ScreenFormat)), ('private8', c_int), ('release', c_int), ('private9', POINTER(struct__XPrivate)), ('private10', POINTER(struct__XPrivate)), ('qlen', c_int), ('last_request_read', c_ulong), ('request', c_ulong), ('private11', XPointer), ('private12', XPointer), ('private13', XPointer), ('private14', XPointer), ('max_request_size', c_uint), ('db', POINTER(struct__XrmHashBucketRec)), ('private15', POINTER(CFUNCTYPE(c_int, POINTER(struct__XDisplay)))), ('display_name', c_char_p), ('default_screen', c_int), ('nscreens', c_int), ('screens', POINTER(Screen)), ('motion_buffer', c_ulong), ('private16', c_ulong), ('min_keycode', c_int), ('max_keycode', c_int), ('private17', XPointer), ('private18', XPointer), ('private19', c_int), ('xdefaults', c_char_p), ] _XPrivDisplay = POINTER(struct_anon_36) # /usr/include/X11/Xlib.h:561 class struct_anon_37(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'state', 'keycode', 'same_screen', ] struct_anon_37._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('root', Window), ('subwindow', Window), ('time', Time), ('x', c_int), ('y', c_int), ('x_root', c_int), ('y_root', c_int), ('state', c_uint), ('keycode', c_uint), ('same_screen', c_int), ] XKeyEvent = struct_anon_37 # /usr/include/X11/Xlib.h:582 XKeyPressedEvent = XKeyEvent # /usr/include/X11/Xlib.h:583 XKeyReleasedEvent = XKeyEvent # /usr/include/X11/Xlib.h:584 class struct_anon_38(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'state', 'button', 'same_screen', ] struct_anon_38._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('root', Window), ('subwindow', Window), ('time', Time), ('x', c_int), ('y', c_int), ('x_root', c_int), ('y_root', c_int), ('state', c_uint), ('button', c_uint), ('same_screen', c_int), ] XButtonEvent = struct_anon_38 # /usr/include/X11/Xlib.h:600 XButtonPressedEvent = XButtonEvent # /usr/include/X11/Xlib.h:601 XButtonReleasedEvent = XButtonEvent # /usr/include/X11/Xlib.h:602 class struct_anon_39(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'state', 'is_hint', 'same_screen', ] struct_anon_39._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('root', Window), ('subwindow', Window), ('time', Time), ('x', c_int), ('y', c_int), ('x_root', c_int), ('y_root', c_int), ('state', c_uint), ('is_hint', c_char), ('same_screen', c_int), ] XMotionEvent = struct_anon_39 # /usr/include/X11/Xlib.h:618 XPointerMovedEvent = XMotionEvent # /usr/include/X11/Xlib.h:619 class struct_anon_40(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'root', 'subwindow', 'time', 'x', 'y', 'x_root', 'y_root', 'mode', 'detail', 'same_screen', 'focus', 'state', ] struct_anon_40._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('root', Window), ('subwindow', Window), ('time', Time), ('x', c_int), ('y', c_int), ('x_root', c_int), ('y_root', c_int), ('mode', c_int), ('detail', c_int), ('same_screen', c_int), ('focus', c_int), ('state', c_uint), ] XCrossingEvent = struct_anon_40 # /usr/include/X11/Xlib.h:641 XEnterWindowEvent = XCrossingEvent # /usr/include/X11/Xlib.h:642 XLeaveWindowEvent = XCrossingEvent # /usr/include/X11/Xlib.h:643 class struct_anon_41(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'mode', 'detail', ] struct_anon_41._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('mode', c_int), ('detail', c_int), ] XFocusChangeEvent = struct_anon_41 # /usr/include/X11/Xlib.h:659 XFocusInEvent = XFocusChangeEvent # /usr/include/X11/Xlib.h:660 XFocusOutEvent = XFocusChangeEvent # /usr/include/X11/Xlib.h:661 class struct_anon_42(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'key_vector', ] struct_anon_42._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('key_vector', c_char * 32), ] XKeymapEvent = struct_anon_42 # /usr/include/X11/Xlib.h:671 class struct_anon_43(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'x', 'y', 'width', 'height', 'count', ] struct_anon_43._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('count', c_int), ] XExposeEvent = struct_anon_43 # /usr/include/X11/Xlib.h:682 class struct_anon_44(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'drawable', 'x', 'y', 'width', 'height', 'count', 'major_code', 'minor_code', ] struct_anon_44._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('drawable', Drawable), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('count', c_int), ('major_code', c_int), ('minor_code', c_int), ] XGraphicsExposeEvent = struct_anon_44 # /usr/include/X11/Xlib.h:695 class struct_anon_45(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'drawable', 'major_code', 'minor_code', ] struct_anon_45._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('drawable', Drawable), ('major_code', c_int), ('minor_code', c_int), ] XNoExposeEvent = struct_anon_45 # /usr/include/X11/Xlib.h:705 class struct_anon_46(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'state', ] struct_anon_46._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('state', c_int), ] XVisibilityEvent = struct_anon_46 # /usr/include/X11/Xlib.h:714 class struct_anon_47(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'parent', 'window', 'x', 'y', 'width', 'height', 'border_width', 'override_redirect', ] struct_anon_47._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('parent', Window), ('window', Window), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('border_width', c_int), ('override_redirect', c_int), ] XCreateWindowEvent = struct_anon_47 # /usr/include/X11/Xlib.h:727 class struct_anon_48(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', ] struct_anon_48._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ] XDestroyWindowEvent = struct_anon_48 # /usr/include/X11/Xlib.h:736 class struct_anon_49(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'from_configure', ] struct_anon_49._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('from_configure', c_int), ] XUnmapEvent = struct_anon_49 # /usr/include/X11/Xlib.h:746 class struct_anon_50(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'override_redirect', ] struct_anon_50._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('override_redirect', c_int), ] XMapEvent = struct_anon_50 # /usr/include/X11/Xlib.h:756 class struct_anon_51(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'parent', 'window', ] struct_anon_51._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('parent', Window), ('window', Window), ] XMapRequestEvent = struct_anon_51 # /usr/include/X11/Xlib.h:765 class struct_anon_52(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'parent', 'x', 'y', 'override_redirect', ] struct_anon_52._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('parent', Window), ('x', c_int), ('y', c_int), ('override_redirect', c_int), ] XReparentEvent = struct_anon_52 # /usr/include/X11/Xlib.h:777 class struct_anon_53(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'x', 'y', 'width', 'height', 'border_width', 'above', 'override_redirect', ] struct_anon_53._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('border_width', c_int), ('above', Window), ('override_redirect', c_int), ] XConfigureEvent = struct_anon_53 # /usr/include/X11/Xlib.h:791 class struct_anon_54(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'x', 'y', ] struct_anon_54._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('x', c_int), ('y', c_int), ] XGravityEvent = struct_anon_54 # /usr/include/X11/Xlib.h:801 class struct_anon_55(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'width', 'height', ] struct_anon_55._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('width', c_int), ('height', c_int), ] XResizeRequestEvent = struct_anon_55 # /usr/include/X11/Xlib.h:810 class struct_anon_56(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'parent', 'window', 'x', 'y', 'width', 'height', 'border_width', 'above', 'detail', 'value_mask', ] struct_anon_56._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('parent', Window), ('window', Window), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('border_width', c_int), ('above', Window), ('detail', c_int), ('value_mask', c_ulong), ] XConfigureRequestEvent = struct_anon_56 # /usr/include/X11/Xlib.h:825 class struct_anon_57(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'event', 'window', 'place', ] struct_anon_57._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('event', Window), ('window', Window), ('place', c_int), ] XCirculateEvent = struct_anon_57 # /usr/include/X11/Xlib.h:835 class struct_anon_58(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'parent', 'window', 'place', ] struct_anon_58._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('parent', Window), ('window', Window), ('place', c_int), ] XCirculateRequestEvent = struct_anon_58 # /usr/include/X11/Xlib.h:845 class struct_anon_59(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'atom', 'time', 'state', ] struct_anon_59._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('atom', Atom), ('time', Time), ('state', c_int), ] XPropertyEvent = struct_anon_59 # /usr/include/X11/Xlib.h:856 class struct_anon_60(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'selection', 'time', ] struct_anon_60._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('selection', Atom), ('time', Time), ] XSelectionClearEvent = struct_anon_60 # /usr/include/X11/Xlib.h:866 class struct_anon_61(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'owner', 'requestor', 'selection', 'target', 'property', 'time', ] struct_anon_61._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('owner', Window), ('requestor', Window), ('selection', Atom), ('target', Atom), ('property', Atom), ('time', Time), ] XSelectionRequestEvent = struct_anon_61 # /usr/include/X11/Xlib.h:879 class struct_anon_62(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'requestor', 'selection', 'target', 'property', 'time', ] struct_anon_62._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('requestor', Window), ('selection', Atom), ('target', Atom), ('property', Atom), ('time', Time), ] XSelectionEvent = struct_anon_62 # /usr/include/X11/Xlib.h:891 class struct_anon_63(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'colormap', 'new', 'state', ] struct_anon_63._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('colormap', Colormap), ('new', c_int), ('state', c_int), ] XColormapEvent = struct_anon_63 # /usr/include/X11/Xlib.h:906 class struct_anon_64(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'message_type', 'format', 'data', ] class struct_anon_65(Union): __slots__ = [ 'b', 's', 'l', ] struct_anon_65._fields_ = [ ('b', c_char * 20), ('s', c_short * 10), ('l', c_long * 5), ] struct_anon_64._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('message_type', Atom), ('format', c_int), ('data', struct_anon_65), ] XClientMessageEvent = struct_anon_64 # /usr/include/X11/Xlib.h:921 class struct_anon_66(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', 'request', 'first_keycode', 'count', ] struct_anon_66._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ('request', c_int), ('first_keycode', c_int), ('count', c_int), ] XMappingEvent = struct_anon_66 # /usr/include/X11/Xlib.h:933 class struct_anon_67(Structure): __slots__ = [ 'type', 'display', 'resourceid', 'serial', 'error_code', 'request_code', 'minor_code', ] struct_anon_67._fields_ = [ ('type', c_int), ('display', POINTER(Display)), ('resourceid', XID), ('serial', c_ulong), ('error_code', c_ubyte), ('request_code', c_ubyte), ('minor_code', c_ubyte), ] XErrorEvent = struct_anon_67 # /usr/include/X11/Xlib.h:943 class struct_anon_68(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'window', ] struct_anon_68._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('window', Window), ] XAnyEvent = struct_anon_68 # /usr/include/X11/Xlib.h:951 class struct_anon_69(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'extension', 'evtype', ] struct_anon_69._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('extension', c_int), ('evtype', c_int), ] XGenericEvent = struct_anon_69 # /usr/include/X11/Xlib.h:967 class struct_anon_70(Structure): __slots__ = [ 'type', 'serial', 'send_event', 'display', 'extension', 'evtype', 'cookie', 'data', ] struct_anon_70._fields_ = [ ('type', c_int), ('serial', c_ulong), ('send_event', c_int), ('display', POINTER(Display)), ('extension', c_int), ('evtype', c_int), ('cookie', c_uint), ('data', POINTER(None)), ] XGenericEventCookie = struct_anon_70 # /usr/include/X11/Xlib.h:978 class struct__XEvent(Union): __slots__ = [ 'type', 'xany', 'xkey', 'xbutton', 'xmotion', 'xcrossing', 'xfocus', 'xexpose', 'xgraphicsexpose', 'xnoexpose', 'xvisibility', 'xcreatewindow', 'xdestroywindow', 'xunmap', 'xmap', 'xmaprequest', 'xreparent', 'xconfigure', 'xgravity', 'xresizerequest', 'xconfigurerequest', 'xcirculate', 'xcirculaterequest', 'xproperty', 'xselectionclear', 'xselectionrequest', 'xselection', 'xcolormap', 'xclient', 'xmapping', 'xerror', 'xkeymap', 'xgeneric', 'xcookie', 'pad', ] struct__XEvent._fields_ = [ ('type', c_int), ('xany', XAnyEvent), ('xkey', XKeyEvent), ('xbutton', XButtonEvent), ('xmotion', XMotionEvent), ('xcrossing', XCrossingEvent), ('xfocus', XFocusChangeEvent), ('xexpose', XExposeEvent), ('xgraphicsexpose', XGraphicsExposeEvent), ('xnoexpose', XNoExposeEvent), ('xvisibility', XVisibilityEvent), ('xcreatewindow', XCreateWindowEvent), ('xdestroywindow', XDestroyWindowEvent), ('xunmap', XUnmapEvent), ('xmap', XMapEvent), ('xmaprequest', XMapRequestEvent), ('xreparent', XReparentEvent), ('xconfigure', XConfigureEvent), ('xgravity', XGravityEvent), ('xresizerequest', XResizeRequestEvent), ('xconfigurerequest', XConfigureRequestEvent), ('xcirculate', XCirculateEvent), ('xcirculaterequest', XCirculateRequestEvent), ('xproperty', XPropertyEvent), ('xselectionclear', XSelectionClearEvent), ('xselectionrequest', XSelectionRequestEvent), ('xselection', XSelectionEvent), ('xcolormap', XColormapEvent), ('xclient', XClientMessageEvent), ('xmapping', XMappingEvent), ('xerror', XErrorEvent), ('xkeymap', XKeymapEvent), ('xgeneric', XGenericEvent), ('xcookie', XGenericEventCookie), ('pad', c_long * 24), ] XEvent = struct__XEvent # /usr/include/X11/Xlib.h:1020 class struct_anon_71(Structure): __slots__ = [ 'lbearing', 'rbearing', 'width', 'ascent', 'descent', 'attributes', ] struct_anon_71._fields_ = [ ('lbearing', c_short), ('rbearing', c_short), ('width', c_short), ('ascent', c_short), ('descent', c_short), ('attributes', c_ushort), ] XCharStruct = struct_anon_71 # /usr/include/X11/Xlib.h:1035 class struct_anon_72(Structure): __slots__ = [ 'name', 'card32', ] struct_anon_72._fields_ = [ ('name', Atom), ('card32', c_ulong), ] XFontProp = struct_anon_72 # /usr/include/X11/Xlib.h:1044 class struct_anon_73(Structure): __slots__ = [ 'ext_data', 'fid', 'direction', 'min_char_or_byte2', 'max_char_or_byte2', 'min_byte1', 'max_byte1', 'all_chars_exist', 'default_char', 'n_properties', 'properties', 'min_bounds', 'max_bounds', 'per_char', 'ascent', 'descent', ] struct_anon_73._fields_ = [ ('ext_data', POINTER(XExtData)), ('fid', Font), ('direction', c_uint), ('min_char_or_byte2', c_uint), ('max_char_or_byte2', c_uint), ('min_byte1', c_uint), ('max_byte1', c_uint), ('all_chars_exist', c_int), ('default_char', c_uint), ('n_properties', c_int), ('properties', POINTER(XFontProp)), ('min_bounds', XCharStruct), ('max_bounds', XCharStruct), ('per_char', POINTER(XCharStruct)), ('ascent', c_int), ('descent', c_int), ] XFontStruct = struct_anon_73 # /usr/include/X11/Xlib.h:1063 class struct_anon_74(Structure): __slots__ = [ 'chars', 'nchars', 'delta', 'font', ] struct_anon_74._fields_ = [ ('chars', c_char_p), ('nchars', c_int), ('delta', c_int), ('font', Font), ] XTextItem = struct_anon_74 # /usr/include/X11/Xlib.h:1073 class struct_anon_75(Structure): __slots__ = [ 'byte1', 'byte2', ] struct_anon_75._fields_ = [ ('byte1', c_ubyte), ('byte2', c_ubyte), ] XChar2b = struct_anon_75 # /usr/include/X11/Xlib.h:1078 class struct_anon_76(Structure): __slots__ = [ 'chars', 'nchars', 'delta', 'font', ] struct_anon_76._fields_ = [ ('chars', POINTER(XChar2b)), ('nchars', c_int), ('delta', c_int), ('font', Font), ] XTextItem16 = struct_anon_76 # /usr/include/X11/Xlib.h:1085 class struct_anon_77(Union): __slots__ = [ 'display', 'gc', 'visual', 'screen', 'pixmap_format', 'font', ] struct_anon_77._fields_ = [ ('display', POINTER(Display)), ('gc', GC), ('visual', POINTER(Visual)), ('screen', POINTER(Screen)), ('pixmap_format', POINTER(ScreenFormat)), ('font', POINTER(XFontStruct)), ] XEDataObject = struct_anon_77 # /usr/include/X11/Xlib.h:1093 class struct_anon_78(Structure): __slots__ = [ 'max_ink_extent', 'max_logical_extent', ] struct_anon_78._fields_ = [ ('max_ink_extent', XRectangle), ('max_logical_extent', XRectangle), ] XFontSetExtents = struct_anon_78 # /usr/include/X11/Xlib.h:1098 class struct__XOM(Structure): __slots__ = [ ] struct__XOM._fields_ = [ ('_opaque_struct', c_int) ] class struct__XOM(Structure): __slots__ = [ ] struct__XOM._fields_ = [ ('_opaque_struct', c_int) ] XOM = POINTER(struct__XOM) # /usr/include/X11/Xlib.h:1104 class struct__XOC(Structure): __slots__ = [ ] struct__XOC._fields_ = [ ('_opaque_struct', c_int) ] class struct__XOC(Structure): __slots__ = [ ] struct__XOC._fields_ = [ ('_opaque_struct', c_int) ] XOC = POINTER(struct__XOC) # /usr/include/X11/Xlib.h:1105 class struct__XOC(Structure): __slots__ = [ ] struct__XOC._fields_ = [ ('_opaque_struct', c_int) ] class struct__XOC(Structure): __slots__ = [ ] struct__XOC._fields_ = [ ('_opaque_struct', c_int) ] XFontSet = POINTER(struct__XOC) # /usr/include/X11/Xlib.h:1105 class struct_anon_79(Structure): __slots__ = [ 'chars', 'nchars', 'delta', 'font_set', ] struct_anon_79._fields_ = [ ('chars', c_char_p), ('nchars', c_int), ('delta', c_int), ('font_set', XFontSet), ] XmbTextItem = struct_anon_79 # /usr/include/X11/Xlib.h:1112 class struct_anon_80(Structure): __slots__ = [ 'chars', 'nchars', 'delta', 'font_set', ] struct_anon_80._fields_ = [ ('chars', c_wchar_p), ('nchars', c_int), ('delta', c_int), ('font_set', XFontSet), ] XwcTextItem = struct_anon_80 # /usr/include/X11/Xlib.h:1119 class struct_anon_81(Structure): __slots__ = [ 'charset_count', 'charset_list', ] struct_anon_81._fields_ = [ ('charset_count', c_int), ('charset_list', POINTER(c_char_p)), ] XOMCharSetList = struct_anon_81 # /usr/include/X11/Xlib.h:1135 enum_anon_82 = c_int XOMOrientation_LTR_TTB = 0 XOMOrientation_RTL_TTB = 1 XOMOrientation_TTB_LTR = 2 XOMOrientation_TTB_RTL = 3 XOMOrientation_Context = 4 XOrientation = enum_anon_82 # /usr/include/X11/Xlib.h:1143 class struct_anon_83(Structure): __slots__ = [ 'num_orientation', 'orientation', ] struct_anon_83._fields_ = [ ('num_orientation', c_int), ('orientation', POINTER(XOrientation)), ] XOMOrientation = struct_anon_83 # /usr/include/X11/Xlib.h:1148 class struct_anon_84(Structure): __slots__ = [ 'num_font', 'font_struct_list', 'font_name_list', ] struct_anon_84._fields_ = [ ('num_font', c_int), ('font_struct_list', POINTER(POINTER(XFontStruct))), ('font_name_list', POINTER(c_char_p)), ] XOMFontInfo = struct_anon_84 # /usr/include/X11/Xlib.h:1154 class struct__XIM(Structure): __slots__ = [ ] struct__XIM._fields_ = [ ('_opaque_struct', c_int) ] class struct__XIM(Structure): __slots__ = [ ] struct__XIM._fields_ = [ ('_opaque_struct', c_int) ] XIM = POINTER(struct__XIM) # /usr/include/X11/Xlib.h:1156 class struct__XIC(Structure): __slots__ = [ ] struct__XIC._fields_ = [ ('_opaque_struct', c_int) ] class struct__XIC(Structure): __slots__ = [ ] struct__XIC._fields_ = [ ('_opaque_struct', c_int) ] XIC = POINTER(struct__XIC) # /usr/include/X11/Xlib.h:1157 # /usr/include/X11/Xlib.h:1159 XIMProc = CFUNCTYPE(None, XIM, XPointer, XPointer) # /usr/include/X11/Xlib.h:1165 XICProc = CFUNCTYPE(c_int, XIC, XPointer, XPointer) XIDProc = CFUNCTYPE(None, POINTER(Display), XPointer, XPointer) # /usr/include/X11/Xlib.h:1171 XIMStyle = c_ulong # /usr/include/X11/Xlib.h:1177 class struct_anon_85(Structure): __slots__ = [ 'count_styles', 'supported_styles', ] struct_anon_85._fields_ = [ ('count_styles', c_ushort), ('supported_styles', POINTER(XIMStyle)), ] XIMStyles = struct_anon_85 # /usr/include/X11/Xlib.h:1182 XIMPreeditArea = 1 # /usr/include/X11/Xlib.h:1184 XIMPreeditCallbacks = 2 # /usr/include/X11/Xlib.h:1185 XIMPreeditPosition = 4 # /usr/include/X11/Xlib.h:1186 XIMPreeditNothing = 8 # /usr/include/X11/Xlib.h:1187 XIMPreeditNone = 16 # /usr/include/X11/Xlib.h:1188 XIMStatusArea = 256 # /usr/include/X11/Xlib.h:1189 XIMStatusCallbacks = 512 # /usr/include/X11/Xlib.h:1190 XIMStatusNothing = 1024 # /usr/include/X11/Xlib.h:1191 XIMStatusNone = 2048 # /usr/include/X11/Xlib.h:1192 XBufferOverflow = -1 # /usr/include/X11/Xlib.h:1238 XLookupNone = 1 # /usr/include/X11/Xlib.h:1239 XLookupChars = 2 # /usr/include/X11/Xlib.h:1240 XLookupKeySym = 3 # /usr/include/X11/Xlib.h:1241 XLookupBoth = 4 # /usr/include/X11/Xlib.h:1242 XVaNestedList = POINTER(None) # /usr/include/X11/Xlib.h:1244 class struct_anon_86(Structure): __slots__ = [ 'client_data', 'callback', ] struct_anon_86._fields_ = [ ('client_data', XPointer), ('callback', XIMProc), ] XIMCallback = struct_anon_86 # /usr/include/X11/Xlib.h:1249 class struct_anon_87(Structure): __slots__ = [ 'client_data', 'callback', ] struct_anon_87._fields_ = [ ('client_data', XPointer), ('callback', XICProc), ] XICCallback = struct_anon_87 # /usr/include/X11/Xlib.h:1254 XIMFeedback = c_ulong # /usr/include/X11/Xlib.h:1256 XIMReverse = 1 # /usr/include/X11/Xlib.h:1258 XIMUnderline = 2 # /usr/include/X11/Xlib.h:1259 XIMHighlight = 4 # /usr/include/X11/Xlib.h:1260 XIMPrimary = 32 # /usr/include/X11/Xlib.h:1261 XIMSecondary = 64 # /usr/include/X11/Xlib.h:1262 XIMTertiary = 128 # /usr/include/X11/Xlib.h:1263 XIMVisibleToForward = 256 # /usr/include/X11/Xlib.h:1264 XIMVisibleToBackword = 512 # /usr/include/X11/Xlib.h:1265 XIMVisibleToCenter = 1024 # /usr/include/X11/Xlib.h:1266 class struct__XIMText(Structure): __slots__ = [ 'length', 'feedback', 'encoding_is_wchar', 'string', ] class struct_anon_88(Union): __slots__ = [ 'multi_byte', 'wide_char', ] struct_anon_88._fields_ = [ ('multi_byte', c_char_p), ('wide_char', c_wchar_p), ] struct__XIMText._fields_ = [ ('length', c_ushort), ('feedback', POINTER(XIMFeedback)), ('encoding_is_wchar', c_int), ('string', struct_anon_88), ] XIMText = struct__XIMText # /usr/include/X11/Xlib.h:1276 XIMPreeditState = c_ulong # /usr/include/X11/Xlib.h:1278 XIMPreeditUnKnown = 0 # /usr/include/X11/Xlib.h:1280 XIMPreeditEnable = 1 # /usr/include/X11/Xlib.h:1281 XIMPreeditDisable = 2 # /usr/include/X11/Xlib.h:1282 class struct__XIMPreeditStateNotifyCallbackStruct(Structure): __slots__ = [ 'state', ] struct__XIMPreeditStateNotifyCallbackStruct._fields_ = [ ('state', XIMPreeditState), ] # /usr/include/X11/Xlib.h:1286 XIMPreeditStateNotifyCallbackStruct = struct__XIMPreeditStateNotifyCallbackStruct XIMResetState = c_ulong # /usr/include/X11/Xlib.h:1288 XIMInitialState = 1 # /usr/include/X11/Xlib.h:1290 XIMPreserveState = 2 # /usr/include/X11/Xlib.h:1291 XIMStringConversionFeedback = c_ulong # /usr/include/X11/Xlib.h:1293 XIMStringConversionLeftEdge = 1 # /usr/include/X11/Xlib.h:1295 XIMStringConversionRightEdge = 2 # /usr/include/X11/Xlib.h:1296 XIMStringConversionTopEdge = 4 # /usr/include/X11/Xlib.h:1297 XIMStringConversionBottomEdge = 8 # /usr/include/X11/Xlib.h:1298 XIMStringConversionConcealed = 16 # /usr/include/X11/Xlib.h:1299 XIMStringConversionWrapped = 32 # /usr/include/X11/Xlib.h:1300 class struct__XIMStringConversionText(Structure): __slots__ = [ 'length', 'feedback', 'encoding_is_wchar', 'string', ] class struct_anon_89(Union): __slots__ = [ 'mbs', 'wcs', ] struct_anon_89._fields_ = [ ('mbs', c_char_p), ('wcs', c_wchar_p), ] struct__XIMStringConversionText._fields_ = [ ('length', c_ushort), ('feedback', POINTER(XIMStringConversionFeedback)), ('encoding_is_wchar', c_int), ('string', struct_anon_89), ] # /usr/include/X11/Xlib.h:1310 XIMStringConversionText = struct__XIMStringConversionText XIMStringConversionPosition = c_ushort # /usr/include/X11/Xlib.h:1312 XIMStringConversionType = c_ushort # /usr/include/X11/Xlib.h:1314 XIMStringConversionBuffer = 1 # /usr/include/X11/Xlib.h:1316 XIMStringConversionLine = 2 # /usr/include/X11/Xlib.h:1317 XIMStringConversionWord = 3 # /usr/include/X11/Xlib.h:1318 XIMStringConversionChar = 4 # /usr/include/X11/Xlib.h:1319 XIMStringConversionOperation = c_ushort # /usr/include/X11/Xlib.h:1321 XIMStringConversionSubstitution = 1 # /usr/include/X11/Xlib.h:1323 XIMStringConversionRetrieval = 2 # /usr/include/X11/Xlib.h:1324 enum_anon_90 = c_int XIMForwardChar = 0 XIMBackwardChar = 1 XIMForwardWord = 2 XIMBackwardWord = 3 XIMCaretUp = 4 XIMCaretDown = 5 XIMNextLine = 6 XIMPreviousLine = 7 XIMLineStart = 8 XIMLineEnd = 9 XIMAbsolutePosition = 10 XIMDontChange = 11 XIMCaretDirection = enum_anon_90 # /usr/include/X11/Xlib.h:1334 class struct__XIMStringConversionCallbackStruct(Structure): __slots__ = [ 'position', 'direction', 'operation', 'factor', 'text', ] struct__XIMStringConversionCallbackStruct._fields_ = [ ('position', XIMStringConversionPosition), ('direction', XIMCaretDirection), ('operation', XIMStringConversionOperation), ('factor', c_ushort), ('text', POINTER(XIMStringConversionText)), ] # /usr/include/X11/Xlib.h:1342 XIMStringConversionCallbackStruct = struct__XIMStringConversionCallbackStruct class struct__XIMPreeditDrawCallbackStruct(Structure): __slots__ = [ 'caret', 'chg_first', 'chg_length', 'text', ] struct__XIMPreeditDrawCallbackStruct._fields_ = [ ('caret', c_int), ('chg_first', c_int), ('chg_length', c_int), ('text', POINTER(XIMText)), ] # /usr/include/X11/Xlib.h:1349 XIMPreeditDrawCallbackStruct = struct__XIMPreeditDrawCallbackStruct enum_anon_91 = c_int XIMIsInvisible = 0 XIMIsPrimary = 1 XIMIsSecondary = 2 XIMCaretStyle = enum_anon_91 # /usr/include/X11/Xlib.h:1355 class struct__XIMPreeditCaretCallbackStruct(Structure): __slots__ = [ 'position', 'direction', 'style', ] struct__XIMPreeditCaretCallbackStruct._fields_ = [ ('position', c_int), ('direction', XIMCaretDirection), ('style', XIMCaretStyle), ] # /usr/include/X11/Xlib.h:1361 XIMPreeditCaretCallbackStruct = struct__XIMPreeditCaretCallbackStruct enum_anon_92 = c_int XIMTextType = 0 XIMBitmapType = 1 XIMStatusDataType = enum_anon_92 # /usr/include/X11/Xlib.h:1366 class struct__XIMStatusDrawCallbackStruct(Structure): __slots__ = [ 'type', 'data', ] class struct_anon_93(Union): __slots__ = [ 'text', 'bitmap', ] struct_anon_93._fields_ = [ ('text', POINTER(XIMText)), ('bitmap', Pixmap), ] struct__XIMStatusDrawCallbackStruct._fields_ = [ ('type', XIMStatusDataType), ('data', struct_anon_93), ] # /usr/include/X11/Xlib.h:1374 XIMStatusDrawCallbackStruct = struct__XIMStatusDrawCallbackStruct class struct__XIMHotKeyTrigger(Structure): __slots__ = [ 'keysym', 'modifier', 'modifier_mask', ] struct__XIMHotKeyTrigger._fields_ = [ ('keysym', KeySym), ('modifier', c_int), ('modifier_mask', c_int), ] XIMHotKeyTrigger = struct__XIMHotKeyTrigger # /usr/include/X11/Xlib.h:1380 class struct__XIMHotKeyTriggers(Structure): __slots__ = [ 'num_hot_key', 'key', ] struct__XIMHotKeyTriggers._fields_ = [ ('num_hot_key', c_int), ('key', POINTER(XIMHotKeyTrigger)), ] XIMHotKeyTriggers = struct__XIMHotKeyTriggers # /usr/include/X11/Xlib.h:1385 XIMHotKeyState = c_ulong # /usr/include/X11/Xlib.h:1387 XIMHotKeyStateON = 1 # /usr/include/X11/Xlib.h:1389 XIMHotKeyStateOFF = 2 # /usr/include/X11/Xlib.h:1390 class struct_anon_94(Structure): __slots__ = [ 'count_values', 'supported_values', ] struct_anon_94._fields_ = [ ('count_values', c_ushort), ('supported_values', POINTER(c_char_p)), ] XIMValuesList = struct_anon_94 # /usr/include/X11/Xlib.h:1395 # /usr/include/X11/Xlib.h:1405 XLoadQueryFont = _lib.XLoadQueryFont XLoadQueryFont.restype = POINTER(XFontStruct) XLoadQueryFont.argtypes = [POINTER(Display), c_char_p] # /usr/include/X11/Xlib.h:1410 XQueryFont = _lib.XQueryFont XQueryFont.restype = POINTER(XFontStruct) XQueryFont.argtypes = [POINTER(Display), XID] # /usr/include/X11/Xlib.h:1416 XGetMotionEvents = _lib.XGetMotionEvents XGetMotionEvents.restype = POINTER(XTimeCoord) XGetMotionEvents.argtypes = [ POINTER(Display), Window, Time, Time, POINTER(c_int)] # /usr/include/X11/Xlib.h:1424 XDeleteModifiermapEntry = _lib.XDeleteModifiermapEntry XDeleteModifiermapEntry.restype = POINTER(XModifierKeymap) XDeleteModifiermapEntry.argtypes = [POINTER(XModifierKeymap), KeyCode, c_int] # /usr/include/X11/Xlib.h:1434 XGetModifierMapping = _lib.XGetModifierMapping XGetModifierMapping.restype = POINTER(XModifierKeymap) XGetModifierMapping.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1438 XInsertModifiermapEntry = _lib.XInsertModifiermapEntry XInsertModifiermapEntry.restype = POINTER(XModifierKeymap) XInsertModifiermapEntry.argtypes = [POINTER(XModifierKeymap), KeyCode, c_int] # /usr/include/X11/Xlib.h:1448 XNewModifiermap = _lib.XNewModifiermap XNewModifiermap.restype = POINTER(XModifierKeymap) XNewModifiermap.argtypes = [c_int] # /usr/include/X11/Xlib.h:1452 XCreateImage = _lib.XCreateImage XCreateImage.restype = POINTER(XImage) XCreateImage.argtypes = [ POINTER(Display), POINTER(Visual), c_uint, c_int, c_int, c_char_p, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:1464 XInitImage = _lib.XInitImage XInitImage.restype = c_int XInitImage.argtypes = [POINTER(XImage)] # /usr/include/X11/Xlib.h:1467 XGetImage = _lib.XGetImage XGetImage.restype = POINTER(XImage) XGetImage.argtypes = [ POINTER(Display), Drawable, c_int, c_int, c_uint, c_uint, c_ulong, c_int] # /usr/include/X11/Xlib.h:1477 XGetSubImage = _lib.XGetSubImage XGetSubImage.restype = POINTER(XImage) XGetSubImage.argtypes = [ POINTER(Display), Drawable, c_int, c_int, c_uint, c_uint, c_ulong, c_int, POINTER(XImage), c_int, c_int] # /usr/include/X11/Xlib.h:1494 XOpenDisplay = _lib.XOpenDisplay XOpenDisplay.restype = POINTER(Display) XOpenDisplay.argtypes = [c_char_p] # /usr/include/X11/Xlib.h:1498 XrmInitialize = _lib.XrmInitialize XrmInitialize.restype = None XrmInitialize.argtypes = [] # /usr/include/X11/Xlib.h:1502 XFetchBytes = _lib.XFetchBytes XFetchBytes.restype = c_char_p XFetchBytes.argtypes = [POINTER(Display), POINTER(c_int)] # /usr/include/X11/Xlib.h:1506 XFetchBuffer = _lib.XFetchBuffer XFetchBuffer.restype = c_char_p XFetchBuffer.argtypes = [POINTER(Display), POINTER(c_int), c_int] # /usr/include/X11/Xlib.h:1511 XGetAtomName = _lib.XGetAtomName XGetAtomName.restype = c_char_p XGetAtomName.argtypes = [POINTER(Display), Atom] # /usr/include/X11/Xlib.h:1515 XGetAtomNames = _lib.XGetAtomNames XGetAtomNames.restype = c_int XGetAtomNames.argtypes = [ POINTER(Display), POINTER(Atom), c_int, POINTER(c_char_p)] # /usr/include/X11/Xlib.h:1521 XGetDefault = _lib.XGetDefault XGetDefault.restype = c_char_p XGetDefault.argtypes = [POINTER(Display), c_char_p, c_char_p] # /usr/include/X11/Xlib.h:1526 XDisplayName = _lib.XDisplayName XDisplayName.restype = c_char_p XDisplayName.argtypes = [c_char_p] # /usr/include/X11/Xlib.h:1529 XKeysymToString = _lib.XKeysymToString XKeysymToString.restype = c_char_p XKeysymToString.argtypes = [KeySym] # /usr/include/X11/Xlib.h:1533 XSynchronize = _lib.XSynchronize XSynchronize.restype = POINTER(CFUNCTYPE(c_int, POINTER(Display))) XSynchronize.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1539 XSetAfterFunction = _lib.XSetAfterFunction XSetAfterFunction.restype = POINTER(CFUNCTYPE(c_int, POINTER(Display))) XSetAfterFunction.argtypes = [ POINTER(Display), CFUNCTYPE( c_int, POINTER(Display))] # /usr/include/X11/Xlib.h:1547 XInternAtom = _lib.XInternAtom XInternAtom.restype = Atom XInternAtom.argtypes = [POINTER(Display), c_char_p, c_int] # /usr/include/X11/Xlib.h:1552 XInternAtoms = _lib.XInternAtoms XInternAtoms.restype = c_int XInternAtoms.argtypes = [ POINTER(Display), POINTER(c_char_p), c_int, c_int, POINTER(Atom)] # /usr/include/X11/Xlib.h:1559 XCopyColormapAndFree = _lib.XCopyColormapAndFree XCopyColormapAndFree.restype = Colormap XCopyColormapAndFree.argtypes = [POINTER(Display), Colormap] # /usr/include/X11/Xlib.h:1563 XCreateColormap = _lib.XCreateColormap XCreateColormap.restype = Colormap XCreateColormap.argtypes = [POINTER(Display), Window, POINTER(Visual), c_int] # /usr/include/X11/Xlib.h:1569 XCreatePixmapCursor = _lib.XCreatePixmapCursor XCreatePixmapCursor.restype = Cursor XCreatePixmapCursor.argtypes = [ POINTER(Display), Pixmap, Pixmap, POINTER(XColor), POINTER(XColor), c_uint, c_uint] # /usr/include/X11/Xlib.h:1578 XCreateGlyphCursor = _lib.XCreateGlyphCursor XCreateGlyphCursor.restype = Cursor XCreateGlyphCursor.argtypes = [ POINTER(Display), Font, Font, c_uint, c_uint, POINTER(XColor), POINTER(XColor)] # /usr/include/X11/Xlib.h:1587 XCreateFontCursor = _lib.XCreateFontCursor XCreateFontCursor.restype = Cursor XCreateFontCursor.argtypes = [POINTER(Display), c_uint] # /usr/include/X11/Xlib.h:1591 XLoadFont = _lib.XLoadFont XLoadFont.restype = Font XLoadFont.argtypes = [POINTER(Display), c_char_p] # /usr/include/X11/Xlib.h:1595 XCreateGC = _lib.XCreateGC XCreateGC.restype = GC XCreateGC.argtypes = [POINTER(Display), Drawable, c_ulong, POINTER(XGCValues)] # /usr/include/X11/Xlib.h:1601 XGContextFromGC = _lib.XGContextFromGC XGContextFromGC.restype = GContext XGContextFromGC.argtypes = [GC] # /usr/include/X11/Xlib.h:1604 XFlushGC = _lib.XFlushGC XFlushGC.restype = None XFlushGC.argtypes = [POINTER(Display), GC] # /usr/include/X11/Xlib.h:1608 XCreatePixmap = _lib.XCreatePixmap XCreatePixmap.restype = Pixmap XCreatePixmap.argtypes = [POINTER(Display), Drawable, c_uint, c_uint, c_uint] # /usr/include/X11/Xlib.h:1615 XCreateBitmapFromData = _lib.XCreateBitmapFromData XCreateBitmapFromData.restype = Pixmap XCreateBitmapFromData.argtypes = [ POINTER(Display), Drawable, c_char_p, c_uint, c_uint] # /usr/include/X11/Xlib.h:1622 XCreatePixmapFromBitmapData = _lib.XCreatePixmapFromBitmapData XCreatePixmapFromBitmapData.restype = Pixmap XCreatePixmapFromBitmapData.argtypes = [ POINTER(Display), Drawable, c_char_p, c_uint, c_uint, c_ulong, c_ulong, c_uint] # /usr/include/X11/Xlib.h:1632 XCreateSimpleWindow = _lib.XCreateSimpleWindow XCreateSimpleWindow.restype = Window XCreateSimpleWindow.argtypes = [ POINTER(Display), Window, c_int, c_int, c_uint, c_uint, c_uint, c_ulong, c_ulong] # /usr/include/X11/Xlib.h:1643 XGetSelectionOwner = _lib.XGetSelectionOwner XGetSelectionOwner.restype = Window XGetSelectionOwner.argtypes = [POINTER(Display), Atom] # /usr/include/X11/Xlib.h:1647 XCreateWindow = _lib.XCreateWindow XCreateWindow.restype = Window XCreateWindow.argtypes = [ POINTER(Display), Window, c_int, c_int, c_uint, c_uint, c_uint, c_int, c_uint, POINTER(Visual), c_ulong, POINTER(XSetWindowAttributes)] # /usr/include/X11/Xlib.h:1661 XListInstalledColormaps = _lib.XListInstalledColormaps XListInstalledColormaps.restype = POINTER(Colormap) XListInstalledColormaps.argtypes = [POINTER(Display), Window, POINTER(c_int)] # /usr/include/X11/Xlib.h:1666 XListFonts = _lib.XListFonts XListFonts.restype = POINTER(c_char_p) XListFonts.argtypes = [POINTER(Display), c_char_p, c_int, POINTER(c_int)] # /usr/include/X11/Xlib.h:1672 XListFontsWithInfo = _lib.XListFontsWithInfo XListFontsWithInfo.restype = POINTER(c_char_p) XListFontsWithInfo.argtypes = [ POINTER(Display), c_char_p, c_int, POINTER(c_int), POINTER( POINTER(XFontStruct))] # /usr/include/X11/Xlib.h:1679 XGetFontPath = _lib.XGetFontPath XGetFontPath.restype = POINTER(c_char_p) XGetFontPath.argtypes = [POINTER(Display), POINTER(c_int)] # /usr/include/X11/Xlib.h:1683 XListExtensions = _lib.XListExtensions XListExtensions.restype = POINTER(c_char_p) XListExtensions.argtypes = [POINTER(Display), POINTER(c_int)] # /usr/include/X11/Xlib.h:1687 XListProperties = _lib.XListProperties XListProperties.restype = POINTER(Atom) XListProperties.argtypes = [POINTER(Display), Window, POINTER(c_int)] # /usr/include/X11/Xlib.h:1692 XListHosts = _lib.XListHosts XListHosts.restype = POINTER(XHostAddress) XListHosts.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:1697 XKeycodeToKeysym = _lib.XKeycodeToKeysym XKeycodeToKeysym.restype = KeySym XKeycodeToKeysym.argtypes = [POINTER(Display), KeyCode, c_int] # /usr/include/X11/Xlib.h:1706 XLookupKeysym = _lib.XLookupKeysym XLookupKeysym.restype = KeySym XLookupKeysym.argtypes = [POINTER(XKeyEvent), c_int] # /usr/include/X11/Xlib.h:1710 XGetKeyboardMapping = _lib.XGetKeyboardMapping XGetKeyboardMapping.restype = POINTER(KeySym) XGetKeyboardMapping.argtypes = [ POINTER(Display), KeyCode, c_int, POINTER(c_int)] # /usr/include/X11/Xlib.h:1720 XStringToKeysym = _lib.XStringToKeysym XStringToKeysym.restype = KeySym XStringToKeysym.argtypes = [c_char_p] # /usr/include/X11/Xlib.h:1723 XMaxRequestSize = _lib.XMaxRequestSize XMaxRequestSize.restype = c_long XMaxRequestSize.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1726 XExtendedMaxRequestSize = _lib.XExtendedMaxRequestSize XExtendedMaxRequestSize.restype = c_long XExtendedMaxRequestSize.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1729 XResourceManagerString = _lib.XResourceManagerString XResourceManagerString.restype = c_char_p XResourceManagerString.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1732 XScreenResourceString = _lib.XScreenResourceString XScreenResourceString.restype = c_char_p XScreenResourceString.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1735 XDisplayMotionBufferSize = _lib.XDisplayMotionBufferSize XDisplayMotionBufferSize.restype = c_ulong XDisplayMotionBufferSize.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1738 XVisualIDFromVisual = _lib.XVisualIDFromVisual XVisualIDFromVisual.restype = VisualID XVisualIDFromVisual.argtypes = [POINTER(Visual)] # /usr/include/X11/Xlib.h:1744 XInitThreads = _lib.XInitThreads XInitThreads.restype = c_int XInitThreads.argtypes = [] # /usr/include/X11/Xlib.h:1748 XLockDisplay = _lib.XLockDisplay XLockDisplay.restype = None XLockDisplay.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1752 XUnlockDisplay = _lib.XUnlockDisplay XUnlockDisplay.restype = None XUnlockDisplay.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1758 XInitExtension = _lib.XInitExtension XInitExtension.restype = POINTER(XExtCodes) XInitExtension.argtypes = [POINTER(Display), c_char_p] # /usr/include/X11/Xlib.h:1763 XAddExtension = _lib.XAddExtension XAddExtension.restype = POINTER(XExtCodes) XAddExtension.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1766 XFindOnExtensionList = _lib.XFindOnExtensionList XFindOnExtensionList.restype = POINTER(XExtData) XFindOnExtensionList.argtypes = [POINTER(POINTER(XExtData)), c_int] # /usr/include/X11/Xlib.h:1770 XEHeadOfExtensionList = _lib.XEHeadOfExtensionList XEHeadOfExtensionList.restype = POINTER(POINTER(XExtData)) XEHeadOfExtensionList.argtypes = [XEDataObject] # /usr/include/X11/Xlib.h:1775 XRootWindow = _lib.XRootWindow XRootWindow.restype = Window XRootWindow.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1779 XDefaultRootWindow = _lib.XDefaultRootWindow XDefaultRootWindow.restype = Window XDefaultRootWindow.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1782 XRootWindowOfScreen = _lib.XRootWindowOfScreen XRootWindowOfScreen.restype = Window XRootWindowOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1785 XDefaultVisual = _lib.XDefaultVisual XDefaultVisual.restype = POINTER(Visual) XDefaultVisual.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1789 XDefaultVisualOfScreen = _lib.XDefaultVisualOfScreen XDefaultVisualOfScreen.restype = POINTER(Visual) XDefaultVisualOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1792 XDefaultGC = _lib.XDefaultGC XDefaultGC.restype = GC XDefaultGC.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1796 XDefaultGCOfScreen = _lib.XDefaultGCOfScreen XDefaultGCOfScreen.restype = GC XDefaultGCOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1799 XBlackPixel = _lib.XBlackPixel XBlackPixel.restype = c_ulong XBlackPixel.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1803 XWhitePixel = _lib.XWhitePixel XWhitePixel.restype = c_ulong XWhitePixel.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1807 XAllPlanes = _lib.XAllPlanes XAllPlanes.restype = c_ulong XAllPlanes.argtypes = [] # /usr/include/X11/Xlib.h:1810 XBlackPixelOfScreen = _lib.XBlackPixelOfScreen XBlackPixelOfScreen.restype = c_ulong XBlackPixelOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1813 XWhitePixelOfScreen = _lib.XWhitePixelOfScreen XWhitePixelOfScreen.restype = c_ulong XWhitePixelOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1816 XNextRequest = _lib.XNextRequest XNextRequest.restype = c_ulong XNextRequest.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1819 XLastKnownRequestProcessed = _lib.XLastKnownRequestProcessed XLastKnownRequestProcessed.restype = c_ulong XLastKnownRequestProcessed.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1822 XServerVendor = _lib.XServerVendor XServerVendor.restype = c_char_p XServerVendor.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1825 XDisplayString = _lib.XDisplayString XDisplayString.restype = c_char_p XDisplayString.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1828 XDefaultColormap = _lib.XDefaultColormap XDefaultColormap.restype = Colormap XDefaultColormap.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1832 XDefaultColormapOfScreen = _lib.XDefaultColormapOfScreen XDefaultColormapOfScreen.restype = Colormap XDefaultColormapOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1835 XDisplayOfScreen = _lib.XDisplayOfScreen XDisplayOfScreen.restype = POINTER(Display) XDisplayOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1838 XScreenOfDisplay = _lib.XScreenOfDisplay XScreenOfDisplay.restype = POINTER(Screen) XScreenOfDisplay.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:1842 XDefaultScreenOfDisplay = _lib.XDefaultScreenOfDisplay XDefaultScreenOfDisplay.restype = POINTER(Screen) XDefaultScreenOfDisplay.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1845 XEventMaskOfScreen = _lib.XEventMaskOfScreen XEventMaskOfScreen.restype = c_long XEventMaskOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:1849 XScreenNumberOfScreen = _lib.XScreenNumberOfScreen XScreenNumberOfScreen.restype = c_int XScreenNumberOfScreen.argtypes = [POINTER(Screen)] XErrorHandler = CFUNCTYPE(c_int, POINTER(Display), POINTER( XErrorEvent)) # /usr/include/X11/Xlib.h:1853 # /usr/include/X11/Xlib.h:1858 XSetErrorHandler = _lib.XSetErrorHandler XSetErrorHandler.restype = XErrorHandler XSetErrorHandler.argtypes = [XErrorHandler] # /usr/include/X11/Xlib.h:1863 XIOErrorHandler = CFUNCTYPE(c_int, POINTER(Display)) # /usr/include/X11/Xlib.h:1867 XSetIOErrorHandler = _lib.XSetIOErrorHandler XSetIOErrorHandler.restype = XIOErrorHandler XSetIOErrorHandler.argtypes = [XIOErrorHandler] # /usr/include/X11/Xlib.h:1872 XListPixmapFormats = _lib.XListPixmapFormats XListPixmapFormats.restype = POINTER(XPixmapFormatValues) XListPixmapFormats.argtypes = [POINTER(Display), POINTER(c_int)] # /usr/include/X11/Xlib.h:1876 XListDepths = _lib.XListDepths XListDepths.restype = POINTER(c_int) XListDepths.argtypes = [POINTER(Display), c_int, POINTER(c_int)] # /usr/include/X11/Xlib.h:1884 XReconfigureWMWindow = _lib.XReconfigureWMWindow XReconfigureWMWindow.restype = c_int XReconfigureWMWindow.argtypes = [ POINTER(Display), Window, c_int, c_uint, POINTER(XWindowChanges)] # /usr/include/X11/Xlib.h:1892 XGetWMProtocols = _lib.XGetWMProtocols XGetWMProtocols.restype = c_int XGetWMProtocols.argtypes = [ POINTER(Display), Window, POINTER( POINTER(Atom)), POINTER(c_int)] # /usr/include/X11/Xlib.h:1898 XSetWMProtocols = _lib.XSetWMProtocols XSetWMProtocols.restype = c_int XSetWMProtocols.argtypes = [POINTER(Display), Window, POINTER(Atom), c_int] # /usr/include/X11/Xlib.h:1904 XIconifyWindow = _lib.XIconifyWindow XIconifyWindow.restype = c_int XIconifyWindow.argtypes = [POINTER(Display), Window, c_int] # /usr/include/X11/Xlib.h:1909 XWithdrawWindow = _lib.XWithdrawWindow XWithdrawWindow.restype = c_int XWithdrawWindow.argtypes = [POINTER(Display), Window, c_int] # /usr/include/X11/Xlib.h:1914 XGetCommand = _lib.XGetCommand XGetCommand.restype = c_int XGetCommand.argtypes = [ POINTER(Display), Window, POINTER( POINTER(c_char_p)), POINTER(c_int)] # /usr/include/X11/Xlib.h:1920 XGetWMColormapWindows = _lib.XGetWMColormapWindows XGetWMColormapWindows.restype = c_int XGetWMColormapWindows.argtypes = [ POINTER(Display), Window, POINTER( POINTER(Window)), POINTER(c_int)] # /usr/include/X11/Xlib.h:1926 XSetWMColormapWindows = _lib.XSetWMColormapWindows XSetWMColormapWindows.restype = c_int XSetWMColormapWindows.argtypes = [ POINTER(Display), Window, POINTER(Window), c_int] # /usr/include/X11/Xlib.h:1932 XFreeStringList = _lib.XFreeStringList XFreeStringList.restype = None XFreeStringList.argtypes = [POINTER(c_char_p)] # /usr/include/X11/Xlib.h:1935 XSetTransientForHint = _lib.XSetTransientForHint XSetTransientForHint.restype = c_int XSetTransientForHint.argtypes = [POINTER(Display), Window, Window] # /usr/include/X11/Xlib.h:1943 XActivateScreenSaver = _lib.XActivateScreenSaver XActivateScreenSaver.restype = c_int XActivateScreenSaver.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:1947 XAddHost = _lib.XAddHost XAddHost.restype = c_int XAddHost.argtypes = [POINTER(Display), POINTER(XHostAddress)] # /usr/include/X11/Xlib.h:1952 XAddHosts = _lib.XAddHosts XAddHosts.restype = c_int XAddHosts.argtypes = [POINTER(Display), POINTER(XHostAddress), c_int] # /usr/include/X11/Xlib.h:1958 XAddToExtensionList = _lib.XAddToExtensionList XAddToExtensionList.restype = c_int XAddToExtensionList.argtypes = [ POINTER( POINTER(struct__XExtData)), POINTER(XExtData)] # /usr/include/X11/Xlib.h:1963 XAddToSaveSet = _lib.XAddToSaveSet XAddToSaveSet.restype = c_int XAddToSaveSet.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:1968 XAllocColor = _lib.XAllocColor XAllocColor.restype = c_int XAllocColor.argtypes = [POINTER(Display), Colormap, POINTER(XColor)] # /usr/include/X11/Xlib.h:1974 XAllocColorCells = _lib.XAllocColorCells XAllocColorCells.restype = c_int XAllocColorCells.argtypes = [ POINTER(Display), Colormap, c_int, POINTER(c_ulong), c_uint, POINTER(c_ulong), c_uint] # /usr/include/X11/Xlib.h:1984 XAllocColorPlanes = _lib.XAllocColorPlanes XAllocColorPlanes.restype = c_int XAllocColorPlanes.argtypes = [ POINTER(Display), Colormap, c_int, POINTER(c_ulong), c_int, c_int, c_int, c_int, POINTER(c_ulong), POINTER(c_ulong), POINTER(c_ulong)] # /usr/include/X11/Xlib.h:1998 XAllocNamedColor = _lib.XAllocNamedColor XAllocNamedColor.restype = c_int XAllocNamedColor.argtypes = [ POINTER(Display), Colormap, c_char_p, POINTER(XColor), POINTER(XColor)] # /usr/include/X11/Xlib.h:2006 XAllowEvents = _lib.XAllowEvents XAllowEvents.restype = c_int XAllowEvents.argtypes = [POINTER(Display), c_int, Time] # /usr/include/X11/Xlib.h:2012 XAutoRepeatOff = _lib.XAutoRepeatOff XAutoRepeatOff.restype = c_int XAutoRepeatOff.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2016 XAutoRepeatOn = _lib.XAutoRepeatOn XAutoRepeatOn.restype = c_int XAutoRepeatOn.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2020 XBell = _lib.XBell XBell.restype = c_int XBell.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2025 XBitmapBitOrder = _lib.XBitmapBitOrder XBitmapBitOrder.restype = c_int XBitmapBitOrder.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2029 XBitmapPad = _lib.XBitmapPad XBitmapPad.restype = c_int XBitmapPad.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2033 XBitmapUnit = _lib.XBitmapUnit XBitmapUnit.restype = c_int XBitmapUnit.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2037 XCellsOfScreen = _lib.XCellsOfScreen XCellsOfScreen.restype = c_int XCellsOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2041 XChangeActivePointerGrab = _lib.XChangeActivePointerGrab XChangeActivePointerGrab.restype = c_int XChangeActivePointerGrab.argtypes = [POINTER(Display), c_uint, Cursor, Time] # /usr/include/X11/Xlib.h:2048 XChangeGC = _lib.XChangeGC XChangeGC.restype = c_int XChangeGC.argtypes = [POINTER(Display), GC, c_ulong, POINTER(XGCValues)] # /usr/include/X11/Xlib.h:2055 XChangeKeyboardControl = _lib.XChangeKeyboardControl XChangeKeyboardControl.restype = c_int XChangeKeyboardControl.argtypes = [ POINTER(Display), c_ulong, POINTER(XKeyboardControl)] # /usr/include/X11/Xlib.h:2061 XChangeKeyboardMapping = _lib.XChangeKeyboardMapping XChangeKeyboardMapping.restype = c_int XChangeKeyboardMapping.argtypes = [ POINTER(Display), c_int, c_int, POINTER(KeySym), c_int] # /usr/include/X11/Xlib.h:2069 XChangePointerControl = _lib.XChangePointerControl XChangePointerControl.restype = c_int XChangePointerControl.argtypes = [ POINTER(Display), c_int, c_int, c_int, c_int, c_int] # /usr/include/X11/Xlib.h:2078 XChangeProperty = _lib.XChangeProperty XChangeProperty.restype = c_int XChangeProperty.argtypes = [ POINTER(Display), Window, Atom, Atom, c_int, c_int, POINTER(c_ubyte), c_int] # /usr/include/X11/Xlib.h:2089 XChangeSaveSet = _lib.XChangeSaveSet XChangeSaveSet.restype = c_int XChangeSaveSet.argtypes = [POINTER(Display), Window, c_int] # /usr/include/X11/Xlib.h:2095 XChangeWindowAttributes = _lib.XChangeWindowAttributes XChangeWindowAttributes.restype = c_int XChangeWindowAttributes.argtypes = [ POINTER(Display), Window, c_ulong, POINTER(XSetWindowAttributes)] # /usr/include/X11/Xlib.h:2102 XCheckIfEvent = _lib.XCheckIfEvent XCheckIfEvent.restype = c_int XCheckIfEvent.argtypes = [ POINTER(Display), POINTER(XEvent), CFUNCTYPE( c_int, POINTER(Display), POINTER(XEvent), XPointer), XPointer] # /usr/include/X11/Xlib.h:2113 XCheckMaskEvent = _lib.XCheckMaskEvent XCheckMaskEvent.restype = c_int XCheckMaskEvent.argtypes = [POINTER(Display), c_long, POINTER(XEvent)] # /usr/include/X11/Xlib.h:2119 XCheckTypedEvent = _lib.XCheckTypedEvent XCheckTypedEvent.restype = c_int XCheckTypedEvent.argtypes = [POINTER(Display), c_int, POINTER(XEvent)] # /usr/include/X11/Xlib.h:2125 XCheckTypedWindowEvent = _lib.XCheckTypedWindowEvent XCheckTypedWindowEvent.restype = c_int XCheckTypedWindowEvent.argtypes = [ POINTER(Display), Window, c_int, POINTER(XEvent)] # /usr/include/X11/Xlib.h:2132 XCheckWindowEvent = _lib.XCheckWindowEvent XCheckWindowEvent.restype = c_int XCheckWindowEvent.argtypes = [ POINTER(Display), Window, c_long, POINTER(XEvent)] # /usr/include/X11/Xlib.h:2139 XCirculateSubwindows = _lib.XCirculateSubwindows XCirculateSubwindows.restype = c_int XCirculateSubwindows.argtypes = [POINTER(Display), Window, c_int] # /usr/include/X11/Xlib.h:2145 XCirculateSubwindowsDown = _lib.XCirculateSubwindowsDown XCirculateSubwindowsDown.restype = c_int XCirculateSubwindowsDown.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2150 XCirculateSubwindowsUp = _lib.XCirculateSubwindowsUp XCirculateSubwindowsUp.restype = c_int XCirculateSubwindowsUp.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2155 XClearArea = _lib.XClearArea XClearArea.restype = c_int XClearArea.argtypes = [ POINTER(Display), Window, c_int, c_int, c_uint, c_uint, c_int] # /usr/include/X11/Xlib.h:2165 XClearWindow = _lib.XClearWindow XClearWindow.restype = c_int XClearWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2170 XCloseDisplay = _lib.XCloseDisplay XCloseDisplay.restype = c_int XCloseDisplay.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2174 XConfigureWindow = _lib.XConfigureWindow XConfigureWindow.restype = c_int XConfigureWindow.argtypes = [ POINTER(Display), Window, c_uint, POINTER(XWindowChanges)] # /usr/include/X11/Xlib.h:2181 XConnectionNumber = _lib.XConnectionNumber XConnectionNumber.restype = c_int XConnectionNumber.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2185 XConvertSelection = _lib.XConvertSelection XConvertSelection.restype = c_int XConvertSelection.argtypes = [POINTER(Display), Atom, Atom, Atom, Window, Time] # /usr/include/X11/Xlib.h:2194 XCopyArea = _lib.XCopyArea XCopyArea.restype = c_int XCopyArea.argtypes = [ POINTER(Display), Drawable, Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:2207 XCopyGC = _lib.XCopyGC XCopyGC.restype = c_int XCopyGC.argtypes = [POINTER(Display), GC, c_ulong, GC] # /usr/include/X11/Xlib.h:2214 XCopyPlane = _lib.XCopyPlane XCopyPlane.restype = c_int XCopyPlane.argtypes = [ POINTER(Display), Drawable, Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int, c_ulong] # /usr/include/X11/Xlib.h:2228 XDefaultDepth = _lib.XDefaultDepth XDefaultDepth.restype = c_int XDefaultDepth.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2233 XDefaultDepthOfScreen = _lib.XDefaultDepthOfScreen XDefaultDepthOfScreen.restype = c_int XDefaultDepthOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2237 XDefaultScreen = _lib.XDefaultScreen XDefaultScreen.restype = c_int XDefaultScreen.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2241 XDefineCursor = _lib.XDefineCursor XDefineCursor.restype = c_int XDefineCursor.argtypes = [POINTER(Display), Window, Cursor] # /usr/include/X11/Xlib.h:2247 XDeleteProperty = _lib.XDeleteProperty XDeleteProperty.restype = c_int XDeleteProperty.argtypes = [POINTER(Display), Window, Atom] # /usr/include/X11/Xlib.h:2253 XDestroyWindow = _lib.XDestroyWindow XDestroyWindow.restype = c_int XDestroyWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2258 XDestroySubwindows = _lib.XDestroySubwindows XDestroySubwindows.restype = c_int XDestroySubwindows.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2263 XDoesBackingStore = _lib.XDoesBackingStore XDoesBackingStore.restype = c_int XDoesBackingStore.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2267 XDoesSaveUnders = _lib.XDoesSaveUnders XDoesSaveUnders.restype = c_int XDoesSaveUnders.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2271 XDisableAccessControl = _lib.XDisableAccessControl XDisableAccessControl.restype = c_int XDisableAccessControl.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2276 XDisplayCells = _lib.XDisplayCells XDisplayCells.restype = c_int XDisplayCells.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2281 XDisplayHeight = _lib.XDisplayHeight XDisplayHeight.restype = c_int XDisplayHeight.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2286 XDisplayHeightMM = _lib.XDisplayHeightMM XDisplayHeightMM.restype = c_int XDisplayHeightMM.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2291 XDisplayKeycodes = _lib.XDisplayKeycodes XDisplayKeycodes.restype = c_int XDisplayKeycodes.argtypes = [POINTER(Display), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:2297 XDisplayPlanes = _lib.XDisplayPlanes XDisplayPlanes.restype = c_int XDisplayPlanes.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2302 XDisplayWidth = _lib.XDisplayWidth XDisplayWidth.restype = c_int XDisplayWidth.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2307 XDisplayWidthMM = _lib.XDisplayWidthMM XDisplayWidthMM.restype = c_int XDisplayWidthMM.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2312 XDrawArc = _lib.XDrawArc XDrawArc.restype = c_int XDrawArc.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:2324 XDrawArcs = _lib.XDrawArcs XDrawArcs.restype = c_int XDrawArcs.argtypes = [POINTER(Display), Drawable, GC, POINTER(XArc), c_int] # /usr/include/X11/Xlib.h:2332 XDrawImageString = _lib.XDrawImageString XDrawImageString.restype = c_int XDrawImageString.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:2342 XDrawImageString16 = _lib.XDrawImageString16 XDrawImageString16.restype = c_int XDrawImageString16.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XChar2b), c_int] # /usr/include/X11/Xlib.h:2352 XDrawLine = _lib.XDrawLine XDrawLine.restype = c_int XDrawLine.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, c_int, c_int] # /usr/include/X11/Xlib.h:2362 XDrawLines = _lib.XDrawLines XDrawLines.restype = c_int XDrawLines.argtypes = [ POINTER(Display), Drawable, GC, POINTER(XPoint), c_int, c_int] # /usr/include/X11/Xlib.h:2371 XDrawPoint = _lib.XDrawPoint XDrawPoint.restype = c_int XDrawPoint.argtypes = [POINTER(Display), Drawable, GC, c_int, c_int] # /usr/include/X11/Xlib.h:2379 XDrawPoints = _lib.XDrawPoints XDrawPoints.restype = c_int XDrawPoints.argtypes = [ POINTER(Display), Drawable, GC, POINTER(XPoint), c_int, c_int] # /usr/include/X11/Xlib.h:2388 XDrawRectangle = _lib.XDrawRectangle XDrawRectangle.restype = c_int XDrawRectangle.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, c_uint, c_uint] # /usr/include/X11/Xlib.h:2398 XDrawRectangles = _lib.XDrawRectangles XDrawRectangles.restype = c_int XDrawRectangles.argtypes = [ POINTER(Display), Drawable, GC, POINTER(XRectangle), c_int] # /usr/include/X11/Xlib.h:2406 XDrawSegments = _lib.XDrawSegments XDrawSegments.restype = c_int XDrawSegments.argtypes = [ POINTER(Display), Drawable, GC, POINTER(XSegment), c_int] # /usr/include/X11/Xlib.h:2414 XDrawString = _lib.XDrawString XDrawString.restype = c_int XDrawString.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:2424 XDrawString16 = _lib.XDrawString16 XDrawString16.restype = c_int XDrawString16.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XChar2b), c_int] # /usr/include/X11/Xlib.h:2434 XDrawText = _lib.XDrawText XDrawText.restype = c_int XDrawText.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XTextItem), c_int] # /usr/include/X11/Xlib.h:2444 XDrawText16 = _lib.XDrawText16 XDrawText16.restype = c_int XDrawText16.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XTextItem16), c_int] # /usr/include/X11/Xlib.h:2454 XEnableAccessControl = _lib.XEnableAccessControl XEnableAccessControl.restype = c_int XEnableAccessControl.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2458 XEventsQueued = _lib.XEventsQueued XEventsQueued.restype = c_int XEventsQueued.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2463 XFetchName = _lib.XFetchName XFetchName.restype = c_int XFetchName.argtypes = [POINTER(Display), Window, POINTER(c_char_p)] # /usr/include/X11/Xlib.h:2469 XFillArc = _lib.XFillArc XFillArc.restype = c_int XFillArc.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:2481 XFillArcs = _lib.XFillArcs XFillArcs.restype = c_int XFillArcs.argtypes = [POINTER(Display), Drawable, GC, POINTER(XArc), c_int] # /usr/include/X11/Xlib.h:2489 XFillPolygon = _lib.XFillPolygon XFillPolygon.restype = c_int XFillPolygon.argtypes = [ POINTER(Display), Drawable, GC, POINTER(XPoint), c_int, c_int, c_int] # /usr/include/X11/Xlib.h:2499 XFillRectangle = _lib.XFillRectangle XFillRectangle.restype = c_int XFillRectangle.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, c_uint, c_uint] # /usr/include/X11/Xlib.h:2509 XFillRectangles = _lib.XFillRectangles XFillRectangles.restype = c_int XFillRectangles.argtypes = [ POINTER(Display), Drawable, GC, POINTER(XRectangle), c_int] # /usr/include/X11/Xlib.h:2517 XFlush = _lib.XFlush XFlush.restype = c_int XFlush.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2521 XForceScreenSaver = _lib.XForceScreenSaver XForceScreenSaver.restype = c_int XForceScreenSaver.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:2526 XFree = _lib.XFree XFree.restype = c_int XFree.argtypes = [POINTER(None)] # /usr/include/X11/Xlib.h:2530 XFreeColormap = _lib.XFreeColormap XFreeColormap.restype = c_int XFreeColormap.argtypes = [POINTER(Display), Colormap] # /usr/include/X11/Xlib.h:2535 XFreeColors = _lib.XFreeColors XFreeColors.restype = c_int XFreeColors.argtypes = [ POINTER(Display), Colormap, POINTER(c_ulong), c_int, c_ulong] # /usr/include/X11/Xlib.h:2543 XFreeCursor = _lib.XFreeCursor XFreeCursor.restype = c_int XFreeCursor.argtypes = [POINTER(Display), Cursor] # /usr/include/X11/Xlib.h:2548 XFreeExtensionList = _lib.XFreeExtensionList XFreeExtensionList.restype = c_int XFreeExtensionList.argtypes = [POINTER(c_char_p)] # /usr/include/X11/Xlib.h:2552 XFreeFont = _lib.XFreeFont XFreeFont.restype = c_int XFreeFont.argtypes = [POINTER(Display), POINTER(XFontStruct)] # /usr/include/X11/Xlib.h:2557 XFreeFontInfo = _lib.XFreeFontInfo XFreeFontInfo.restype = c_int XFreeFontInfo.argtypes = [POINTER(c_char_p), POINTER(XFontStruct), c_int] # /usr/include/X11/Xlib.h:2563 XFreeFontNames = _lib.XFreeFontNames XFreeFontNames.restype = c_int XFreeFontNames.argtypes = [POINTER(c_char_p)] # /usr/include/X11/Xlib.h:2567 XFreeFontPath = _lib.XFreeFontPath XFreeFontPath.restype = c_int XFreeFontPath.argtypes = [POINTER(c_char_p)] # /usr/include/X11/Xlib.h:2571 XFreeGC = _lib.XFreeGC XFreeGC.restype = c_int XFreeGC.argtypes = [POINTER(Display), GC] # /usr/include/X11/Xlib.h:2576 XFreeModifiermap = _lib.XFreeModifiermap XFreeModifiermap.restype = c_int XFreeModifiermap.argtypes = [POINTER(XModifierKeymap)] # /usr/include/X11/Xlib.h:2580 XFreePixmap = _lib.XFreePixmap XFreePixmap.restype = c_int XFreePixmap.argtypes = [POINTER(Display), Pixmap] # /usr/include/X11/Xlib.h:2585 XGeometry = _lib.XGeometry XGeometry.restype = c_int XGeometry.argtypes = [ POINTER(Display), c_int, c_char_p, c_char_p, c_uint, c_uint, c_uint, c_int, c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:2601 XGetErrorDatabaseText = _lib.XGetErrorDatabaseText XGetErrorDatabaseText.restype = c_int XGetErrorDatabaseText.argtypes = [ POINTER(Display), c_char_p, c_char_p, c_char_p, c_char_p, c_int] # /usr/include/X11/Xlib.h:2610 XGetErrorText = _lib.XGetErrorText XGetErrorText.restype = c_int XGetErrorText.argtypes = [POINTER(Display), c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:2617 XGetFontProperty = _lib.XGetFontProperty XGetFontProperty.restype = c_int XGetFontProperty.argtypes = [POINTER(XFontStruct), Atom, POINTER(c_ulong)] # /usr/include/X11/Xlib.h:2623 XGetGCValues = _lib.XGetGCValues XGetGCValues.restype = c_int XGetGCValues.argtypes = [POINTER(Display), GC, c_ulong, POINTER(XGCValues)] # /usr/include/X11/Xlib.h:2630 XGetGeometry = _lib.XGetGeometry XGetGeometry.restype = c_int XGetGeometry.argtypes = [ POINTER(Display), Drawable, POINTER(Window), POINTER(c_int), POINTER(c_int), POINTER(c_uint), POINTER(c_uint), POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2642 XGetIconName = _lib.XGetIconName XGetIconName.restype = c_int XGetIconName.argtypes = [POINTER(Display), Window, POINTER(c_char_p)] # /usr/include/X11/Xlib.h:2648 XGetInputFocus = _lib.XGetInputFocus XGetInputFocus.restype = c_int XGetInputFocus.argtypes = [POINTER(Display), POINTER(Window), POINTER(c_int)] # /usr/include/X11/Xlib.h:2654 XGetKeyboardControl = _lib.XGetKeyboardControl XGetKeyboardControl.restype = c_int XGetKeyboardControl.argtypes = [POINTER(Display), POINTER(XKeyboardState)] # /usr/include/X11/Xlib.h:2659 XGetPointerControl = _lib.XGetPointerControl XGetPointerControl.restype = c_int XGetPointerControl.argtypes = [ POINTER(Display), POINTER(c_int), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:2666 XGetPointerMapping = _lib.XGetPointerMapping XGetPointerMapping.restype = c_int XGetPointerMapping.argtypes = [POINTER(Display), POINTER(c_ubyte), c_int] # /usr/include/X11/Xlib.h:2672 XGetScreenSaver = _lib.XGetScreenSaver XGetScreenSaver.restype = c_int XGetScreenSaver.argtypes = [ POINTER(Display), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:2680 XGetTransientForHint = _lib.XGetTransientForHint XGetTransientForHint.restype = c_int XGetTransientForHint.argtypes = [POINTER(Display), Window, POINTER(Window)] # /usr/include/X11/Xlib.h:2686 XGetWindowProperty = _lib.XGetWindowProperty XGetWindowProperty.restype = c_int XGetWindowProperty.argtypes = [ POINTER(Display), Window, Atom, c_long, c_long, c_int, Atom, POINTER(Atom), POINTER(c_int), POINTER(c_ulong), POINTER(c_ulong), POINTER( POINTER(c_ubyte))] # /usr/include/X11/Xlib.h:2701 XGetWindowAttributes = _lib.XGetWindowAttributes XGetWindowAttributes.restype = c_int XGetWindowAttributes.argtypes = [ POINTER(Display), Window, POINTER(XWindowAttributes)] # /usr/include/X11/Xlib.h:2707 XGrabButton = _lib.XGrabButton XGrabButton.restype = c_int XGrabButton.argtypes = [ POINTER(Display), c_uint, c_uint, Window, c_int, c_uint, c_int, c_int, Window, Cursor] # /usr/include/X11/Xlib.h:2720 XGrabKey = _lib.XGrabKey XGrabKey.restype = c_int XGrabKey.argtypes = [ POINTER(Display), c_int, c_uint, Window, c_int, c_int, c_int] # /usr/include/X11/Xlib.h:2730 XGrabKeyboard = _lib.XGrabKeyboard XGrabKeyboard.restype = c_int XGrabKeyboard.argtypes = [POINTER(Display), Window, c_int, c_int, c_int, Time] # /usr/include/X11/Xlib.h:2739 XGrabPointer = _lib.XGrabPointer XGrabPointer.restype = c_int XGrabPointer.argtypes = [ POINTER(Display), Window, c_int, c_uint, c_int, c_int, Window, Cursor, Time] # /usr/include/X11/Xlib.h:2751 XGrabServer = _lib.XGrabServer XGrabServer.restype = c_int XGrabServer.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2755 XHeightMMOfScreen = _lib.XHeightMMOfScreen XHeightMMOfScreen.restype = c_int XHeightMMOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2759 XHeightOfScreen = _lib.XHeightOfScreen XHeightOfScreen.restype = c_int XHeightOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2763 XIfEvent = _lib.XIfEvent XIfEvent.restype = c_int XIfEvent.argtypes = [ POINTER(Display), POINTER(XEvent), CFUNCTYPE( c_int, POINTER(Display), POINTER(XEvent), XPointer), XPointer] # /usr/include/X11/Xlib.h:2774 XImageByteOrder = _lib.XImageByteOrder XImageByteOrder.restype = c_int XImageByteOrder.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2778 XInstallColormap = _lib.XInstallColormap XInstallColormap.restype = c_int XInstallColormap.argtypes = [POINTER(Display), Colormap] # /usr/include/X11/Xlib.h:2783 XKeysymToKeycode = _lib.XKeysymToKeycode XKeysymToKeycode.restype = KeyCode XKeysymToKeycode.argtypes = [POINTER(Display), KeySym] # /usr/include/X11/Xlib.h:2788 XKillClient = _lib.XKillClient XKillClient.restype = c_int XKillClient.argtypes = [POINTER(Display), XID] # /usr/include/X11/Xlib.h:2793 XLookupColor = _lib.XLookupColor XLookupColor.restype = c_int XLookupColor.argtypes = [ POINTER(Display), Colormap, c_char_p, POINTER(XColor), POINTER(XColor)] # /usr/include/X11/Xlib.h:2801 XLowerWindow = _lib.XLowerWindow XLowerWindow.restype = c_int XLowerWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2806 XMapRaised = _lib.XMapRaised XMapRaised.restype = c_int XMapRaised.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2811 XMapSubwindows = _lib.XMapSubwindows XMapSubwindows.restype = c_int XMapSubwindows.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2816 XMapWindow = _lib.XMapWindow XMapWindow.restype = c_int XMapWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:2821 XMaskEvent = _lib.XMaskEvent XMaskEvent.restype = c_int XMaskEvent.argtypes = [POINTER(Display), c_long, POINTER(XEvent)] # /usr/include/X11/Xlib.h:2827 XMaxCmapsOfScreen = _lib.XMaxCmapsOfScreen XMaxCmapsOfScreen.restype = c_int XMaxCmapsOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2831 XMinCmapsOfScreen = _lib.XMinCmapsOfScreen XMinCmapsOfScreen.restype = c_int XMinCmapsOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2835 XMoveResizeWindow = _lib.XMoveResizeWindow XMoveResizeWindow.restype = c_int XMoveResizeWindow.argtypes = [ POINTER(Display), Window, c_int, c_int, c_uint, c_uint] # /usr/include/X11/Xlib.h:2844 XMoveWindow = _lib.XMoveWindow XMoveWindow.restype = c_int XMoveWindow.argtypes = [POINTER(Display), Window, c_int, c_int] # /usr/include/X11/Xlib.h:2851 XNextEvent = _lib.XNextEvent XNextEvent.restype = c_int XNextEvent.argtypes = [POINTER(Display), POINTER(XEvent)] # /usr/include/X11/Xlib.h:2856 XNoOp = _lib.XNoOp XNoOp.restype = c_int XNoOp.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2860 XParseColor = _lib.XParseColor XParseColor.restype = c_int XParseColor.argtypes = [POINTER(Display), Colormap, c_char_p, POINTER(XColor)] # /usr/include/X11/Xlib.h:2867 XParseGeometry = _lib.XParseGeometry XParseGeometry.restype = c_int XParseGeometry.argtypes = [ c_char_p, POINTER(c_int), POINTER(c_int), POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2875 XPeekEvent = _lib.XPeekEvent XPeekEvent.restype = c_int XPeekEvent.argtypes = [POINTER(Display), POINTER(XEvent)] # /usr/include/X11/Xlib.h:2880 XPeekIfEvent = _lib.XPeekIfEvent XPeekIfEvent.restype = c_int XPeekIfEvent.argtypes = [ POINTER(Display), POINTER(XEvent), CFUNCTYPE( c_int, POINTER(Display), POINTER(XEvent), XPointer), XPointer] # /usr/include/X11/Xlib.h:2891 XPending = _lib.XPending XPending.restype = c_int XPending.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2895 XPlanesOfScreen = _lib.XPlanesOfScreen XPlanesOfScreen.restype = c_int XPlanesOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:2899 XProtocolRevision = _lib.XProtocolRevision XProtocolRevision.restype = c_int XProtocolRevision.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2903 XProtocolVersion = _lib.XProtocolVersion XProtocolVersion.restype = c_int XProtocolVersion.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2908 XPutBackEvent = _lib.XPutBackEvent XPutBackEvent.restype = c_int XPutBackEvent.argtypes = [POINTER(Display), POINTER(XEvent)] # /usr/include/X11/Xlib.h:2913 XPutImage = _lib.XPutImage XPutImage.restype = c_int XPutImage.argtypes = [ POINTER(Display), Drawable, GC, POINTER(XImage), c_int, c_int, c_int, c_int, c_uint, c_uint] # /usr/include/X11/Xlib.h:2926 XQLength = _lib.XQLength XQLength.restype = c_int XQLength.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:2930 XQueryBestCursor = _lib.XQueryBestCursor XQueryBestCursor.restype = c_int XQueryBestCursor.argtypes = [ POINTER(Display), Drawable, c_uint, c_uint, POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2939 XQueryBestSize = _lib.XQueryBestSize XQueryBestSize.restype = c_int XQueryBestSize.argtypes = [ POINTER(Display), c_int, Drawable, c_uint, c_uint, POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2949 XQueryBestStipple = _lib.XQueryBestStipple XQueryBestStipple.restype = c_int XQueryBestStipple.argtypes = [ POINTER(Display), Drawable, c_uint, c_uint, POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2958 XQueryBestTile = _lib.XQueryBestTile XQueryBestTile.restype = c_int XQueryBestTile.argtypes = [ POINTER(Display), Drawable, c_uint, c_uint, POINTER(c_uint), POINTER(c_uint)] # /usr/include/X11/Xlib.h:2967 XQueryColor = _lib.XQueryColor XQueryColor.restype = c_int XQueryColor.argtypes = [POINTER(Display), Colormap, POINTER(XColor)] # /usr/include/X11/Xlib.h:2973 XQueryColors = _lib.XQueryColors XQueryColors.restype = c_int XQueryColors.argtypes = [POINTER(Display), Colormap, POINTER(XColor), c_int] # /usr/include/X11/Xlib.h:2980 XQueryExtension = _lib.XQueryExtension XQueryExtension.restype = c_int XQueryExtension.argtypes = [ POINTER(Display), c_char_p, POINTER(c_int), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:2988 XQueryKeymap = _lib.XQueryKeymap XQueryKeymap.restype = c_int XQueryKeymap.argtypes = [POINTER(Display), c_char * 32] # /usr/include/X11/Xlib.h:2993 XQueryPointer = _lib.XQueryPointer XQueryPointer.restype = c_int XQueryPointer.argtypes = [ POINTER(Display), Window, POINTER(Window), POINTER(Window), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_uint)] # /usr/include/X11/Xlib.h:3005 XQueryTextExtents = _lib.XQueryTextExtents XQueryTextExtents.restype = c_int XQueryTextExtents.argtypes = [ POINTER(Display), XID, c_char_p, c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(XCharStruct)] # /usr/include/X11/Xlib.h:3016 XQueryTextExtents16 = _lib.XQueryTextExtents16 XQueryTextExtents16.restype = c_int XQueryTextExtents16.argtypes = [ POINTER(Display), XID, POINTER(XChar2b), c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(XCharStruct)] # /usr/include/X11/Xlib.h:3027 XQueryTree = _lib.XQueryTree XQueryTree.restype = c_int XQueryTree.argtypes = [ POINTER(Display), Window, POINTER(Window), POINTER(Window), POINTER( POINTER(Window)), POINTER(c_uint)] # /usr/include/X11/Xlib.h:3036 XRaiseWindow = _lib.XRaiseWindow XRaiseWindow.restype = c_int XRaiseWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:3041 XReadBitmapFile = _lib.XReadBitmapFile XReadBitmapFile.restype = c_int XReadBitmapFile.argtypes = [ POINTER(Display), Drawable, c_char_p, POINTER(c_uint), POINTER(c_uint), POINTER(Pixmap), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:3052 XReadBitmapFileData = _lib.XReadBitmapFileData XReadBitmapFileData.restype = c_int XReadBitmapFileData.argtypes = [ c_char_p, POINTER(c_uint), POINTER(c_uint), POINTER( POINTER(c_ubyte)), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xlib.h:3061 XRebindKeysym = _lib.XRebindKeysym XRebindKeysym.restype = c_int XRebindKeysym.argtypes = [ POINTER(Display), KeySym, POINTER(KeySym), c_int, POINTER(c_ubyte), c_int] # /usr/include/X11/Xlib.h:3070 XRecolorCursor = _lib.XRecolorCursor XRecolorCursor.restype = c_int XRecolorCursor.argtypes = [ POINTER(Display), Cursor, POINTER(XColor), POINTER(XColor)] # /usr/include/X11/Xlib.h:3077 XRefreshKeyboardMapping = _lib.XRefreshKeyboardMapping XRefreshKeyboardMapping.restype = c_int XRefreshKeyboardMapping.argtypes = [POINTER(XMappingEvent)] # /usr/include/X11/Xlib.h:3081 XRemoveFromSaveSet = _lib.XRemoveFromSaveSet XRemoveFromSaveSet.restype = c_int XRemoveFromSaveSet.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:3086 XRemoveHost = _lib.XRemoveHost XRemoveHost.restype = c_int XRemoveHost.argtypes = [POINTER(Display), POINTER(XHostAddress)] # /usr/include/X11/Xlib.h:3091 XRemoveHosts = _lib.XRemoveHosts XRemoveHosts.restype = c_int XRemoveHosts.argtypes = [POINTER(Display), POINTER(XHostAddress), c_int] # /usr/include/X11/Xlib.h:3097 XReparentWindow = _lib.XReparentWindow XReparentWindow.restype = c_int XReparentWindow.argtypes = [POINTER(Display), Window, Window, c_int, c_int] # /usr/include/X11/Xlib.h:3105 XResetScreenSaver = _lib.XResetScreenSaver XResetScreenSaver.restype = c_int XResetScreenSaver.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:3109 XResizeWindow = _lib.XResizeWindow XResizeWindow.restype = c_int XResizeWindow.argtypes = [POINTER(Display), Window, c_uint, c_uint] # /usr/include/X11/Xlib.h:3116 XRestackWindows = _lib.XRestackWindows XRestackWindows.restype = c_int XRestackWindows.argtypes = [POINTER(Display), POINTER(Window), c_int] # /usr/include/X11/Xlib.h:3122 XRotateBuffers = _lib.XRotateBuffers XRotateBuffers.restype = c_int XRotateBuffers.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:3127 XRotateWindowProperties = _lib.XRotateWindowProperties XRotateWindowProperties.restype = c_int XRotateWindowProperties.argtypes = [ POINTER(Display), Window, POINTER(Atom), c_int, c_int] # /usr/include/X11/Xlib.h:3135 XScreenCount = _lib.XScreenCount XScreenCount.restype = c_int XScreenCount.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:3139 XSelectInput = _lib.XSelectInput XSelectInput.restype = c_int XSelectInput.argtypes = [POINTER(Display), Window, c_long] # /usr/include/X11/Xlib.h:3145 XSendEvent = _lib.XSendEvent XSendEvent.restype = c_int XSendEvent.argtypes = [ POINTER(Display), Window, c_int, c_long, POINTER(XEvent)] # /usr/include/X11/Xlib.h:3153 XSetAccessControl = _lib.XSetAccessControl XSetAccessControl.restype = c_int XSetAccessControl.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:3158 XSetArcMode = _lib.XSetArcMode XSetArcMode.restype = c_int XSetArcMode.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3164 XSetBackground = _lib.XSetBackground XSetBackground.restype = c_int XSetBackground.argtypes = [POINTER(Display), GC, c_ulong] # /usr/include/X11/Xlib.h:3170 XSetClipMask = _lib.XSetClipMask XSetClipMask.restype = c_int XSetClipMask.argtypes = [POINTER(Display), GC, Pixmap] # /usr/include/X11/Xlib.h:3176 XSetClipOrigin = _lib.XSetClipOrigin XSetClipOrigin.restype = c_int XSetClipOrigin.argtypes = [POINTER(Display), GC, c_int, c_int] # /usr/include/X11/Xlib.h:3183 XSetClipRectangles = _lib.XSetClipRectangles XSetClipRectangles.restype = c_int XSetClipRectangles.argtypes = [ POINTER(Display), GC, c_int, c_int, POINTER(XRectangle), c_int, c_int] # /usr/include/X11/Xlib.h:3193 XSetCloseDownMode = _lib.XSetCloseDownMode XSetCloseDownMode.restype = c_int XSetCloseDownMode.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:3198 XSetCommand = _lib.XSetCommand XSetCommand.restype = c_int XSetCommand.argtypes = [POINTER(Display), Window, POINTER(c_char_p), c_int] # /usr/include/X11/Xlib.h:3205 XSetDashes = _lib.XSetDashes XSetDashes.restype = c_int XSetDashes.argtypes = [POINTER(Display), GC, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:3213 XSetFillRule = _lib.XSetFillRule XSetFillRule.restype = c_int XSetFillRule.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3219 XSetFillStyle = _lib.XSetFillStyle XSetFillStyle.restype = c_int XSetFillStyle.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3225 XSetFont = _lib.XSetFont XSetFont.restype = c_int XSetFont.argtypes = [POINTER(Display), GC, Font] # /usr/include/X11/Xlib.h:3231 XSetFontPath = _lib.XSetFontPath XSetFontPath.restype = c_int XSetFontPath.argtypes = [POINTER(Display), POINTER(c_char_p), c_int] # /usr/include/X11/Xlib.h:3237 XSetForeground = _lib.XSetForeground XSetForeground.restype = c_int XSetForeground.argtypes = [POINTER(Display), GC, c_ulong] # /usr/include/X11/Xlib.h:3243 XSetFunction = _lib.XSetFunction XSetFunction.restype = c_int XSetFunction.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3249 XSetGraphicsExposures = _lib.XSetGraphicsExposures XSetGraphicsExposures.restype = c_int XSetGraphicsExposures.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3255 XSetIconName = _lib.XSetIconName XSetIconName.restype = c_int XSetIconName.argtypes = [POINTER(Display), Window, c_char_p] # /usr/include/X11/Xlib.h:3261 XSetInputFocus = _lib.XSetInputFocus XSetInputFocus.restype = c_int XSetInputFocus.argtypes = [POINTER(Display), Window, c_int, Time] # /usr/include/X11/Xlib.h:3268 XSetLineAttributes = _lib.XSetLineAttributes XSetLineAttributes.restype = c_int XSetLineAttributes.argtypes = [ POINTER(Display), GC, c_uint, c_int, c_int, c_int] # /usr/include/X11/Xlib.h:3277 XSetModifierMapping = _lib.XSetModifierMapping XSetModifierMapping.restype = c_int XSetModifierMapping.argtypes = [POINTER(Display), POINTER(XModifierKeymap)] # /usr/include/X11/Xlib.h:3282 XSetPlaneMask = _lib.XSetPlaneMask XSetPlaneMask.restype = c_int XSetPlaneMask.argtypes = [POINTER(Display), GC, c_ulong] # /usr/include/X11/Xlib.h:3288 XSetPointerMapping = _lib.XSetPointerMapping XSetPointerMapping.restype = c_int XSetPointerMapping.argtypes = [POINTER(Display), POINTER(c_ubyte), c_int] # /usr/include/X11/Xlib.h:3294 XSetScreenSaver = _lib.XSetScreenSaver XSetScreenSaver.restype = c_int XSetScreenSaver.argtypes = [POINTER(Display), c_int, c_int, c_int, c_int] # /usr/include/X11/Xlib.h:3302 XSetSelectionOwner = _lib.XSetSelectionOwner XSetSelectionOwner.restype = c_int XSetSelectionOwner.argtypes = [POINTER(Display), Atom, Window, Time] # /usr/include/X11/Xlib.h:3309 XSetState = _lib.XSetState XSetState.restype = c_int XSetState.argtypes = [POINTER(Display), GC, c_ulong, c_ulong, c_int, c_ulong] # /usr/include/X11/Xlib.h:3318 XSetStipple = _lib.XSetStipple XSetStipple.restype = c_int XSetStipple.argtypes = [POINTER(Display), GC, Pixmap] # /usr/include/X11/Xlib.h:3324 XSetSubwindowMode = _lib.XSetSubwindowMode XSetSubwindowMode.restype = c_int XSetSubwindowMode.argtypes = [POINTER(Display), GC, c_int] # /usr/include/X11/Xlib.h:3330 XSetTSOrigin = _lib.XSetTSOrigin XSetTSOrigin.restype = c_int XSetTSOrigin.argtypes = [POINTER(Display), GC, c_int, c_int] # /usr/include/X11/Xlib.h:3337 XSetTile = _lib.XSetTile XSetTile.restype = c_int XSetTile.argtypes = [POINTER(Display), GC, Pixmap] # /usr/include/X11/Xlib.h:3343 XSetWindowBackground = _lib.XSetWindowBackground XSetWindowBackground.restype = c_int XSetWindowBackground.argtypes = [POINTER(Display), Window, c_ulong] # /usr/include/X11/Xlib.h:3349 XSetWindowBackgroundPixmap = _lib.XSetWindowBackgroundPixmap XSetWindowBackgroundPixmap.restype = c_int XSetWindowBackgroundPixmap.argtypes = [POINTER(Display), Window, Pixmap] # /usr/include/X11/Xlib.h:3355 XSetWindowBorder = _lib.XSetWindowBorder XSetWindowBorder.restype = c_int XSetWindowBorder.argtypes = [POINTER(Display), Window, c_ulong] # /usr/include/X11/Xlib.h:3361 XSetWindowBorderPixmap = _lib.XSetWindowBorderPixmap XSetWindowBorderPixmap.restype = c_int XSetWindowBorderPixmap.argtypes = [POINTER(Display), Window, Pixmap] # /usr/include/X11/Xlib.h:3367 XSetWindowBorderWidth = _lib.XSetWindowBorderWidth XSetWindowBorderWidth.restype = c_int XSetWindowBorderWidth.argtypes = [POINTER(Display), Window, c_uint] # /usr/include/X11/Xlib.h:3373 XSetWindowColormap = _lib.XSetWindowColormap XSetWindowColormap.restype = c_int XSetWindowColormap.argtypes = [POINTER(Display), Window, Colormap] # /usr/include/X11/Xlib.h:3379 XStoreBuffer = _lib.XStoreBuffer XStoreBuffer.restype = c_int XStoreBuffer.argtypes = [POINTER(Display), c_char_p, c_int, c_int] # /usr/include/X11/Xlib.h:3386 XStoreBytes = _lib.XStoreBytes XStoreBytes.restype = c_int XStoreBytes.argtypes = [POINTER(Display), c_char_p, c_int] # /usr/include/X11/Xlib.h:3392 XStoreColor = _lib.XStoreColor XStoreColor.restype = c_int XStoreColor.argtypes = [POINTER(Display), Colormap, POINTER(XColor)] # /usr/include/X11/Xlib.h:3398 XStoreColors = _lib.XStoreColors XStoreColors.restype = c_int XStoreColors.argtypes = [POINTER(Display), Colormap, POINTER(XColor), c_int] # /usr/include/X11/Xlib.h:3405 XStoreName = _lib.XStoreName XStoreName.restype = c_int XStoreName.argtypes = [POINTER(Display), Window, c_char_p] # /usr/include/X11/Xlib.h:3411 XStoreNamedColor = _lib.XStoreNamedColor XStoreNamedColor.restype = c_int XStoreNamedColor.argtypes = [ POINTER(Display), Colormap, c_char_p, c_ulong, c_int] # /usr/include/X11/Xlib.h:3419 XSync = _lib.XSync XSync.restype = c_int XSync.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:3424 XTextExtents = _lib.XTextExtents XTextExtents.restype = c_int XTextExtents.argtypes = [ POINTER(XFontStruct), c_char_p, c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(XCharStruct)] # /usr/include/X11/Xlib.h:3434 XTextExtents16 = _lib.XTextExtents16 XTextExtents16.restype = c_int XTextExtents16.argtypes = [ POINTER(XFontStruct), POINTER(XChar2b), c_int, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(XCharStruct)] # /usr/include/X11/Xlib.h:3444 XTextWidth = _lib.XTextWidth XTextWidth.restype = c_int XTextWidth.argtypes = [POINTER(XFontStruct), c_char_p, c_int] # /usr/include/X11/Xlib.h:3450 XTextWidth16 = _lib.XTextWidth16 XTextWidth16.restype = c_int XTextWidth16.argtypes = [POINTER(XFontStruct), POINTER(XChar2b), c_int] # /usr/include/X11/Xlib.h:3456 XTranslateCoordinates = _lib.XTranslateCoordinates XTranslateCoordinates.restype = c_int XTranslateCoordinates.argtypes = [ POINTER(Display), Window, Window, c_int, c_int, POINTER(c_int), POINTER(c_int), POINTER(Window)] # /usr/include/X11/Xlib.h:3467 XUndefineCursor = _lib.XUndefineCursor XUndefineCursor.restype = c_int XUndefineCursor.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:3472 XUngrabButton = _lib.XUngrabButton XUngrabButton.restype = c_int XUngrabButton.argtypes = [POINTER(Display), c_uint, c_uint, Window] # /usr/include/X11/Xlib.h:3479 XUngrabKey = _lib.XUngrabKey XUngrabKey.restype = c_int XUngrabKey.argtypes = [POINTER(Display), c_int, c_uint, Window] # /usr/include/X11/Xlib.h:3486 XUngrabKeyboard = _lib.XUngrabKeyboard XUngrabKeyboard.restype = c_int XUngrabKeyboard.argtypes = [POINTER(Display), Time] # /usr/include/X11/Xlib.h:3491 XUngrabPointer = _lib.XUngrabPointer XUngrabPointer.restype = c_int XUngrabPointer.argtypes = [POINTER(Display), Time] # /usr/include/X11/Xlib.h:3496 XUngrabServer = _lib.XUngrabServer XUngrabServer.restype = c_int XUngrabServer.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:3500 XUninstallColormap = _lib.XUninstallColormap XUninstallColormap.restype = c_int XUninstallColormap.argtypes = [POINTER(Display), Colormap] # /usr/include/X11/Xlib.h:3505 XUnloadFont = _lib.XUnloadFont XUnloadFont.restype = c_int XUnloadFont.argtypes = [POINTER(Display), Font] # /usr/include/X11/Xlib.h:3510 XUnmapSubwindows = _lib.XUnmapSubwindows XUnmapSubwindows.restype = c_int XUnmapSubwindows.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:3515 XUnmapWindow = _lib.XUnmapWindow XUnmapWindow.restype = c_int XUnmapWindow.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xlib.h:3520 XVendorRelease = _lib.XVendorRelease XVendorRelease.restype = c_int XVendorRelease.argtypes = [POINTER(Display)] # /usr/include/X11/Xlib.h:3524 XWarpPointer = _lib.XWarpPointer XWarpPointer.restype = c_int XWarpPointer.argtypes = [ POINTER(Display), Window, Window, c_int, c_int, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:3536 XWidthMMOfScreen = _lib.XWidthMMOfScreen XWidthMMOfScreen.restype = c_int XWidthMMOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:3540 XWidthOfScreen = _lib.XWidthOfScreen XWidthOfScreen.restype = c_int XWidthOfScreen.argtypes = [POINTER(Screen)] # /usr/include/X11/Xlib.h:3544 XWindowEvent = _lib.XWindowEvent XWindowEvent.restype = c_int XWindowEvent.argtypes = [POINTER(Display), Window, c_long, POINTER(XEvent)] # /usr/include/X11/Xlib.h:3551 XWriteBitmapFile = _lib.XWriteBitmapFile XWriteBitmapFile.restype = c_int XWriteBitmapFile.argtypes = [ POINTER(Display), c_char_p, Pixmap, c_uint, c_uint, c_int, c_int] # /usr/include/X11/Xlib.h:3561 XSupportsLocale = _lib.XSupportsLocale XSupportsLocale.restype = c_int XSupportsLocale.argtypes = [] # /usr/include/X11/Xlib.h:3563 XSetLocaleModifiers = _lib.XSetLocaleModifiers XSetLocaleModifiers.restype = c_char_p XSetLocaleModifiers.argtypes = [c_char_p] class struct__XrmHashBucketRec(Structure): __slots__ = [ ] struct__XrmHashBucketRec._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/X11/Xlib.h:3567 XOpenOM = _lib.XOpenOM XOpenOM.restype = XOM XOpenOM.argtypes = [ POINTER(Display), POINTER(struct__XrmHashBucketRec), c_char_p, c_char_p] # /usr/include/X11/Xlib.h:3574 XCloseOM = _lib.XCloseOM XCloseOM.restype = c_int XCloseOM.argtypes = [XOM] # /usr/include/X11/Xlib.h:3578 XSetOMValues = _lib.XSetOMValues XSetOMValues.restype = c_char_p XSetOMValues.argtypes = [XOM] # /usr/include/X11/Xlib.h:3583 XGetOMValues = _lib.XGetOMValues XGetOMValues.restype = c_char_p XGetOMValues.argtypes = [XOM] # /usr/include/X11/Xlib.h:3588 XDisplayOfOM = _lib.XDisplayOfOM XDisplayOfOM.restype = POINTER(Display) XDisplayOfOM.argtypes = [XOM] # /usr/include/X11/Xlib.h:3592 XLocaleOfOM = _lib.XLocaleOfOM XLocaleOfOM.restype = c_char_p XLocaleOfOM.argtypes = [XOM] # /usr/include/X11/Xlib.h:3596 XCreateOC = _lib.XCreateOC XCreateOC.restype = XOC XCreateOC.argtypes = [XOM] # /usr/include/X11/Xlib.h:3601 XDestroyOC = _lib.XDestroyOC XDestroyOC.restype = None XDestroyOC.argtypes = [XOC] # /usr/include/X11/Xlib.h:3605 XOMOfOC = _lib.XOMOfOC XOMOfOC.restype = XOM XOMOfOC.argtypes = [XOC] # /usr/include/X11/Xlib.h:3609 XSetOCValues = _lib.XSetOCValues XSetOCValues.restype = c_char_p XSetOCValues.argtypes = [XOC] # /usr/include/X11/Xlib.h:3614 XGetOCValues = _lib.XGetOCValues XGetOCValues.restype = c_char_p XGetOCValues.argtypes = [XOC] # /usr/include/X11/Xlib.h:3619 XCreateFontSet = _lib.XCreateFontSet XCreateFontSet.restype = XFontSet XCreateFontSet.argtypes = [ POINTER(Display), c_char_p, POINTER( POINTER(c_char_p)), POINTER(c_int), POINTER(c_char_p)] # /usr/include/X11/Xlib.h:3627 XFreeFontSet = _lib.XFreeFontSet XFreeFontSet.restype = None XFreeFontSet.argtypes = [POINTER(Display), XFontSet] # /usr/include/X11/Xlib.h:3632 XFontsOfFontSet = _lib.XFontsOfFontSet XFontsOfFontSet.restype = c_int XFontsOfFontSet.argtypes = [ XFontSet, POINTER( POINTER( POINTER(XFontStruct))), POINTER( POINTER(c_char_p))] # /usr/include/X11/Xlib.h:3638 XBaseFontNameListOfFontSet = _lib.XBaseFontNameListOfFontSet XBaseFontNameListOfFontSet.restype = c_char_p XBaseFontNameListOfFontSet.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3642 XLocaleOfFontSet = _lib.XLocaleOfFontSet XLocaleOfFontSet.restype = c_char_p XLocaleOfFontSet.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3646 XContextDependentDrawing = _lib.XContextDependentDrawing XContextDependentDrawing.restype = c_int XContextDependentDrawing.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3650 XDirectionalDependentDrawing = _lib.XDirectionalDependentDrawing XDirectionalDependentDrawing.restype = c_int XDirectionalDependentDrawing.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3654 XContextualDrawing = _lib.XContextualDrawing XContextualDrawing.restype = c_int XContextualDrawing.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3658 XExtentsOfFontSet = _lib.XExtentsOfFontSet XExtentsOfFontSet.restype = POINTER(XFontSetExtents) XExtentsOfFontSet.argtypes = [XFontSet] # /usr/include/X11/Xlib.h:3662 XmbTextEscapement = _lib.XmbTextEscapement XmbTextEscapement.restype = c_int XmbTextEscapement.argtypes = [XFontSet, c_char_p, c_int] # /usr/include/X11/Xlib.h:3668 XwcTextEscapement = _lib.XwcTextEscapement XwcTextEscapement.restype = c_int XwcTextEscapement.argtypes = [XFontSet, c_wchar_p, c_int] # /usr/include/X11/Xlib.h:3674 Xutf8TextEscapement = _lib.Xutf8TextEscapement Xutf8TextEscapement.restype = c_int Xutf8TextEscapement.argtypes = [XFontSet, c_char_p, c_int] # /usr/include/X11/Xlib.h:3680 XmbTextExtents = _lib.XmbTextExtents XmbTextExtents.restype = c_int XmbTextExtents.argtypes = [ XFontSet, c_char_p, c_int, POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3688 XwcTextExtents = _lib.XwcTextExtents XwcTextExtents.restype = c_int XwcTextExtents.argtypes = [ XFontSet, c_wchar_p, c_int, POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3696 Xutf8TextExtents = _lib.Xutf8TextExtents Xutf8TextExtents.restype = c_int Xutf8TextExtents.argtypes = [ XFontSet, c_char_p, c_int, POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3704 XmbTextPerCharExtents = _lib.XmbTextPerCharExtents XmbTextPerCharExtents.restype = c_int XmbTextPerCharExtents.argtypes = [ XFontSet, c_char_p, c_int, POINTER(XRectangle), POINTER(XRectangle), c_int, POINTER(c_int), POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3716 XwcTextPerCharExtents = _lib.XwcTextPerCharExtents XwcTextPerCharExtents.restype = c_int XwcTextPerCharExtents.argtypes = [ XFontSet, c_wchar_p, c_int, POINTER(XRectangle), POINTER(XRectangle), c_int, POINTER(c_int), POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3728 Xutf8TextPerCharExtents = _lib.Xutf8TextPerCharExtents Xutf8TextPerCharExtents.restype = c_int Xutf8TextPerCharExtents.argtypes = [ XFontSet, c_char_p, c_int, POINTER(XRectangle), POINTER(XRectangle), c_int, POINTER(c_int), POINTER(XRectangle), POINTER(XRectangle)] # /usr/include/X11/Xlib.h:3740 XmbDrawText = _lib.XmbDrawText XmbDrawText.restype = None XmbDrawText.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XmbTextItem), c_int] # /usr/include/X11/Xlib.h:3750 XwcDrawText = _lib.XwcDrawText XwcDrawText.restype = None XwcDrawText.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XwcTextItem), c_int] # /usr/include/X11/Xlib.h:3760 Xutf8DrawText = _lib.Xutf8DrawText Xutf8DrawText.restype = None Xutf8DrawText.argtypes = [ POINTER(Display), Drawable, GC, c_int, c_int, POINTER(XmbTextItem), c_int] # /usr/include/X11/Xlib.h:3770 XmbDrawString = _lib.XmbDrawString XmbDrawString.restype = None XmbDrawString.argtypes = [ POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:3781 XwcDrawString = _lib.XwcDrawString XwcDrawString.restype = None XwcDrawString.argtypes = [ POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_wchar_p, c_int] # /usr/include/X11/Xlib.h:3792 Xutf8DrawString = _lib.Xutf8DrawString Xutf8DrawString.restype = None Xutf8DrawString.argtypes = [ POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:3803 XmbDrawImageString = _lib.XmbDrawImageString XmbDrawImageString.restype = None XmbDrawImageString.argtypes = [ POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:3814 XwcDrawImageString = _lib.XwcDrawImageString XwcDrawImageString.restype = None XwcDrawImageString.argtypes = [ POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_wchar_p, c_int] # /usr/include/X11/Xlib.h:3825 Xutf8DrawImageString = _lib.Xutf8DrawImageString Xutf8DrawImageString.restype = None Xutf8DrawImageString.argtypes = [ POINTER(Display), Drawable, XFontSet, GC, c_int, c_int, c_char_p, c_int] class struct__XrmHashBucketRec(Structure): __slots__ = [ ] struct__XrmHashBucketRec._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/X11/Xlib.h:3836 XOpenIM = _lib.XOpenIM XOpenIM.restype = XIM XOpenIM.argtypes = [ POINTER(Display), POINTER(struct__XrmHashBucketRec), c_char_p, c_char_p] # /usr/include/X11/Xlib.h:3843 XCloseIM = _lib.XCloseIM XCloseIM.restype = c_int XCloseIM.argtypes = [XIM] # /usr/include/X11/Xlib.h:3847 XGetIMValues = _lib.XGetIMValues XGetIMValues.restype = c_char_p XGetIMValues.argtypes = [XIM] # /usr/include/X11/Xlib.h:3851 XSetIMValues = _lib.XSetIMValues XSetIMValues.restype = c_char_p XSetIMValues.argtypes = [XIM] # /usr/include/X11/Xlib.h:3855 XDisplayOfIM = _lib.XDisplayOfIM XDisplayOfIM.restype = POINTER(Display) XDisplayOfIM.argtypes = [XIM] # /usr/include/X11/Xlib.h:3859 XLocaleOfIM = _lib.XLocaleOfIM XLocaleOfIM.restype = c_char_p XLocaleOfIM.argtypes = [XIM] # /usr/include/X11/Xlib.h:3863 XCreateIC = _lib.XCreateIC XCreateIC.restype = XIC XCreateIC.argtypes = [XIM] # /usr/include/X11/Xlib.h:3867 XDestroyIC = _lib.XDestroyIC XDestroyIC.restype = None XDestroyIC.argtypes = [XIC] # /usr/include/X11/Xlib.h:3871 XSetICFocus = _lib.XSetICFocus XSetICFocus.restype = None XSetICFocus.argtypes = [XIC] # /usr/include/X11/Xlib.h:3875 XUnsetICFocus = _lib.XUnsetICFocus XUnsetICFocus.restype = None XUnsetICFocus.argtypes = [XIC] # /usr/include/X11/Xlib.h:3879 XwcResetIC = _lib.XwcResetIC XwcResetIC.restype = c_wchar_p XwcResetIC.argtypes = [XIC] # /usr/include/X11/Xlib.h:3883 XmbResetIC = _lib.XmbResetIC XmbResetIC.restype = c_char_p XmbResetIC.argtypes = [XIC] # /usr/include/X11/Xlib.h:3887 Xutf8ResetIC = _lib.Xutf8ResetIC Xutf8ResetIC.restype = c_char_p Xutf8ResetIC.argtypes = [XIC] # /usr/include/X11/Xlib.h:3891 XSetICValues = _lib.XSetICValues XSetICValues.restype = c_char_p XSetICValues.argtypes = [XIC] # /usr/include/X11/Xlib.h:3895 XGetICValues = _lib.XGetICValues XGetICValues.restype = c_char_p XGetICValues.argtypes = [XIC] # /usr/include/X11/Xlib.h:3899 XIMOfIC = _lib.XIMOfIC XIMOfIC.restype = XIM XIMOfIC.argtypes = [XIC] # /usr/include/X11/Xlib.h:3903 XFilterEvent = _lib.XFilterEvent XFilterEvent.restype = c_int XFilterEvent.argtypes = [POINTER(XEvent), Window] # /usr/include/X11/Xlib.h:3908 XmbLookupString = _lib.XmbLookupString XmbLookupString.restype = c_int XmbLookupString.argtypes = [ XIC, POINTER(XKeyPressedEvent), c_char_p, c_int, POINTER(KeySym), POINTER(c_int)] # /usr/include/X11/Xlib.h:3917 XwcLookupString = _lib.XwcLookupString XwcLookupString.restype = c_int XwcLookupString.argtypes = [ XIC, POINTER(XKeyPressedEvent), c_wchar_p, c_int, POINTER(KeySym), POINTER(c_int)] # /usr/include/X11/Xlib.h:3926 Xutf8LookupString = _lib.Xutf8LookupString Xutf8LookupString.restype = c_int Xutf8LookupString.argtypes = [ XIC, POINTER(XKeyPressedEvent), c_char_p, c_int, POINTER(KeySym), POINTER(c_int)] # /usr/include/X11/Xlib.h:3935 XVaCreateNestedList = _lib.XVaCreateNestedList XVaCreateNestedList.restype = XVaNestedList XVaCreateNestedList.argtypes = [c_int] class struct__XrmHashBucketRec(Structure): __slots__ = [ ] struct__XrmHashBucketRec._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/X11/Xlib.h:3941 XRegisterIMInstantiateCallback = _lib.XRegisterIMInstantiateCallback XRegisterIMInstantiateCallback.restype = c_int XRegisterIMInstantiateCallback.argtypes = [POINTER(Display), POINTER( struct__XrmHashBucketRec), c_char_p, c_char_p, XIDProc, XPointer] class struct__XrmHashBucketRec(Structure): __slots__ = [ ] struct__XrmHashBucketRec._fields_ = [ ('_opaque_struct', c_int) ] # /usr/include/X11/Xlib.h:3950 XUnregisterIMInstantiateCallback = _lib.XUnregisterIMInstantiateCallback XUnregisterIMInstantiateCallback.restype = c_int XUnregisterIMInstantiateCallback.argtypes = [POINTER(Display), POINTER( struct__XrmHashBucketRec), c_char_p, c_char_p, XIDProc, XPointer] XConnectionWatchProc = CFUNCTYPE( None, POINTER(Display), XPointer, c_int, c_int, POINTER(XPointer)) # /usr/include/X11/Xlib.h:3959 # /usr/include/X11/Xlib.h:3968 XInternalConnectionNumbers = _lib.XInternalConnectionNumbers XInternalConnectionNumbers.restype = c_int XInternalConnectionNumbers.argtypes = [ POINTER(Display), POINTER( POINTER(c_int)), POINTER(c_int)] # /usr/include/X11/Xlib.h:3974 XProcessInternalConnection = _lib.XProcessInternalConnection XProcessInternalConnection.restype = None XProcessInternalConnection.argtypes = [POINTER(Display), c_int] # /usr/include/X11/Xlib.h:3979 XAddConnectionWatch = _lib.XAddConnectionWatch XAddConnectionWatch.restype = c_int XAddConnectionWatch.argtypes = [ POINTER(Display), XConnectionWatchProc, XPointer] # /usr/include/X11/Xlib.h:3985 XRemoveConnectionWatch = _lib.XRemoveConnectionWatch XRemoveConnectionWatch.restype = None XRemoveConnectionWatch.argtypes = [ POINTER(Display), XConnectionWatchProc, XPointer] # /usr/include/X11/Xlib.h:3991 XSetAuthorization = _lib.XSetAuthorization XSetAuthorization.restype = None XSetAuthorization.argtypes = [c_char_p, c_int, c_char_p, c_int] # /usr/include/X11/Xlib.h:3998 _Xmbtowc = _lib._Xmbtowc _Xmbtowc.restype = c_int _Xmbtowc.argtypes = [c_wchar_p, c_char_p, c_int] # /usr/include/X11/Xlib.h:4009 _Xwctomb = _lib._Xwctomb _Xwctomb.restype = c_int _Xwctomb.argtypes = [c_char_p, c_wchar] # /usr/include/X11/Xlib.h:4014 XGetEventData = _lib.XGetEventData XGetEventData.restype = c_int XGetEventData.argtypes = [POINTER(Display), POINTER(XGenericEventCookie)] # /usr/include/X11/Xlib.h:4019 XFreeEventData = _lib.XFreeEventData XFreeEventData.restype = None XFreeEventData.argtypes = [POINTER(Display), POINTER(XGenericEventCookie)] NoValue = 0 # /usr/include/X11/Xutil.h:4805 XValue = 1 # /usr/include/X11/Xutil.h:4806 YValue = 2 # /usr/include/X11/Xutil.h:4807 WidthValue = 4 # /usr/include/X11/Xutil.h:4808 HeightValue = 8 # /usr/include/X11/Xutil.h:4809 AllValues = 15 # /usr/include/X11/Xutil.h:4810 XNegative = 16 # /usr/include/X11/Xutil.h:4811 YNegative = 32 # /usr/include/X11/Xutil.h:4812 class struct_anon_95(Structure): __slots__ = [ 'flags', 'x', 'y', 'width', 'height', 'min_width', 'min_height', 'max_width', 'max_height', 'width_inc', 'height_inc', 'min_aspect', 'max_aspect', 'base_width', 'base_height', 'win_gravity', ] class struct_anon_96(Structure): __slots__ = [ 'x', 'y', ] struct_anon_96._fields_ = [ ('x', c_int), ('y', c_int), ] class struct_anon_97(Structure): __slots__ = [ 'x', 'y', ] struct_anon_97._fields_ = [ ('x', c_int), ('y', c_int), ] struct_anon_95._fields_ = [ ('flags', c_long), ('x', c_int), ('y', c_int), ('width', c_int), ('height', c_int), ('min_width', c_int), ('min_height', c_int), ('max_width', c_int), ('max_height', c_int), ('width_inc', c_int), ('height_inc', c_int), ('min_aspect', struct_anon_96), ('max_aspect', struct_anon_97), ('base_width', c_int), ('base_height', c_int), ('win_gravity', c_int), ] XSizeHints = struct_anon_95 # /usr/include/X11/Xutil.h:4831 USPosition = 1 # /usr/include/X11/Xutil.h:4839 USSize = 2 # /usr/include/X11/Xutil.h:4840 PPosition = 4 # /usr/include/X11/Xutil.h:4842 PSize = 8 # /usr/include/X11/Xutil.h:4843 PMinSize = 16 # /usr/include/X11/Xutil.h:4844 PMaxSize = 32 # /usr/include/X11/Xutil.h:4845 PResizeInc = 64 # /usr/include/X11/Xutil.h:4846 PAspect = 128 # /usr/include/X11/Xutil.h:4847 PBaseSize = 256 # /usr/include/X11/Xutil.h:4848 PWinGravity = 512 # /usr/include/X11/Xutil.h:4849 PAllHints = 252 # /usr/include/X11/Xutil.h:4852 class struct_anon_98(Structure): __slots__ = [ 'flags', 'input', 'initial_state', 'icon_pixmap', 'icon_window', 'icon_x', 'icon_y', 'icon_mask', 'window_group', ] struct_anon_98._fields_ = [ ('flags', c_long), ('input', c_int), ('initial_state', c_int), ('icon_pixmap', Pixmap), ('icon_window', Window), ('icon_x', c_int), ('icon_y', c_int), ('icon_mask', Pixmap), ('window_group', XID), ] XWMHints = struct_anon_98 # /usr/include/X11/Xutil.h:4867 InputHint = 1 # /usr/include/X11/Xutil.h:4871 StateHint = 2 # /usr/include/X11/Xutil.h:4872 IconPixmapHint = 4 # /usr/include/X11/Xutil.h:4873 IconWindowHint = 8 # /usr/include/X11/Xutil.h:4874 IconPositionHint = 16 # /usr/include/X11/Xutil.h:4875 IconMaskHint = 32 # /usr/include/X11/Xutil.h:4876 WindowGroupHint = 64 # /usr/include/X11/Xutil.h:4877 AllHints = 127 # /usr/include/X11/Xutil.h:4878 XUrgencyHint = 256 # /usr/include/X11/Xutil.h:4880 WithdrawnState = 0 # /usr/include/X11/Xutil.h:4883 NormalState = 1 # /usr/include/X11/Xutil.h:4884 IconicState = 3 # /usr/include/X11/Xutil.h:4885 DontCareState = 0 # /usr/include/X11/Xutil.h:4890 ZoomState = 2 # /usr/include/X11/Xutil.h:4891 InactiveState = 4 # /usr/include/X11/Xutil.h:4892 class struct_anon_99(Structure): __slots__ = [ 'value', 'encoding', 'format', 'nitems', ] struct_anon_99._fields_ = [ ('value', POINTER(c_ubyte)), ('encoding', Atom), ('format', c_int), ('nitems', c_ulong), ] XTextProperty = struct_anon_99 # /usr/include/X11/Xutil.h:4905 XNoMemory = -1 # /usr/include/X11/Xutil.h:4907 XLocaleNotSupported = -2 # /usr/include/X11/Xutil.h:4908 XConverterNotFound = -3 # /usr/include/X11/Xutil.h:4909 enum_anon_100 = c_int XStringStyle = 0 XCompoundTextStyle = 1 XTextStyle = 2 XStdICCTextStyle = 3 XUTF8StringStyle = 4 XICCEncodingStyle = enum_anon_100 # /usr/include/X11/Xutil.h:4918 class struct_anon_101(Structure): __slots__ = [ 'min_width', 'min_height', 'max_width', 'max_height', 'width_inc', 'height_inc', ] struct_anon_101._fields_ = [ ('min_width', c_int), ('min_height', c_int), ('max_width', c_int), ('max_height', c_int), ('width_inc', c_int), ('height_inc', c_int), ] XIconSize = struct_anon_101 # /usr/include/X11/Xutil.h:4924 class struct_anon_102(Structure): __slots__ = [ 'res_name', 'res_class', ] struct_anon_102._fields_ = [ ('res_name', c_char_p), ('res_class', c_char_p), ] XClassHint = struct_anon_102 # /usr/include/X11/Xutil.h:4929 class struct__XComposeStatus(Structure): __slots__ = [ 'compose_ptr', 'chars_matched', ] struct__XComposeStatus._fields_ = [ ('compose_ptr', XPointer), ('chars_matched', c_int), ] XComposeStatus = struct__XComposeStatus # /usr/include/X11/Xutil.h:4971 class struct__XRegion(Structure): __slots__ = [ ] struct__XRegion._fields_ = [ ('_opaque_struct', c_int) ] class struct__XRegion(Structure): __slots__ = [ ] struct__XRegion._fields_ = [ ('_opaque_struct', c_int) ] Region = POINTER(struct__XRegion) # /usr/include/X11/Xutil.h:5010 RectangleOut = 0 # /usr/include/X11/Xutil.h:5014 RectangleIn = 1 # /usr/include/X11/Xutil.h:5015 RectanglePart = 2 # /usr/include/X11/Xutil.h:5016 class struct_anon_103(Structure): __slots__ = [ 'visual', 'visualid', 'screen', 'depth', 'class', 'red_mask', 'green_mask', 'blue_mask', 'colormap_size', 'bits_per_rgb', ] struct_anon_103._fields_ = [ ('visual', POINTER(Visual)), ('visualid', VisualID), ('screen', c_int), ('depth', c_int), ('class', c_int), ('red_mask', c_ulong), ('green_mask', c_ulong), ('blue_mask', c_ulong), ('colormap_size', c_int), ('bits_per_rgb', c_int), ] XVisualInfo = struct_anon_103 # /usr/include/X11/Xutil.h:5039 VisualNoMask = 0 # /usr/include/X11/Xutil.h:5041 VisualIDMask = 1 # /usr/include/X11/Xutil.h:5042 VisualScreenMask = 2 # /usr/include/X11/Xutil.h:5043 VisualDepthMask = 4 # /usr/include/X11/Xutil.h:5044 VisualClassMask = 8 # /usr/include/X11/Xutil.h:5045 VisualRedMaskMask = 16 # /usr/include/X11/Xutil.h:5046 VisualGreenMaskMask = 32 # /usr/include/X11/Xutil.h:5047 VisualBlueMaskMask = 64 # /usr/include/X11/Xutil.h:5048 VisualColormapSizeMask = 128 # /usr/include/X11/Xutil.h:5049 VisualBitsPerRGBMask = 256 # /usr/include/X11/Xutil.h:5050 VisualAllMask = 511 # /usr/include/X11/Xutil.h:5051 class struct_anon_104(Structure): __slots__ = [ 'colormap', 'red_max', 'red_mult', 'green_max', 'green_mult', 'blue_max', 'blue_mult', 'base_pixel', 'visualid', 'killid', ] struct_anon_104._fields_ = [ ('colormap', Colormap), ('red_max', c_ulong), ('red_mult', c_ulong), ('green_max', c_ulong), ('green_mult', c_ulong), ('blue_max', c_ulong), ('blue_mult', c_ulong), ('base_pixel', c_ulong), ('visualid', VisualID), ('killid', XID), ] XStandardColormap = struct_anon_104 # /usr/include/X11/Xutil.h:5068 BitmapSuccess = 0 # /usr/include/X11/Xutil.h:5076 BitmapOpenFailed = 1 # /usr/include/X11/Xutil.h:5077 BitmapFileInvalid = 2 # /usr/include/X11/Xutil.h:5078 BitmapNoMemory = 3 # /usr/include/X11/Xutil.h:5079 XCSUCCESS = 0 # /usr/include/X11/Xutil.h:5090 XCNOMEM = 1 # /usr/include/X11/Xutil.h:5091 XCNOENT = 2 # /usr/include/X11/Xutil.h:5092 XContext = c_int # /usr/include/X11/Xutil.h:5094 # /usr/include/X11/Xutil.h:5103 XAllocClassHint = _lib.XAllocClassHint XAllocClassHint.restype = POINTER(XClassHint) XAllocClassHint.argtypes = [] # /usr/include/X11/Xutil.h:5107 XAllocIconSize = _lib.XAllocIconSize XAllocIconSize.restype = POINTER(XIconSize) XAllocIconSize.argtypes = [] # /usr/include/X11/Xutil.h:5111 XAllocSizeHints = _lib.XAllocSizeHints XAllocSizeHints.restype = POINTER(XSizeHints) XAllocSizeHints.argtypes = [] # /usr/include/X11/Xutil.h:5115 XAllocStandardColormap = _lib.XAllocStandardColormap XAllocStandardColormap.restype = POINTER(XStandardColormap) XAllocStandardColormap.argtypes = [] # /usr/include/X11/Xutil.h:5119 XAllocWMHints = _lib.XAllocWMHints XAllocWMHints.restype = POINTER(XWMHints) XAllocWMHints.argtypes = [] # /usr/include/X11/Xutil.h:5123 XClipBox = _lib.XClipBox XClipBox.restype = c_int XClipBox.argtypes = [Region, POINTER(XRectangle)] # /usr/include/X11/Xutil.h:5128 XCreateRegion = _lib.XCreateRegion XCreateRegion.restype = Region XCreateRegion.argtypes = [] # /usr/include/X11/Xutil.h:5132 XDefaultString = _lib.XDefaultString XDefaultString.restype = c_char_p XDefaultString.argtypes = [] # /usr/include/X11/Xutil.h:5134 XDeleteContext = _lib.XDeleteContext XDeleteContext.restype = c_int XDeleteContext.argtypes = [POINTER(Display), XID, XContext] # /usr/include/X11/Xutil.h:5140 XDestroyRegion = _lib.XDestroyRegion XDestroyRegion.restype = c_int XDestroyRegion.argtypes = [Region] # /usr/include/X11/Xutil.h:5144 XEmptyRegion = _lib.XEmptyRegion XEmptyRegion.restype = c_int XEmptyRegion.argtypes = [Region] # /usr/include/X11/Xutil.h:5148 XEqualRegion = _lib.XEqualRegion XEqualRegion.restype = c_int XEqualRegion.argtypes = [Region, Region] # /usr/include/X11/Xutil.h:5153 XFindContext = _lib.XFindContext XFindContext.restype = c_int XFindContext.argtypes = [POINTER(Display), XID, XContext, POINTER(XPointer)] # /usr/include/X11/Xutil.h:5160 XGetClassHint = _lib.XGetClassHint XGetClassHint.restype = c_int XGetClassHint.argtypes = [POINTER(Display), Window, POINTER(XClassHint)] # /usr/include/X11/Xutil.h:5166 XGetIconSizes = _lib.XGetIconSizes XGetIconSizes.restype = c_int XGetIconSizes.argtypes = [ POINTER(Display), Window, POINTER( POINTER(XIconSize)), POINTER(c_int)] # /usr/include/X11/Xutil.h:5173 XGetNormalHints = _lib.XGetNormalHints XGetNormalHints.restype = c_int XGetNormalHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5179 XGetRGBColormaps = _lib.XGetRGBColormaps XGetRGBColormaps.restype = c_int XGetRGBColormaps.argtypes = [ POINTER(Display), Window, POINTER( POINTER(XStandardColormap)), POINTER(c_int), Atom] # /usr/include/X11/Xutil.h:5187 XGetSizeHints = _lib.XGetSizeHints XGetSizeHints.restype = c_int XGetSizeHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints), Atom] # /usr/include/X11/Xutil.h:5194 XGetStandardColormap = _lib.XGetStandardColormap XGetStandardColormap.restype = c_int XGetStandardColormap.argtypes = [ POINTER(Display), Window, POINTER(XStandardColormap), Atom] # /usr/include/X11/Xutil.h:5201 XGetTextProperty = _lib.XGetTextProperty XGetTextProperty.restype = c_int XGetTextProperty.argtypes = [ POINTER(Display), Window, POINTER(XTextProperty), Atom] # /usr/include/X11/Xutil.h:5208 XGetVisualInfo = _lib.XGetVisualInfo XGetVisualInfo.restype = POINTER(XVisualInfo) XGetVisualInfo.argtypes = [ POINTER(Display), c_long, POINTER(XVisualInfo), POINTER(c_int)] # /usr/include/X11/Xutil.h:5215 XGetWMClientMachine = _lib.XGetWMClientMachine XGetWMClientMachine.restype = c_int XGetWMClientMachine.argtypes = [ POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5221 XGetWMHints = _lib.XGetWMHints XGetWMHints.restype = POINTER(XWMHints) XGetWMHints.argtypes = [POINTER(Display), Window] # /usr/include/X11/Xutil.h:5226 XGetWMIconName = _lib.XGetWMIconName XGetWMIconName.restype = c_int XGetWMIconName.argtypes = [POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5232 XGetWMName = _lib.XGetWMName XGetWMName.restype = c_int XGetWMName.argtypes = [POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5238 XGetWMNormalHints = _lib.XGetWMNormalHints XGetWMNormalHints.restype = c_int XGetWMNormalHints.argtypes = [ POINTER(Display), Window, POINTER(XSizeHints), POINTER(c_long)] # /usr/include/X11/Xutil.h:5245 XGetWMSizeHints = _lib.XGetWMSizeHints XGetWMSizeHints.restype = c_int XGetWMSizeHints.argtypes = [ POINTER(Display), Window, POINTER(XSizeHints), POINTER(c_long), Atom] # /usr/include/X11/Xutil.h:5253 XGetZoomHints = _lib.XGetZoomHints XGetZoomHints.restype = c_int XGetZoomHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5259 XIntersectRegion = _lib.XIntersectRegion XIntersectRegion.restype = c_int XIntersectRegion.argtypes = [Region, Region, Region] # /usr/include/X11/Xutil.h:5265 XConvertCase = _lib.XConvertCase XConvertCase.restype = None XConvertCase.argtypes = [KeySym, POINTER(KeySym), POINTER(KeySym)] # /usr/include/X11/Xutil.h:5271 XLookupString = _lib.XLookupString XLookupString.restype = c_int XLookupString.argtypes = [ POINTER(XKeyEvent), c_char_p, c_int, POINTER(KeySym), POINTER(XComposeStatus)] # /usr/include/X11/Xutil.h:5279 XMatchVisualInfo = _lib.XMatchVisualInfo XMatchVisualInfo.restype = c_int XMatchVisualInfo.argtypes = [ POINTER(Display), c_int, c_int, c_int, POINTER(XVisualInfo)] # /usr/include/X11/Xutil.h:5287 XOffsetRegion = _lib.XOffsetRegion XOffsetRegion.restype = c_int XOffsetRegion.argtypes = [Region, c_int, c_int] # /usr/include/X11/Xutil.h:5293 XPointInRegion = _lib.XPointInRegion XPointInRegion.restype = c_int XPointInRegion.argtypes = [Region, c_int, c_int] # /usr/include/X11/Xutil.h:5299 XPolygonRegion = _lib.XPolygonRegion XPolygonRegion.restype = Region XPolygonRegion.argtypes = [POINTER(XPoint), c_int, c_int] # /usr/include/X11/Xutil.h:5305 XRectInRegion = _lib.XRectInRegion XRectInRegion.restype = c_int XRectInRegion.argtypes = [Region, c_int, c_int, c_uint, c_uint] # /usr/include/X11/Xutil.h:5313 XSaveContext = _lib.XSaveContext XSaveContext.restype = c_int XSaveContext.argtypes = [POINTER(Display), XID, XContext, c_char_p] # /usr/include/X11/Xutil.h:5320 XSetClassHint = _lib.XSetClassHint XSetClassHint.restype = c_int XSetClassHint.argtypes = [POINTER(Display), Window, POINTER(XClassHint)] # /usr/include/X11/Xutil.h:5326 XSetIconSizes = _lib.XSetIconSizes XSetIconSizes.restype = c_int XSetIconSizes.argtypes = [POINTER(Display), Window, POINTER(XIconSize), c_int] # /usr/include/X11/Xutil.h:5333 XSetNormalHints = _lib.XSetNormalHints XSetNormalHints.restype = c_int XSetNormalHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5339 XSetRGBColormaps = _lib.XSetRGBColormaps XSetRGBColormaps.restype = None XSetRGBColormaps.argtypes = [ POINTER(Display), Window, POINTER(XStandardColormap), c_int, Atom] # /usr/include/X11/Xutil.h:5347 XSetSizeHints = _lib.XSetSizeHints XSetSizeHints.restype = c_int XSetSizeHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints), Atom] # /usr/include/X11/Xutil.h:5354 XSetStandardProperties = _lib.XSetStandardProperties XSetStandardProperties.restype = c_int XSetStandardProperties.argtypes = [ POINTER(Display), Window, c_char_p, c_char_p, Pixmap, POINTER(c_char_p), c_int, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5365 XSetTextProperty = _lib.XSetTextProperty XSetTextProperty.restype = None XSetTextProperty.argtypes = [ POINTER(Display), Window, POINTER(XTextProperty), Atom] # /usr/include/X11/Xutil.h:5372 XSetWMClientMachine = _lib.XSetWMClientMachine XSetWMClientMachine.restype = None XSetWMClientMachine.argtypes = [ POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5378 XSetWMHints = _lib.XSetWMHints XSetWMHints.restype = c_int XSetWMHints.argtypes = [POINTER(Display), Window, POINTER(XWMHints)] # /usr/include/X11/Xutil.h:5384 XSetWMIconName = _lib.XSetWMIconName XSetWMIconName.restype = None XSetWMIconName.argtypes = [POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5390 XSetWMName = _lib.XSetWMName XSetWMName.restype = None XSetWMName.argtypes = [POINTER(Display), Window, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5396 XSetWMNormalHints = _lib.XSetWMNormalHints XSetWMNormalHints.restype = None XSetWMNormalHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5402 XSetWMProperties = _lib.XSetWMProperties XSetWMProperties.restype = None XSetWMProperties.argtypes = [ POINTER(Display), Window, POINTER(XTextProperty), POINTER(XTextProperty), POINTER(c_char_p), c_int, POINTER(XSizeHints), POINTER(XWMHints), POINTER(XClassHint)] # /usr/include/X11/Xutil.h:5414 XmbSetWMProperties = _lib.XmbSetWMProperties XmbSetWMProperties.restype = None XmbSetWMProperties.argtypes = [ POINTER(Display), Window, c_char_p, c_char_p, POINTER(c_char_p), c_int, POINTER(XSizeHints), POINTER(XWMHints), POINTER(XClassHint)] # /usr/include/X11/Xutil.h:5426 Xutf8SetWMProperties = _lib.Xutf8SetWMProperties Xutf8SetWMProperties.restype = None Xutf8SetWMProperties.argtypes = [ POINTER(Display), Window, c_char_p, c_char_p, POINTER(c_char_p), c_int, POINTER(XSizeHints), POINTER(XWMHints), POINTER(XClassHint)] # /usr/include/X11/Xutil.h:5438 XSetWMSizeHints = _lib.XSetWMSizeHints XSetWMSizeHints.restype = None XSetWMSizeHints.argtypes = [ POINTER(Display), Window, POINTER(XSizeHints), Atom] # /usr/include/X11/Xutil.h:5445 XSetRegion = _lib.XSetRegion XSetRegion.restype = c_int XSetRegion.argtypes = [POINTER(Display), GC, Region] # /usr/include/X11/Xutil.h:5451 XSetStandardColormap = _lib.XSetStandardColormap XSetStandardColormap.restype = None XSetStandardColormap.argtypes = [ POINTER(Display), Window, POINTER(XStandardColormap), Atom] # /usr/include/X11/Xutil.h:5458 XSetZoomHints = _lib.XSetZoomHints XSetZoomHints.restype = c_int XSetZoomHints.argtypes = [POINTER(Display), Window, POINTER(XSizeHints)] # /usr/include/X11/Xutil.h:5464 XShrinkRegion = _lib.XShrinkRegion XShrinkRegion.restype = c_int XShrinkRegion.argtypes = [Region, c_int, c_int] # /usr/include/X11/Xutil.h:5470 XStringListToTextProperty = _lib.XStringListToTextProperty XStringListToTextProperty.restype = c_int XStringListToTextProperty.argtypes = [ POINTER(c_char_p), c_int, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5476 XSubtractRegion = _lib.XSubtractRegion XSubtractRegion.restype = c_int XSubtractRegion.argtypes = [Region, Region, Region] # /usr/include/X11/Xutil.h:5482 XmbTextListToTextProperty = _lib.XmbTextListToTextProperty XmbTextListToTextProperty.restype = c_int XmbTextListToTextProperty.argtypes = [POINTER(Display), POINTER( c_char_p), c_int, XICCEncodingStyle, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5490 XwcTextListToTextProperty = _lib.XwcTextListToTextProperty XwcTextListToTextProperty.restype = c_int XwcTextListToTextProperty.argtypes = [ POINTER(Display), POINTER(c_wchar_p), c_int, XICCEncodingStyle, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5498 Xutf8TextListToTextProperty = _lib.Xutf8TextListToTextProperty Xutf8TextListToTextProperty.restype = c_int Xutf8TextListToTextProperty.argtypes = [ POINTER(Display), POINTER(c_char_p), c_int, XICCEncodingStyle, POINTER(XTextProperty)] # /usr/include/X11/Xutil.h:5506 XwcFreeStringList = _lib.XwcFreeStringList XwcFreeStringList.restype = None XwcFreeStringList.argtypes = [POINTER(c_wchar_p)] # /usr/include/X11/Xutil.h:5510 XTextPropertyToStringList = _lib.XTextPropertyToStringList XTextPropertyToStringList.restype = c_int XTextPropertyToStringList.argtypes = [ POINTER(XTextProperty), POINTER( POINTER(c_char_p)), POINTER(c_int)] # /usr/include/X11/Xutil.h:5516 XmbTextPropertyToTextList = _lib.XmbTextPropertyToTextList XmbTextPropertyToTextList.restype = c_int XmbTextPropertyToTextList.argtypes = [ POINTER(Display), POINTER(XTextProperty), POINTER( POINTER(c_char_p)), POINTER(c_int)] # /usr/include/X11/Xutil.h:5523 XwcTextPropertyToTextList = _lib.XwcTextPropertyToTextList XwcTextPropertyToTextList.restype = c_int XwcTextPropertyToTextList.argtypes = [ POINTER(Display), POINTER(XTextProperty), POINTER( POINTER(c_wchar_p)), POINTER(c_int)] # /usr/include/X11/Xutil.h:5530 Xutf8TextPropertyToTextList = _lib.Xutf8TextPropertyToTextList Xutf8TextPropertyToTextList.restype = c_int Xutf8TextPropertyToTextList.argtypes = [ POINTER(Display), POINTER(XTextProperty), POINTER( POINTER(c_char_p)), POINTER(c_int)] # /usr/include/X11/Xutil.h:5537 XUnionRectWithRegion = _lib.XUnionRectWithRegion XUnionRectWithRegion.restype = c_int XUnionRectWithRegion.argtypes = [POINTER(XRectangle), Region, Region] # /usr/include/X11/Xutil.h:5543 XUnionRegion = _lib.XUnionRegion XUnionRegion.restype = c_int XUnionRegion.argtypes = [Region, Region, Region] # /usr/include/X11/Xutil.h:5549 XWMGeometry = _lib.XWMGeometry XWMGeometry.restype = c_int XWMGeometry.argtypes = [ POINTER(Display), c_int, c_char_p, c_char_p, c_uint, POINTER(XSizeHints), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int)] # /usr/include/X11/Xutil.h:5563 XXorRegion = _lib.XXorRegion XXorRegion.restype = c_int XXorRegion.argtypes = [Region, Region, Region] __all__ = ['XlibSpecificationRelease', 'X_PROTOCOL', 'X_PROTOCOL_REVISION', 'XID', 'Mask', 'Atom', 'VisualID', 'Time', 'Window', 'Drawable', 'Font', 'Pixmap', 'Cursor', 'Colormap', 'GContext', 'KeySym', 'KeyCode', 'None_', 'ParentRelative', 'CopyFromParent', 'PointerWindow', 'InputFocus', 'PointerRoot', 'AnyPropertyType', 'AnyKey', 'AnyButton', 'AllTemporary', 'CurrentTime', 'NoSymbol', 'NoEventMask', 'KeyPressMask', 'KeyReleaseMask', 'ButtonPressMask', 'ButtonReleaseMask', 'EnterWindowMask', 'LeaveWindowMask', 'PointerMotionMask', 'PointerMotionHintMask', 'Button1MotionMask', 'Button2MotionMask', 'Button3MotionMask', 'Button4MotionMask', 'Button5MotionMask', 'ButtonMotionMask', 'KeymapStateMask', 'ExposureMask', 'VisibilityChangeMask', 'StructureNotifyMask', 'ResizeRedirectMask', 'SubstructureNotifyMask', 'SubstructureRedirectMask', 'FocusChangeMask', 'PropertyChangeMask', 'ColormapChangeMask', 'OwnerGrabButtonMask', 'KeyPress', 'KeyRelease', 'ButtonPress', 'ButtonRelease', 'MotionNotify', 'EnterNotify', 'LeaveNotify', 'FocusIn', 'FocusOut', 'KeymapNotify', 'Expose', 'GraphicsExpose', 'NoExpose', 'VisibilityNotify', 'CreateNotify', 'DestroyNotify', 'UnmapNotify', 'MapNotify', 'MapRequest', 'ReparentNotify', 'ConfigureNotify', 'ConfigureRequest', 'GravityNotify', 'ResizeRequest', 'CirculateNotify', 'CirculateRequest', 'PropertyNotify', 'SelectionClear', 'SelectionRequest', 'SelectionNotify', 'ColormapNotify', 'ClientMessage', 'MappingNotify', 'GenericEvent', 'LASTEvent', 'ShiftMask', 'LockMask', 'ControlMask', 'Mod1Mask', 'Mod2Mask', 'Mod3Mask', 'Mod4Mask', 'Mod5Mask', 'ShiftMapIndex', 'LockMapIndex', 'ControlMapIndex', 'Mod1MapIndex', 'Mod2MapIndex', 'Mod3MapIndex', 'Mod4MapIndex', 'Mod5MapIndex', 'Button1Mask', 'Button2Mask', 'Button3Mask', 'Button4Mask', 'Button5Mask', 'AnyModifier', 'Button1', 'Button2', 'Button3', 'Button4', 'Button5', 'NotifyNormal', 'NotifyGrab', 'NotifyUngrab', 'NotifyWhileGrabbed', 'NotifyHint', 'NotifyAncestor', 'NotifyVirtual', 'NotifyInferior', 'NotifyNonlinear', 'NotifyNonlinearVirtual', 'NotifyPointer', 'NotifyPointerRoot', 'NotifyDetailNone', 'VisibilityUnobscured', 'VisibilityPartiallyObscured', 'VisibilityFullyObscured', 'PlaceOnTop', 'PlaceOnBottom', 'FamilyInternet', 'FamilyDECnet', 'FamilyChaos', 'FamilyInternet6', 'FamilyServerInterpreted', 'PropertyNewValue', 'PropertyDelete', 'ColormapUninstalled', 'ColormapInstalled', 'GrabModeSync', 'GrabModeAsync', 'GrabSuccess', 'AlreadyGrabbed', 'GrabInvalidTime', 'GrabNotViewable', 'GrabFrozen', 'AsyncPointer', 'SyncPointer', 'ReplayPointer', 'AsyncKeyboard', 'SyncKeyboard', 'ReplayKeyboard', 'AsyncBoth', 'SyncBoth', 'RevertToParent', 'Success', 'BadRequest', 'BadValue', 'BadWindow', 'BadPixmap', 'BadAtom', 'BadCursor', 'BadFont', 'BadMatch', 'BadDrawable', 'BadAccess', 'BadAlloc', 'BadColor', 'BadGC', 'BadIDChoice', 'BadName', 'BadLength', 'BadImplementation', 'FirstExtensionError', 'LastExtensionError', 'InputOutput', 'InputOnly', 'CWBackPixmap', 'CWBackPixel', 'CWBorderPixmap', 'CWBorderPixel', 'CWBitGravity', 'CWWinGravity', 'CWBackingStore', 'CWBackingPlanes', 'CWBackingPixel', 'CWOverrideRedirect', 'CWSaveUnder', 'CWEventMask', 'CWDontPropagate', 'CWColormap', 'CWCursor', 'CWX', 'CWY', 'CWWidth', 'CWHeight', 'CWBorderWidth', 'CWSibling', 'CWStackMode', 'ForgetGravity', 'NorthWestGravity', 'NorthGravity', 'NorthEastGravity', 'WestGravity', 'CenterGravity', 'EastGravity', 'SouthWestGravity', 'SouthGravity', 'SouthEastGravity', 'StaticGravity', 'UnmapGravity', 'NotUseful', 'WhenMapped', 'Always', 'IsUnmapped', 'IsUnviewable', 'IsViewable', 'SetModeInsert', 'SetModeDelete', 'DestroyAll', 'RetainPermanent', 'RetainTemporary', 'Above', 'Below', 'TopIf', 'BottomIf', 'Opposite', 'RaiseLowest', 'LowerHighest', 'PropModeReplace', 'PropModePrepend', 'PropModeAppend', 'GXclear', 'GXand', 'GXandReverse', 'GXcopy', 'GXandInverted', 'GXnoop', 'GXxor', 'GXor', 'GXnor', 'GXequiv', 'GXinvert', 'GXorReverse', 'GXcopyInverted', 'GXorInverted', 'GXnand', 'GXset', 'LineSolid', 'LineOnOffDash', 'LineDoubleDash', 'CapNotLast', 'CapButt', 'CapRound', 'CapProjecting', 'JoinMiter', 'JoinRound', 'JoinBevel', 'FillSolid', 'FillTiled', 'FillStippled', 'FillOpaqueStippled', 'EvenOddRule', 'WindingRule', 'ClipByChildren', 'IncludeInferiors', 'Unsorted', 'YSorted', 'YXSorted', 'YXBanded', 'CoordModeOrigin', 'CoordModePrevious', 'Complex', 'Nonconvex', 'Convex', 'ArcChord', 'ArcPieSlice', 'GCFunction', 'GCPlaneMask', 'GCForeground', 'GCBackground', 'GCLineWidth', 'GCLineStyle', 'GCCapStyle', 'GCJoinStyle', 'GCFillStyle', 'GCFillRule', 'GCTile', 'GCStipple', 'GCTileStipXOrigin', 'GCTileStipYOrigin', 'GCFont', 'GCSubwindowMode', 'GCGraphicsExposures', 'GCClipXOrigin', 'GCClipYOrigin', 'GCClipMask', 'GCDashOffset', 'GCDashList', 'GCArcMode', 'GCLastBit', 'FontLeftToRight', 'FontRightToLeft', 'FontChange', 'XYBitmap', 'XYPixmap', 'ZPixmap', 'AllocNone', 'AllocAll', 'DoRed', 'DoGreen', 'DoBlue', 'CursorShape', 'TileShape', 'StippleShape', 'AutoRepeatModeOff', 'AutoRepeatModeOn', 'AutoRepeatModeDefault', 'LedModeOff', 'LedModeOn', 'KBKeyClickPercent', 'KBBellPercent', 'KBBellPitch', 'KBBellDuration', 'KBLed', 'KBLedMode', 'KBKey', 'KBAutoRepeatMode', 'MappingSuccess', 'MappingBusy', 'MappingFailed', 'MappingModifier', 'MappingKeyboard', 'MappingPointer', 'DontPreferBlanking', 'PreferBlanking', 'DefaultBlanking', 'DisableScreenSaver', 'DisableScreenInterval', 'DontAllowExposures', 'AllowExposures', 'DefaultExposures', 'ScreenSaverReset', 'ScreenSaverActive', 'HostInsert', 'HostDelete', 'EnableAccess', 'DisableAccess', 'StaticGray', 'GrayScale', 'StaticColor', 'PseudoColor', 'TrueColor', 'DirectColor', 'LSBFirst', 'MSBFirst', '_Xmblen', 'X_HAVE_UTF8_STRING', 'XPointer', 'Bool', 'Status', 'True_', 'False_', 'QueuedAlready', 'QueuedAfterReading', 'QueuedAfterFlush', 'XExtData', 'XExtCodes', 'XPixmapFormatValues', 'XGCValues', 'GC', 'Visual', 'Depth', 'Screen', 'ScreenFormat', 'XSetWindowAttributes', 'XWindowAttributes', 'XHostAddress', 'XServerInterpretedAddress', 'XImage', 'XWindowChanges', 'XColor', 'XSegment', 'XPoint', 'XRectangle', 'XArc', 'XKeyboardControl', 'XKeyboardState', 'XTimeCoord', 'XModifierKeymap', 'Display', '_XPrivDisplay', 'XKeyEvent', 'XKeyPressedEvent', 'XKeyReleasedEvent', 'XButtonEvent', 'XButtonPressedEvent', 'XButtonReleasedEvent', 'XMotionEvent', 'XPointerMovedEvent', 'XCrossingEvent', 'XEnterWindowEvent', 'XLeaveWindowEvent', 'XFocusChangeEvent', 'XFocusInEvent', 'XFocusOutEvent', 'XKeymapEvent', 'XExposeEvent', 'XGraphicsExposeEvent', 'XNoExposeEvent', 'XVisibilityEvent', 'XCreateWindowEvent', 'XDestroyWindowEvent', 'XUnmapEvent', 'XMapEvent', 'XMapRequestEvent', 'XReparentEvent', 'XConfigureEvent', 'XGravityEvent', 'XResizeRequestEvent', 'XConfigureRequestEvent', 'XCirculateEvent', 'XCirculateRequestEvent', 'XPropertyEvent', 'XSelectionClearEvent', 'XSelectionRequestEvent', 'XSelectionEvent', 'XColormapEvent', 'XClientMessageEvent', 'XMappingEvent', 'XErrorEvent', 'XAnyEvent', 'XGenericEvent', 'XGenericEventCookie', 'XEvent', 'XCharStruct', 'XFontProp', 'XFontStruct', 'XTextItem', 'XChar2b', 'XTextItem16', 'XEDataObject', 'XFontSetExtents', 'XOM', 'XOC', 'XFontSet', 'XmbTextItem', 'XwcTextItem', 'XOMCharSetList', 'XOrientation', 'XOMOrientation_LTR_TTB', 'XOMOrientation_RTL_TTB', 'XOMOrientation_TTB_LTR', 'XOMOrientation_TTB_RTL', 'XOMOrientation_Context', 'XOMOrientation', 'XOMFontInfo', 'XIM', 'XIC', 'XIMProc', 'XICProc', 'XIDProc', 'XIMStyle', 'XIMStyles', 'XIMPreeditArea', 'XIMPreeditCallbacks', 'XIMPreeditPosition', 'XIMPreeditNothing', 'XIMPreeditNone', 'XIMStatusArea', 'XIMStatusCallbacks', 'XIMStatusNothing', 'XIMStatusNone', 'XBufferOverflow', 'XLookupNone', 'XLookupChars', 'XLookupKeySym', 'XLookupBoth', 'XVaNestedList', 'XIMCallback', 'XICCallback', 'XIMFeedback', 'XIMReverse', 'XIMUnderline', 'XIMHighlight', 'XIMPrimary', 'XIMSecondary', 'XIMTertiary', 'XIMVisibleToForward', 'XIMVisibleToBackword', 'XIMVisibleToCenter', 'XIMText', 'XIMPreeditState', 'XIMPreeditUnKnown', 'XIMPreeditEnable', 'XIMPreeditDisable', 'XIMPreeditStateNotifyCallbackStruct', 'XIMResetState', 'XIMInitialState', 'XIMPreserveState', 'XIMStringConversionFeedback', 'XIMStringConversionLeftEdge', 'XIMStringConversionRightEdge', 'XIMStringConversionTopEdge', 'XIMStringConversionBottomEdge', 'XIMStringConversionConcealed', 'XIMStringConversionWrapped', 'XIMStringConversionText', 'XIMStringConversionPosition', 'XIMStringConversionType', 'XIMStringConversionBuffer', 'XIMStringConversionLine', 'XIMStringConversionWord', 'XIMStringConversionChar', 'XIMStringConversionOperation', 'XIMStringConversionSubstitution', 'XIMStringConversionRetrieval', 'XIMCaretDirection', 'XIMForwardChar', 'XIMBackwardChar', 'XIMForwardWord', 'XIMBackwardWord', 'XIMCaretUp', 'XIMCaretDown', 'XIMNextLine', 'XIMPreviousLine', 'XIMLineStart', 'XIMLineEnd', 'XIMAbsolutePosition', 'XIMDontChange', 'XIMStringConversionCallbackStruct', 'XIMPreeditDrawCallbackStruct', 'XIMCaretStyle', 'XIMIsInvisible', 'XIMIsPrimary', 'XIMIsSecondary', 'XIMPreeditCaretCallbackStruct', 'XIMStatusDataType', 'XIMTextType', 'XIMBitmapType', 'XIMStatusDrawCallbackStruct', 'XIMHotKeyTrigger', 'XIMHotKeyTriggers', 'XIMHotKeyState', 'XIMHotKeyStateON', 'XIMHotKeyStateOFF', 'XIMValuesList', 'XLoadQueryFont', 'XQueryFont', 'XGetMotionEvents', 'XDeleteModifiermapEntry', 'XGetModifierMapping', 'XInsertModifiermapEntry', 'XNewModifiermap', 'XCreateImage', 'XInitImage', 'XGetImage', 'XGetSubImage', 'XOpenDisplay', 'XrmInitialize', 'XFetchBytes', 'XFetchBuffer', 'XGetAtomName', 'XGetAtomNames', 'XGetDefault', 'XDisplayName', 'XKeysymToString', 'XSynchronize', 'XSetAfterFunction', 'XInternAtom', 'XInternAtoms', 'XCopyColormapAndFree', 'XCreateColormap', 'XCreatePixmapCursor', 'XCreateGlyphCursor', 'XCreateFontCursor', 'XLoadFont', 'XCreateGC', 'XGContextFromGC', 'XFlushGC', 'XCreatePixmap', 'XCreateBitmapFromData', 'XCreatePixmapFromBitmapData', 'XCreateSimpleWindow', 'XGetSelectionOwner', 'XCreateWindow', 'XListInstalledColormaps', 'XListFonts', 'XListFontsWithInfo', 'XGetFontPath', 'XListExtensions', 'XListProperties', 'XListHosts', 'XKeycodeToKeysym', 'XLookupKeysym', 'XGetKeyboardMapping', 'XStringToKeysym', 'XMaxRequestSize', 'XExtendedMaxRequestSize', 'XResourceManagerString', 'XScreenResourceString', 'XDisplayMotionBufferSize', 'XVisualIDFromVisual', 'XInitThreads', 'XLockDisplay', 'XUnlockDisplay', 'XInitExtension', 'XAddExtension', 'XFindOnExtensionList', 'XEHeadOfExtensionList', 'XRootWindow', 'XDefaultRootWindow', 'XRootWindowOfScreen', 'XDefaultVisual', 'XDefaultVisualOfScreen', 'XDefaultGC', 'XDefaultGCOfScreen', 'XBlackPixel', 'XWhitePixel', 'XAllPlanes', 'XBlackPixelOfScreen', 'XWhitePixelOfScreen', 'XNextRequest', 'XLastKnownRequestProcessed', 'XServerVendor', 'XDisplayString', 'XDefaultColormap', 'XDefaultColormapOfScreen', 'XDisplayOfScreen', 'XScreenOfDisplay', 'XDefaultScreenOfDisplay', 'XEventMaskOfScreen', 'XScreenNumberOfScreen', 'XErrorHandler', 'XSetErrorHandler', 'XIOErrorHandler', 'XSetIOErrorHandler', 'XListPixmapFormats', 'XListDepths', 'XReconfigureWMWindow', 'XGetWMProtocols', 'XSetWMProtocols', 'XIconifyWindow', 'XWithdrawWindow', 'XGetCommand', 'XGetWMColormapWindows', 'XSetWMColormapWindows', 'XFreeStringList', 'XSetTransientForHint', 'XActivateScreenSaver', 'XAddHost', 'XAddHosts', 'XAddToExtensionList', 'XAddToSaveSet', 'XAllocColor', 'XAllocColorCells', 'XAllocColorPlanes', 'XAllocNamedColor', 'XAllowEvents', 'XAutoRepeatOff', 'XAutoRepeatOn', 'XBell', 'XBitmapBitOrder', 'XBitmapPad', 'XBitmapUnit', 'XCellsOfScreen', 'XChangeActivePointerGrab', 'XChangeGC', 'XChangeKeyboardControl', 'XChangeKeyboardMapping', 'XChangePointerControl', 'XChangeProperty', 'XChangeSaveSet', 'XChangeWindowAttributes', 'XCheckIfEvent', 'XCheckMaskEvent', 'XCheckTypedEvent', 'XCheckTypedWindowEvent', 'XCheckWindowEvent', 'XCirculateSubwindows', 'XCirculateSubwindowsDown', 'XCirculateSubwindowsUp', 'XClearArea', 'XClearWindow', 'XCloseDisplay', 'XConfigureWindow', 'XConnectionNumber', 'XConvertSelection', 'XCopyArea', 'XCopyGC', 'XCopyPlane', 'XDefaultDepth', 'XDefaultDepthOfScreen', 'XDefaultScreen', 'XDefineCursor', 'XDeleteProperty', 'XDestroyWindow', 'XDestroySubwindows', 'XDoesBackingStore', 'XDoesSaveUnders', 'XDisableAccessControl', 'XDisplayCells', 'XDisplayHeight', 'XDisplayHeightMM', 'XDisplayKeycodes', 'XDisplayPlanes', 'XDisplayWidth', 'XDisplayWidthMM', 'XDrawArc', 'XDrawArcs', 'XDrawImageString', 'XDrawImageString16', 'XDrawLine', 'XDrawLines', 'XDrawPoint', 'XDrawPoints', 'XDrawRectangle', 'XDrawRectangles', 'XDrawSegments', 'XDrawString', 'XDrawString16', 'XDrawText', 'XDrawText16', 'XEnableAccessControl', 'XEventsQueued', 'XFetchName', 'XFillArc', 'XFillArcs', 'XFillPolygon', 'XFillRectangle', 'XFillRectangles', 'XFlush', 'XForceScreenSaver', 'XFree', 'XFreeColormap', 'XFreeColors', 'XFreeCursor', 'XFreeExtensionList', 'XFreeFont', 'XFreeFontInfo', 'XFreeFontNames', 'XFreeFontPath', 'XFreeGC', 'XFreeModifiermap', 'XFreePixmap', 'XGeometry', 'XGetErrorDatabaseText', 'XGetErrorText', 'XGetFontProperty', 'XGetGCValues', 'XGetGeometry', 'XGetIconName', 'XGetInputFocus', 'XGetKeyboardControl', 'XGetPointerControl', 'XGetPointerMapping', 'XGetScreenSaver', 'XGetTransientForHint', 'XGetWindowProperty', 'XGetWindowAttributes', 'XGrabButton', 'XGrabKey', 'XGrabKeyboard', 'XGrabPointer', 'XGrabServer', 'XHeightMMOfScreen', 'XHeightOfScreen', 'XIfEvent', 'XImageByteOrder', 'XInstallColormap', 'XKeysymToKeycode', 'XKillClient', 'XLookupColor', 'XLowerWindow', 'XMapRaised', 'XMapSubwindows', 'XMapWindow', 'XMaskEvent', 'XMaxCmapsOfScreen', 'XMinCmapsOfScreen', 'XMoveResizeWindow', 'XMoveWindow', 'XNextEvent', 'XNoOp', 'XParseColor', 'XParseGeometry', 'XPeekEvent', 'XPeekIfEvent', 'XPending', 'XPlanesOfScreen', 'XProtocolRevision', 'XProtocolVersion', 'XPutBackEvent', 'XPutImage', 'XQLength', 'XQueryBestCursor', 'XQueryBestSize', 'XQueryBestStipple', 'XQueryBestTile', 'XQueryColor', 'XQueryColors', 'XQueryExtension', 'XQueryKeymap', 'XQueryPointer', 'XQueryTextExtents', 'XQueryTextExtents16', 'XQueryTree', 'XRaiseWindow', 'XReadBitmapFile', 'XReadBitmapFileData', 'XRebindKeysym', 'XRecolorCursor', 'XRefreshKeyboardMapping', 'XRemoveFromSaveSet', 'XRemoveHost', 'XRemoveHosts', 'XReparentWindow', 'XResetScreenSaver', 'XResizeWindow', 'XRestackWindows', 'XRotateBuffers', 'XRotateWindowProperties', 'XScreenCount', 'XSelectInput', 'XSendEvent', 'XSetAccessControl', 'XSetArcMode', 'XSetBackground', 'XSetClipMask', 'XSetClipOrigin', 'XSetClipRectangles', 'XSetCloseDownMode', 'XSetCommand', 'XSetDashes', 'XSetFillRule', 'XSetFillStyle', 'XSetFont', 'XSetFontPath', 'XSetForeground', 'XSetFunction', 'XSetGraphicsExposures', 'XSetIconName', 'XSetInputFocus', 'XSetLineAttributes', 'XSetModifierMapping', 'XSetPlaneMask', 'XSetPointerMapping', 'XSetScreenSaver', 'XSetSelectionOwner', 'XSetState', 'XSetStipple', 'XSetSubwindowMode', 'XSetTSOrigin', 'XSetTile', 'XSetWindowBackground', 'XSetWindowBackgroundPixmap', 'XSetWindowBorder', 'XSetWindowBorderPixmap', 'XSetWindowBorderWidth', 'XSetWindowColormap', 'XStoreBuffer', 'XStoreBytes', 'XStoreColor', 'XStoreColors', 'XStoreName', 'XStoreNamedColor', 'XSync', 'XTextExtents', 'XTextExtents16', 'XTextWidth', 'XTextWidth16', 'XTranslateCoordinates', 'XUndefineCursor', 'XUngrabButton', 'XUngrabKey', 'XUngrabKeyboard', 'XUngrabPointer', 'XUngrabServer', 'XUninstallColormap', 'XUnloadFont', 'XUnmapSubwindows', 'XUnmapWindow', 'XVendorRelease', 'XWarpPointer', 'XWidthMMOfScreen', 'XWidthOfScreen', 'XWindowEvent', 'XWriteBitmapFile', 'XSupportsLocale', 'XSetLocaleModifiers', 'XOpenOM', 'XCloseOM', 'XSetOMValues', 'XGetOMValues', 'XDisplayOfOM', 'XLocaleOfOM', 'XCreateOC', 'XDestroyOC', 'XOMOfOC', 'XSetOCValues', 'XGetOCValues', 'XCreateFontSet', 'XFreeFontSet', 'XFontsOfFontSet', 'XBaseFontNameListOfFontSet', 'XLocaleOfFontSet', 'XContextDependentDrawing', 'XDirectionalDependentDrawing', 'XContextualDrawing', 'XExtentsOfFontSet', 'XmbTextEscapement', 'XwcTextEscapement', 'Xutf8TextEscapement', 'XmbTextExtents', 'XwcTextExtents', 'Xutf8TextExtents', 'XmbTextPerCharExtents', 'XwcTextPerCharExtents', 'Xutf8TextPerCharExtents', 'XmbDrawText', 'XwcDrawText', 'Xutf8DrawText', 'XmbDrawString', 'XwcDrawString', 'Xutf8DrawString', 'XmbDrawImageString', 'XwcDrawImageString', 'Xutf8DrawImageString', 'XOpenIM', 'XCloseIM', 'XGetIMValues', 'XSetIMValues', 'XDisplayOfIM', 'XLocaleOfIM', 'XCreateIC', 'XDestroyIC', 'XSetICFocus', 'XUnsetICFocus', 'XwcResetIC', 'XmbResetIC', 'Xutf8ResetIC', 'XSetICValues', 'XGetICValues', 'XIMOfIC', 'XFilterEvent', 'XmbLookupString', 'XwcLookupString', 'Xutf8LookupString', 'XVaCreateNestedList', 'XRegisterIMInstantiateCallback', 'XUnregisterIMInstantiateCallback', 'XConnectionWatchProc', 'XInternalConnectionNumbers', 'XProcessInternalConnection', 'XAddConnectionWatch', 'XRemoveConnectionWatch', 'XSetAuthorization', '_Xmbtowc', '_Xwctomb', 'XGetEventData', 'XFreeEventData', 'NoValue', 'XValue', 'YValue', 'WidthValue', 'HeightValue', 'AllValues', 'XNegative', 'YNegative', 'XSizeHints', 'USPosition', 'USSize', 'PPosition', 'PSize', 'PMinSize', 'PMaxSize', 'PResizeInc', 'PAspect', 'PBaseSize', 'PWinGravity', 'PAllHints', 'XWMHints', 'InputHint', 'StateHint', 'IconPixmapHint', 'IconWindowHint', 'IconPositionHint', 'IconMaskHint', 'WindowGroupHint', 'AllHints', 'XUrgencyHint', 'WithdrawnState', 'NormalState', 'IconicState', 'DontCareState', 'ZoomState', 'InactiveState', 'XTextProperty', 'XNoMemory', 'XLocaleNotSupported', 'XConverterNotFound', 'XICCEncodingStyle', 'XStringStyle', 'XCompoundTextStyle', 'XTextStyle', 'XStdICCTextStyle', 'XUTF8StringStyle', 'XIconSize', 'XClassHint', 'XComposeStatus', 'Region', 'RectangleOut', 'RectangleIn', 'RectanglePart', 'XVisualInfo', 'VisualNoMask', 'VisualIDMask', 'VisualScreenMask', 'VisualDepthMask', 'VisualClassMask', 'VisualRedMaskMask', 'VisualGreenMaskMask', 'VisualBlueMaskMask', 'VisualColormapSizeMask', 'VisualBitsPerRGBMask', 'VisualAllMask', 'XStandardColormap', 'BitmapSuccess', 'BitmapOpenFailed', 'BitmapFileInvalid', 'BitmapNoMemory', 'XCSUCCESS', 'XCNOMEM', 'XCNOENT', 'XContext', 'XAllocClassHint', 'XAllocIconSize', 'XAllocSizeHints', 'XAllocStandardColormap', 'XAllocWMHints', 'XClipBox', 'XCreateRegion', 'XDefaultString', 'XDeleteContext', 'XDestroyRegion', 'XEmptyRegion', 'XEqualRegion', 'XFindContext', 'XGetClassHint', 'XGetIconSizes', 'XGetNormalHints', 'XGetRGBColormaps', 'XGetSizeHints', 'XGetStandardColormap', 'XGetTextProperty', 'XGetVisualInfo', 'XGetWMClientMachine', 'XGetWMHints', 'XGetWMIconName', 'XGetWMName', 'XGetWMNormalHints', 'XGetWMSizeHints', 'XGetZoomHints', 'XIntersectRegion', 'XConvertCase', 'XLookupString', 'XMatchVisualInfo', 'XOffsetRegion', 'XPointInRegion', 'XPolygonRegion', 'XRectInRegion', 'XSaveContext', 'XSetClassHint', 'XSetIconSizes', 'XSetNormalHints', 'XSetRGBColormaps', 'XSetSizeHints', 'XSetStandardProperties', 'XSetTextProperty', 'XSetWMClientMachine', 'XSetWMHints', 'XSetWMIconName', 'XSetWMName', 'XSetWMNormalHints', 'XSetWMProperties', 'XmbSetWMProperties', 'Xutf8SetWMProperties', 'XSetWMSizeHints', 'XSetRegion', 'XSetStandardColormap', 'XSetZoomHints', 'XShrinkRegion', 'XStringListToTextProperty', 'XSubtractRegion', 'XmbTextListToTextProperty', 'XwcTextListToTextProperty', 'Xutf8TextListToTextProperty', 'XwcFreeStringList', 'XTextPropertyToStringList', 'XmbTextPropertyToTextList', 'XwcTextPropertyToTextList', 'Xutf8TextPropertyToTextList', 'XUnionRectWithRegion', 'XUnionRegion', 'XWMGeometry', 'XXorRegion']
190,917
Python
.py
5,936
28.121631
89
0.687832
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,669
__init__.py
psychopy_psychopy/psychopy/iohub/devices/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import collections import copy import os import importlib from collections import deque from operator import itemgetter import sys from psychopy.plugins.util import getEntryPoints import numpy as np from .computer import Computer from ..errors import print2err, printExceptionDetailsToStdErr from ..util import convertCamelToSnake class ioDeviceError(Exception): def __init__(self, device, msg): Exception.__init__(self, msg) self.device = device self.msg = msg def __str__(self): return repr(self) def __repr__(self): return 'ioDeviceError:\n\tMsg: {0:>s}\n\tDevice: {1}\n'.format( self.msg, repr(self.device)) class ioObjectMetaClass(type): def __new__(meta, name, bases, dct): return type.__new__(meta, name, bases, dct) def __init__(cls, name, bases, dct): type.__init__(cls, name, bases, dct) if '_newDataTypes' not in dct: cls._newDataTypes = [] if '_baseDataTypes' not in dct: parent = cls._findDeviceParent(bases) if parent: cls._baseDataTypes = parent._dataType else: cls._baseDataTypes = [] cls._dataType = cls._baseDataTypes + cls._newDataTypes cls.CLASS_ATTRIBUTE_NAMES = [e[0] for e in cls._dataType] cls.NUMPY_DTYPE = np.dtype(cls._dataType) if len(cls.__subclasses__()) == 0 and 'DeviceEvent' in [ c.__name__ for c in cls.mro()]: cls.namedTupleClass = collections.namedtuple( name + 'NT', cls.CLASS_ATTRIBUTE_NAMES) def _findDeviceParent(cls, bases): parent = None if len(bases) == 1: parent = bases[0] else: for p in bases: if 'Device' in p.__name__: parent = p break if parent is None or 'object' in parent.__name__: return None return parent class ioObject(metaclass=ioObjectMetaClass): """The ioObject class is the base class for all ioHub Device and DeviceEvent classes. Any ioHub Device or DeviceEvent class (i.e devices like Keyboard Device, Mouse Device, etc; and device events like Message, KeyboardPressEvent, MouseMoveEvent, etc.) also include the methods and attributes of this class. """ __slots__ = ['_attribute_values', ] def __init__(self, *args, **kwargs): self._attribute_values = [] if len(args) > 0: for i, n in enumerate(self.CLASS_ATTRIBUTE_NAMES): setattr(self, n, args[i]) self._attribute_values.append(args[i]) elif len(kwargs) > 0: for key in self.CLASS_ATTRIBUTE_NAMES: value = kwargs[key] setattr(self, key, value) self._attribute_values.append(value) def _asDict(self): """Return the ioObject in dictionary format, with keys as the ioObject's attribute names, and dictionary values equal to the attribute values. Return (dict): dictionary of ioObjects attribute_name, attributes values. """ return dict(list(zip(self.CLASS_ATTRIBUTE_NAMES, self._attribute_values))) def _asList(self): """Return the ioObject in list format, which is a 1D list of the ioObject's attribute values, in the order the ioObject expects them if passed to a class constructor. Return (list): 1D list of ioObjects _attribute_values """ return self._attribute_values def _asNumpyArray(self): """Return the ioObject as a numpy array, with the array values being equal to what would be returned by the asList() method, and the array cell data types being specified by NUMPY_DTYPE class constant. Return (numpy.array): numpy array representation of object. """ return np.array([tuple(self._attribute_values), ], self.NUMPY_DTYPE) def _getRPCInterface(self): rpcList = [] dlist = dir(self) for d in dlist: if d[0] != '_' and d not in ['asNumpyArray', ]: if callable(getattr(self, d)): rpcList.append(d) return rpcList # ########## Base Abstract Device that all other Devices inherit from ########## class Device(ioObject): """The Device class is the base class for all ioHub Device types. Any ioHub Device class (i.e Keyboard, Mouse, etc) also include the methods and attributes of this class. """ DEVICE_USER_LABEL_INDEX = 0 DEVICE_BUFFER_LENGTH_INDEX = 1 DEVICE_NUMBER_INDEX = 2 DEVICE_MANUFACTURER_NAME_INDEX = 3 DEVICE_MODEL_NAME_INDEX = 4 DEVICE_MAX_ATTRIBUTE_INDEX = 4 # Multiplier to use to convert this devices event time stamps to sec format. # This is set by the author of the device class or interface # implementation. DEVICE_TIMEBASE_TO_SEC = 1.0 _baseDataTypes = ioObject._baseDataTypes _newDataTypes = [ # The name given to this device instance. User Defined. Should be ('name', '|S24'), ('event_buffer_length', np.uint16), # unique within all devices of the same type_id for a given experiment. # For devices that support multiple connected to the computer at once, # with some devices the device_number can be used to select which # device to use. ('device_number', np.uint8), # The name of the manufacturer for the device being used. ('manufacturer_name', '|S64'), # The string name of the device model being used. Some devices support # different models. ('model_name', '|S32'), ] EVENT_CLASS_NAMES = [] _next_event_id = 1 _display_device = None _iohub_server = None next_filter_id = 1 DEVICE_TYPE_ID = None DEVICE_TYPE_STRING = None # _hw_interface_status constants HW_STAT_UNDEFINED = u"HW_STAT_UNDEFINED" HW_STAT_NOT_INITIALIZED = u"HW_NOT_INITIALIZED" HW_STAT_ERROR = u"HW_ERROR" HW_STAT_OK = u"HW_OK" __slots__ = [e[0] for e in _newDataTypes] + ['_hw_interface_status', '_hw_error_str', '_native_event_buffer', '_event_listeners', '_iohub_event_buffer', '_last_poll_time', '_last_callback_time', '_is_reporting_events', '_configuration', 'monitor_event_types', '_filters'] def __init__(self, *args, **kwargs): #: The user defined name given to this device instance. A device name must be #: unique for all devices of the same type_id in a given experiment. self.name = None #: For device classes that support having multiple of the same type #: being monitored by the ioHub Process at the same time (for example XInput gamepads), #: device_number is used to indicate which of the connected devices of that #: type a given ioHub Device instance should connect to. self.device_number = None #: The maximum size ( in event objects ) of the device level event buffer for this #: device instance. If the buffer becomes full, when a new event #: is added, the oldest event in the buffer is removed. self.event_buffer_length = None #: A list of event class names that can be generated by this device type #: and should be monitored and reported by the ioHub Process. self.monitor_event_types = None #: The name of the manufacturer of the device. self.manufacturer_name = None #: The model of this Device subclasses instance. Some Device types #: explicitedly support different models of the device and use different #: logic in the ioHub Device implementation based on the model_name given. self.model_name = None ioObject.__init__(self, *args, **kwargs) self._is_reporting_events = kwargs.get('auto_report_events', False) self._iohub_event_buffer = dict() self._event_listeners = dict() self._configuration = kwargs self._last_poll_time = 0 self._last_callback_time = 0 self._native_event_buffer = deque(maxlen=self.event_buffer_length) self._filters = dict() self._hw_interface_status = self.HW_STAT_UNDEFINED self._hw_error_str = u'' @staticmethod def _getNextEventID(): n = Device._next_event_id Device._next_event_id += 1 return n def getConfiguration(self): """Retrieve the configuration settings information used to create the device instance. This will the default settings for the device, found in iohub.devices.<device_name>.default_<device_name>.yaml, updated with any device settings provided via launchHubServer(...). Changing any values in the returned dictionary has no effect on the device state. Args: None Returns: (dict): The dictionary of the device configuration settings used to create the device. """ return self._configuration def getEvents(self, *args, **kwargs): """Retrieve any DeviceEvents that have occurred since the last call to the device's getEvents() or clearEvents() methods. Note that calling getEvents() at a device level does not change the Global Event Buffer's contents. Args: event_type_id (int): If specified, provides the ioHub DeviceEvent ID for which events should be returned for. Events that have occurred but do not match the event ID specified are ignored. Event type ID's can be accessed via the EventConstants class; all available event types are class attributes of EventConstants. clearEvents (int): Can be used to indicate if the events being returned should also be removed from the device event buffer. True (the default) indicates to remove events being returned. False results in events being left in the device event buffer. asType (str): Optional kwarg giving the object type to return events as. Valid values are 'namedtuple' (the default), 'dict', 'list', or 'object'. Returns: (list): New events that the ioHub has received since the last getEvents() or clearEvents() call to the device. Events are ordered by the ioHub time of each event, older event at index 0. The event object type is determined by the asType parameter passed to the method. By default a namedtuple object is returned for each event. """ self._iohub_server.processDeviceEvents() eventTypeID = None clearEvents = True if len(args) == 1: eventTypeID = args[0] elif len(args) == 2: eventTypeID = args[0] clearEvents = args[1] if eventTypeID is None: eventTypeID = kwargs.get('event_type_id', None) if eventTypeID is None: eventTypeID = kwargs.get('event_type', None) clearEvents = kwargs.get('clearEvents', True) filter_id = kwargs.get('filter_id', None) currentEvents = [] if eventTypeID: currentEvents = list(self._iohub_event_buffer.get(eventTypeID, [])) if filter_id: currentEvents = [ e for e in currentEvents if e[ DeviceEvent.EVENT_FILTER_ID_INDEX] == filter_id] if clearEvents is True and len(currentEvents) > 0: self.clearEvents( eventTypeID, filter_id=filter_id, call_proc_events=False) else: if filter_id: [currentEvents.extend( [fe for fe in event if fe[ DeviceEvent.EVENT_FILTER_ID_INDEX] == filter_id] ) for event in list(self._iohub_event_buffer.values())] else: [currentEvents.extend(event) for event in list(self._iohub_event_buffer.values())] if clearEvents is True and len(currentEvents) > 0: self.clearEvents(filter_id=filter_id, call_proc_events=False) if len(currentEvents) > 0: currentEvents = sorted( currentEvents, key=itemgetter( DeviceEvent.EVENT_HUB_TIME_INDEX)) return currentEvents def clearEvents( self, event_type=None, filter_id=None, call_proc_events=True): """Clears any DeviceEvents that have occurred since the last call to the device's getEvents(), or clearEvents() methods. Note that calling clearEvents() at the device level only clears the given device's event buffer. The ioHub Process's Global Event Buffer is unchanged. Args: None Returns: None """ if call_proc_events: self._iohub_server.processDeviceEvents() if event_type: if filter_id: event_que = self._iohub_event_buffer[event_type] newque = deque([e for e in event_que if e[ DeviceEvent.EVENT_FILTER_ID_INDEX] != filter_id], maxlen=self.event_buffer_length) self._iohub_event_buffer[event_type] = newque else: self._iohub_event_buffer.setdefault( event_type, deque(maxlen=self.event_buffer_length)).clear() else: if filter_id: for event_type, event_deque in list(self._iohub_event_buffer.items()): newque = deque([e for e in event_deque if e[ DeviceEvent.EVENT_FILTER_ID_INDEX] != filter_id], maxlen=self.event_buffer_length) self._iohub_event_buffer[event_type] = newque else: self._iohub_event_buffer.clear() def enableEventReporting(self, enabled=True): """ Specifies if the device should be reporting events to the ioHub Process (enabled=True) or whether the device should stop reporting events to the ioHub Process (enabled=False). Args: enabled (bool): True (default) == Start to report device events to the ioHub Process. False == Stop Reporting Events to the ioHub Process. Most Device types automatically start sending events to the ioHUb Process, however some devices like the EyeTracker and AnlogInput device's do not. The setting to control this behavior is 'auto_report_events' Returns: bool: The current reporting state. """ self.clearEvents() self._is_reporting_events = enabled return self._is_reporting_events def isReportingEvents(self): """Returns whether a Device is currently reporting events to the ioHub Process. Args: None Returns: (bool): Current reporting state. """ return self._is_reporting_events def _setHardwareInterfaceStatus(self, status, error_msg=u''): if status is True: self._hw_interface_status = self.HW_STAT_OK self._hw_error_str = u"" elif status is False: self._hw_interface_status = self.HW_STAT_ERROR self._hw_error_str = error_msg else: self._hw_interface_status = status self._hw_error_str = error_msg def getLastInterfaceErrorString(self): return self._hw_error_str def getInterfaceStatus(self): return self._hw_interface_status def addFilter(self, filter_file_path, filter_class_name, kwargs): """Take the filter_file_path and add the filters module dir to sys.path if it does not already exist. Then import the filter module (file) class based on filter_class_name. Create a filter instance, and add it to the _filters dict: self._filters[filter_file_path+'.'+filter_class_name] :param filter_path: :return: """ try: import importlib filter_file_path = os.path.normpath( os.path.abspath(filter_file_path)) fdir, ffile = os.path.split(filter_file_path) if not ffile.endswith('.py'): ffile = ffile + '.py' if os.path.isdir(fdir) and os.path.exists(filter_file_path): if fdir not in sys.path: sys.path.append(fdir) # import module using ffile filter_module = importlib.import_module(ffile[:-3]) # import class filter_class_name filter_class = getattr(filter_module, filter_class_name, None) if filter_class is None: print2err('Can not create Filter, filter class not found') return -1 else: # Create instance of class # For now, just use a class level counter. filter_class_instance = filter_class(**kwargs) filter_class_instance._parent_device_type = self.DEVICE_TYPE_ID # Add to filter list for device filter_key = filter_file_path + '.' + filter_class_name filter_class_instance._filter_key = filter_key self._filters[filter_key] = filter_class_instance return filter_class_instance.filter_id else: print2err('Could not add filter . File not found.') return -1 except Exception: printExceptionDetailsToStdErr() print2err('ERROR During Add Filter') def removeFilter(self, filter_file_path, filter_class_name): filter_key = filter_file_path + '.' + filter_class_name if filter_key in self._filters: del self._filters[filter_key] return True return False def resetFilter(self, filter_file_path, filter_class_name): filter_key = filter_file_path + '.' + filter_class_name if filter_key in self._filters: self._filters[filter_key].reset() return True return False def enableFilters(self, yes=True): for f in list(self._filters.values()): f.enable = yes def _handleEvent(self, e): event_type_id = e[DeviceEvent.EVENT_TYPE_ID_INDEX] self._iohub_event_buffer.setdefault( event_type_id, deque( maxlen=self.event_buffer_length)).append(e) # Add the event to any filters bound to the device which # list wanting the event's type and events filter_id input_evt_filter_id = e[DeviceEvent.EVENT_FILTER_ID_INDEX] for event_filter in list(self._filters.values()): if event_filter.enable is True: current_filter_id = event_filter.filter_id if current_filter_id != input_evt_filter_id: # stops circular event processing evt_filter_ids = event_filter.input_event_types.get( event_type_id, []) if input_evt_filter_id in evt_filter_ids: event_filter._addInputEvent(copy.deepcopy(e)) def _getNativeEventBuffer(self): return self._native_event_buffer def _addNativeEventToBuffer(self, e): if self.isReportingEvents(): self._native_event_buffer.append(e) def _addEventListener(self, event, eventTypeIDs): for ei in eventTypeIDs: self._event_listeners.setdefault(ei, []).append(event) def _removeEventListener(self, event): for etypelisteners in list(self._event_listeners.values()): if event in etypelisteners: etypelisteners.remove(event) def _getEventListeners(self, forEventType): return self._event_listeners.get(forEventType, []) def getCurrentDeviceState(self, clear_events=True): result_dict = {} self._iohub_server.processDeviceEvents() events = {str(key): tuple(value) for key, value in list(self._iohub_event_buffer.items())} result_dict['events'] = events if clear_events: self.clearEvents(call_proc_events=False) result_dict['reporting_events'] = self._is_reporting_events return result_dict def resetState(self): self.clearEvents() def _poll(self): """The _poll method is used when an ioHub Device needs to periodically check for new events received from the native device / device API. Normally this means that the native device interface is using some data buffer or queue for new device events until the ioHub Device reads them. The ioHub Device can *poll* and check for any new events that are available, retrieve the new events, and process them to create ioHub Events as necessary. Each subclass of ioHub.devives.Device that wishes to use event polling **must** override the _poll method in the Device classes implementation. The configuration section of the iohub_config.yaml for the device **must** also contain the device_timer: interval parameter as explained below. .. note:: When an event is created by an ioHub Device, it is represented in the form of an ordered list, where the number of elements in the list equals the number of public attributes of the event, and the order of the element values matches the order that the values would be provided to the constructor of the associated DeviceEvent class. This list format keeps internal event representation overhead (both in terms of creation time and memory footprint) to a minimum. The list event format also allows for the most compact representation of the event object when being transferred between the ioHub and Experiment processes. The ioHub Process can convert these list event representations to one of several, user-friendly, object formats ( namedtuple [default], dict, or the correct ioHub.devices.DeviceEvent subclass. ) for use within the experiment script. If an ioHub Device uses polling to check for new device events, the ioHub device configuration must include the following property in the devices section of the iohub_config.yaml file for the experiment: device_timer: interval: sec.msec The device_timer.interval preference informs ioHub how often the Device._poll method should be called while the Device is running. For example: device_timer: interval: 0.01 indicates that the Device._poll method should ideally be called every 10 msec to check for any new events received by the device hardware interface. The correct or optimal value for device_timer.interval depends on the device type and the expected rate of device events. For devices that receive events rapidly, for example at an average rate of 500 Hz or more, or for devices that do not provide native event time stamps (and the ioHub Process must time stamp the event) the device_timer.interval should be set to 0.001 (1 msec). For devices that receive events at lower rates and have native time stamps that are being converted to the ioHub time base, a slower polling rate is usually acceptable. A general suggestion would be to set the device_timer.interval to be equal to two to four times the expected average event input rate in Hz, but not exceeding a device_timer.interval 0.001 seconds (a polling rate of 1000 Hz). For example, if a device sends events at an average rate of 60 Hz, or once every 16.667 msec, then the polling rate could be set to the equivalent of a 120 - 240 Hz. Expressed in sec.msec format, as is required for the device_timer.interval setting, this would equal about 0.008 to 0.004 seconds. Of course it would be ideal if every device that polled for events was polling at 1000 to 2000 Hz, or 0.001 to 0.0005 msec, however if too many devices are requested to poll at such high rates, all will suffer in terms of the actual polling rate achieved. In devices with slow event output rates, such high polling rates will result in many calls to Device._poll that do not find any new events to process, causing extra processing overhead that is not needed in many cases. Args: None Returns: None """ pass def _handleNativeEvent(self, *args, **kwargs): """The _handleEvent method can be used by the native device interface (implemented by the ioHub Device class) to register new native device events by calling this method of the ioHub Device class. When a native device interface uses the _handleNativeEvent method it is employing an event callback approach to notify the ioHub Process when new native device events are available. This is in contrast to devices that use a polling method to check for new native device events, which would implement the _poll() method instead of this method. Generally speaking this method is called by the native device interface once for each new event that is available for the ioHub Process. However, with good cause, there is no reason why a single call to this method could not handle multiple new native device events. .. note:: If using _handleNativeEvent, be sure to remove the device_timer property from the devices configuration section of the iohub_config.yaml. Any arguments or kwargs passed to this method are determined by the ioHub Device implementation and should contain all the information needed to create an ioHub Device Event. Since any callbacks should take as little time to process as possible, a two stage approach is used to turn a native device event into an ioHub Device event representation: #. This method is called by the native device interface as a callback, providing the necessary # information to be able to create an ioHub event. As little processing should be done in this # method as possible. #. The data passed to this method, along with the time the callback was called, are passed as a # tuple to the Device classes _addNativeEventToBuffer method. #. During the ioHub Servers event processing routine, any new native events that have been added # to the ioHub Server using the _addNativeEventToBuffer method are passed individually to the # _getIOHubEventObject method, which must also be implemented by the given Device subclass. #. The _getIOHubEventObject method is responsible for the actual conversion of the native event # representation to the required ioHub Event representation for the accociated event type. Args: args(tuple): tuple of non keyword arguments passed to the callback. Kwargs: kwargs(dict): dict of keyword arguments passed to the callback. Returns: None """ return False def _getIOHubEventObject(self, native_event_data): """The _getIOHubEventObject method is called by the ioHub Process to convert new native device event objects that have been received to the appropriate ioHub Event type representation. If the ioHub Device has been implemented to use the _poll() method of checking for new events, then this method simply should return what it is passed, and is the default implementation for the method. If the ioHub Device has been implemented to use the event callback method to register new native device events with the ioHub Process, then this method should be overwritten by the Device subclass to convert the native event data into an appropriate ioHub Event representation. See the implementation of the Keyboard or Mouse device classes for an example of such an implementation. Args: native_event_data: object or tuple of (callback_time, native_event_object) Returns: tuple: The appropriate ioHub Event type in list form. """ return native_event_data def _close(self): try: self.__class__._iohub_server = None self.__class__._display_device = None except Exception: pass def __del__(self): self._close() # ########## Base Device Event that all other Device Events inherit from ## class DeviceEvent(ioObject): """The DeviceEvent class is the base class for all ioHub DeviceEvent types. Any ioHub DeviceEvent class (i.e MouseMoveEvent, MouseScrollEvent, MouseButtonPressEvent, KeyboardPressEvent, KeyboardReleaseEvent, etc.) also has access to the methods and attributes of the DeviceEvent class. """ EVENT_EXPERIMENT_ID_INDEX = 0 EVENT_SESSION_ID_INDEX = 1 DEVICE_ID_INDEX = 2 EVENT_ID_INDEX = 3 EVENT_TYPE_ID_INDEX = 4 EVENT_DEVICE_TIME_INDEX = 5 EVENT_LOGGED_TIME_INDEX = 6 EVENT_HUB_TIME_INDEX = 7 EVENT_CONFIDENCE_INTERVAL_INDEX = 8 EVENT_DELAY_INDEX = 9 EVENT_FILTER_ID_INDEX = 10 BASE_EVENT_MAX_ATTRIBUTE_INDEX = EVENT_FILTER_ID_INDEX # The Device Class that generates the given type of event. PARENT_DEVICE = None # The string label for the given DeviceEvent type. Should be usable to get Event type # from ioHub.EventConstants.getName(EVENT_TYPE_STRING), the value of which is the # event type id. This is set by the author of the event class # implementation. EVENT_TYPE_STRING = 'UNDEFINED_EVENT' # The type id int for the given DeviceEvent type. Should be one of the int values in # ioHub.EventConstants.EVENT_TYPE_ID. This is set by the author of the # event class implementation. EVENT_TYPE_ID = 0 _baseDataTypes = ioObject._baseDataTypes _newDataTypes = [ # The ioDataStore experiment ID assigned to the experiment code ('experiment_id', np.uint8), # specified in the experiment configuration file for the experiment. # The ioDataStore session ID assigned to the currently running ('session_id', np.uint8), # experiment session. Each time the experiment script is run, # a new session id is generated for use within the hdf5 file. # The unique id assigned to the device that generated the event. ('device_id', np.uint8), # Currently not used, but will be in the future for device types that # support > one instance of that device type to be enabled # during an experiment. Currently only one device of a given type # can be used in an experiment. # The id assigned to the current device event instance. Every device ('event_id', np.uint32), # event generated by monitored devices during an experiment session is # assigned a unique id, starting from 0 for each session, incrementing # by +1 for each new event. # The type id for the event. This is used to create DeviceEvent objects ('type', np.uint8), # or dictionary representations of an event based on the data from an # event value list. # If the device that generates the given device event type also time # stamps ('device_time', np.float64), # events, this field is the time of the event as given by the device, # converted to sec.msec-usec for consistency with all other ioHub device times. # If the device that generates the given event type does not time stamp # events, then the device_time is set to the logged_time for the event. # The sec time that the event was 'received' by the ioHub Server # Process. ('logged_time', np.float64), # For devices that poll for events, this is the sec time that the poll # method was called for the device and the event was retrieved. For # devices that use the event callback, this is the sec time the callback # executed and accept the event. Time is in sec.msec-usec # Time is in the normalized time base that all events share, ('time', np.float64), # regardless of device type. Time is calculated differently depending # on the device and perhaps event type. # Time is what should be used when comparing times of events across # different devices. Time is in sec.msec-usec. # This property attempts to give a sense of the amount to which ('confidence_interval', np.float32), # the event time may be off relative to the true time the event # occurred. confidence_interval is calculated differently depending # on the device and perhaps event types. In general though, the # smaller the confidence_interval, the more likely it is that the # calculated time of the event is correct. For devices where # a realistic confidence_interval can not be calculated, # for example if the event device delay is unknown, then a value # of -1.0 should be used. Valid confidence_interval values are # in sec.msec-usec and will range from 0.000000 sec.msec-usec # and higher. # The delay of an event is the known (or estimated) delay from when the ('delay', np.float32), # real world event occurred to when the ioHub received the event for # processing. This is often called the real-time end-to-end delay # of an event. If the delay for an event can not be reasonably estimated # or is not known, a delay of -1.0 is set. Delays are in sec.msec-usec # and valid values will range from 0.000000 sec.msec-usec and higher. # The filter identifier that the event passed through before being # saved. ('filter_id', np.int16) # If the event did not pass through any filter devices, then the value will be 0. # Otherwise, the value is the | combination of the filter set that the # event passed through before being made available to the experiment, # or saved to the ioDataStore. The filter id can be used to determine # which filters an event was handled by, but not the order in which handling was done. # Default value is 0. ] # The name of the hdf5 table used to store events of this type in the ioDataStore pytables file. # This is set by the author of the event class implementation. IOHUB_DATA_TABLE = None __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The ioHub DataStore experiment ID assigned to the experiment that is running when the event is collected. #: 0 indicates no experiment has been defined. self.experiment_id = None #: The ioHub DataStore session ID assigned for the current experiment run. #: Each time the experiment script is run, a new session id is generated for use #: by the ioHub DataStore within the hdf5 file. self.session_id = None self.device_id = None #: The id assigned to the current event instance. Every device #: event generated by the ioHub Process is assigned a unique id, #: starting from 0 for each session, incrementing by +1 for each new event. self.event_id = None #: The type id for the event. This is used to create DeviceEvent objects #: or dictionary representations of an event based on the data from an #: event value list. Event types are all defined in the #: iohub.constants.EventConstants class as class attributes. self.type = None #: If the device that generates an event type also time stamps #: the events, this field is the time of the event as given by the device, #: converted to sec.msec-usec for consistency with all other device times. #: If the device that generates the event does not time stamp #: events, then the device_time is set to the logged_time for the event. self.device_time = None #: The sec.msec time that the event was 'received' by the ioHub Process. #: For devices where the ioHub polls for events, this is the time that the poll #: method was called for the device and the event was retrieved. For #: devices that use the event callback to inform the ioHub of new events, #: this is the time the callback began to be executed. Time is in sec.msec-usec self.logged_time = None #: The calculated ioHub time is in the normalized time base that all events share, #: regardless of device type. Time is calculated differently depending #: on the device and perhaps event type. #: Time is what should be used when comparing times of events across #: different devices or with times given py psychopy.core.getTime(). Time is in sec.msec-usec. self.time = None #: This property attempts to give a sense of the amount to which #: the event time may be off relative to the true time the event #: may have become available to the ioHub Process. #: confidence_interval is calculated differently depending #: on the device and perhaps event types. In general though, the #: smaller the confidence_interval, the more accurate the #: calculated time of the event will be. For devices where #: a meaningful confidence_interval can not be calculated, a value #: of 0.0 is used. Valid confidence_interval values are #: in sec.msec-usec and will range from 0.000001 sec.msec-usec #: and higher. self.confidence_interval = None #: The delay of an event is the known (or estimated) delay from when the #: real world event occurred to when the ioHub received the event for #: processing. This is often called the real-time end-to-end delay #: of an event. If the delay for an event can not be reasonably estimated #: or is not known at all, a delay of 0.0 is set. Delays are in sec.msec-usec #: and valid values will range from 0.000001 sec.msec-usec and higher. #: the delay of an event is suptracted from the initially determined ioHub #: time for the eventso that the event.time attribute reports the actual #: event time as accurately as possible. self.delay = None self.filter_id = None ioObject.__init__(self, *args, **kwargs) def __cmp__(self, other): return self.time - other.time @classmethod def createEventAsClass(cls, eventValueList): kwargs = cls.createEventAsDict(eventValueList) return cls(**kwargs) @classmethod def createEventAsDict(cls, values): return dict(list(zip(cls.CLASS_ATTRIBUTE_NAMES, values))) # noinspection PyUnresolvedReferences @classmethod def createEventAsNamedTuple(cls, valueList): return cls.namedTupleClass(*valueList) # # Import Devices and DeviceEvents # def importDeviceModule(modulePath): """ Resolve an import string to import the module for a particular device. Will iteratively check plugin entry points too. Parameters ---------- modulePath : str Import path for the requested module Return ------ types.ModuleType Requested module Raises ------ ModuleNotFoundError If module doesn't exist, will raise this error. """ module = None try: # try importing as is (this was the only way prior to plugins) module = importlib.import_module(modulePath) except ModuleNotFoundError: # get entry point groups targeting iohub.devices entryPoints = getEntryPoints("psychopy.iohub.devices", submodules=True, flatten=False) # iterate through found groups for group in entryPoints: # skip irrelevant groups if not modulePath.startswith(group): continue # get the module of the entry point group module_group = importlib.import_module(group) # get the entry point target module(s) for ep in entryPoints[group]: module_name = ep.name ep_target = ep.load() # bind each entry point module to the existing module tree setattr(module_group, module_name, ep_target) sys.modules[group + '.' + module_name] = ep_target # re-try importing the module try: module = importlib.import_module(modulePath) except ModuleNotFoundError: pass # raise error if all import options failed if module is None: raise ModuleNotFoundError( f"Could not find module `{modulePath}`. Tried importing directly " f"and iteratively using entry points." ) return module def import_device(module_path, device_class_name): # get module from module_path module = importDeviceModule(module_path) # get device class from module device_class = getattr(module, device_class_name) setattr(sys.modules[__name__], device_class_name, device_class) event_classes = dict() for event_class_name in device_class.EVENT_CLASS_NAMES: event_constant_string = convertCamelToSnake( event_class_name[:-5], False) event_class = getattr(module, event_class_name) event_class.DEVICE_PARENT = device_class event_classes[event_constant_string] = event_class setattr(sys.modules[__name__], event_class_name, event_class) return device_class, device_class_name, event_classes try: if getattr(sys.modules[__name__], 'Display', None) is None: display_class, device_class_name, event_classes = import_device('psychopy.iohub.devices.display', 'Display') setattr(sys.modules[__name__], 'Display', display_class) except Exception: print2err('Warning: display device module could not be imported.') printExceptionDetailsToStdErr()
43,547
Python
.py
837
41.640382
117
0.646494
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,670
eventfilters.py
psychopy_psychopy/psychopy/iohub/devices/eventfilters.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import numpy as np from collections import deque from ..util import NumPyRingBuffer from . import Device, DeviceEvent, Computer from ..constants import EventConstants # Event Filter / Translator / Parser Class Prototype class DeviceEventFilter(): """Base class for creating a filtered / processed event stream from a device's iohub events. Any device event filter class MUST use this class as the base class type. The following properties must be implemented by a DeviceEventFilter subclass: * filter_id * input_event_types The following methods must be implemented by a DeviceEventFilter subclass: * process The class __init__ can accept a set of kwargs, which will automatically be converted into class_instance.key = value attributes. """ event_filter_id_index = DeviceEvent.EVENT_FILTER_ID_INDEX event_id_index = DeviceEvent.EVENT_ID_INDEX event_time_index = DeviceEvent.EVENT_HUB_TIME_INDEX def __init__(self, **kwargs): # _parent_device_type filled in by iohub self._parent_device_type = None # _filter_id filled in by iohub self._filter_key = None self._input_events = [] self._output_events = [] for key, value in list(kwargs.items()): setattr(self, key, value) self._enabled = False @property def enable(self): return self._enabled @enable.setter def enable(self, v): self._enabled = v def getInputEvents(self): return self._input_events def clearInputEvents(self): self._input_events = [] def reset(self): self._input_events = [] self._output_events = [] @property def filter_id(self): raise RuntimeError('filter_id property must be set by subclass.') @property def input_event_types(self): raise RuntimeError( 'input_event_types property must be set by subclass.') # Example: # # Request MouseMove events that have not been filtered (filter id 0): # # event_type_and_filter_ids = dict() # event_type_and_filter_ids[EventConstants.MOUSE_MOVE]=[0,] # return event_type_and_filter_ids def process(self): """ *** This method must be implemented by the sub class. *** # Process / filter events. # # Called by the iohub server each time an iohub device # receives a new iohub event. # # Get new events to process by calling getInputEvents(). # Add processed events that are ready to be output by iohub by # calling addOutputEvent(e). # # Optionally remove the input events processed so they are not # repeatedly retrieved using clearInputEvents(. # # The events returned by getInputEvents() are copies of the # original event lists, so it is fine to filter in place if desired. # # Each event passed to addOutputEvent() will have it's event_id and # filter_id updated appropriately; this is done for you. """ raise RuntimeError('process method must be implemented by subclass.') def addOutputEvent(self, e): e[self.event_id_index] = Device._getNextEventID() e[self.event_filter_id_index] = self.filter_id self._output_events.append(e) def _addInputEvent(self, evt): """Takes event from parent device for processing.""" self._input_events.append(evt) self.process() def _removeOutputEvents(self): """Called by the iohub Server when processing device events.""" oevts = self._output_events self._output_events = [] return oevts ####################### Device Event Field Filter Types ################## class MovingWindowFilter(): """Maintains a moving window of size 'length', for a specific event field value, given by 'event_field_name'. knot_pos defines where in the window the next filtered value should always be returned from. knot_pos can be an index between 0 - length-1, or a string constant: 'center': use the middle value in the window. Window length must be odd. 'latest': the value just added to the window is filtered and returned 'oldest': the last value in the buffer is filtered and returned If the windowing buffer is full, a filtered value is returned when a value is added to the MovingWindow using MovingWindow.add. None is returned until the MovingWindow is full. The base class implements a moving window averaging filter, no weights. To change the filter used, extend this class and replace the filteredValue method. """ def __init__(self, **kwargs): self._inplace = kwargs.get('inplace') knot_pos = kwargs.get('knot_pos') length = kwargs.get('length') event_type = kwargs.get('event_type') event_field_name = kwargs.get('event_field_name') if isinstance(knot_pos, str): if knot_pos == 'center' and length % 2 == 0: raise ValueError( 'MovingWindow length must be odd for a centered knot_pos.') if knot_pos == 'center': self._active_index = length // 2 elif knot_pos == 'latest': self._active_index = 0 elif knot_pos == 'oldest': self._active_index = length - 1 else: raise ValueError( "MovingWindow knot_pos must be an index between 0 - length-1, or a string constantin ['center','latest','oldest']") else: if knot_pos < 0 or knot_pos >= length: raise ValueError( 'MovingWindow knot_pos must be between 0 and length-1.') self._active_index = knot_pos self._event_field_index = None self._events = None if event_type and event_field_name: self._event_field_index = EventConstants.getClass( event_type).CLASS_ATTRIBUTE_NAMES.index(event_field_name) self._events = deque(maxlen=length) self._filtering_buffer = NumPyRingBuffer(length) def filteredValue(self): """Returns a filtered value based on the data in the window. The base implementation returns the average value of the window values. Sub classes of MovingWindowFilter can implement their own filteredValue method so that different moving window filter types can be created. """ return self._filtering_buffer.mean() def add(self, event): """Add the given iohub event ( in list form ) to the moving window. The value of the specified event attribute when the filter was created is what is used to calculate return values for the filter. If the window is full, this method returns an iohub event that has been filtered, and the filtered value of the field being filtered. """ if isinstance(event, (list, tuple)): self._filtering_buffer.append(event[self._event_field_index]) self._events.append(event) if self.isFull(): if self._inplace: self._events[ self._active_index][ self._event_field_index] = self.filteredValue() return self._events[self._active_index], self.filteredValue() else: self._filtering_buffer.append(event) if self.isFull(): return None, self.filteredValue() def isFull(self): return self._filtering_buffer.isFull() def clear(self): self._filtering_buffer.clear() if self._events: self._events.clear() # ------ class PassThroughFilter(MovingWindowFilter): """Returns the median value of the moving window. Length must be odd. """ def __init__(self, **kwargs): kwargs['length'] = 1 kwargs['knot_pos'] = 0 MovingWindowFilter.__init__(self, **kwargs) def filteredValue(self): return self._filtering_buffer[0] # ------ class MedianFilter(MovingWindowFilter): """Returns the median value of the moving window. Length must be odd. """ def __init__(self, **kwargs): MovingWindowFilter.__init__(self, **kwargs) def filteredValue(self): return np.median(self._filtering_buffer.getElements()) # ------ class WeightedAverageFilter(MovingWindowFilter): """ Returns the weighted average of the moving window. Window length is equal to len(weights). The weights array will be normalized using: weights = weights / numpy.sum(weights) before being used by the filter. """ def __init__(self, **kwargs): weights = kwargs.get('weights') length = len(weights) kwargs['length'] = length MovingWindowFilter.__init__(self, **kwargs) weights = np.asanyarray(weights) self._weights = weights / np.sum(weights) def filteredValue(self): return np.convolve( self._filtering_buffer.getElements(), self._weights, 'valid') # ------ class StampFilter(MovingWindowFilter): """ Implements The Stampe Filter (created by Dave Stampe of SR Research). The filter has a window length of 3. If the window values (v1,v2,v3) are non monotonic, then the middle value is replaced by the mean of v1 and v3. Otherwise v2 is returned unmodified. level arg indicates how many iterations of the Stampe filter should be applied before starting to return filtered data. Default = 1. If levels = 2, then the filter would use data returned from a sub filter instance of the Stampe filter., Etc. """ def __init__(self, **kwargs): level = kwargs.get('level') self._level = level kwargs['knot_pos'] = 'center' kwargs['length'] = 3 self.sub_filter = None MovingWindowFilter.__init__(self, **kwargs) if level > 1: level = level - 1 kwargs['inplace'] = False kwargs['level'] = level self.sub_filter = StampFilter(**kwargs) def filteredValue(self): if self.sub_filter: return self.sub_filter.filteredValue() e1, e2, e3 = self._filtering_buffer[0:3] if not(e1 < e2 and e2 < e3) or not (e3 < e2 and e2 < e1): return (e1 + e3) / 2.0 return e2 def add(self, event): if self.sub_filter: sub_result = self.sub_filter.add(event) if sub_result: self._filtering_buffer.append(sub_result[1]) self._events.append(event) return MovingWindowFilter.add(self, event) # ------ #################### TEST ############################### if __name__ == '__main__': # Create a list of iohub Mouse move events. from collections import OrderedDict events = [] events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=12, type=36, device_time=139960.228, logged_time=4.668474991165567, time=4.668474991165567, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-84, y_position=157, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=13, type=36, device_time=139960.228, logged_time=4.67646576158586, time=4.67646576158586, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-85, y_position=157, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=14, type=36, device_time=139960.243, logged_time=4.684467700717505, time=4.684467700717505, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-87, y_position=158, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=15, type=36, device_time=139960.243, logged_time=4.692443981941324, time=4.692443981941324, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-88, y_position=158, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=16, type=36, device_time=139960.259, logged_time=4.700467051123269, time=4.700467051123269, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-93, y_position=157, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=17, type=36, device_time=139960.259, logged_time=4.708441823080648, time=4.708441823080648, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-96, y_position=154, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=18, type=36, device_time=139960.275, logged_time=4.716453723493032, time=4.716453723493032, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-103, y_position=150, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=19, type=36, device_time=139960.275, logged_time=4.724468038795749, time=4.724468038795749, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-117, y_position=145, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=20, type=36, device_time=139960.29, logged_time=4.73246877049678, time=4.73246877049678, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-126, y_position=138, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=21, type=36, device_time=139960.29, logged_time=4.740443542454159, time=4.740443542454159, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-135, y_position=129, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=22, type=36, device_time=139960.306, logged_time=4.748473252460826, time=4.748473252460826, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-141, y_position=123, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=23, type=36, device_time=139960.306, logged_time=4.756493303051684, time=4.756493303051684, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-145, y_position=117, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=24, type=36, device_time=139960.321, logged_time=4.764460830425378, time=4.764460830425378, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-151, y_position=113, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=25, type=36, device_time=139960.321, logged_time=4.772470014140708, time=4.772470014140708, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-153, y_position=109, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=26, type=36, device_time=139960.337, logged_time=4.780456860404229, time=4.780456860404229, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-153, y_position=109, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=27, type=36, device_time=139960.337, logged_time=4.788497135421494, time=4.788497135421494, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-153, y_position=108, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=28, type=36, device_time=139960.353, logged_time=4.796479151962558, time=4.796479151962558, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-153, y_position=103, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=29, type=36, device_time=139960.353, logged_time=4.804472035379149, time=4.804472035379149, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-150, y_position=97, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=30, type=36, device_time=139960.368, logged_time=4.81250325468136, time=4.81250325468136, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-146, y_position=91, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=31, type=36, device_time=139960.368, logged_time=4.820451161329402, time=4.820451161329402, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-142, y_position=87, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=32, type=36, device_time=139960.384, logged_time=4.828460043179803, time=4.828460043179803, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-133, y_position=78, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=33, type=36, device_time=139960.384, logged_time=4.836455341457622, time=4.836455341457622, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-124, y_position=69, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=34, type=36, device_time=139960.399, logged_time=4.844488975621061, time=4.844488975621061, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-115, y_position=63, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=35, type=36, device_time=139960.399, logged_time=4.852467369870283, time=4.852467369870283, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-104, y_position=58, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=36, type=36, device_time=139960.415, logged_time=4.860472931293771, time=4.860472931293771, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-93, y_position=54, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=37, type=36, device_time=139960.415, logged_time=4.868483020574786, time=4.868483020574786, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-84, y_position=52, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=38, type=36, device_time=139960.431, logged_time=4.8764499442477245, time=4.8764499442477245, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-78, y_position=52, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=39, type=36, device_time=139960.431, logged_time=4.8844805598200765, time=4.8844805598200765, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-73, y_position=52, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=40, type=36, device_time=139960.446, logged_time=4.892454426211771, time=4.892454426211771, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-67, y_position=53, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=41, type=36, device_time=139960.446, logged_time=4.900474174937699, time=4.900474174937699, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-64, y_position=54, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=42, type=36, device_time=139960.462, logged_time=4.908475510368589, time=4.908475510368589, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-57, y_position=58, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=43, type=36, device_time=139960.462, logged_time=4.916455112048425, time=4.916455112048425, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-53, y_position=65, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=44, type=36, device_time=139960.477, logged_time=4.924477879336337, time=4.924477879336337, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-49, y_position=73, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=45, type=36, device_time=139960.493, logged_time=4.932478611037368, time=4.932478611037368, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-47, y_position=82, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=46, type=36, device_time=139960.493, logged_time=4.940512547065737, time=4.940512547065737, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-47, y_position=90, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=47, type=36, device_time=139960.509, logged_time=4.94846588713699, time=4.94846588713699, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-47, y_position=101, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=48, type=36, device_time=139960.509, logged_time=4.956459676119266, time=4.956459676119266, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-48, y_position=112, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=49, type=36, device_time=139960.524, logged_time=4.964475198852597, time=4.964475198852597, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-50, y_position=123, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=50, type=36, device_time=139960.524, logged_time=4.972453894966748, time=4.972453894966748, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-55, y_position=132, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=51, type=36, device_time=139960.54, logged_time=4.980477869685274, time=4.980477869685274, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-57, y_position=140, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=52, type=36, device_time=139960.54, logged_time=4.9884749790944625, time=4.9884749790944625, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-61, y_position=146, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=53, type=36, device_time=139960.555, logged_time=4.997502026119037, time=4.997502026119037, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-65, y_position=153, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=54, type=36, device_time=139960.555, logged_time=5.004507533827564, time=5.004507533827564, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-69, y_position=156, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=55, type=36, device_time=139960.571, logged_time=5.012471137044486, time=5.012471137044486, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-69, y_position=157, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=56, type=36, device_time=139960.571, logged_time=5.02049752662424, time=5.02049752662424, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-70, y_position=157, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=57, type=36, device_time=139960.587, logged_time=5.028478637599619, time=5.028478637599619, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-73, y_position=158, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=58, type=36, device_time=139960.587, logged_time=5.036483293457422, time=5.036483293457422, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-76, y_position=158, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=59, type=36, device_time=139960.602, logged_time=5.044499118026579, time=5.044499118026579, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-80, y_position=156, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=60, type=36, device_time=139960.602, logged_time=5.052488681016257, time=5.052488681016257, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-88, y_position=149, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=61, type=36, device_time=139960.618, logged_time=5.060469188261777, time=5.060469188261777, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-95, y_position=143, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=62, type=36, device_time=139960.618, logged_time=5.068480786838336, time=5.068480786838336, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-99, y_position=132, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=63, type=36, device_time=139960.633, logged_time=5.07647849994828, time=5.07647849994828, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-102, y_position=114, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=64, type=36, device_time=139960.633, logged_time=5.084472590795485, time=5.084472590795485, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-100, y_position=91, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=65, type=36, device_time=139960.649, logged_time=5.092484189372044, time=5.092484189372044, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-97, y_position=72, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=66, type=36, device_time=139960.649, logged_time=5.1004631873220205, time=5.1004631873220205, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-87, y_position=46, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=67, type=36, device_time=139960.665, logged_time=5.108479615621036, time=5.108479615621036, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-75, y_position=25, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=68, type=36, device_time=139960.665, logged_time=5.116496345784981, time=5.116496345784981, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-59, y_position=2, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=69, type=36, device_time=139960.68, logged_time=5.124480173457414, time=5.124480173457414, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-49, y_position=-10, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=70, type=36, device_time=139960.68, logged_time=5.132490866468288, time=5.132490866468288, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-40, y_position=-17, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=71, type=36, device_time=139960.696, logged_time=5.140464430995053, time=5.140464430995053, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-34, y_position=-23, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=72, type=36, device_time=139960.696, logged_time=5.148476935137296, time=5.148476935137296, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-26, y_position=-25, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=73, type=36, device_time=139960.711, logged_time=5.156460762809729, time=5.156460762809729, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-17, y_position=-27, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=74, type=36, device_time=139960.711, logged_time=5.164469040959375, time=5.164469040959375, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-3, y_position=-26, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=75, type=36, device_time=139960.727, logged_time=5.172525616275379, time=5.172525616275379, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=10, y_position=-24, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=76, type=36, device_time=139960.727, logged_time=5.180502199393231, time=5.180502199393231, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=22, y_position=-19, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=77, type=36, device_time=139960.743, logged_time=5.188485725229839, time=5.188485725229839, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=31, y_position=-10, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=78, type=36, device_time=139960.743, logged_time=5.19647377889487, time=5.19647377889487, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=40, y_position=-3, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=79, type=36, device_time=139960.758, logged_time=5.20449745177757, time=5.20449745177757, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=46, y_position=8, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=80, type=36, device_time=139960.758, logged_time=5.212564893969102, time=5.212564893969102, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=51, y_position=19, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=81, type=36, device_time=139960.774, logged_time=5.22048744460335, time=5.22048744460335, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=53, y_position=30, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=82, type=36, device_time=139960.774, logged_time=5.228505080303876, time=5.228505080303876, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=53, y_position=41, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=83, type=36, device_time=139960.789, logged_time=5.236476531834342, time=5.236476531834342, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=52, y_position=52, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=84, type=36, device_time=139960.805, logged_time=5.244548803777434, time=5.244548803777434, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=45, y_position=67, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=85, type=36, device_time=139960.805, logged_time=5.252519349713111, time=5.252519349713111, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=40, y_position=76, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=86, type=36, device_time=139960.821, logged_time=5.260487480816664, time=5.260487480816664, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=36, y_position=85, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=87, type=36, device_time=139960.821, logged_time=5.26849726823275, time=5.26849726823275, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=32, y_position=91, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=88, type=36, device_time=139960.836, logged_time=5.27647656807676, time=5.27647656807676, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=28, y_position=94, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=89, type=36, device_time=139960.836, logged_time=5.284469451493351, time=5.284469451493351, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=25, y_position=96, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=90, type=36, device_time=139960.852, logged_time=5.292507009784458, time=5.292507009784458, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=19, y_position=96, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=91, type=36, device_time=139960.852, logged_time=5.300493554183049, time=5.300493554183049, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=14, y_position=96, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=92, type=36, device_time=139960.867, logged_time=5.308489758026553, time=5.308489758026553, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=8, y_position=95, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=93, type=36, device_time=139960.867, logged_time=5.316499545471743, time=5.316499545471743, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-1, y_position=91, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=94, type=36, device_time=139960.883, logged_time=5.324469487706665, time=5.324469487706665, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-7, y_position=87, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=95, type=36, device_time=139960.883, logged_time=5.332472936133854, time=5.332472936133854, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-14, y_position=80, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=96, type=36, device_time=139960.899, logged_time=5.340496307122521, time=5.340496307122521, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-18, y_position=74, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=97, type=36, device_time=139960.899, logged_time=5.348478927393444, time=5.348478927393444, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-22, y_position=68, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=98, type=36, device_time=139960.914, logged_time=5.356487809243845, time=5.356487809243845, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-24, y_position=60, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=99, type=36, device_time=139960.914, logged_time=5.3645060486742295, time=5.3645060486742295, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-24, y_position=56, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=100, type=36, device_time=139960.93, logged_time=5.3725043655140325, time=5.3725043655140325, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-24, y_position=53, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=101, type=36, device_time=139960.93, logged_time=5.380504493514309, time=5.380504493514309, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-24, y_position=50, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=102, type=36, device_time=139960.945, logged_time=5.388510054937797, time=5.388510054937797, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-23, y_position=47, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=103, type=36, device_time=139960.945, logged_time=5.396494788175914, time=5.396494788175914, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-19, y_position=41, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=104, type=36, device_time=139960.961, logged_time=5.404487973457435, time=5.404487973457435, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-13, y_position=37, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=105, type=36, device_time=139960.961, logged_time=5.412510740745347, time=5.412510740745347, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-4, y_position=32, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=106, type=36, device_time=139960.977, logged_time=5.420487323863199, time=5.420487323863199, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=4, y_position=30, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=107, type=36, device_time=139960.977, logged_time=5.4285116004466545, time=5.4285116004466545, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=15, y_position=30, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=108, type=36, device_time=139960.992, logged_time=5.436502069002017, time=5.436502069002017, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=26, y_position=32, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=109, type=36, device_time=139960.992, logged_time=5.4445049136993475, time=5.4445049136993475, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=37, y_position=36, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=110, type=36, device_time=139961.008, logged_time=5.452508362126537, time=5.452508362126537, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=43, y_position=38, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=111, type=36, device_time=139961.008, logged_time=5.4604792099271435, time=5.4604792099271435, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=49, y_position=42, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=112, type=36, device_time=139961.023, logged_time=5.468485676916316, time=5.468485676916316, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=53, y_position=46, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=113, type=36, device_time=139961.023, logged_time=5.476476145471679, time=5.476476145471679, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=53, y_position=49, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=114, type=36, device_time=139961.039, logged_time=5.484498309058836, time=5.484498309058836, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=52, y_position=54, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=115, type=36, device_time=139961.039, logged_time=5.492511718766764, time=5.492511718766764, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=50, y_position=60, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=116, type=36, device_time=139961.055, logged_time=5.500507318880409, time=5.500507318880409, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=44, y_position=69, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=117, type=36, device_time=139961.055, logged_time=5.508503522723913, time=5.508503522723913, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=40, y_position=73, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=118, type=36, device_time=139961.07, logged_time=5.516478294681292, time=5.516478294681292, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=36, y_position=79, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=119, type=36, device_time=139961.07, logged_time=5.524498647137079, time=5.524498647137079, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=33, y_position=81, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=120, type=36, device_time=139961.086, logged_time=5.532514773571165, time=5.532514773571165, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=29, y_position=82, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=121, type=36, device_time=139961.086, logged_time=5.5405037328309845, time=5.5405037328309845, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=24, y_position=82, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=122, type=36, device_time=139961.101, logged_time=5.548520764830755, time=5.548520764830755, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=18, y_position=81, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=123, type=36, device_time=139961.117, logged_time=5.556483160646167, time=5.556483160646167, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=9, y_position=79, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=124, type=36, device_time=139961.117, logged_time=5.564633311791113, time=5.564633311791113, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-6, y_position=72, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=125, type=36, device_time=139961.133, logged_time=5.572515413514338, time=5.572515413514338, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-15, y_position=63, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=126, type=36, device_time=139961.133, logged_time=5.580504372774158, time=5.580504372774158, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-24, y_position=54, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=127, type=36, device_time=139961.148, logged_time=5.588501180318417, time=5.588501180318417, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-28, y_position=42, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=128, type=36, device_time=139961.148, logged_time=5.596497686026851, time=5.596497686026851, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-33, y_position=31, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=129, type=36, device_time=139961.164, logged_time=5.604483324859757, time=5.604483324859757, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-33, y_position=23, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=130, type=36, device_time=139961.164, logged_time=5.612715279363329, time=5.612715279363329, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-33, y_position=17, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=131, type=36, device_time=139961.179, logged_time=5.620532481727423, time=5.620532481727423, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-32, y_position=12, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=132, type=36, device_time=139961.179, logged_time=5.6285226484178565, time=5.6285226484178565, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-30, y_position=6, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=133, type=36, device_time=139961.195, logged_time=5.636515531834448, time=5.636515531834448, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-28, y_position=2, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=134, type=36, device_time=139961.195, logged_time=5.644488794496283, time=5.644488794496283, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-24, y_position=-4, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=135, type=36, device_time=139961.211, logged_time=5.652492544788402, time=5.652492544788402, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-15, y_position=-8, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=136, type=36, device_time=139961.211, logged_time=5.660516519506928, time=5.660516519506928, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=-7, y_position=-13, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=137, type=36, device_time=139961.226, logged_time=5.668525703222258, time=5.668525703222258, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=7, y_position=-13, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) events.append( OrderedDict( experiment_id=0, session_id=0, device_id=0, event_id=138, type=36, device_time=139961.226, logged_time=5.676524020062061, time=5.676524020062061, confidence_interval=0.0, delay=0.0, filter_id=0, display_id=0, button_state=0, button_id=0, pressed_buttons=0, x_position=18, y_position=-11, scroll_dx=0, scroll_x=0, scroll_dy=0, scroll_y=0, modifiers=[], window_id=984208)) #events = [e.values() for e in events] # Using event class and fields #mx_filter = MedianFilter(5, EventConstants.MOUSE_MOVE, 'x_position', knot_pos='center', inplace = True) #my_filter = MedianFilter(5, EventConstants.MOUSE_MOVE, 'y_position', knot_pos='center', inplace = True) # mx_filter = WeightedAverageFilter([17.0,33.0,50.0,33.0,17.0], EventConstants.MOUSE_MOVE, 'x_position', knot_pos='center', inplace = True) # my_filter = WeightedAverageFilter([17.0,33.0,50.0,33.0,17.0], EventConstants.MOUSE_MOVE, 'y_position', knot_pos='center', inplace = True) #mx_filter = StampFilter(EventConstants.MOUSE_MOVE, 'x_position', level = 2, inplace = True) #my_filter = StampFilter(EventConstants.MOUSE_MOVE, 'y_position', level = 2, inplace = True) # print "FIRST SOURCE EVENT ID:",events[0]['event_id'] # for e in events: # r = mx_filter.add(e) # if r: # event, filtered_x=r # r = my_filter.add(e) # if r: # event, filtered_y=r # if r: # print "filtered event: ",event['event_id'],filtered_x, filtered_y # Using values only mx_filter = WeightedAverageFilter( weights=[ 17.0, 33.0, 50.0, 33.0, 17.0], event_type=None, event_field_name=None, knot_pos='center', inplace=True) my_filter = WeightedAverageFilter( weights=[ 17.0, 33.0, 50.0, 33.0, 17.0], event_type=None, event_field_name=None, knot_pos='center', inplace=True) print('FIRST SOURCE EVENT ID:', events[0]['event_id']) for e in events: r = mx_filter.add(e['x_position']) filtered_x = None filtered_y = None if r: _junk, filtered_x = r r = my_filter.add(e['y_position']) if r: _junk, filtered_y = r print('filtered values: ', filtered_x, filtered_y)
100,440
Python
.py
3,490
16.629226
142
0.471363
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,671
eye_events.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/eye_events.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from .. import DeviceEvent from ...constants import EventConstants from . import EyeTrackerDevice import numpy as np class EyeTrackerEvent(DeviceEvent): PARENT_DEVICE = EyeTrackerDevice class MonocularEyeSampleEvent(EyeTrackerEvent): """A MonocularEyeSampleEvent represents the eye position and eye attribute data collected from one frame or reading of an eye tracker device that is recoding from only one eye, or is recording from both eyes and averaging the binocular data. Event Type ID: EventConstants.MONOCULAR_EYE_SAMPLE Event Type String: 'MONOCULAR_EYE_SAMPLE' """ _newDataTypes = [ # The eye type that the sample is from. Valid values are: ('eye', 'u1'), # EyeTrackerConstants.LEFT_EYE # EyeTrackerConstants.RIGHT_EYE # EyeTrackerConstants.BINOCULAR # EyeTrackerConstants.BINOCULAR_AVERAGED # EyeTrackerConstants.SIMULATED_MONOCULAR # EyeTrackerConstants.SIMULATED_BINOCULAR # The calibrated horizontal eye position on the calibration plane. ('gaze_x', 'f4'), # This value is specified in Display Coordinate Type Units. # The calibrated vertical eye position on the calibration plane. ('gaze_y', 'f4'), # This value is specified in Display Coordinate Type Units. # The calculated point of gaze in depth. Generally This can only be ('gaze_z', 'f4'), # provided if binocular reporting is being performed. # The x eye position in an eye trackers 3D coordinate space. ('eye_cam_x', 'f4'), # Generally this field is only available by systems that are also # calculating eye data using a 3D model of eye position relative to # the eye camera(s) for example. # The y eye position in an eye trackers 3D coordinate space. ('eye_cam_y', 'f4'), # Generally this field is only available by systems that are also # calculating eye data using a 3D model of eye position relative to # the eye camera(s) for example. # The z eye position in an eye trackers 3D coordinate space. ('eye_cam_z', 'f4'), # Generally this field is only available by systems that are also # calculating eye data using a 3D model of eye position relative to # the eye camera(s) for example. # The horizontal angle of eye the relative to the head. ('angle_x', 'f4'), # The vertical angle of eye the relative to the head. ('angle_y', 'f4'), # The non-calibrated x position of the calculated eye 'center' ('raw_x', 'f4'), # on the camera sensor image, # factoring in any corneal reflection adjustments. # This is typically reported in some arbitrary unit space that # often has sub-pixel resolution due to image processing techniques # being applied. # The non-calibrated y position of the calculated eye 'center' ('raw_y', 'f4'), # on the camera sensor image, # factoring in any corneal reflection adjustments. # This is typically reported in some arbitrary unit space that # often has sub-pixel resolution due to image processing techniques # being applied. # A measure related to pupil size or diameter. Attribute ('pupil_measure1', 'f4'), # pupil_measure1_type defines what type the measure represents. # Several possible pupil_measure types available: ('pupil_measure1_type', 'u1'), # EyeTrackerConstants.PUPIL_AREA # EyeTrackerConstants.PUPIL_DIAMETER # EyeTrackerConstants.PUPIL_WIDTH # EyeTrackerConstants.PUPIL_HEIGHT # EyeTrackerConstants.PUPIL_MAJOR_AXIS # EyeTrackerConstants.PUPIL_MINOR_AXIS # A measure related to pupil size or diameter. Attribute ('pupil_measure2', 'f4'), # pupil_measure2_type defines what type the measure represents. # Several possible pupil_measure types are available: ('pupil_measure2_type', 'u1'), # EyeTrackerConstants.PUPIL_AREA # EyeTrackerConstants.PUPIL_DIAMETER # EyeTrackerConstants.PUPIL_WIDTH # EyeTrackerConstants.PUPIL_HEIGHT # EyeTrackerConstants.PUPIL_MAJOR_AXIS # EyeTrackerConstants.PUPIL_MINOR_AXIS ('ppd_x', 'f4'), # Horizontal pixels per visual degree for this eye position # as reported by the eye tracker. ('ppd_y', 'f4'), # Vertical pixels per visual degree for this eye position # as reported by the eye tracker. # Horizontal velocity of the eye at the time of the sample; ('velocity_x', 'f4'), # as reported by the eye tracker. # Vertical velocity of the eye at the time of the sample; ('velocity_y', 'f4'), # as reported by the eye tracker. ('velocity_xy', 'f4'), # 2D Velocity of the eye at the time of the sample; # as reported by the eye tracker. # An available status word for the eye tracker sample. ('status', 'u1') # Meaning is completely tracker dependent. ] EVENT_TYPE_ID = EventConstants.MONOCULAR_EYE_SAMPLE EVENT_TYPE_STRING = 'MONOCULAR_EYE_SAMPLE' IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The eye type that the sample is from. Valid values are: #: #: EventConstants.LEFT_EYE #: EventConstants.RIGHT_EYE #: EventConstants.SIMULATED_MONOCULAR #: EventConstants.MONOCULAR self.eye = None #: The calibrated horizontal eye position on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.gaze_x = None #: The calibrated vertical eye position on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.gaze_y = None #: The calculated point of gaze in depth. Generally this can only be #: provided if binocular reporting is being performed. self.gaze_z = None #: The x eye position in an eye trackers 3D coordinate space. #: Generally this field is only available by systems that are also #: calculating eye data using a 3D model of eye position relative to #: the eye camera(s) for example. self.eye_cam_x = None #: The y eye position in an eye trackers 3D coordinate space. #: Generally this field is only available by systems that are also #: calculating eye data using a 3D model of eye position relative to #: the eye camera(s) for example. self.eye_cam_y = None #: The z eye position in an eye trackers 3D coordinate space. #: Generally this field is only available by systems that are also #: calculating eye data using a 3D model of eye position relative to #: the eye camera(s) for example. self.eye_cam_z = None #: The horizontal angle of eye the relative to the head. self.angle_x = None #: The vertical angle of eye the relative to the head. self.angle_y = None #: The non-calibrated x position of the calculated eye 'center' #: on the camera sensor image, factoring in any corneal reflection #: or other low level adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.raw_x = None #: The non-calibrated y position of the calculated eye 'center' #: on the camera sensor image, factoring in any corneal reflection #: or other low level adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.raw_y = None #: A measure related to pupil size or diameter. The attribute #: pupil_measure1_type defines what type the measure represents. self.pupil_measure1 = None #: The type of pupil size or shape information provided in the pupil_measure1 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.pupil_measure1_type = None #: A second measure related to pupil size or diameter. The attribute #: pupil_measure2_type defines what type the measure represents. self.pupil_measure2 = None #: The type of pupil size or shape information provided in the pupil_measure2 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.pupil_measure2_type = None #: Horizontal pixels per visual degree for this eye position #: as reported by the eye tracker. self.ppd_x = None #: Vertical pixels per visual degree for this eye position #: as reported by the eye tracker. self.ppd_y = None #: Horizontal velocity of the eye at the time of the sample; #: as reported by the eye tracker. self.velocity_x = None #: Vertical velocity of the eye at the time of the sample; #: as reported by the eye tracker. self.velocity_y = None #: 2D Velocity of the eye at the time of the sample; #: as reported by the eye tracker. self.velocity_xy = None #: An available status byte for the eye tracker sample. #: Meaning is completely tracker dependent. self.status = None DeviceEvent.__init__(self, *args, **kwargs) class EyeSampleEvent(EyeTrackerEvent): """A EyeSampleEvent reports minimal data regarding an eye sample, containing a subset of the full MonocularEyeSampleEvent fields. Support for this event type is optional. If requested but not supported, no events of this type will be returned. Both EyeSampleEvents and MonocularEyeSampleEvent / BinocularEyeSampleEvents can be requested from the eye tracker, although doing so is redundant and therefore not suggested. ;) If binocular eye data is available from the device sample, left and right eye data will be combined to provide a single x,y position and pupil size. How the binocular eye data is combined into a EyeSampleEvent is determined by each eye tracker interface. Please refer to the implementation specific documentation for the eye tracker of interest for more details. Event Type ID: EventConstants.EYE_SAMPLE Event Type String: 'EYE_SAMPLE' """ _newDataTypes = [ ('x', np.float32), # The horizontal eye position. Unit type used is # implementation specific. ('y', np.float32), # The vertical eye position. Unit type used is # implementation specific. ('pupil', np.float32), # Pupil size or diameter. # Unit type used is implementation specific. ('frame', np.uint64), # Device frame number for the sample. ('status', np.uint32) # Status of the eye tracker sample. ] EVENT_TYPE_ID = EventConstants.EYE_SAMPLE EVENT_TYPE_STRING = 'EYE_SAMPLE' IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The horizontal eye position. self.x = None #: The vertical eye position. self.y = None #: Pupil size or diameter. self.pupil = None #: Device frame number for the sample. self.frame = None #: An available status byte for the eye tracker sample. #: Meaning is completely tracker dependent. self.status = None DeviceEvent.__init__(self, *args, **kwargs) class BinocularEyeSampleEvent(EyeTrackerEvent): """The BinocularEyeSampleEvent event represents the eye position and eye attribute data collected from one frame or reading of an eye tracker device that is recording both eyes of a participant. Event Type ID: EventConstants.BINOCULAR_EYE_SAMPLE Event Type String: 'BINOCULAR_EYE_SAMPLE' """ _newDataTypes = [ ('left_gaze_x', 'f4'), ('left_gaze_y', 'f4'), ('left_gaze_z', 'f4'), ('left_eye_cam_x', 'f4'), ('left_eye_cam_y', 'f4'), ('left_eye_cam_z', 'f4'), ('left_angle_x', 'f4'), ('left_angle_y', 'f4'), ('left_raw_x', 'f4'), ('left_raw_y', 'f4'), ('left_pupil_measure1', 'f4'), ('left_pupil_measure1_type', 'u1'), ('left_pupil_measure2', 'f4'), ('left_pupil_measure2_type', 'u1'), ('left_ppd_x', 'f4'), ('left_ppd_y', 'f4'), ('left_velocity_x', 'f4'), ('left_velocity_y', 'f4'), ('left_velocity_xy', 'f4'), ('right_gaze_x', 'f4'), ('right_gaze_y', 'f4'), ('right_gaze_z', 'f4'), ('right_eye_cam_x', 'f4'), ('right_eye_cam_y', 'f4'), ('right_eye_cam_z', 'f4'), ('right_angle_x', 'f4'), ('right_angle_y', 'f4'), ('right_raw_x', 'f4'), ('right_raw_y', 'f4'), ('right_pupil_measure1', 'f4'), ('right_pupil_measure1_type', 'u1'), ('right_pupil_measure2', 'f4'), ('right_pupil_measure2_type', 'u1'), ('right_ppd_x', 'f4'), ('right_ppd_y', 'f4'), ('right_velocity_x', 'f4'), ('right_velocity_y', 'f4'), ('right_velocity_xy', 'f4'), ('status', 'u1') ] EVENT_TYPE_ID = EventConstants.BINOCULAR_EYE_SAMPLE EVENT_TYPE_STRING = 'BINOCULAR_EYE_SAMPLE' IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The calibrated horizontal left eye position on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.left_gaze_x = None #: The calibrated vertical left eye position on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.left_gaze_y = None #: The calculated point of gaze in depth. Generally this can only be #: provided if binocular reporting is being performed. self.left_gaze_z = None #: The x left eye position in an eye trackers 3D coordinate space. #: Generally this field is only available by systems that are also #: calculating eye data using a 3D model of eye position relative to #: the eye camera(s) for example. self.left_eye_cam_x = None #: The y left eye position in an eye trackers 3D coordinate space. #: Generally this field is only available by systems that are also #: calculating eye data using a 3D model of eye position relative to #: the eye camera(s) for example. self.left_eye_cam_y = None #: The z left eye position in an eye trackers 3D coordinate space. #: Generally this field is only available by systems that are also #: calculating eye data using a 3D model of eye position relative to #: the eye camera(s) for example. self.left_eye_cam_z = None #: The horizontal angle of left eye the relative to the head. self.left_angle_x = None #: The vertical angle of left eye the relative to the head. self.left_angle_y = None #: The non-calibrated x position of the calculated left eye 'center' #: on the camera sensor image, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.left_raw_x = None #: The non-calibrated y position of the calculated left eye 'center' #: on the camera sensor image, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.left_raw_y = None #: A measure related to left pupil size or diameter. The attribute #: pupil_measure1_type defines what type the measure represents. self.left_pupil_measure1 = None #: The type of left pupil size or shape information provided in the pupil_measure1 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.left_pupil_measure1_type = None #: A second measure related to left pupil size or diameter. The attribute #: pupil_measure2_type defines what type the measure represents. self.left_pupil_measure2 = None #: The type of left pupil size or shape information provided in the pupil_measure2 #: attribute. Several possible pupil_measure types available: #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.left_pupil_measure2_type = None #: Horizontal pixels per visual degree for this left eye position #: as reported by the eye tracker. self.left_ppd_x = None #: Vertical pixels per visual degree for this left eye position #: as reported by the eye tracker. self.left_ppd_y = None #: Horizontal velocity of the left eye at the time of the sample; #: as reported by the eye tracker. self.left_velocity_x = None #: Vertical velocity of the left eye at the time of the sample; #: as reported by the eye tracker. self.left_velocity_y = None #: 2D Velocity of the left eye at the time of the sample; #: as reported by the eye tracker. self.left_velocity_xy = None #: The calibrated horizontal right eye position on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.right_gaze_x = None #: The calibrated vertical right eye position on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.right_gaze_y = None #: The calculated point of gaze in depth. Generally this can only be #: provided if binocular reporting is being performed. self.right_gaze_z = None #: The x right eye position in an eye trackers 3D coordinate space. #: Generally this field is only available by systems that are also #: calculating eye data using a 3D model of eye position relative to #: the eye camera(s) for example. self.right_eye_cam_x = None #: The y right eye position in an eye trackers 3D coordinate space. #: Generally this field is only available by systems that are also #: calculating eye data using a 3D model of eye position relative to #: the eye camera(s) for example. self.right_eye_cam_y = None #: The z right eye position in an eye trackers 3D coordinate space. #: Generally this field is only available by systems that are also #: calculating eye data using a 3D model of eye position relative to #: the eye camera(s) for example. self.right_eye_cam_z = None #: The horizontal angle of right eye the relative to the head. self.right_angle_x = None #: The vertical angle of right eye the relative to the head. self.right_angle_y = None #: The non-calibrated x position of the calculated right eye 'center' #: on the camera sensor image, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.right_raw_x = None #: The non-calibrated y position of the calculated right eye 'center' #: on the camera sensor image, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.right_raw_y = None #: A measure related to right pupil size or diameter. The attribute #: pupil_measure1_type defines what type the measure represents. self.right_pupil_measure1 = None #: The type of right pupil size or shape information provided in the pupil_measure1 #: attribute. Several possible pupil_measure types available: #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.right_pupil_measure1_type = None #: A second measure related to right pupil size or diameter. The attribute #: pupil_measure2_type defines what type the measure represents. self.right_pupil_measure2 = None #: The type of right pupil size or shape information provided in the pupil_measure2 #: attribute. Several possible pupil_measure types available: #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.right_pupil_measure2_type = None #: Horizontal pixels per visual degree for this right eye position #: as reported by the eye tracker. self.right_ppd_x = None #: Vertical pixels per visual degree for this right eye position #: as reported by the eye tracker. self.right_ppd_y = None #: Horizontal velocity of the right eye at the time of the sample; #: as reported by the eye tracker. self.right_velocity_x = None #: Vertical velocity of the right eye at the time of the sample; #: as reported by the eye tracker. self.right_velocity_y = None #: 2D Velocity of the right eye at the time of the sample; #: as reported by the eye tracker. self.right_velocity_xy = None #: An available status byte for the eye tracker sample. #: Meaning is completely tracker dependent. self.status = None DeviceEvent.__init__(self, *args, **kwargs) class GazepointSampleEvent(EyeTrackerEvent): """GazePointSampleEvent contains the data collected from a GazePoint sample, which can contain both gazepoint eye and biometric data, depending on the hardware being used. Fields related to eye data are a subset of the standard BinocularEyeSampleEvent. Event Type ID: EventConstants.GAZEPOINT_SAMPLE Event Type String: 'GAZEPOINT_SAMPLE' """ _newDataTypes = [ ('left_gaze_x', 'f4'), ('left_gaze_y', 'f4'), ('left_raw_x', 'f4'), ('left_raw_y', 'f4'), ('left_pupil_measure1', 'f4'), ('left_pupil_measure1_type', 'u1'), ('left_pupil_measure2', 'f4'), ('left_pupil_measure2_type', 'u1'), ('right_gaze_x', 'f4'), ('right_gaze_y', 'f4'), ('right_raw_x', 'f4'), ('right_raw_y', 'f4'), ('right_pupil_measure1', 'f4'), ('right_pupil_measure1_type', 'u1'), ('right_pupil_measure2', 'f4'), ('right_pupil_measure2_type', 'u1'), ('dial', 'f4'), ('dialv', 'u1'), ('gsr', 'f4'), ('gsrv', 'u1'), ('hr', 'f4'), ('hrv', 'u1'), ('hrp', 'f4'), ('status', 'u1') ] EVENT_TYPE_ID = EventConstants.GAZEPOINT_SAMPLE EVENT_TYPE_STRING = 'GAZEPOINT_SAMPLE' IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The calibrated horizontal left eye position on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.left_gaze_x = None #: The calibrated vertical left eye position on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.left_gaze_y = None #: The non-calibrated x position of the calculated left eye 'center' #: on the camera sensor image, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.left_raw_x = None #: The non-calibrated y position of the calculated left eye 'center' #: on the camera sensor image, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.left_raw_y = None #: A measure related to left pupil size or diameter. The attribute #: pupil_measure1_type defines what type the measure represents. self.left_pupil_measure1 = None #: * EyeTrackerConstants.PUPIL_DIAMETER self.left_pupil_measure1_type = None #: A second measure related to left pupil size or diameter. The attribute #: pupil_measure2_type defines what type the measure represents. self.left_pupil_measure2 = None #: The type of left pupil size or shape information provided in the pupil_measure2 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_DIAMETER_MM self.left_pupil_measure2_type = None #: The calibrated horizontal right eye position on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.right_gaze_x = None #: The calibrated vertical right eye position on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.right_gaze_y = None #: The non-calibrated x position of the calculated right eye 'center' #: on the camera sensor image, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.right_raw_x = None #: The non-calibrated y position of the calculated right eye 'center' #: on the camera sensor image, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.right_raw_y = None #: A measure related to right pupil size or diameter. The attribute #: pupil_measure1_type defines what type the measure represents. self.right_pupil_measure1 = None #: * EyeTrackerConstants.PUPIL_DIAMETER self.right_pupil_measure1_type = None #: A second measure related to right pupil size or diameter. The attribute #: pupil_measure2_type defines what type the measure represents. self.right_pupil_measure2 = None #: * EyeTrackerConstants.PUPIL_DIAMETER_MM self.right_pupil_measure2_type = None #: Dial value from Gazepoint biometrics kit, 0-1 self.dial = None self.dialv = None #: GSR resistance value from Gazepoint biometrics kit, ohms self.gsr = None self.gsrv = None #: Heart rate value from Gazepoint biometrics kit, bpm self.hr = None self.hrv = None self.hrp = None #: An available status byte for the eye tracker sample. #: Meaning is completely tracker dependent. self.status = None DeviceEvent.__init__(self, *args, **kwargs) # ################### Fixation Event Types ########################## # class FixationStartEvent(EyeTrackerEvent): """A FixationStartEvent is generated when the beginning of an eye fixation ( in very general terms, a period of relatively stable eye position ) is detected by the eye trackers sample parsing algorithms. Event Type ID: EventConstants.FIXATION_START Event Type String: 'FIXATION_START' """ _newDataTypes = [ # The eye type that the fixation is from. Valid values are: ('eye', 'u1'), # EyeTrackerConstants.LEFT_EYE # EyeTrackerConstants.RIGHT_EYE # EyeTrackerConstants.BINOCULAR_AVERAGED # EyeTrackerConstants.SIMULATED_MONOCULAR # The calibrated horizontal eye position on the calibration plane. ('gaze_x', 'f4'), # This value is specified in Display Coordinate Type Units. # The calibrated vertical eye position on the calibration plane. ('gaze_y', 'f4'), # This value is specified in Display Coordinate Type Units. # The calculated point of gaze in depth. Generally This can only be ('gaze_z', 'f4'), # provided if binocular reporting is being performed. # The horizontal angle of eye the relative to the head. ('angle_x', 'f4'), # The vertical angle of eye the relative to the head. ('angle_y', 'f4'), # The non-calibrated x position of the calculated eye 'center' ('raw_x', 'f4'), # on the camera sensor image, # factoring in any corneal reflection adjustments. # This is typically reported in some arbitrary unit space that # often has sub-pixel resolution due to image processing techniques # being applied. # The non-calibrated y position of the calculated eye 'center' ('raw_y', 'f4'), # on the camera sensor image, # factoring in any corneal reflection adjustments. # This is typically reported in some arbitrary unit space that # often has sub-pixel resolution due to image processing techniques # being applied. # A measure related to pupil size or diameter. Attribute ('pupil_measure1', 'f4'), # pupil_measure1_type defines what type the measure represents. # Several possible pupil_measure types available: ('pupil_measure1_type', 'u1'), # EyeTrackerConstants.PUPIL_AREA # EyeTrackerConstants.PUPIL_DIAMETER # EyeTrackerConstants.PUPIL_WIDTH # EyeTrackerConstants.PUPIL_HEIGHT # EyeTrackerConstants.PUPIL_MAJOR_AXIS # EyeTrackerConstants.PUPIL_MINOR_AXIS # A measure related to pupil size or diameter. Attribute ('pupil_measure2', 'f4'), # pupil_measure2_type defines what type the measure represents. # Several possible pupil_measure types are available: ('pupil_measure2_type', 'u1'), # EyeTrackerConstants.PUPIL_AREA # EyeTrackerConstants.PUPIL_DIAMETER # EyeTrackerConstants.PUPIL_WIDTH # EyeTrackerConstants.PUPIL_HEIGHT # EyeTrackerConstants.PUPIL_MAJOR_AXIS # EyeTrackerConstants.PUPIL_MINOR_AXIS ('ppd_x', 'f4'), # Horizontal pixels per visual degree for this eye position # as reported by the eye tracker. ('ppd_y', 'f4'), # Vertical pixels per visual degree for this eye position # as reported by the eye tracker. # Horizontal velocity of the eye at the time of the fixation start # sample; ('velocity_x', 'f4'), # as reported by the eye tracker. # Vertical velocity of the eye at the time of the fixation start # sample; ('velocity_y', 'f4'), # as reported by the eye tracker. # 2D Velocity of the eye at the time of the fixation start sample; ('velocity_xy', 'f4'), # as reported by the eye tracker. # An available status word for the eye tracker fixation start event. ('status', 'u1') # Meaning is completely tracker dependent. ] EVENT_TYPE_ID = EventConstants.FIXATION_START EVENT_TYPE_STRING = EventConstants.getName(EVENT_TYPE_ID) IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The eye type that the event is from. Valid values are: #: EyeTrackerConstants.LEFT_EYE #: EyeTrackerConstants.RIGHT_EYE #: EyeTrackerConstants.MONOCULAR #: EyeTrackerConstants.SIMULATED_MONOCULAR self.eye = None #: The calibrated horizontal eye position at the start of the eye event #: on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.gaze_x = None #: The calibrated vertical eye position at the start of the eye event on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.gaze_y = None #: The calculated point of gaze in depth at the start of the eye event. Generally this can only be #: provided if binocular reporting is being performed. self.gaze_z = None #: The horizontal angle of eye the relative to the head at the start of the eye event. self.angle_x = None #: The vertical angle of eye the relative to the head at the start of the eye event. self.angle_y = None #: The non-calibrated x position of the calculated eye 'center' #: on the camera sensor image at the start of the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.raw_x = None #: The non-calibrated y position of the calculated eye 'center' #: on the camera sensor image at the start of the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.raw_y = None #: A measure related to pupil size or diameter at the start of the eye event. #: The attribute pupil_measure1_type defines what type the measure represents. self.pupil_measure1 = None #: The type of pupil size or shape information provided in the pupil_measure1 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.pupil_measure1_type = None #: A second measure related to pupil size or diameter at the start of the eye event. #: The attribute pupil_measure2_type defines what type the measure represents. self.pupil_measure2 = None #: The type of pupil size or shape information provided in the pupil_measure2 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.pupil_measure2_type = None #: Horizontal pixels per visual degree for this eye position at the start of the eye event #: as reported by the eye tracker. self.ppd_x = None #: Vertical pixels per visual degree for this eye position at the start of the eye event #: as reported by the eye tracker. self.ppd_y = None #: Horizontal velocity of the eye at the start of the eye event; #: as reported by the eye tracker. self.velocity_x = None #: Vertical velocity of the eye at the start of the eye event; #: as reported by the eye tracker. self.velocity_y = None #: 2D Velocity of the eye at the start of the eye event; #: as reported by the eye tracker. self.velocity_xy = None #: An available status byte for the eye tracker event. #: Meaning or use is completely tracker dependent. self.status = None DeviceEvent.__init__(self, *args, **kwargs) class FixationEndEvent(EyeTrackerEvent): """A FixationEndEvent is generated when the end of an eye fixation ( in very general terms, a period of relatively stable eye position ) is detected by the eye trackers sample parsing algorithms. Event Type ID: EventConstants.FIXATION_END Event Type String: 'FIXATION_END' """ _newDataTypes = [ ('eye', 'u1'), ('duration', 'f4'), ('start_gaze_x', 'f4'), ('start_gaze_y', 'f4'), ('start_gaze_z', 'f4'), ('start_angle_x', 'f4'), ('start_angle_y', 'f4'), ('start_raw_x', 'f4'), ('start_raw_y', 'f4'), ('start_pupil_measure1', 'f4'), ('start_pupil_measure1_type', 'u1'), ('start_pupil_measure2', 'f4'), ('start_pupil_measure2_type', 'u1'), ('start_ppd_x', 'f4'), ('start_ppd_y', 'f4'), ('start_velocity_x', 'f4'), ('start_velocity_y', 'f4'), ('start_velocity_xy', 'f4'), ('end_gaze_x', 'f4'), ('end_gaze_y', 'f4'), ('end_gaze_z', 'f4'), ('end_angle_x', 'f4'), ('end_angle_y', 'f4'), ('end_raw_x', 'f4'), ('end_raw_y', 'f4'), ('end_pupil_measure1', 'f4'), ('end_pupil_measure1_type', 'u1'), ('end_pupil_measure2', 'f4'), ('end_pupil_measure2_type', 'u1'), ('end_ppd_x', 'f4'), ('end_ppd_y', 'f4'), ('end_velocity_x', 'f4'), ('end_velocity_y', 'f4'), ('end_velocity_xy', 'f4'), ('average_gaze_x', 'f4'), ('average_gaze_y', 'f4'), ('average_gaze_z', 'f4'), ('average_angle_x', 'f4'), ('average_angle_y', 'f4'), ('average_raw_x', 'f4'), ('average_raw_y', 'f4'), ('average_pupil_measure1', 'f4'), ('average_pupil_measure1_type', 'u1'), ('average_pupil_measure2', 'f4'), ('average_pupil_measure2_type', 'u1'), ('average_ppd_x', 'f4'), ('average_ppd_y', 'f4'), ('average_velocity_x', 'f4'), ('average_velocity_y', 'f4'), ('average_velocity_xy', 'f4'), ('peak_velocity_x', 'f4'), ('peak_velocity_y', 'f4'), ('peak_velocity_xy', 'f4'), ('status', 'u1') ] EVENT_TYPE_ID = EventConstants.FIXATION_END EVENT_TYPE_STRING = EventConstants.getName(EVENT_TYPE_ID) IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The eye type that the event is from. Valid values are: #: The eye type that the sample is from. Valid values are: #: #: EventConstants.LEFT_EYE #: EventConstants.RIGHT_EYE #: EventConstants.SIMULATED_MONOCULAR #: EventConstants.MONOCULAR self.eye = None #: The calculated duration of the Eye event in sec.msec-usec #: format. self.duration = None #: The calibrated horizontal eye position at the start of the eye event #: on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.start_gaze_x = None #: The calibrated vertical eye position at the start of the eye event on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.start_gaze_y = None #: The calculated point of gaze in depth at the start of the eye event. Generally this can only be #: provided if binocular reporting is being performed. self.start_gaze_z = None #: The horizontal angle of eye the relative to the head at the start of the eye event. self.start_angle_x = None #: The vertical angle of eye the relative to the head at the start of the eye event. self.start_angle_y = None #: The non-calibrated x position of the calculated eye 'center' #: on the camera sensor image at the start of the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.start_raw_x = None #: The non-calibrated y position of the calculated eye 'center' #: on the camera sensor image at the start of the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.start_raw_y = None #: A measure related to pupil size or diameter at the start of the eye event. #: The attribute pupil_measure1_type defines what type the measure represents. self.start_pupil_measure1 = None #: The type of pupil size or shape information provided in the pupil_measure1 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.start_pupil_measure1_type = None #: A second measure related to pupil size or diameter at the start of the eye event. #: The attribute pupil_measure2_type defines what type the measure represents. self.start_pupil_measure2 = None #: The type of pupil size or shape information provided in the pupil_measure2 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.start_pupil_measure2_type = None #: Horizontal pixels per visual degree for this eye position at the start of the eye event #: as reported by the eye tracker. self.start_ppd_x = None #: Vertical pixels per visual degree for this eye position at the start of the eye event #: as reported by the eye tracker. self.start_ppd_y = None #: Horizontal velocity of the eye at the start of the eye event; #: as reported by the eye tracker. self.start_velocity_x = None #: Vertical velocity of the eye at the start of the eye event; #: as reported by the eye tracker. self.start_velocity_y = None #: 2D Velocity of the eye at the start of the eye event; #: as reported by the eye tracker. self.start_velocity_xy = None #: The calibrated horizontal eye position at the end of the eye event #: on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.end_gaze_x = None #: The calibrated vertical eye position at the end of the eye event on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.end_gaze_y = None #: The calculated point of gaze in depth at the end of the eye event. Generally this can only be #: provided if binocular reporting is being performed. self.end_gaze_z = None #: The horizontal angle of eye the relative to the head at the end of the eye event. self.end_angle_x = None #: The vertical angle of eye the relative to the head at the end of the eye event. self.end_angle_y = None #: The non-calibrated x position of the calculated eye 'center' #: on the camera sensor image at the end of the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.end_raw_x = None #: The non-calibrated y position of the calculated eye 'center' #: on the camera sensor image at the end of the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.end_raw_y = None #: A measure related to pupil size or diameter at the end of the eye event. #: The attribute pupil_measure1_type defines what type the measure represents. self.end_pupil_measure1 = None #: The type of pupil size or shape information provided in the pupil_measure1 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.end_pupil_measure1_type = None #: A second measure related to pupil size or diameter at the end of the eye event. #: The attribute pupil_measure2_type defines what type the measure represents. self.end_pupil_measure2 = None #: The type of pupil size or shape information provided in the pupil_measure2 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.end_pupil_measure2_type = None #: Horizontal pixels per visual degree for this eye position at the end of the eye event #: as reported by the eye tracker. self.end_ppd_x = None #: Vertical pixels per visual degree for this eye position at the end of the eye event #: as reported by the eye tracker. self.end_ppd_y = None #: Horizontal velocity of the eye at the end of the eye event; #: as reported by the eye tracker. self.end_velocity_x = None #: Vertical velocity of the eye at the end of the eye event; #: as reported by the eye tracker. self.end_velocity_y = None #: 2D Velocity of the eye at the end of the eye event; #: as reported by the eye tracker. self.end_velocity_xy = None #: Average calibrated horizontal eye position during the eye event #: on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.average_gaze_x = None #: Average calibrated vertical eye position during the eye event on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.average_gaze_y = None #: Average calculated point of gaze in depth during the eye event. Generally this can only be #: provided if binocular reporting is being performed. self.average_gaze_z = None #: Average horizontal angle of eye the relative to the head during the eye event. self.average_angle_x = None #: Average vertical angle of eye the relative to the head during the eye event. self.average_angle_y = None #: Average non-calibrated x position of the calculated eye 'center' #: on the camera sensor image during the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.average_raw_x = None #: The average non-calibrated y position of the calculated eye 'center' #: on the camera sensor image during the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.average_raw_y = None #: A measure related to average pupil size or diameter during the eye event. #: The attribute pupil_measure1_type defines what type the measure represents. self.average_pupil_measure1 = None #: The type of pupil size or shape information provided in the pupil_measure1 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.average_pupil_measure1_type = None #: A second measure related to average pupil size or diameter during the eye event. #: The attribute pupil_measure2_type defines what type the measure represents. self.average_pupil_measure2 = None #: The type of pupil size or shape information provided in the pupil_measure2 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.average_pupil_measure2_type = None #: Average Horizontal pixels per visual degree for this eye position during the eye event #: as reported by the eye tracker. self.average_ppd_x = None #: Average Vertical pixels per visual degree for this eye position during the eye event #: as reported by the eye tracker. self.average_ppd_y = None #: Average Horizontal velocity of the eye during the eye event; #: as reported by the eye tracker. self.average_velocity_x = None #: Average Vertical velocity of the eye during the eye event; #: as reported by the eye tracker. self.average_velocity_y = None #: Average 2D Velocity of the eye at the during the eye event; #: as reported by the eye tracker. self.average_velocity_xy = None #: Peak Horizontal velocity of the eye during the eye event; #: as reported by the eye tracker. self.peak_velocity_x = None #: Peak Vertical velocity of the eye during the eye event; #: as reported by the eye tracker. self.peak_velocity_y = None #: Peak 2D Velocity of the eye at the during the eye event; #: as reported by the eye tracker. self.peak_velocity_xy = None #: An available status byte for the eye tracker event. #: Meaning or use is completely tracker dependent. self.status = None DeviceEvent.__init__(self, *args, **kwargs) ################### Saccade Event Types ########################## # class SaccadeStartEvent(FixationStartEvent): EVENT_TYPE_ID = EventConstants.SACCADE_START EVENT_TYPE_STRING = EventConstants.getName(EVENT_TYPE_ID) IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [] def __init__(self, *args, **kwargs): FixationStartEvent.__init__(self, *args, **kwargs) class SaccadeEndEvent(EyeTrackerEvent): _newDataTypes = [ ('eye', 'u1'), ('duration', 'f4'), ('amplitude_x', 'f4'), ('amplitude_y', 'f4'), ('angle', 'f4'), ('start_gaze_x', 'f4'), ('start_gaze_y', 'f4'), ('start_gaze_z', 'f4'), ('start_angle_x', 'f4'), ('start_angle_y', 'f4'), ('start_raw_x', 'f4'), ('start_raw_y', 'f4'), ('start_pupil_measure1', 'f4'), ('start_pupil_measure1_type', 'u1'), ('start_pupil_measure2', 'f4'), ('start_pupil_measure2_type', 'f4'), ('start_ppd_x', 'f4'), ('start_ppd_y', 'f4'), ('start_velocity_x', 'f4'), ('start_velocity_y', 'f4'), ('start_velocity_xy', 'f4'), ('end_gaze_x', 'f4'), ('end_gaze_y', 'f4'), ('end_gaze_z', 'f4'), ('end_angle_x', 'f4'), ('end_angle_y', 'f4'), ('end_raw_x', 'f4'), ('end_raw_y', 'f4'), ('end_pupil_measure1', 'f4'), ('end_pupil_measure1_type', 'u1'), ('end_pupil_measure2', 'f4'), ('end_pupil_measure2_type', 'u1'), ('end_ppd_x', 'f4'), ('end_ppd_y', 'f4'), ('end_velocity_x', 'f4'), ('end_velocity_y', 'f4'), ('end_velocity_xy', 'f4'), ('average_velocity_x', 'f4'), ('average_velocity_y', 'f4'), ('average_velocity_xy', 'f4'), ('peak_velocity_x', 'f4'), ('peak_velocity_y', 'f4'), ('peak_velocity_xy', 'f4'), ('status', 'u1') ] EVENT_TYPE_ID = EventConstants.SACCADE_END EVENT_TYPE_STRING = EventConstants.getName(EVENT_TYPE_ID) IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The eye type that the event is from. Valid values are: #: EyeTrackerConstants.LEFT_EYE #: EyeTrackerConstants.RIGHT_EYE #: EyeTrackerConstants.MONOCULAR #: EyeTrackerConstants.SIMULATED_MONOCULAR self.eye = None #: The calculated duration of the Eye event in sec.msec-usec #: format. self.duration = None #: The amplitude of the Saccade in the horizonatal direction. #: Usually specified in visual degrees. self.amplitude_x #: The amplitude of the Saccade in the vertical direction. #: Usually specified in visual degrees. self.amplitude_y #: The angle of the Saccade based on the start and end gaze positions. #: Usually specified in degrees. self.angle #: The calibrated horizontal eye position at the start of the eye event #: on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.start_gaze_x = None #: The calibrated vertical eye position at the start of the eye event on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.start_gaze_y = None #: The calculated point of gaze in depth at the start of the eye event. Generally this can only be #: provided if binocular reporting is being performed. self.start_gaze_z = None #: The horizontal angle of eye the relative to the head at the start of the eye event. self.start_angle_x = None #: The vertical angle of eye the relative to the head at the start of the eye event. self.start_angle_y = None #: The non-calibrated x position of the calculated eye 'center' #: on the camera sensor image at the start of the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.start_raw_x = None #: The non-calibrated y position of the calculated eye 'center' #: on the camera sensor image at the start of the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.start_raw_y = None #: A measure related to pupil size or diameter at the start of the eye event. #: The attribute pupil_measure1_type defines what type the measure represents. self.start_pupil_measure1 = None #: The type of pupil size or shape information provided in the pupil_measure1 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.start_pupil_measure1_type = None #: A second measure related to pupil size or diameter at the start of the eye event. #: The attribute pupil_measure2_type defines what type the measure represents. self.start_pupil_measure2 = None #: The type of pupil size or shape information provided in the pupil_measure2 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.start_pupil_measure2_type = None #: Horizontal pixels per visual degree for this eye position at the start of the eye event #: as reported by the eye tracker. self.start_ppd_x = None #: Vertical pixels per visual degree for this eye position at the start of the eye event #: as reported by the eye tracker. self.start_ppd_y = None #: Horizontal velocity of the eye at the start of the eye event; #: as reported by the eye tracker. self.start_velocity_x = None #: Vertical velocity of the eye at the start of the eye event; #: as reported by the eye tracker. self.start_velocity_y = None #: The calibrated horizontal eye position at the end of the eye event #: on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.end_gaze_x = None #: The calibrated vertical eye position at the end of the eye event on the calibration plane. #: This value is specified in Display Coordinate Type Units. self.end_gaze_y = None #: The calculated point of gaze in depth at the end of the eye event. Generally this can only be #: provided if binocular reporting is being performed. self.end_gaze_z = None #: The horizontal angle of eye the relative to the head at the end of the eye event. self.end_angle_x = None #: The vertical angle of eye the relative to the head at the end of the eye event. self.end_angle_y = None #: The non-calibrated x position of the calculated eye 'center' #: on the camera sensor image at the end of the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.end_raw_x = None #: The non-calibrated y position of the calculated eye 'center' #: on the camera sensor image at the end of the eye event, #: factoring in any corneal reflection adjustments. #: This is typically reported in some arbitrary unit space that #: often has sub-pixel resolution due to image processing techniques #: being applied. self.end_raw_y = None #: A measure related to pupil size or diameter at the end of the eye event. #: The attribute pupil_measure1_type defines what type the measure represents. self.end_pupil_measure1 = None #: The type of pupil size or shape information provided in the pupil_measure1 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.end_pupil_measure1_type = None #: A second measure related to pupil size or diameter at the end of the eye event. #: The attribute pupil_measure2_type defines what type the measure represents. self.end_pupil_measure2 = None #: The type of pupil size or shape information provided in the pupil_measure2 #: attribute. Several possible pupil_measure types available: #: #: * EyeTrackerConstants.PUPIL_AREA #: * EyeTrackerConstants.PUPIL_DIAMETER #: * EyeTrackerConstants.PUPIL_AREA_MM #: * EyeTrackerConstants.PUPIL_DIAMETER_MM #: * EyeTrackerConstants.PUPIL_WIDTH #: * EyeTrackerConstants.PUPIL_HEIGHT #: * EyeTrackerConstants.PUPIL_WIDTH_MM #: * EyeTrackerConstants.PUPIL_HEIGHT_MM #: * EyeTrackerConstants.PUPIL_MAJOR_AXIS #: * EyeTrackerConstants.PUPIL_MINOR_AXIS self.end_pupil_measure2_type = None #: Horizontal pixels per visual degree for this eye position at the end of the eye event #: as reported by the eye tracker. self.end_ppd_x = None #: Vertical pixels per visual degree for this eye position at the end of the eye event #: as reported by the eye tracker. self.end_ppd_y = None #: Horizontal velocity of the eye at the end of the eye event; #: as reported by the eye tracker. self.end_velocity_x = None #: Vertical velocity of the eye at the end of the eye event; #: as reported by the eye tracker. self.end_velocity_y = None #: 2D Velocity of the eye at the end of the eye event; #: as reported by the eye tracker. self.end_velocity_xy = None #: Average Horizontal velocity of the eye during the eye event; #: as reported by the eye tracker. self.average_velocity_x = None #: Average Vertical velocity of the eye during the eye event; #: as reported by the eye tracker. self.average_velocity_y = None #: Average 2D Velocity of the eye at the during the eye event; #: as reported by the eye tracker. self.average_velocity_xy = None #: Peak Horizontal velocity of the eye during the eye event; #: as reported by the eye tracker. self.peak_velocity_x = None #: Peak Vertical velocity of the eye during the eye event; #: as reported by the eye tracker. self.peak_velocity_y = None #: Peak 2D Velocity of the eye at the during the eye event; #: as reported by the eye tracker. self.peak_velocity_xy = None #: An available status byte for the eye tracker event. #: Meaning or use is completely tracker dependent. self.status = None DeviceEvent.__init__(self, *args, **kwargs) ################### Blink Event Types ########################## # class BlinkStartEvent(EyeTrackerEvent): _newDataTypes = [ # The eye type that the fixation is from. Valid values are: ('eye', 'u1'), # EyeTrackerConstants.LEFT_EYE # EyeTrackerConstants.RIGHT_EYE # EyeTrackerConstants.BINOCULAR_AVERAGED # EyeTrackerConstants.SIMULATED_MONOCULAR # An available status byte for the eye tracker blink start event. ('status', 'u1') # Meaning is completely tracker dependent. ] __slots__ = [e[0] for e in _newDataTypes] EVENT_TYPE_ID = EventConstants.BLINK_START EVENT_TYPE_STRING = EventConstants.getName(EVENT_TYPE_ID) IOHUB_DATA_TABLE = EVENT_TYPE_STRING def __init__(self, *args, **kwargs): #: The eye type that the event is from. Valid values are: #: EyeTrackerConstants.LEFT_EYE #: EyeTrackerConstants.RIGHT_EYE #: EyeTrackerConstants.MONOCULAR #: EyeTrackerConstants.SIMULATED_MONOCULAR self.eye = None #: An available status byte for the eye tracker event. #: Meaning or use is completely tracker dependent. self.status = None DeviceEvent.__init__(self, *args, **kwargs) class BlinkEndEvent(EyeTrackerEvent): _newDataTypes = [ # The eye type that the fixation is from. Valid values are: ('eye', 'u1'), # EyeTrackerConstants.LEFT_EYE # EyeTrackerConstants.RIGHT_EYE # EyeTrackerConstants.BINOCULAR_AVERAGED # EyeTrackerConstants.SIMULATED_MONOCULAR ('duration', 'f4'), # The duration of the blink event. # An available status byte for the eye tracker blink start event. ('status', 'u1') # Meaning is completely tracker dependent. ] EVENT_TYPE_ID = EventConstants.BLINK_END EVENT_TYPE_STRING = EventConstants.getName(EVENT_TYPE_ID) IOHUB_DATA_TABLE = EVENT_TYPE_STRING __slots__ = [e[0] for e in _newDataTypes] def __init__(self, *args, **kwargs): #: The eye type that the event is from. Valid values are: #: EyeTrackerConstants.LEFT_EYE #: EyeTrackerConstants.RIGHT_EYE #: EyeTrackerConstants.MONOCULAR #: EyeTrackerConstants.SIMULATED_MONOCULAR self.eye = None #: The calculated duration of the Eye event in sec.msec-usec #: format. self.duration = None #: An available status byte for the eye tracker event. #: Meaning or use is completely tracker dependent. self.status = None DeviceEvent.__init__(self, *args, **kwargs)
71,885
Python
.py
1,427
41.607568
106
0.64942
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,672
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from .. import Device, ioDeviceError from ...constants import DeviceConstants, EyeTrackerConstants from . import hw from ...errors import print2err class EyeTrackerDevice(Device): """The EyeTrackerDevice class is the main class for the ioHub Common Eye Tracker interface. The Common Eye Tracker Interface--a set of common functions and methods such that the same experiment script and data analyses can be shared, used, and compared regardless of the actual eye tracker used--works by extending the EyeTrackerDevice class to configure device monitoring and data access to individual eye tracker manufacturers and models. Not every EyeTrackerDevice subclass will support all of the umbrella functionality within the Common Eye Tracker Interface, but a core set of critical functions are supported by all eye tracker models to date. Any Common Eye Tracker Interface method not supported by the configured Eye Tracker hardware returns a constant (EyeTrackerConstants.FUNCTIONALITY_NOT_SUPPORTED). Methods in the EyeTrackerDevice class are broken down into several categories: #. Initializing the Eye Tracker / Setting the Device State. #. Defining the Graphics Layer for Calibration / System Setup. #. Starting and Stopping of Data Recording. #. Sending Messages or Codes to Synchronize the ioHub with the Eye Tracker. #. Accessing Eye Tracker Data During Recording. #. Accessing the Eye Tracker native time base. #. Synchronizing the ioHub time base with the Eye Tracker time base .. note:: Only **one** instance of EyeTracker can be created within an experiment. Attempting to create > 1 instance will raise an exception. """ # Used to hold the EyeTracker subclass instance to ensure only one instance of # a given eye tracker type is created. This is a current ioHub limitation, not the limitation of # all eye tracking hardware. _INSTANCE = None #: The multiplier needed to convert a device's native time base to sec.msec-usec times. DEVICE_TIMEBASE_TO_SEC = 1.0 # Used by pyEyeTrackerDevice implementations to store relationships between an eye # trackers command names supported for EyeTrackerDevice sendCommand method and # a private python function to call for that command. This allows an implementation # of the interface to expose functions that are not in the core EyeTrackerDevice spec # without have to use the EXT extension class. _COMMAND_TO_FUNCTION = {} DEVICE_TYPE_ID = DeviceConstants.EYETRACKER DEVICE_TYPE_STRING = 'EYETRACKER' __slots__ = [ '_latest_sample', '_latest_gaze_position', '_runtime_settings'] def __init__(self, *args, **kwargs): if self.__class__._INSTANCE is not None: raise ioDeviceError( self, 'EyeTracker object has already been created; ' 'only one instance can exist. Delete existing ' 'instance before recreating EyeTracker object.') else: self.__class__._INSTANCE = self Device.__init__(self, *args, **kwargs['dconfig']) # hold last received ioHub eye sample (in ordered array format) from # tracker. self._latest_sample = EyeTrackerConstants.FUNCTIONALITY_NOT_SUPPORTED # holds the last gaze position read from the eye tracker as an x,y tuple. If binocular recording is # being performed, this is an average of the left and right gaze # position x,y fields. self._latest_gaze_position = EyeTrackerConstants.FUNCTIONALITY_NOT_SUPPORTED # stores the eye tracker runtime related configuration settings from # the ioHub .yaml config file self._runtime_settings = kwargs[ 'dconfig'].get('runtime_settings', None) # TODO: Add support for message ID to Message text lookup table in ioDataStore # data table that can be used by ET systems that support sending int codes, # but not text to tracker at runtime for syncing. def trackerTime(self): """trackerTime returns the current time reported by the eye tracker device. The time base is implementation dependent. Args: None Return: float: The eye tracker hardware's reported current time. """ return EyeTrackerConstants.FUNCTIONALITY_NOT_SUPPORTED def trackerSec(self): """ trackerSec takes the time received by the EyeTracker.trackerTime() method and returns the time in sec.usec-msec format. Args: None Return: float: The eye tracker hardware's reported current time in sec.msec-usec format. """ return EyeTrackerConstants.FUNCTIONALITY_NOT_SUPPORTED def setConnectionState(self, enable): """setConnectionState either connects ( setConnectionState(True) ) or disables ( setConnectionState(False) ) active communication between the ioHub and the Eye Tracker. .. note:: A connection to the Eye Tracker is automatically established when the ioHub Process is initialized (based on the device settings in the iohub_config.yaml), so there is no need to explicitly call this method in the experiment script. .. note:: Connecting an Eye Tracker to the ioHub does **not** necessarily collect and send eye sample data to the ioHub Process. To start actual data collection, use the Eye Tracker method setRecordingState(bool) or the ioHub Device method (device type independent) enableEventRecording(bool). Args: enable (bool): True = enable the connection, False = disable the connection. Return: bool: indicates the current connection state to the eye tracking hardware. """ return EyeTrackerConstants.FUNCTIONALITY_NOT_SUPPORTED def isConnected(self): """isConnected returns whether the ioHub EyeTracker Device is connected to the eye tracker hardware or not. An eye tracker must be connected to the ioHub for any of the Common Eye Tracker Interface functionality to work. Args: None Return: bool: True = the eye tracking hardware is connected. False otherwise. """ return EyeTrackerConstants.FUNCTIONALITY_NOT_SUPPORTED def sendCommand(self, key, value=None): """ The sendCommand method allows arbitrary *commands* or *requests* to be issued to the eye tracker device. Valid values for the arguments of this method are completely implementation-specific, so please refer to the eye tracker implementation page for the eye tracker being used for a list of valid key and value combinations (if any). In general, eye tracker implementations should **not** need to support this method unless there is critical eye tracker functionality that is not accessible using the other methods in the EyeTrackerDevice class. Args: key (str): the command or function name that should be run. value (object): the (optional) value associated with the key. Return: object: the result of the command call int: EyeTrackerConstants.EYETRACKER_OK int: EyeTrackerConstants.EYETRACKER_ERROR int: EyeTrackerConstants.EYETRACKER_INTERFACE_METHOD_NOT_SUPPORTED """ return EyeTrackerConstants.FUNCTIONALITY_NOT_SUPPORTED def sendMessage(self, message_contents, time_offset=None): """The sendMessage method sends a text message to the eye tracker. Messages are generally used to send information you want saved with the native eye data file and are often used to synchronize stimulus changes in the experiment with the eye data stream being saved to the native eye tracker data file (if any). This means that the sendMessage implementation needs to perform in real-time, with a delay of <1 msec from when a message is sent to when it is time stamped by the eye tracker, for it to be accurate in this regard. If this standard can not be met, the expected delay and message timing precision (variability) should be provided in the eye tracker's implementation notes. .. note:: If using the ioDataStore to save the eye tracker data, the use of this method is quite optional, as Experiment Device Message Events will likely be preferred. ioHub Message Events are stored in the ioDataStore, alongside all other device data collected via the ioHub, and not in the native eye tracker data. Args: message_contents (str): If message_contents is a string, check with the implementations documentation if there are any string length limits. Kwargs: time_offset (float): sec.msec_usec time offset that the time stamp of the message should be offset in the eye tracker data file. time_offset can be used so that a message can be sent for a display change **BEFORE** or **AFTER** the actual flip occurred, using the following formula: time_offset = sendMessage_call_time - event_time_message_represent Both times should be based on the iohub.devices.Computer.getTime() time base. If time_offset is not supported by the eye tracker implementation being used, a warning message will be printed to stdout. Return: (int): EyeTrackerConstants.EYETRACKER_OK, EyeTrackerConstants.EYETRACKER_ERROR, or EyeTrackerConstants.EYETRACKER_INTERFACE_METHOD_NOT_SUPPORTED """ return EyeTrackerConstants.FUNCTIONALITY_NOT_SUPPORTED def runSetupProcedure(self, calibration_args={}): """ The runSetupProcedure method starts the eye tracker calibration routine. If calibration_args are provided, they should be used to update calibration related settings prior to starting the calibration. The details of this method are implementation-specific. .. note:: This is a blocking call for the PsychoPy Process and will not return to the experiment script until the necessary steps have been completed so that the eye tracker is ready to start collecting eye sample data when the method returns. Args: None """ return EyeTrackerConstants.EYETRACKER_INTERFACE_METHOD_NOT_SUPPORTED @staticmethod def getCalibrationDict(calib): """ Create a dict describing the given Calibration object, respecting this eyetracker's specific limitations. If not overloaded by a subclass, this will use the same fields and values as MouseGaze. Parameters ---------- calib : psychopy.hardware.eyetracker.EyetrackerCalibration Object to create a dict from Returns ------- dict Dict describing the given Calibration object """ return { 'target_attributes': { # target outer circle 'outer_diameter': calib.target.radius * 2, 'outer_stroke_width': calib.target.outer.lineWidth, 'outer_fill_color': getattr(calib.target.outer._fillColor, calib.colorSpace) if calib.target.outer._fillColor else getattr(calib.target.win._color, calib.colorSpace), 'outer_line_color': getattr(calib.target.outer._borderColor, calib.colorSpace) if calib.target.outer._borderColor else getattr(calib.target.win._color, calib.colorSpace), # target inner circle 'inner_diameter': calib.target.innerRadius * 2, 'inner_stroke_width': calib.target.inner.lineWidth, 'inner_fill_color': getattr(calib.target.inner._borderColor, calib.colorSpace) if calib.target.inner._borderColor else getattr(calib.target.win._color, calib.colorSpace), 'inner_line_color': getattr(calib.target.inner._borderColor, calib.colorSpace) if calib.target.inner._borderColor else getattr(calib.target.win._color, calib.colorSpace), # target animation 'animate':{ 'enable': calib.movementAnimation, 'expansion_ratio': calib.expandScale, 'contract_only': calib.expandScale == 1, }, }, 'type': calib.targetLayout, 'randomize': calib.randomisePos, 'auto_pace': calib.progressMode == "time", 'pacing_speed': calib.targetDelay, 'unit_type': calib.units, 'color_type': calib.colorSpace, 'text_color': calib.textColor if str(calib.textColor).lower() != "auto" else None, 'screen_background_color': getattr(calib.win._color, calib.colorSpace), } def setRecordingState(self, recording): """The setRecordingState method is used to start or stop the recording and transmission of eye data from the eye tracking device to the ioHub Process. Args: recording (bool): if True, the eye tracker will start recordng data.; false = stop recording data. Return: bool: the current recording state of the eye tracking device """ # Implementation Note: Perform your implementation specific logic for # this method here print2err( 'EyeTracker should handle setRecordingState method with recording value of {0} now.'.format(recording)) # Implementation Note: change current_recording_state to be True or # False, based on whether the eye tracker is now recording or not. current_recording_state = EyeTrackerConstants.EYETRACKER_INTERFACE_METHOD_NOT_SUPPORTED return current_recording_state def isRecordingEnabled(self): """The isRecordingEnabled method indicates if the eye tracker device is currently recording data. Args: None Return: bool: True == the device is recording data; False == Recording is not occurring """ # Implementation Note: Perform your implementation specific logic for # this method here print2err('EyeTracker should handle isRecordingEnabled method now.') # Implementation Note: change is_recording to be True or False, based # on whether the eye tracker is recording or not. is_recording = EyeTrackerConstants.EYETRACKER_INTERFACE_METHOD_NOT_SUPPORTED return is_recording def getLastSample(self): """The getLastSample method returns the most recent eye sample received from the Eye Tracker. The Eye Tracker must be in a recording state for a sample event to be returned, otherwise None is returned. Args: None Returns: int: If this method is not supported by the eye tracker interface, EyeTrackerConstants.FUNCTIONALITY_NOT_SUPPORTED is returned. None: If the eye tracker is not currently recording data. EyeSample: If the eye tracker is recording in a monocular tracking mode, the latest sample event of this event type is returned. BinocularEyeSample: If the eye tracker is recording in a binocular tracking mode, the latest sample event of this event type is returned. """ return self._latest_sample def getLastGazePosition(self): """The getLastGazePosition method returns the most recent eye gaze position received from the Eye Tracker. This is the position on the calibrated 2D surface that the eye tracker is reporting as the current eye position. The units are in the units in use by the ioHub Display device. If binocular recording is being performed, the average position of both eyes is returned. If no samples have been received from the eye tracker, or the eye tracker is not currently recording data, None is returned. Args: None Returns: int: If this method is not supported by the eye tracker interface, EyeTrackerConstants.EYETRACKER_INTERFACE_METHOD_NOT_SUPPORTED is returned. None: If the eye tracker is not currently recording data or no eye samples have been received. tuple: Latest (gaze_x,gaze_y) position of the eye(s) """ return self._latest_gaze_position def getPosition(self): """ See getLastGazePosition(). """ return self.getLastGazePosition() def getPos(self): """ See getLastGazePosition(). """ return self.getLastGazePosition() def _eyeTrackerToDisplayCoords(self, eyetracker_point): """The _eyeTrackerToDisplayCoords method is required for implementation of the Common Eye Tracker Interface in order to convert the native Eye Tracker coordinate space to the ioHub.devices.Display coordinate space being used in the PsychoPy experiment. Any screen based coordinates that exist in the data provided to the ioHub by the device implementation must use this method to convert the x,y eye tracker point to the correct coordinate space. Default implementation is to call the Display device method: self._display_device._pixel2DisplayCoord(gaze_x,gaze_y,self._display_device.getIndex()) where gaze_x,gaze_y = eyetracker_point, which is assumed to be in screen pixel coordinates, with a top-left origin. If the eye tracker provides the eye position data in a coordinate space other than screen pixel position with top-left origin, the eye tracker position should first be converted to this coordinate space before passing the position data px,py to the _pixel2DisplayCoord method. self._display_device.getIndex() provides the index of the display for multi display setups. 0 is the default index, and valid values are 0 - N-1, where N is the number of connected, active, displays on the computer being used. Args: eyetracker_point (object): eye tracker implementation specific data type representing an x, y position on the calibrated 2D plane (typically a computer display screen). Returns: (x,y): The x,y eye position on the calibrated surface in the current ioHub.devices.Display coordinate type and space. """ gaze_x = eyetracker_point[0] gaze_y = eyetracker_point[1] # If the eyetracker_point does not represent eye data as display # pixel position using a top-left origin, convert the naive eye tracker # gaze coordinate space to a display pixel position using a top-left origin # here before passing gaze_x,gaze_y to the _pixel2DisplayCoord method. # .... return self._display_device._pixel2DisplayCoord( gaze_x, gaze_y, self._display_device.getIndex()) def _displayToEyeTrackerCoords(self, display_x, display_y): """The _displayToEyeTrackerCoords method must be used by an eye trackers implementation of the Common Eye Tracker Interface to convert any gaze positions provided by the ioHub to the appropriate x,y gaze position coordinate space for the eye tracking device in use. This method is simply the inverse operation performed by the _eyeTrackerToDisplayCoords method. Default implementation is to just return the result of self._display_device.display2PixelCoord(...). Args: display_x (float): The horizontal eye position on the calibrated 2D surface in ioHub.devices.Display coordinate space. display_y (float): The vertical eye position on the calibrated 2D surface in ioHub.devices.Display coordinate space. Returns: (object): eye tracker implementation specific data type representing an x, y position on the calibrated 2D plane (typically a computer display screen). """ pixel_x, pixel_y = self._display_device.display2PIxelCoord( display_x, display_y, self._display_device.getIndex()) return pixel_x, pixel_y def __del__(self): """Do any final cleanup of the eye tracker before the object is destroyed.""" self.__class__._INSTANCE = None from .eye_events import ( EyeSampleEvent, MonocularEyeSampleEvent, BinocularEyeSampleEvent, FixationStartEvent, FixationEndEvent, SaccadeStartEvent, SaccadeEndEvent, BlinkStartEvent, BlinkEndEvent)
21,307
Python
.py
373
47.048257
186
0.686518
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,673
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL).
211
Python
.py
4
52
85
0.745192
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,674
eyetracker.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/tobii/eyetracker.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_tobii.tobii.eyetracker import EyeTracker except (ModuleNotFoundError, ImportError, NameError): logging.error( "The Tobii eyetracker requires package 'psychopy-eyetracker-tobii' to " "be installed. Please install this package and restart the session to " "enable support.") if __name__ == "__main__": pass
621
Python
.py
14
40.571429
85
0.736755
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,675
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/tobii/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging yamlFile = None try: from psychopy_eyetracker_tobii.tobii import ( __file__, EyeTracker, MonocularEyeSampleEvent, BinocularEyeSampleEvent, FixationStartEvent, FixationEndEvent, SaccadeStartEvent, SaccadeEndEvent, BlinkStartEvent, BlinkEndEvent ) except (ModuleNotFoundError, ImportError, NameError): logging.error( "The Tobii eyetracker requires package 'psychopy-eyetracker-tobii' to " "be installed. Please install this package and restart the session to " "enable support.") if __name__ == "__main__": pass
884
Python
.py
26
28.115385
85
0.691228
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,676
tobiiwrapper.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/tobii/tobiiwrapper.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_tobii.tobii.tobiiwrapper import ( TobiiTracker, getTime) except (ModuleNotFoundError, ImportError, NameError): logging.error( "The Tobii eyetracker requires package 'psychopy-eyetracker-tobii' to " "be installed. Please install this package and restart the session to " "enable support.") if __name__ == "__main__": pass
645
Python
.py
15
38.866667
85
0.727273
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,677
calibration.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/tobii/calibration.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_tobii.tobii.calibration import ( TobiiCalibrationProcedure) except (ModuleNotFoundError, ImportError, NameError): logging.error( "The Tobii eyetracker requires package 'psychopy-eyetracker-tobii' to " "be installed. Please install this package and restart the session to " "enable support.") if __name__ == "__main__": pass
649
Python
.py
15
39.066667
85
0.731746
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,678
eyetracker.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/mouse/eyetracker.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from psychopy.iohub.errors import print2err, printExceptionDetailsToStdErr from psychopy.iohub.constants import EyeTrackerConstants, EventConstants from psychopy.iohub.devices import Computer, Device from psychopy.iohub.devices.eyetracker import EyeTrackerDevice from psychopy.iohub.devices.eyetracker.hw.mouse.calibration import MouseGazeCalibrationProcedure import math ET_UNDEFINED = EyeTrackerConstants.UNDEFINED getTime = Computer.getTime class EyeTracker(EyeTrackerDevice): """ To start iohub with a Mouse Simulated eye tracker, add the full iohub device name as a kwarg passed to launchHubServer:: eyetracker.hw.mouse.EyeTracker Examples: A. Start ioHub with the Mouse Simulated eye tracker:: from psychopy.iohub import launchHubServer from psychopy.core import getTime, wait iohub_config = {'eyetracker.hw.mouse.EyeTracker': {}} io = launchHubServer(**iohub_config) # Get the eye tracker device. tracker = io.devices.tracker B. Print all eye tracker events received for 2 seconds:: # Check for and print any eye tracker events received... tracker.setRecordingState(True) stime = getTime() while getTime()-stime < 2.0: for e in tracker.getEvents(): print(e) C. Print current eye position for 5 seconds:: # Check for and print current eye position every 100 msec. stime = getTime() while getTime()-stime < 5.0: print(tracker.getPosition()) wait(0.1) tracker.setRecordingState(False) # Stop the ioHub Server io.quit() """ DEVICE_TIMEBASE_TO_SEC = 1.0 EVENT_CLASS_NAMES = [ 'MonocularEyeSampleEvent', 'FixationStartEvent', 'FixationEndEvent', 'SaccadeStartEvent', 'SaccadeEndEvent', 'BlinkStartEvent', 'BlinkEndEvent'] __slots__ = [] _ioMouse = None _recording = False _eye_state = "NONE" _last_mouse_event_time = 0 _ISI = 0.01 # Later set by runtime_settings.sampling_rate _saccade_threshold = 0.5 # Later set by runtime_settings.sampling_rate _move_eye_buttons = [False, False, False] _blink_eye_buttons = [False, False, False] _last_event_start = 0.0 _last_start_event_pos = None _sacc_end_time = 0.0 _sacc_amplitude = 0.0, 0.0 _button_ix = dict(LEFT_BUTTON=0, MIDDLE_BUTTON=1, RIGHT_BUTTON=2) def __init__(self, *args, **kwargs): EyeTrackerDevice.__init__(self, *args, **kwargs) config = self.getConfiguration() # Used to hold the last sample processed by iohub. self._latest_sample = None # Calculate the desired ISI for the mouse sample stream. EyeTracker._ISI = 1.0/config.get('runtime_settings').get('sampling_rate') EyeTracker._saccade_threshold = config.get('controls').get('saccade_threshold') mb_list = config.get('controls').get('move') if isinstance(mb_list, str): mb_list = (mb_list,) if "CONTINUOUS" in mb_list: # CONTINUOUS == no buttons required to move == [] mb_list = [] bb_list = config.get('controls').get('blink') if isinstance(bb_list, str): bb_list = (bb_list,) for mb in mb_list: self._move_eye_buttons[self._button_ix.get(mb)] = True for mb in bb_list: self._blink_eye_buttons[self._button_ix.get(mb)] = True EyeTracker._move_eye_buttons = tuple(self._move_eye_buttons) EyeTracker._blink_eye_buttons = tuple(self._blink_eye_buttons) # Used to hold the last valid gaze position processed by ioHub. # If the last mouse tracker in a blink state, then this is set to None # self._latest_gaze_position = None def _connectMouse(self): if self._iohub_server: for dev in self._iohub_server.devices: if dev.__class__.__name__ == 'Mouse': EyeTracker._ioMouse = dev def _poll(self): if self.isConnected() and self.isRecordingEnabled(): if EyeTracker._last_mouse_event_time == 0: EyeTracker._last_mouse_event_time = getTime() - self._ISI # Start off mousegaze pos with current mouse position self._latest_gaze_position = self._ioMouse.getPosition() while getTime() - EyeTracker._last_mouse_event_time >= self._ISI: # Generate an eye sample every ISI seconds button_states = self._ioMouse.getCurrentButtonStates() last_gpos = self._latest_gaze_position if EyeTracker._eye_state == 'SACC' and getTime() >= EyeTracker._sacc_end_time: # Create end saccade event. end_pos = self._latest_gaze_position start_pos = self._last_start_event_pos self._addSaccadeEvent(False, start_pos, end_pos) self._addFixationEvent(True) create_blink_start = False if button_states == self._blink_eye_buttons: # In blink state.... # None means eyes are missing. if self._latest_gaze_position: # Blink just started, create event.... create_blink_start = True else: if self._eye_state == "BLINK": # Not in blink state anymore, create BlinkEndEvent self._latest_gaze_position = self._ioMouse.getPosition() self._addBlinkEvent(False) if button_states == self._move_eye_buttons: if self._eye_state == "FIX": display = self._display_device sacc_end_pos = self._ioMouse.getPosition() sacc_start_pos = self._latest_gaze_position spix = display._displayCoord2Pixel(sacc_start_pos[0], sacc_start_pos[1]) epix = display._displayCoord2Pixel(sacc_end_pos[0], sacc_end_pos[1]) sx = (epix[0]-spix[0])/display.getPixelsPerDegree()[0] sy = (epix[1]-spix[1])/display.getPixelsPerDegree()[1] sacc_amp_xy = math.fabs(math.hypot(sx, sy)) if sacc_amp_xy > EyeTracker._saccade_threshold: EyeTracker._sacc_amplitude = sx, sy self._addFixationEvent(False, sacc_start_pos) self._addSaccadeEvent(True, sacc_start_pos, sacc_end_pos) else: self._latest_gaze_position = self._ioMouse.getPosition() else: self._latest_gaze_position = self._ioMouse.getPosition() if self._eye_state not in ["FIX","SACC"] and self._latest_gaze_position: # Fixation start self._addFixationEvent(True) elif self._eye_state == "FIX" and create_blink_start: # Fixation End self._addFixationEvent(False, last_gpos) if create_blink_start: self._latest_gaze_position = None self._addBlinkEvent(True) EyeTracker._last_mouse_event_time += self._ISI next_sample_time = EyeTracker._last_mouse_event_time self._addSample(next_sample_time) def _addSaccadeEvent(self, startEvent, sacc_start_pos, sacc_end_pos): stime = EyeTracker._last_mouse_event_time if startEvent: eye_evt = [0, 0, 0, Device._getNextEventID(), EventConstants.SACCADE_START, stime, stime, stime, 0, 0, 0, EyeTrackerConstants.RIGHT_EYE, sacc_start_pos[0], sacc_start_pos[1], ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, 5, EyeTrackerConstants.PUPIL_DIAMETER_MM, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, 0] EyeTracker._eye_state = 'SACC' EyeTracker._last_event_start = stime sacc_amp_xy = math.fabs(math.hypot(*EyeTracker._sacc_amplitude)) saccade_duration = 2.2 * sacc_amp_xy + 21.0 saccade_duration = saccade_duration/1000.0 # convert to seconds EyeTracker._sacc_end_time = stime + saccade_duration EyeTracker._last_start_event_pos = sacc_start_pos self._latest_gaze_position = sacc_end_pos else: start_event_time = EyeTracker._last_event_start end_event_time = EyeTracker._sacc_end_time event_duration = end_event_time - start_event_time s_gaze = sacc_start_pos s_pupilsize = 4 e_gaze = sacc_end_pos e_pupilsize = 5 eye_evt = [0, 0, 0, Device._getNextEventID(), EventConstants.SACCADE_END, end_event_time, end_event_time, end_event_time, 0, 0, 0, EyeTrackerConstants.RIGHT_EYE, event_duration, EyeTracker._sacc_amplitude[0], # e_amp[0], EyeTracker._sacc_amplitude[1], # e_amp[1], 0, # e_angle, s_gaze[0], s_gaze[1], ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, s_pupilsize, EyeTrackerConstants.PUPIL_DIAMETER_MM, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, e_gaze[0], e_gaze[1], ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, e_pupilsize, EyeTrackerConstants.PUPIL_DIAMETER_MM, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, 0] EyeTracker._eye_state = 'FIX' EyeTracker._sacc_end_time = 0 self._addNativeEventToBuffer(eye_evt) def _addFixationEvent(self, startEvent, end_pos=None): ftime = EyeTracker._last_mouse_event_time gaze = self._latest_gaze_position if startEvent: eye_evt = [0, 0, 0, Device._getNextEventID(), EventConstants.FIXATION_START, ftime, ftime, ftime, 0, 0, 0, EyeTrackerConstants.RIGHT_EYE, gaze[0], gaze[1], ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, 5, EyeTrackerConstants.PUPIL_DIAMETER_MM, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, 0] EyeTracker._last_event_start = ftime EyeTracker._last_start_event_pos = gaze EyeTracker._eye_state = "FIX" else: start_event_time = EyeTracker._last_event_start end_event_time = ftime event_duration = end_event_time - start_event_time s_gaze = self._last_start_event_pos e_gaze = end_pos a_gaze = (s_gaze[0]+e_gaze[0])/2, (s_gaze[1]+e_gaze[1])/2 EyeTracker._last_event_start = 0.0 EyeTracker._last_start_event_pos = None eye_evt = [0, 0, 0, Device._getNextEventID(), EventConstants.FIXATION_END, ftime, ftime, ftime, 0, 0, 0, EyeTrackerConstants.RIGHT_EYE, event_duration, s_gaze[0], s_gaze[1], ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, 4, EyeTrackerConstants.PUPIL_DIAMETER_MM, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, e_gaze[0], e_gaze[1], ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, 5, EyeTrackerConstants.PUPIL_DIAMETER_MM, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, a_gaze[0], a_gaze[1], ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, 4.5, EyeTrackerConstants.PUPIL_DIAMETER_MM, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, 0] self._addNativeEventToBuffer(eye_evt) def _addBlinkEvent(self, startEvent): btime = EyeTracker._last_mouse_event_time if startEvent: # Create a blink start EyeTracker._last_event_start = btime EyeTracker._eye_state = "BLINK" eye_evt = [0, 0, 0, # device id (not currently used) Device._getNextEventID(), EventConstants.BLINK_START, btime, btime, btime, 0, 0, 0, EyeTrackerConstants.RIGHT_EYE, 0] else: # Create a blink end eye_evt = [ 0, 0, 0, Device._getNextEventID(), EventConstants.BLINK_END, btime, btime, btime, 0, 0, 0, EyeTrackerConstants.RIGHT_EYE, btime - EyeTracker._last_event_start, 0 ] EyeTracker._last_event_start = 0.0 self._addNativeEventToBuffer(eye_evt) def _addSample(self, sample_time): if self._latest_gaze_position: gx, gy = self._latest_gaze_position status = 0 else: gx, gy = EyeTrackerConstants.UNDEFINED, EyeTrackerConstants.UNDEFINED status = 2 pupilSize = 5 monoSample = [0, 0, 0, Device._getNextEventID(), EventConstants.MONOCULAR_EYE_SAMPLE, sample_time, sample_time, sample_time, 0, 0, 0, EyeTrackerConstants.RIGHT_EYE, gx, gy, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, pupilSize, EyeTrackerConstants.PUPIL_DIAMETER_MM, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, ET_UNDEFINED, status ] self._latest_sample = monoSample self._addNativeEventToBuffer(monoSample) def trackerTime(self): """ Current eye tracker time. Returns: float: current eye tracker time in seconds. """ return getTime() def trackerSec(self): """ Same as trackerTime(). """ return getTime() def setConnectionState(self, enable): """ When 'connected', the Mouse Simulated Eye Tracker taps into the ioHub Mouse event stream. """ if enable and self._ioMouse is None: self._connectMouse() elif enable is False and self._ioMouse: EyeTracker._ioMouse = None return self.isConnected() def isConnected(self): """ """ return self._ioMouse is not None def enableEventReporting(self, enabled=True): """enableEventReporting is functionally identical to the eye tracker device specific setRecordingState method.""" try: self.setRecordingState(enabled) enabled = EyeTrackerDevice.enableEventReporting(self, enabled) return enabled except Exception as e: print2err('Exception in EyeTracker.enableEventReporting: ', str(e)) printExceptionDetailsToStdErr() def setRecordingState(self, recording): """ setRecordingState is used to start or stop the recording of data from the eye tracking device. """ current_state = self.isRecordingEnabled() if recording is True and current_state is False: EyeTracker._recording = True if self._ioMouse is None: self._connectMouse() elif recording is False and current_state is True: EyeTracker._recording = False self._latest_sample = None EyeTracker._last_mouse_event_time = 0 return EyeTrackerDevice.enableEventReporting(self, recording) def isRecordingEnabled(self): """ isRecordingEnabled returns the recording state from the eye tracking device. Return: bool: True == the device is recording data; False == Recording is not occurring """ return self._recording def runSetupProcedure(self, calibration_args={}): """ runSetupProcedure displays a mock calibration procedure. No calibration is actually done. """ calibration = MouseGazeCalibrationProcedure(self, calibration_args) cal_run = calibration.runCalibration() calibration.window.close() calibration._unregisterEventMonitors() calibration.clearAllEventBuffers() del calibration.window del calibration if cal_run: return {"RESULT": "CALIBRATION_OK"} else: return {"RESULT": "CALIBRATION_ABORTED"} def _getIOHubEventObject(self, native_event_data): """The _getIOHubEventObject method is called by the ioHub Process to convert new native device event objects that have been received to the appropriate ioHub Event type representation.""" self._latest_sample = native_event_data return self._latest_sample def _eyeTrackerToDisplayCoords(self, eyetracker_point=()): """Converts MouseGaze positions to the Display device coordinate space. """ return eyetracker_point[0], eyetracker_point[1] def _displayToEyeTrackerCoords(self, display_x, display_y): """Converts a Display device point to MouseGaze position coordinate space. """ return display_x, display_y def _close(self): self.setRecordingState(False) self.setConnectionState(False) EyeTrackerDevice._close(self)
19,467
Python
.py
383
36.177546
110
0.574722
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,679
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/mouse/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from .eyetracker import EyeTracker from psychopy.iohub.devices.eyetracker import (MonocularEyeSampleEvent, FixationStartEvent, FixationEndEvent, SaccadeEndEvent, SaccadeStartEvent, BlinkEndEvent, BlinkStartEvent)
473
Python
.py
7
59.714286
114
0.735484
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,680
calibration.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/mouse/calibration.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from psychopy.iohub.devices.eyetracker.calibration import BaseCalibrationProcedure class MouseGazeCalibrationProcedure(BaseCalibrationProcedure): def __init__(self, eyetrackerInterface, calibration_args): BaseCalibrationProcedure.__init__(self, eyetrackerInterface, calibration_args, allow_escape_in_progress=True)
541
Python
.py
8
64.875
117
0.798493
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,681
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/pupil_labs/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL).
211
Python
.py
4
52
85
0.745192
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,682
bisector.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/pupil_labs/pupil_core/bisector.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_pupil_labs.pupil_labs.pupil_core.bisector import ( DatumNotFoundError, ImmutableBisector, MutableBisector) except (ModuleNotFoundError, ImportError, NameError): logging.error( "Pupil Labs eyetracker support requires the package " "'psychopy-eyetracker-pupil-labs' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
730
Python
.py
17
38.176471
85
0.725352
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,683
eyetracker.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/pupil_labs/pupil_core/eyetracker.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_pupil_labs.pupil_labs.pupil_core.eyetracker import ( EyeTracker) except (ModuleNotFoundError, ImportError, NameError): logging.error( "Pupil Labs eyetracker support requires the package " "'psychopy-eyetracker-pupil-labs' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
671
Python
.py
15
40.6
85
0.730475
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,684
constants.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/pupil_labs/pupil_core/constants.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_pupil_labs.pupil_labs.pupil_core.constants import ( EYE_ID_RIGHT, EYE_ID_LEFT) except (ModuleNotFoundError, ImportError, NameError): logging.error( "Pupil Labs eyetracker support requires the package " "'psychopy-eyetracker-pupil-labs' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
694
Python
.py
16
38.875
85
0.718519
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,685
pupil_remote.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/pupil_labs/pupil_core/pupil_remote.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_pupil_labs.pupil_labs.pupil_core.pupil_remote import ( PupilRemote) except (ModuleNotFoundError, ImportError, NameError): logging.error( "Pupil Labs eyetracker support requires the package " "'psychopy-eyetracker-pupil-labs' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
674
Python
.py
15
40.8
85
0.730183
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,686
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/pupil_labs/pupil_core/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: import psychopy_eyetracker_pupil_labs.pupil_labs.pupil_core as __plugin__ from psychopy_eyetracker_pupil_labs.pupil_labs.pupil_core import ( __file__, MonocularEyeSampleEvent, BinocularEyeSampleEvent, EyeTracker ) except (ModuleNotFoundError, ImportError, NameError): logging.error( "Pupil Labs eyetracker support requires the package " "'psychopy-eyetracker-pupil-labs' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
1,042
Python
.py
24
39
85
0.721619
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,687
data_parse.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/pupil_labs/pupil_core/data_parse.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_pupil_labs.pupil_labs.pupil_core.data_parse import ( eye_sample_from_gaze_3d, eye_sample_from_pupil, _binocular_eye_sample_from_gaze_3d, _monocular_eye_sample_from_gaze_3d, _monocular_eye_sample_from_pupil) except (ModuleNotFoundError, ImportError, NameError): logging.error( "Pupil Labs eyetracker support requires the package " "'psychopy-eyetracker-pupil-labs' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
846
Python
.py
19
39.315789
85
0.711165
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,688
eyetracker.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/pupil_labs/neon/eyetracker.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_pupil_labs.pupil_labs.neon.eyetracker import ( EyeTracker) except (ModuleNotFoundError, ImportError, NameError): logging.error( "Pupil Labs eyetracker support requires the package " "'psychopy-eyetracker-pupil-labs' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
665
Python
.py
15
40.2
85
0.729521
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,689
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/pupil_labs/neon/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: import psychopy_eyetracker_pupil_labs.pupil_labs.pupil_core as __plugin__ from psychopy_eyetracker_pupil_labs.pupil_labs.neon import ( __file__, BinocularEyeSampleEvent, EyeTracker) except (ModuleNotFoundError, ImportError, NameError): logging.error( "Pupil Labs eyetracker support requires the package " "'psychopy-eyetracker-pupil-labs' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
996
Python
.py
22
41.181818
85
0.724742
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,690
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/sr_research/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL).
211
Python
.py
4
52
85
0.745192
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,691
eyetracker.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/sr_research/eyelink/eyetracker.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_sr_research.sr_research.eyelink.eyetracker import ( start_eyelink, stop_eyelink, EyeTracker, MonocularEyeSampleEvent, BinocularEyeSampleEvent, FixationStartEvent, FixationEndEvent, SaccadeStartEvent, SaccadeEndEvent, BlinkStartEvent, BlinkEndEvent, _eyeLinkCalibrationResultDict, _getTrackerMode, _doDriftCorrect, _applyDriftCorrect, _eyeAvailable, _dummyOpen, _getCalibrationMessage, _setIPAddress, _setLockEye, _setNativeRecordingFileSaveDir) except (ModuleNotFoundError, ImportError, NameError): logging.error( "SR Research eyetracker support requires the package " "'psychopy-eyetracker-sr-research' to be installed. Please install " "this package and restart the session to enable support.") if __name__ == "__main__": pass
1,217
Python
.py
35
27.742857
85
0.684746
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,692
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/sr_research/eyelink/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_sr_research.sr_research.eyelink import ( __file__, EyeTracker, MonocularEyeSampleEvent, BinocularEyeSampleEvent, FixationStartEvent, FixationEndEvent, SaccadeStartEvent, SaccadeEndEvent, BlinkStartEvent, BlinkEndEvent ) except (ModuleNotFoundError, ImportError, NameError): logging.error( "SR Research eyetracker support requires the package " "'psychopy-eyetracker-sr-research' to be installed. Please install " "this package and restart the session to enable support.") if __name__ == "__main__": pass
908
Python
.py
25
30.24
85
0.696591
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,693
calibration.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/sr_research/eyelink/calibration.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_sr_research.sr_research.eyelink import ( FixationTarget, BlankScreen, TextLine, IntroScreen, EyeLinkCalibrationProcedure) except (ModuleNotFoundError, ImportError, NameError): logging.error( "SR Research eyetracker support requires the package " "'psychopy-eyetracker-sr-research' to be installed. Please install " "this package and restart the session to enable support.") if __name__ == "__main__": pass
763
Python
.py
19
34.947368
85
0.71525
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,694
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/gazepoint/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_gazepoint.gazepoint.gp3 import ( __file__, EyeTracker, MonocularEyeSampleEvent, BinocularEyeSampleEvent, FixationStartEvent, FixationEndEvent, SaccadeStartEvent, SaccadeEndEvent, BlinkStartEvent, BlinkEndEvent, GazepointSampleEvent ) except (ModuleNotFoundError, ImportError, NameError): logging.error( "The Gazepoint eyetracker requires package " "'psychopy-eyetracker-gazepoint' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
918
Python
.py
26
29.115385
85
0.694382
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,695
eyetracker.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/gazepoint/gp3/eyetracker.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_gazepoint.gazepoint.gp3.eyetracker import ( ET_UNDEFINED, EyeTracker, to_numeric, getTime) except (ModuleNotFoundError, ImportError, NameError): logging.error( "The Gazepoint eyetracker requires package " "'psychopy-eyetracker-gazepoint' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
713
Python
.py
18
34.555556
85
0.709538
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,696
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/gazepoint/gp3/__init__.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_gazepoint.gazepoint.gp3 import ( __file__, EyeTracker, MonocularEyeSampleEvent, BinocularEyeSampleEvent, FixationStartEvent, FixationEndEvent, SaccadeStartEvent, SaccadeEndEvent, BlinkStartEvent, BlinkEndEvent ) except (ModuleNotFoundError, ImportError, NameError): logging.error( "The Gazepoint eyetracker requires package " "'psychopy-eyetracker-gazepoint' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
889
Python
.py
25
29.44
85
0.694541
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,697
calibration.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/hw/gazepoint/gp3/calibration.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import psychopy.logging as logging try: from psychopy_eyetracker_gazepoint.gazepoint.gp3.calibration import ( GazepointCalibrationProcedure) except (ModuleNotFoundError, ImportError, NameError): logging.error( "The Gazepoint eyetracker requires package " "'psychopy-eyetracker-gazepoint' to be installed. Please install this " "package and restart the session to enable support.") if __name__ == "__main__": pass
673
Python
.py
15
40.666667
85
0.738931
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,698
procedure.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/calibration/procedure.py
# -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2012-2020 iSolver Software Solutions (C) 2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from psychopy import visual, layout import gevent from psychopy.iohub.util import convertCamelToSnake, updateSettings, createCustomCalibrationStim from psychopy.iohub.devices import DeviceEvent, Computer from psychopy.iohub.constants import EventConstants as EC from psychopy.iohub.devices.keyboard import KeyboardInputEvent from psychopy.iohub.errors import print2err from psychopy.constants import PLAYING currentTime = Computer.getTime target_position_count = dict(THREE_POINTS=3, FIVE_POINTS=5, NINE_POINTS=9, THIRTEEN_POINTS=13) target_positions = dict() target_positions[3] = [(0.5, 0.1), (0.1, 0.9), (0.9, 0.9)] target_positions[5] = [(0.5, 0.5), (0.1, 0.1), (0.9, 0.1), (0.9, 0.9), (0.1, 0.9)] target_positions[9] = [(0.5, 0.5), (0.1, 0.5), (0.9, 0.5), (0.1, 0.1), (0.5, 0.1), (0.9, 0.1), (0.9, 0.9), (0.5, 0.9), (0.1, 0.9)] target_positions[13] = [(0.5, 0.5), (0.1, 0.5), (0.9, 0.5), (0.1, 0.1), (0.5, 0.1), (0.9, 0.1), (0.9, 0.9), (0.5, 0.9), (0.1, 0.9), (0.25, 0.25), (0.25, 0.75), (0.75, 0.75), (0.75, 0.25)] class BaseCalibrationProcedure: IOHUB_HEARTBEAT_INTERVAL = 0.050 CALIBRATION_POINT_LIST = target_positions[9] _keyboard_key_index = KeyboardInputEvent.CLASS_ATTRIBUTE_NAMES.index('key') def __init__(self, eyetrackerInterface, calibration_args, allow_escape_in_progress=True): self._eyetracker = eyetrackerInterface self.allow_escape = allow_escape_in_progress self.screenSize = eyetrackerInterface._display_device.getPixelResolution() self.width = self.screenSize[0] self.height = self.screenSize[1] self._ioKeyboard = None self._msg_queue = [] self._lastCalibrationOK = False self._device_config = self._eyetracker.getConfiguration() display = self._eyetracker._display_device updateSettings(self._device_config.get('calibration'), calibration_args) self._calibration_args = self._device_config.get('calibration') unit_type = self.getCalibSetting('unit_type') if unit_type is None: unit_type = display.getCoordinateType() self._calibration_args['unit_type'] = unit_type color_type = self.getCalibSetting('color_type') if color_type is None: color_type = display.getColorSpace() self._calibration_args['color_type'] = color_type cal_type = self.getCalibSetting('type') if cal_type in target_position_count: num_points = target_position_count[cal_type] BaseCalibrationProcedure.CALIBRATION_POINT_LIST = target_positions[num_points] self.cal_target_list = self.CALIBRATION_POINT_LIST self.window = visual.Window( self.screenSize, monitor=display.getPsychopyMonitorName(), units=unit_type, fullscr=True, allowGUI=False, screen=display.getIndex(), color=self.getCalibSetting(['screen_background_color']), colorSpace=color_type) self.window.setMouseVisible(False) self.window.flip(clearBuffer=True) self.createGraphics() self._registerEventMonitors() self._lastMsgPumpTime = currentTime() self.clearAllEventBuffers() def getCalibSetting(self, setting): if isinstance(setting, str): setting = [setting, ] calibration_args = self._calibration_args if setting: for s in setting[:-1]: calibration_args = calibration_args.get(s) return calibration_args.get(setting[-1]) def clearAllEventBuffers(self): self._eyetracker._iohub_server.eventBuffer.clear() for d in self._eyetracker._iohub_server.devices: d.clearEvents() def _registerEventMonitors(self): kbDevice = None if self._eyetracker._iohub_server: for dev in self._eyetracker._iohub_server.devices: if dev.__class__.__name__ == 'Keyboard': kbDevice = dev if kbDevice: eventIDs = [] for event_class_name in kbDevice.__class__.EVENT_CLASS_NAMES: eventIDs.append(getattr(EC, convertCamelToSnake(event_class_name[:-5], False))) self._ioKeyboard = kbDevice self._ioKeyboard._addEventListener(self, eventIDs) else: print2err('Warning: %s could not connect to Keyboard device for events.' % self.__class__.__name__) def _unregisterEventMonitors(self): if self._ioKeyboard: self._ioKeyboard._removeEventListener(self) def _handleEvent(self, event): event_type_index = DeviceEvent.EVENT_TYPE_ID_INDEX if event[event_type_index] == EC.KEYBOARD_RELEASE: ek = event[self._keyboard_key_index] if isinstance(ek, bytes): ek = ek.decode('utf-8') if ek == ' ' or ek == 'space': self._msg_queue.append('SPACE_KEY_ACTION') self.clearAllEventBuffers() elif ek == 'escape': self._msg_queue.append('QUIT') self.clearAllEventBuffers() def MsgPump(self): # keep the psychopy window happy ;) if currentTime() - self._lastMsgPumpTime > self.IOHUB_HEARTBEAT_INTERVAL: # try to keep ioHub from being blocked. ;( if self._eyetracker._iohub_server: for dm in self._eyetracker._iohub_server.deviceMonitors: dm.device._poll() self._eyetracker._iohub_server.processDeviceEvents() self._lastMsgPumpTime = currentTime() def getNextMsg(self): if len(self._msg_queue) > 0: msg = self._msg_queue[0] self._msg_queue = self._msg_queue[1:] return msg def createGraphics(self): """ """ color_type = self.getCalibSetting('color_type') unit_type = self.getCalibSetting('unit_type') def setDefaultCalibrationTarget(): # convert sizes to stimulus units radiusPix = self.getCalibSetting(['target_attributes', 'outer_diameter']) / 2 radiusObj = layout.Size(radiusPix, units=unit_type, win=self.window) radius = getattr(radiusObj, unit_type)[1] innerRadiusPix = self.getCalibSetting(['target_attributes', 'inner_diameter']) / 2 innerRadiusObj = layout.Size(innerRadiusPix, units=unit_type, win=self.window) innerRadius = getattr(innerRadiusObj, unit_type)[1] # make target self.targetStim = visual.TargetStim( self.window, name="CP", style="circles", radius=radius, fillColor=self.getCalibSetting(['target_attributes', 'outer_fill_color']), borderColor=self.getCalibSetting(['target_attributes', 'outer_line_color']), lineWidth=self.getCalibSetting(['target_attributes', 'outer_stroke_width']), innerRadius=innerRadius, innerFillColor=self.getCalibSetting(['target_attributes', 'inner_fill_color']), innerBorderColor=self.getCalibSetting(['target_attributes', 'inner_line_color']), innerLineWidth=self.getCalibSetting(['target_attributes', 'inner_stroke_width']), pos=(0, 0), units=unit_type, colorSpace=color_type, autoLog=False ) if self._calibration_args.get('target_type') == 'CIRCLE_TARGET': setDefaultCalibrationTarget() else: self.targetStim = createCustomCalibrationStim(self.window, self._calibration_args) if self.targetStim is None: # Error creating custom stim, so use default target stim type setDefaultCalibrationTarget() self.originalTargetSize = self.targetStim.size self.targetClassHasPlayPause = hasattr(self.targetStim, 'play') and hasattr(self.targetStim, 'pause') self.imagetitlestim = None tctype = color_type tcolor = self.getCalibSetting(['text_color']) if tcolor is None: # If no calibration text color provided, base it on the window background color from psychopy.iohub.util import complement sbcolor = self.getCalibSetting(['screen_background_color']) if sbcolor is None: sbcolor = self.window.color from psychopy.colors import Color tcolor_obj = Color(sbcolor, color_type) tcolor = complement(*tcolor_obj.rgb255) tctype = 'rgb255' instuction_text = 'Press SPACE to Start Calibration; ESCAPE to Exit.' self.textLineStim = visual.TextStim(self.window, text=instuction_text, pos=(0, 0), height=36, color=tcolor, colorSpace=tctype, units='pix', wrapWidth=self.width * 0.9) def startCalibrationHook(self): pass def registerCalibrationPointHook(self, pt): pass def finishCalibrationHook(self, aborted=False): pass def runCalibration(self): """Run calibration sequence """ if self.showIntroScreen() is False: # User pressed escape to exit calibration return False target_delay = self.getCalibSetting('target_delay') target_duration = self.getCalibSetting('target_duration') auto_pace = self.getCalibSetting('auto_pace') randomize_points = self.getCalibSetting('randomize') if randomize_points is True: # Randomize all but first target position. self.cal_target_list = self.CALIBRATION_POINT_LIST[1:] import random random.seed(None) random.shuffle(self.cal_target_list) self.cal_target_list.insert(0, self.CALIBRATION_POINT_LIST[0]) left, top, right, bottom = self._eyetracker._display_device.getCoordBounds() w, h = right - left, top - bottom self.clearCalibrationWindow() self.startCalibrationHook() i = 0 abort_calibration = False for pt in self.cal_target_list: if abort_calibration: break # Convert normalized positions to psychopy window unit positions # by using iohub display/window getCoordBounds. x, y = left + w * pt[0], bottom + h * (1.0 - pt[1]) start_time = currentTime() self.clearAllEventBuffers() # Target animate / delay animate_enable = self.getCalibSetting(['target_attributes', 'animate', 'enable']) animate_expansion_ratio = self.getCalibSetting(['target_attributes', 'animate', 'expansion_ratio']) animate_contract_only = self.getCalibSetting(['target_attributes', 'animate', 'contract_only']) while currentTime()-start_time <= target_delay: if animate_enable and i > 0: t = (currentTime()-start_time) / target_delay v1 = self.cal_target_list[i-1] v2 = pt t = 60.0 * ((1.0 / 10.0) * t ** 5 - (1.0 / 4.0) * t ** 4 + (1.0 / 6.0) * t ** 3) mx, my = ((1.0 - t) * v1[0] + t * v2[0], (1.0 - t) * v1[1] + t * v2[1]) moveTo = left + w * mx, bottom + h * (1.0 - my) self.drawCalibrationTarget(moveTo) elif animate_enable is False: if self.targetClassHasPlayPause and self.targetStim.status == PLAYING: self.targetStim.pause() self.window.flip(clearBuffer=True) gevent.sleep(0.001) self.MsgPump() msg = self.getNextMsg() if self.allow_escape and msg == 'QUIT': abort_calibration = True break # Target expand / contract phase on done if target is a visual.TargetStim class self.resetTargetProperties() if self.targetClassHasPlayPause and self.targetStim.status != PLAYING: self.targetStim.play() self.drawCalibrationTarget((x, y)) start_time = currentTime() stim_size = self.targetStim.size[0] min_stim_size = self.targetStim.size[0] / animate_expansion_ratio if hasattr(self.targetStim, 'minSize'): min_stim_size = self.targetStim.minSize[0] while currentTime()-start_time <= target_duration: elapsed_time = currentTime()-start_time new_size = t = None if animate_contract_only: # Change target size from outer diameter to inner diameter over target_duration seconds. t = elapsed_time / target_duration new_size = stim_size - t * (stim_size - min_stim_size) elif animate_expansion_ratio not in [1, 1.0]: if elapsed_time <= target_duration/2: # In expand phase t = elapsed_time / (target_duration/2) new_size = stim_size + t * (stim_size*animate_expansion_ratio - stim_size) else: # In contract phase t = (elapsed_time-target_duration/2) / (target_duration/2) new_size = stim_size*animate_expansion_ratio - t * (stim_size*animate_expansion_ratio - min_stim_size) if new_size: self.targetStim.size = new_size, new_size self.targetStim.draw() self.window.flip() if auto_pace is False: while 1: if self.targetClassHasPlayPause and self.targetStim.status == PLAYING: self.targetStim.draw() self.window.flip() gevent.sleep(0.001) self.MsgPump() msg = self.getNextMsg() if msg == 'SPACE_KEY_ACTION': break elif self.allow_escape and msg == 'QUIT': abort_calibration = True break gevent.sleep(0.001) self.MsgPump() msg = self.getNextMsg() while msg: if self.allow_escape and msg == 'QUIT': abort_calibration = True break gevent.sleep(0.001) self.MsgPump() msg = self.getNextMsg() self.registerCalibrationPointHook(pt) self.clearCalibrationWindow() self.clearAllEventBuffers() i += 1 if self.targetClassHasPlayPause: self.targetStim.pause() self.finishCalibrationHook(abort_calibration) if abort_calibration is False: self.showFinishedScreen() return not abort_calibration def clearCalibrationWindow(self): self.window.flip(clearBuffer=True) def showIntroScreen(self, text_msg='Press SPACE to Start Calibration; ESCAPE to Exit.'): self.clearAllEventBuffers() while True: self.textLineStim.setText(text_msg) self.textLineStim.draw() self.window.flip() msg = self.getNextMsg() if msg == 'SPACE_KEY_ACTION': self.clearAllEventBuffers() return True elif msg == 'QUIT': self.clearAllEventBuffers() return False self.MsgPump() gevent.sleep(0.001) def showFinishedScreen(self, text_msg="Calibration Complete. Press 'SPACE' key to continue."): self.clearAllEventBuffers() while True: self.textLineStim.setText(text_msg) self.textLineStim.draw() self.window.flip() msg = self.getNextMsg() if msg in ['SPACE_KEY_ACTION', 'QUIT']: self.clearAllEventBuffers() return True self.MsgPump() gevent.sleep(0.001) def resetTargetProperties(self): self.targetStim.size = self.originalTargetSize def drawCalibrationTarget(self, tp): self.targetStim.setPos(tp) self.targetStim.draw() return self.window.flip(clearBuffer=True)
16,871
Python
.py
339
36.637168
126
0.585834
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,699
__init__.py
psychopy_psychopy/psychopy/iohub/devices/eyetracker/filters/__init__.py
"""ioHub Common Eye Tracker Interface""" # Part of the psychopy.iohub library. # Copyright (C) 2012-2016 iSolver Software Solutions # Distributed under the terms of the GNU General Public License (GPL).
206
Python
.py
4
49.75
71
0.772277
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)