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,500
test_components.py
psychopy_psychopy/psychopy/tests/test_experiment/needs_wx/test_components.py
from pathlib import Path import os import io import pytest import warnings from psychopy import constants from psychopy.experiment import getAllComponents, Param, utils from psychopy import experiment from packaging.version import Version # use "python genComponsTemplate.py --out" to generate a new profile to test against # = analogous to a baseline image to compare screenshots # motivation: catch deviations introduced during refactoring # what reference to use? profile = 'componsTemplate.txt' # always ignore hints, labels, and categories. other options: # should it be ok or an error if the param[field] order differs from the profile? ignoreOrder = True # ignore attributes that are there because inherit from object ignoreObjectAttribs = True ignoreList = ['<built-in method __', "<method-wrapper '__", '__slotnames__:'] # profile is not platform specific, which can trigger false positives. # allowedVals can differ across platforms or with prefs: ignoreParallelOutAddresses = True @pytest.mark.components class TestComponents(): @classmethod def setup_class(cls): cls.expPy = experiment.Experiment() # create once, not every test cls.expJS = experiment.Experiment() cls.here = Path(__file__).parent cls.baselineProfile = cls.here / profile # should not need a wx.App with fetchIcons=False try: cls.allComp = getAllComponents(fetchIcons=False) except Exception: import wx if Version(wx.__version__) < Version('2.9'): tmpApp = wx.PySimpleApp() else: tmpApp = wx.App(False) try: from psychopy.app import localization except Exception: pass # not needed if can't import it cls.allComp = getAllComponents(fetchIcons=False) def setup_method(self): """This setup is done for each test individually """ pass def teardown_method(self): pass def test_component_attribs(self): with io.open(self.baselineProfile, 'r', encoding='utf-8-sig', errors='ignore') as f: target = f.read() targetLines = target.splitlines() targetTag = {} for line in targetLines: try: t, val = line.split(':',1) targetTag[t] = val except ValueError: # need more than one value to unpack; this is a weak way to # handle multi-line default values, eg TextComponent.text.default targetTag[t] += '\n' + line # previous t value param = experiment.Param('', '') # want its namespace ignore = ['__doc__', '__init__', '__module__', '__str__', 'next', '__unicode__', '__native__', '__nonzero__', '__long__'] # these are for display only (cosmetic) and can end up being localized # so typically do not want to check during automated testing, at least # not when things are still new-ish and subject to change: ignore += ['hint', 'label', # comment-out to compare labels when checking 'categ', 'next', 'dollarSyntax', ] for field in dir(param): if field.startswith("__"): ignore.append(field) fields = set(dir(param)).difference(ignore) mismatched = [] for compName in sorted(self.allComp): comp = self.allComp[compName](parentName='x', exp=self.expPy) order = '%s.order:%s' % (compName, eval("comp.order")) if order+'\n' not in target: tag = order.split(':',1)[0] try: mismatch = order + ' <== ' + targetTag[tag] except (IndexError, KeyError): # missing mismatch = order + ' <==> NEW (no matching param in the reference profile)' print(mismatch.encode('utf8')) if not ignoreOrder: mismatched.append(mismatch) for parName in comp.params: # default is what you get from param.__str__, which returns its value default = '%s.%s.default:%s' % (compName, parName, comp.params[parName]) lineFields = [] for field in fields: if parName == 'name' and field == 'updates': continue # ignore b/c never want to change the name *during a running experiment* # the default name.updates varies across components: need to ignore or standardize f = '%s.%s.%s:%s' % (compName, parName, field, eval("comp.params[parName].%s" % field)) lineFields.append(f) for line in [default] + lineFields: # some attributes vary by machine so don't check those if line.startswith('ParallelOutComponent.address') and ignoreParallelOutAddresses: continue elif line.startswith('SettingsComponent.OSF Project ID.allowedVals'): continue elif ('SettingsComponent.Use version.allowedVals' in line or 'SettingsComponent.Use version.__dict__' in line): # versions available on travis-ci are only local continue origMatch = line+'\n' in target lineAlt = (line.replace(":\'", ":u'") .replace("\\\\","\\") .replace("\\'", "'")) # start checking params if not (line+'\n' in target or lineAlt+'\n' in target): # mismatch, so report on the tag from orig file # match checks tag + multi-line, because line is multi-line and target is whole file tag = line.split(':',1)[0] try: mismatch = line + ' <== ' + targetTag[tag] except KeyError: # missing mismatch = line + ' <==> NEW (no matching param in the reference profile)' # ignore attributes that inherit from object: if ignoreObjectAttribs: for item in ignoreList: if item in mismatch: break else: mismatched.append(mismatch) else: mismatched.append(mismatch) for mismatch in mismatched: warnings.warn("Non-identical Builder Param: {}".format(mismatch)) @pytest.mark.components def test_flip_before_shutdown_in_settings_component(): exp = experiment.Experiment() script = exp.writeScript() assert 'Flip one final time' in script
7,095
Python
.py
144
35.111111
108
0.552924
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,501
test_Experiment.py
psychopy_psychopy/psychopy/tests/test_experiment/needs_wx/test_Experiment.py
from pathlib import Path import psychopy.experiment from psychopy.experiment.components.text import TextComponent from psychopy.experiment._experiment import RequiredImport from psychopy.tests.utils import TESTS_FONT from os import path import os, shutil, glob import py_compile import difflib from tempfile import mkdtemp import codecs from psychopy import core, prefs import pytest import locale import numpy import sys import re import xmlschema # Jeremy Gray March 2011 # caveats when comparing files: # - dicts have no defined order, can load and save differently: use a # known-diff file to suppress boring errors. This situation was # addressed in 7e2c72a for stimOut by sorting the keys # - namespace.makeValid() can change var names from the orig demos, # but should not do so from a load-save-load because only the first # load should change things allComponents = psychopy.experiment.getComponents(fetchIcons=False) isTime = re.compile(r"\d+:\d+(:\d+)?( [AP]M)?") def _filterout_legal(lines): """Ignore first 5 lines: header info, version, date can differ no problem """ return [line for line in lines[5:] if not "This experiment was created using PsychoPy3 Experiment Builder (" in line and not ("trialList=data.importConditions(" in line and ".xlsx'))" in line)] #-This experiment was created using PsychoPy3 Experiment Builder (v1.65.01), August 03, 2011, at 13:14 #+This experiment was created using PsychoPy3 Experiment Builder (v1.65.02), August 03, 2011, at 13:14 #- trialList=data.importConditions(u'trialTypes.xlsx')) #+ trialList=data.importConditions('trialTypes.xlsx')) #- trialList=data.importConditions(u'mainTrials.xlsx')) #+ trialList=data.importConditions('mainTrials.xlsx')) def _diff(a, b): """ diff of strings; returns a generator, 3 lines of context by default, - or + for changes """ return difflib.unified_diff(a, b) def _diff_file(a, b): """ diff of files read as strings, by line; output is similar to git gui diff """ diff = _diff(open(a).readlines(), open(b).readlines()) return list(diff) class TestExpt(): @classmethod def setup_class(cls): cls.exp = psychopy.experiment.Experiment() # create once, not every test try: cls.tmp_dir = mkdtemp(dir=Path(__file__).root, prefix='psychopy-tests-app') except (PermissionError, OSError): # can't write to root on Linux cls.tmp_dir = mkdtemp(prefix='psychopy-tests-app') def setup_method(self): """This setup is done for each test individually """ self.here = path.abspath(path.dirname(__file__)) self.known_diffs_file = path.join(self.here, '../known_py_diffs.txt') self.tmp_diffs_file = path.join(self.here, 'tmp_py_diffs.txt') # not deleted by mkdtemp cleanup @classmethod def teardown_class(cls): shutil.rmtree(cls.tmp_dir, ignore_errors=True) def _checkLoadSave(self, file): exp = self.exp py_file = file+'.py' psyexp_file = file+'newXML.psyexp' # go from psyexp file on disk to internal builder representation: self.exp.loadFromXML(file) self.exp.saveToXML(psyexp_file) assert len(self.exp.namespace.user) # should populate the namespace assert not self.exp.namespace.getCollisions() # ... without duplicates # generate a script, like 'lastrun.py': script = self.exp.writeScript() assert len(script) > 1500 # default empty script is ~2200 chars # save the script: with codecs.open(py_file, 'w', 'utf-8-sig') as f: f.write(script) return py_file, psyexp_file def _checkPyDiff(self, file_py, file2_py): """return '' for no meaningful diff, or a diff patch""" diff_py_lines = _diff_file(file_py, file2_py)[5:] # ignore first five lines --- +++ if not len(diff_py_lines): return '' bad_diff = False # not all diffs are bad... # get all differing lines only, no context: f1 = _filterout_legal([x[1:] for x in diff_py_lines if x[0] == '+']) f2 = _filterout_legal([x[1:] for x in diff_py_lines if x[0] == '-']) if len(f1) != len(f2): bad_diff = True diff_py_keylines = f1 + f2 # if line starts with stimOut, check for mere variation in order within line = ok # fails for multiple stimOut lines with diff conditionss ==> len(set()) > 1 if not bad_diff: # get only the stimOut lines, ignore leading whitespace: diff_py_stimOut = [y.replace("'", " ' ").strip() for y in diff_py_keylines if y.lstrip().startswith('stimOut')] # in Navon demo, stimOut comes from a dict written as a list, for conditions diff_py_stimOut_sort = [] for line in diff_py_stimOut: sp_line = line.split() sp_line.sort() # squash order diff_py_stimOut_sort.append(' '.join(sp_line)) # for diff lines that start with stimOut, are they same except order? if len(set(diff_py_stimOut_sort)) > 1: # set() squashes duplicates bad_diff = True # are the stimOut lines the only ones that differ? if so, we're ok if len(diff_py_keylines) != len(diff_py_stimOut): bad_diff = True # add another checks here: #if not bad_diff: # some_condition = ... # if some_condition: # bad_diff = True # create a patch / diff file if bad_diff and not already a known-ok-diff: if bad_diff: diff_py_patch = ''.join(diff_py_lines) known_diffs = open(self.known_diffs_file).read() if known_diffs.find(diff_py_patch) < 0: patch = open(self.new_diff_file+'_'+path.basename(file_py)+'.patch', 'wb+') patch.write(path.basename(file_py) + ' load-save difference in resulting .py files: ' + '-'*15 + '\n' + diff_py_patch+'\n' + '-'*80 +'\n\n') patch.close() return diff_py_patch # --> final assert will fail return '' def test_Exp_LoadCompilePsyexp(self): #""" for each builder demo .psyexp: load-save-load, compile (syntax check), namespace""" exp = self.exp self.new_diff_file = self.tmp_diffs_file # make temp copies of all builder demos: for root, dirs, files in os.walk(path.join(self.exp.prefsPaths['demos'], 'builder')): for f in files: if (f.endswith('.psyexp') or f.endswith('.xlsx') or f.endswith('.csv') )\ and not f.startswith('bart'): shutil.copyfile(path.join(root, f), path.join(self.tmp_dir, f)) # also copy any psyexp in 'here' (testExperiment dir) #for f in glob.glob(path.join(self.here, '*.psyexp')): # shutil.copyfile(f, path.join(self.tmp_dir, path.basename(f))) test_psyexp = list(glob.glob(path.join(self.tmp_dir, '*.psyexp'))) if len(test_psyexp) == 0: pytest.skip("No test .psyexp files found (no Builder demos??)") diff_in_file_py = '' # will later assert that this is empty #diff_in_file_psyexp = '' #diff_in_file_pyc = '' #savedLocale = '.'.join(locale.getlocale()) locale.setlocale(locale.LC_ALL, '') # default if not sys.platform.startswith('win'): testlocList = ['en_US', 'en_US.UTF-8', 'ja_JP'] else: testlocList = ['USA', 'JPN'] for file in test_psyexp: # test for any diffs using various locale's: for loc in ['en_US', 'ja_JP']: try: locale.setlocale(locale.LC_ALL, loc) except locale.Error: continue #skip this locale; it isn't installed file_py, file_psyexp = self._checkLoadSave(file) file_pyc = self._checkCompile(file_py) #sha1_first = sha1hex(file_pyc, file=True) file2_py, file2_psyexp = self._checkLoadSave(file_psyexp) file2_pyc = self._checkCompile(file2_py) #sha1_second = sha1hex(file2_pyc, file=True) # check first against second, filtering out uninteresting diffs; catch diff in any of multiple psyexp files d = self._checkPyDiff(file_py, file2_py) if d: diff_in_file_py += os.path.basename(file) + '::' + d #diff_psyexp = _diff_file(file_psyexp,file2_psyexp)[2:] #diff_in_file_psyexp += diff_psyexp #diff_pyc = (sha1_first != sha1_second) #assert not diff_pyc #locale.setlocale(locale.LC_ALL,'C') assert not diff_in_file_py ### see known_py_diffs.txt; potentially a locale issue? ### #assert not diff_in_file_psyexp # was failing most times, uninformative #assert not diff_in_file_pyc # oops, was failing every time despite identical .py file def test_Run_FastStroopPsyExp(self): # start from a psyexp file, loadXML, execute, get keypresses from a emulator thread if sys.platform.startswith('linux'): pytest.skip("response emulation thread not working on linux yet") expfile = path.join(self.exp.prefsPaths['tests'], 'data', 'ghost_stroop.psyexp') with codecs.open(expfile, 'r', encoding='utf-8-sig') as f: text = f.read() # copy conditions file to tmp_dir shutil.copyfile(os.path.join(self.exp.prefsPaths['tests'], 'data', 'ghost_trialTypes.xlsx'), os.path.join(self.tmp_dir,'ghost_trialTypes.xlsx')) # edit the file, to have a consistent font: text = text.replace("'Arial'", "'" + TESTS_FONT +"'") expfile = path.join(self.tmp_dir, 'ghost_stroop.psyexp') with codecs.open(expfile, 'w', encoding='utf-8-sig') as f: f.write(text) self.exp.loadFromXML(expfile) # reload the edited file # supply temp dir to experiment self.exp.settings.params['Saved data folder'].val = os.path.abspath(self.tmp_dir) self.exp.settings.params['Saved data folder'].valType = "str" script = self.exp.writeScript() # reposition its window out from under splashscreen (can't do easily from .psyexp): script = script.replace('fullscr=False,','pos=(40,40), fullscr=False,') # Only log errors. script = script.replace('logging.console.setLevel(logging.WARNING', 'logging.console.setLevel(logging.ERROR') lastrun = path.join(self.tmp_dir, 'ghost_stroop_lastrun.py') with codecs.open(lastrun, 'w', encoding='utf-8-sig') as f: f.write(script) # run: stdout, stderr = core.shellCall([sys.executable, lastrun], stderr=True) assert not stderr def test_Exp_NameSpace(self): namespace = self.exp.namespace assert namespace.exists('psychopy') == "Psychopy module" namespace.add('foo') assert namespace.exists('foo') == "one of your Components, Routines, or condition parameters" namespace.add('foo') assert namespace.getCollisions() == ['foo'] assert not namespace.isValid('123') assert not namespace.isValid('a1 23') assert not namespace.isValid('a123$') assert namespace.makeValid('123') == 'var_123' assert namespace.makeValid('123', prefix='wookie') == 'wookie_123' assert namespace.makeValid('a a a') == 'a_a_a' namespace.add('b') assert namespace.makeValid('b') == 'b_2' assert namespace.makeValid('a123$') == 'a123_' assert namespace.makeLoopIndex('trials') == 'thisTrial' assert namespace.makeLoopIndex('trials_2') == 'thisTrial_2' assert namespace.makeLoopIndex('stimuli') == 'thisStimulus' class TestExpImports(): def setup_method(self): self.exp = psychopy.experiment.Experiment() self.exp.requiredImports = [] def test_requireImportName(self): import_ = RequiredImport(importName='foo', importFrom='', importAs='') self.exp.requireImport(importName='foo') assert import_ in self.exp.requiredImports script = self.exp.writeScript() assert 'import foo\n' in script def test_requireImportFrom(self): import_ = RequiredImport(importName='foo', importFrom='bar', importAs='') self.exp.requireImport(importName='foo', importFrom='bar') assert import_ in self.exp.requiredImports script = self.exp.writeScript() assert 'from bar import foo\n' in script def test_requireImportAs(self): import_ = RequiredImport(importName='foo', importFrom='', importAs='baz') self.exp.requireImport(importName='foo', importAs='baz') assert import_ in self.exp.requiredImports script = self.exp.writeScript() assert 'import foo as baz\n' in script def test_requireImportFromAs(self): import_ = RequiredImport(importName='foo', importFrom='bar', importAs='baz') self.exp.requireImport(importName='foo', importFrom='bar', importAs='baz') assert import_ in self.exp.requiredImports script = self.exp.writeScript() assert 'from bar import foo as baz\n' in script def test_requirePsychopyLibs(self): import_ = RequiredImport(importName='foo', importFrom='psychopy', importAs='') self.exp.requirePsychopyLibs(['foo']) assert import_ in self.exp.requiredImports script = self.exp.writeScript() assert 'from psychopy import foo\n' in script def test_requirePsychopyLibs2(self): import_0 = RequiredImport(importName='foo', importFrom='psychopy', importAs='') import_1 = RequiredImport(importName='foo', importFrom='psychopy', importAs='') self.exp.requirePsychopyLibs(['foo', 'bar']) assert import_0 in self.exp.requiredImports assert import_1 in self.exp.requiredImports script = self.exp.writeScript() assert 'from psychopy import foo, bar\n' in script def test_requireImportAndPsychopyLib(self): import_0 = RequiredImport(importName='foo', importFrom='psychopy', importAs='') import_1 = RequiredImport(importName='bar', importFrom='', importAs='') self.exp.requirePsychopyLibs(['foo']) self.exp.requireImport('bar') assert import_0 in self.exp.requiredImports assert import_1 in self.exp.requiredImports script = self.exp.writeScript() print(script) assert 'from psychopy import foo\n' in script assert 'import bar\n' in script class TestRunOnce(): def setup_method(self): from psychopy.experiment import exports self.buff = exports.IndentingBuffer() def _doSingleTest(self, code): self.buff.writeOnceIndentedLines(code) assert code in self.buff._writtenOnce script = self.buff.getvalue() assert code + '\n' in script def test_runOnceSingleLine(self): self._doSingleTest('foo bar baz') def test_runOnceMultiLine(self): self._doSingleTest('foo bar baz\nbla bla bla') def test_runOnceMultipleStatements(self): code_0 = 'foo bar code0' self.buff.writeOnceIndentedLines(code_0) code_1 = 'bla bla code1' self.buff.writeOnceIndentedLines(code_1) assert code_0 in self.buff._writtenOnce assert code_1 in self.buff._writtenOnce script = self.buff.getvalue() assert (code_0 + '\n' + code_1 + '\n') in script def test_repeatedInsert(self): code = 'uniqueBlah' self.buff.writeOnceIndentedLines(code) # write it twice self.buff.writeOnceIndentedLines(code) # check it appears only once script = self.buff.getvalue() assert script.count(code) == 1
16,508
Python
.py
322
40.92236
123
0.617625
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,502
test_base_routine.py
psychopy_psychopy/psychopy/tests/test_experiment/test_routines/test_base_routine.py
from pathlib import Path import pytest from psychopy import experiment def _make_minimal_experiment(obj): """ Make a minimal experiment with just one routine, the same class as the current standalone routine but with all default params. """ # Skip whole test if required attributes aren't present if not hasattr(obj, "rt"): pytest.skip() # Make blank experiment exp = experiment.Experiment() # Create instance of this component with all default params rtClass = type(obj.rt) rt = rtClass(exp=exp, name=f"test{rtClass.__name__}") exp.addStandaloneRoutine(rt.name, rt) exp.flow.addRoutine(rt, 0) # Return experiment, routine and component return rt, exp class _TestBaseStandaloneRoutinesMixin: def test_icons(self): """Check that routine has icons for each app theme""" # Pathify icon file path icon = Path(self.rt.iconFile) # Get paths for each theme files = [ icon.parent / "light" / icon.name, icon.parent / "dark" / icon.name, icon.parent / "classic" / icon.name, ] # Check that each path is a file for file in files: assert file.is_file() def test_params_used(self): # Make minimal experiment just for this test rt, exp = _make_minimal_experiment(self) # Try with PsychoPy and PsychoJS for target in ("PsychoPy", "PsychoJS"): ## Skip PsychoJS until can write script without saving if target == "PsychoJS": continue # Skip unimplemented targets if target not in rt.targets: continue # Compile script script = exp.writeScript(target=target) # Check that the string value of each param is present in the script experiment.utils.scriptTarget = target # Iterate through every param for routine in exp.flow: for name, param in experiment.getInitVals(routine.params, target).items(): # Conditions to skip... if not param.direct: # Marked as not direct continue if any(name in depend['param'] for depend in routine.depends): # Dependent on another param continue # Check that param is used assert str(param) in script, ( f"Value {param} of <psychopy.experiment.params.Param: val={param.val}, valType={param.valType}> " f"in {type(rt).__name__} not found in {target} script." ) def testDeviceClassRefs(self): """ Check that any references to device classes in this Routine object point to classes which exist. """ # skip test if this element doesn't point to any hardware class if not hasattr(self.rt, "deviceClasses"): pytest.skip() return # get device manager from psychopy.hardware import DeviceManager # iterate through device classes for deviceClass in self.rt.deviceClasses: # resolve any aliases deviceClass = DeviceManager._resolveAlias(deviceClass) # try to import class DeviceManager._resolveClassString(deviceClass) class _TestDisabledMixin: def test_disabled_default_val(self): """ Test that routines created with default params are not disabled """ # Make minimal experiment just for this test rt, exp = _make_minimal_experiment(self) # Check whether it can be disabled assert 'disabled' in rt.params, ( f"{type(rt).__name__} does not have a 'disabled' attribute." ) # Check that disabled defaults to False assert rt.params['disabled'].val is False, f"{type(rt).__name__} is defaulting to disabled." def test_code_muting(self): """ Test that routines are only written when enabled and targets match. """ # Make minimal experiment just for this test rt, exp = _make_minimal_experiment(self) # Write experiment and check that routine is written pyScript = exp.writeScript(target="PsychoPy") if "PsychoPy" in type(rt).targets: assert rt.name in pyScript, ( f"{type(rt).__name__} not found in compiled Python script when enabled and PsychoPy in targets." ) else: assert rt.name not in pyScript, ( f"{type(rt).__name__} found in compiled Python script when enabled but PsychoPy not in targets." ) # ## disabled until js can compile without saving # jsScript = exp.writeScript(target="PsychoJS") # if "PsychoJS" in type(rt).targets: # assert rt.name in jsScript, ( # f"{type(rt).__name__} not found in compiled Python script when enabled and PsychoJS in targets." # ) # else: # assert rt.name not in jsScript, ( # f"{type(rt).__name__} found in compiled Python script when enabled but PsychoJS not in targets." # ) # Disable routine then do same tests but assert not present rt.params['disabled'].val = True pyScript = exp.writeScript(target="PsychoPy") if "PsychoPy" in type(rt).targets: assert rt.name not in pyScript, ( f"{type(rt).__name__} found in compiled Python script when disabled but PsychoPy in targets." ) else: assert rt.name not in pyScript, ( f"{type(rt).__name__} found in compiled Python script when disabled and PsychoPy not in targets." ) # ## disabled until js can compile without saving # jsScript = exp.writeScript(target="PsychoJS") # if "PsychoJS" in type(rt).targets: # assert rt.name not in jsScript, ( # f"{type(rt).__name__} found in compiled Python script when disabled but PsychoJS in targets." # ) # else: # assert rt.name not in jsScript, ( # f"{type(rt).__name__} found in compiled Python script when disabled and PsychoJS not in targets." # )
6,396
Python
.py
141
34.765957
121
0.596924
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,503
test_standalone_routines.py
psychopy_psychopy/psychopy/tests/test_experiment/test_routines/test_standalone_routines.py
import pytest from pathlib import Path from psychopy import experiment @pytest.mark.stdroutines class TestStandaloneRoutines: @classmethod def setup_class(cls): cls.routines = experiment.getAllStandaloneRoutines() # Make basic experiments with one of each standalone routine cls.expPy = experiment.Experiment() cls.expJS = experiment.Experiment() def setup_method(self): """This setup is done for each test individually """ pass def teardown_method(self): pass def test_writing(self): # Test both python and JS for target, exp in {"PsychoPy": self.expPy, "PsychoJS": self.expJS}.items(): for name, routine in self.routines.items(): rt = routine(exp) exp.addStandaloneRoutine(name, rt) exp.flow.addRoutine(rt, 0) # Compile exp.writeScript(target=target) # Remove routines for name, routine in exp.routines.copy().items(): exp.flow.removeComponent(routine) del exp.routines[name]
1,124
Python
.py
30
28.266667
84
0.630515
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,504
test_PhotodiodeValidationRoutine.py
psychopy_psychopy/psychopy/tests/test_experiment/test_routines/test_PhotodiodeValidationRoutine.py
from . import _TestDisabledMixin, _TestBaseStandaloneRoutinesMixin from psychopy import experiment from psychopy.experiment.routines.photodiodeValidator import PhotodiodeValidatorRoutine class TestEyetrackerCalibrationRoutine(_TestBaseStandaloneRoutinesMixin, _TestDisabledMixin): def setup_method(self): self.exp = experiment.Experiment() self.rt = PhotodiodeValidatorRoutine(exp=self.exp, name="testPhotodiodeValidatorRoutine")
451
Python
.py
7
60.428571
97
0.841986
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,505
test_EyetrackerCalibrationRoutine.py
psychopy_psychopy/psychopy/tests/test_experiment/test_routines/test_EyetrackerCalibrationRoutine.py
from . import _TestDisabledMixin, _TestBaseStandaloneRoutinesMixin from psychopy import experiment from psychopy.experiment.routines.eyetracker_calibrate import EyetrackerCalibrationRoutine class TestEyetrackerCalibrationRoutine(_TestBaseStandaloneRoutinesMixin, _TestDisabledMixin): def setup_method(self): self.exp = experiment.Experiment() self.rt = EyetrackerCalibrationRoutine(exp=self.exp, name="testEyetrackerCalibrationRoutine")
459
Python
.py
7
61.428571
101
0.842222
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,506
test_all_routines.py
psychopy_psychopy/psychopy/tests/test_experiment/test_routines/test_all_routines.py
from . import _TestBaseStandaloneRoutinesMixin, _TestDisabledMixin from psychopy import experiment import inspect class _Generic(_TestBaseStandaloneRoutinesMixin, _TestDisabledMixin): def __init__(self, rtClass): self.exp = experiment.Experiment() self.rt = rtClass(exp=self.exp, name=f"test{rtClass.__name__}") def test_all_standalone_routines(): for rtName, rtClass in experiment.getAllStandaloneRoutines().items(): # Make a generic testing object for this component tester = _Generic(rtClass) # Run each method from _TestBaseComponentsMixin on tester for attr, meth in _TestBaseStandaloneRoutinesMixin.__dict__.items(): if inspect.ismethod(meth): meth(tester) # Run each method from _TestBaseComponentsMixin on tester for attr, meth in _TestDisabledMixin.__dict__.items(): if inspect.ismethod(meth): meth(tester)
948
Python
.py
19
41.947368
76
0.695135
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,507
test_DlgFromDictWx.py
psychopy_psychopy/psychopy/tests/test_gui/test_DlgFromDictWx.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import OrderedDict from psychopy.gui.wxgui import DlgFromDict import pytest @pytest.mark.needs_wx class TestDlgFromDictWx: def setup_method(self): self.d = dict( participant='000', handedness=['r', 'l'], exp_type=['foo', 'bar'], exp_version='2017-01-02') self.od = OrderedDict( [('participant', '000'), ('handedness', ['r', 'l']), ('exp_type', ['foo', 'bar']), ('exp_version', '2017-01-02')]) self.title = 'Experiment' def test_title(self): dlg = DlgFromDict(self.d, title=self.title, show=False) assert dlg.Title == self.title def test_sort_keys_true(self): dlg = DlgFromDict(self.d, sortKeys=True, show=False) keys = sorted(self.d) assert keys == dlg._keys def test_sort_keys_false(self): dlg = DlgFromDict(self.d, sortKeys=False, show=False) keys = list(self.d) assert keys == dlg._keys def test_copy_dict_true(self): dlg = DlgFromDict(self.d, copyDict=True, show=False) assert self.d is not dlg.dictionary def test_copy_dict_false(self): dlg = DlgFromDict(self.d, copyDict=False, show=False) assert self.d is dlg.dictionary def test_order_list(self): order = ['exp_type', 'participant', 'handedness', 'exp_version'] # Be certain we will actually request a different order # further down. assert order != list(self.od) dlg = DlgFromDict(self.od, order=order, show=False) assert dlg.inputFieldNames == order def test_order_tuple(self): order = ('exp_type', 'participant', 'handedness', 'exp_version') # Be certain we will actually request a different order # further down. assert list(order) != list(self.od) dlg = DlgFromDict(self.od, order=order, show=False) assert dlg.inputFieldNames == list(order) def test_fixed(self): fixed = 'exp_version' dlg = DlgFromDict(self.d, fixed=fixed, show=False) field = dlg.inputFields[dlg.inputFieldNames.index(fixed)] assert field.Enabled is False def test_tooltips(self): tip = dict(participant='Tooltip') dlg = DlgFromDict(self.d, tip=tip, show=False) field = dlg.inputFields[dlg.inputFieldNames.index('participant')] assert field.ToolTip.GetTip() == tip['participant'] if __name__ == '__main__': cls = TestDlgFromDictWx() cls.setup_method() cls.test_fixed()
2,613
Python
.py
64
32.8125
73
0.619123
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,508
test_DlgFromDictQt.py
psychopy_psychopy/psychopy/tests/test_gui/test_DlgFromDictQt.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import OrderedDict from psychopy.gui.qtgui import DlgFromDict import pytest @pytest.mark.needs_qt class TestDlgFromDictQt: def setup_method(self): self.d = dict( participant='000', handedness=['r', 'l'], exp_type=['foo', 'bar'], exp_version='2017-01-02') self.od = OrderedDict( [('participant', '000'), ('handedness', ['r', 'l']), ('exp_type', ['foo', 'bar']), ('exp_version', '2017-01-02')]) self.title = 'Experiment' def test_title(self): dlg = DlgFromDict(self.d, title=self.title, show=False) assert dlg.windowTitle() == self.title def test_sort_keys_true(self): dlg = DlgFromDict(self.d, sortKeys=True, show=False) keys = list(self.d.copy().keys()) keys.sort() assert keys == dlg._keys def test_sort_keys_false(self): dlg = DlgFromDict(self.d, sortKeys=False, show=False) keys = list(self.d.copy().keys()) assert keys == dlg._keys def test_copy_dict_true(self): dlg = DlgFromDict(self.d, copyDict=True, show=False) assert self.d is not dlg.dictionary def test_copy_dict_false(self): dlg = DlgFromDict(self.d, copyDict=False, show=False) assert self.d is dlg.dictionary def test_order_list(self): order = ['exp_type', 'participant', 'handedness', 'exp_version'] # Be certain we will actually request a different order # further down. assert order != list(self.od.keys()) dlg = DlgFromDict(self.od, order=order, show=False) assert dlg.inputFieldNames == order def test_order_tuple(self): order = ('exp_type', 'participant', 'handedness', 'exp_version') # Be certain we will actually request a different order # further down. assert list(order) != list(self.od.keys()) dlg = DlgFromDict(self.od, order=order, show=False) assert dlg.inputFieldNames == list(order) def test_fixed(self): fixed = 'exp_version' dlg = DlgFromDict(self.d, fixed=fixed, show=False) field = dlg.inputFields[dlg.inputFieldNames.index(fixed)] assert field.isEnabled() is False def test_tooltips(self): tip = dict(participant='Tooltip') dlg = DlgFromDict(self.d, tip=tip, show=False) field = dlg.inputFields[dlg.inputFieldNames.index('participant')] assert field.toolTip() == tip['participant'] if __name__ == '__main__': cls = TestDlgFromDictQt() cls.setup_method() cls.test_fixed()
2,677
Python
.py
65
33.169231
73
0.616185
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,509
test_sound_pygame.py
psychopy_psychopy/psychopy/tests/test_sound/test_sound_pygame.py
"""Test PsychoPy sound.py using pygame backend; will fail if have already used pyo """ from psychopy import prefs, core, plugins prefs.hardware['audioLib'] = ['ptb', 'sounddevice'] import pytest import shutil from tempfile import mkdtemp from psychopy import sound #, microphone import numpy # py.test --cov-report term-missing --cov sound.py tests/test_sound/test_sound_pygame.py from psychopy.tests.utils import TESTS_PATH, TESTS_DATA_PATH @pytest.mark.needs_sound class TestSoundPlay: @classmethod def setup_class(self): self.contextName='ptb' self.tmp = mkdtemp(prefix='psychopy-tests-sound-play') @classmethod def teardown_class(self): if hasattr(self, 'tmp'): shutil.rmtree(self.tmp, ignore_errors=True) def test_init(self): for note in ['A', 440, '440', [1,2,3,4], numpy.array([1,2,3,4])]: sound.Sound(note, secs=.1) with pytest.raises(ValueError): sound.Sound('this is not a file name') with pytest.raises(ValueError): sound.Sound(-1) with pytest.raises(ValueError): sound.Sound(440, secs=-1) with pytest.raises(ValueError): sound.Sound(440, secs=0) with pytest.raises(DeprecationWarning): sound.setaudioLib('foo') points = 100 snd = numpy.ones(points) / 20 #testFile = os.path.join(self.tmp, 'green_48000.wav') #r, d = wavfile.read(testFile) #assert r == 48000 #assert len(d) == 92160 #s = sound.Sound(testFile) def test_play(self): s = sound.Sound(secs=0.1) s.play() core.wait(s.getDuration()+.1) # allows coverage of _onEOS s.play(loops=1) core.wait(s.getDuration()*2+.1) s.play(loops=-1) s.stop() def test_methods(self): s = sound.Sound(secs=0.1) v = s.getVolume() assert v == 1 assert s.setVolume(0.5) == 0.5 #assert s.setLoops(2) == 2
1,998
Python
.py
55
29
88
0.624029
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,510
test_sound.py
psychopy_psychopy/psychopy/tests/test_sound/test_sound.py
"""Test PsychoPy sound.py using pygame backend; will fail if have already used pyo """ from psychopy import prefs, core, plugins prefs.hardware['audioLib'] = ['ptb', 'sounddevice'] import pytest import shutil from tempfile import mkdtemp from psychopy import sound #, microphone import numpy # py.test --cov-report term-missing --cov sound.py tests/test_sound/test_sound_pygame.py from psychopy.tests.utils import TESTS_PATH, TESTS_DATA_PATH @pytest.mark.needs_sound class TesSounds: @classmethod def setup_class(self): self.contextName='ptb' self.tmp = mkdtemp(prefix='psychopy-tests-sound') @classmethod def teardown_class(self): if hasattr(self, 'tmp'): shutil.rmtree(self.tmp, ignore_errors=True) def test_init(self): for note in ['A', 440, '440', [1,2,3,4], numpy.array([1,2,3,4])]: sound.Sound(note, secs=.1) with pytest.raises(ValueError): sound.Sound('this is not a file name') with pytest.raises(ValueError): sound.Sound(-1) with pytest.raises(ValueError): sound.Sound(440, secs=-1) with pytest.raises(ValueError): sound.Sound(440, secs=0) with pytest.raises(DeprecationWarning): sound.setaudioLib('foo') points = 100 snd = numpy.ones(points) / 20 #testFile = os.path.join(self.tmp, 'green_48000.wav') #r, d = wavfile.read(testFile) #assert r == 48000 #assert len(d) == 92160 #s = sound.Sound(testFile) def test_play(self): s = sound.Sound(secs=0.1) s.play() core.wait(s.getDuration()+.1) # allows coverage of _onEOS s.play(loops=1) core.wait(s.getDuration()*2+.1) s.play(loops=-1) s.stop() def test_methods(self): s = sound.Sound(secs=0.1) v = s.getVolume() assert v == 1 assert s.setVolume(0.5) == 0.5 #assert s.setLoops(2) == 2
1,989
Python
.py
55
28.836364
88
0.622789
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,511
test_audioclip.py
psychopy_psychopy/psychopy/tests/test_sound/test_audioclip.py
"""Tests for the `AudioClip` class. """ import os from tempfile import mkdtemp import pytest import numpy as np import psychopy from psychopy.sound import ( AudioClip, AUDIO_CHANNELS_STEREO, AUDIO_CHANNELS_MONO, SAMPLE_RATE_96kHz, SAMPLE_RATE_48kHz, SAMPLE_RATE_16kHz) @pytest.mark.audioclip def test_audioclip_create(): """Create an audio clip object and see if the properties are correct. Basic stress test to check if we get the value we expect. """ nSamples = 1024 rates = (SAMPLE_RATE_16kHz, SAMPLE_RATE_48kHz, SAMPLE_RATE_96kHz) for samplesRateHz in rates: duration = nSamples / float(samplesRateHz) for nChannels in (AUDIO_CHANNELS_MONO, AUDIO_CHANNELS_STEREO): audioClip = AudioClip( samples=np.zeros((nSamples, nChannels)), sampleRateHz=samplesRateHz) # check if the number of channels is correctly specified assert audioClip.channels == nChannels # check if the computed duration makes sense given the sample rate assert np.isclose(audioClip.duration, duration) # check boolean properties for channels if audioClip.channels == AUDIO_CHANNELS_MONO: assert audioClip.isMono # should be the same if mono already monoClip = audioClip.asMono() assert np.allclose(monoClip.samples, audioClip.samples) elif audioClip.channels == AUDIO_CHANNELS_STEREO: assert audioClip.isStereo # set converting to mono monoClip = audioClip.asMono() # make the clip mono inplace audioClip = audioClip.asMono(copy=False) # check if samples are the same assert np.allclose(monoClip.samples, audioClip.samples) @pytest.mark.audioclip def test_audioclip_synth(): """Test `AudioClip` static methods for sound generation. Just check if the sounds created give back data structured as expected. Not testing if the contents are correctly generated (yet). """ duration = 0.25 # quarter second long for all generated sounds rates = (SAMPLE_RATE_16kHz, SAMPLE_RATE_48kHz, SAMPLE_RATE_96kHz) # test different sample rates and channels for sampleRateHz in rates: for nChannels in (AUDIO_CHANNELS_MONO, AUDIO_CHANNELS_STEREO): # test white noise generation whiteNoise = AudioClip.whiteNoise( duration=duration, sampleRateHz=sampleRateHz, channels=nChannels ) assert whiteNoise.channels == nChannels assert np.isclose(whiteNoise.duration, duration) # test silence silence = AudioClip.silence( duration=duration, sampleRateHz=sampleRateHz, channels=nChannels ) assert silence.channels == nChannels assert np.isclose(silence.duration, duration) # test sine wave sineWave = AudioClip.sine( duration=duration, freqHz=440, gain=1.0, sampleRateHz=sampleRateHz, channels=nChannels ) assert sineWave.channels == nChannels assert np.isclose(sineWave.duration, duration) # test sine wave squareWave = AudioClip.square( duration=duration, freqHz=440, dutyCycle=0.5, gain=1.0, sampleRateHz=sampleRateHz, channels=nChannels ) assert squareWave.channels == nChannels assert np.isclose(squareWave.duration, duration) # test sine wave sawtoothWave = AudioClip.sawtooth( duration=duration, freqHz=440, peak=1.0, gain=1.0, sampleRateHz=sampleRateHz, channels=nChannels ) assert sawtoothWave.channels == nChannels assert np.isclose(sawtoothWave.duration, duration) @pytest.mark.audioclip def test_audioclip_attrib(): """Test `AudioClip` attribute setters and getters. Tests attributes `samples`, `sampleRateHz`, `duration`, and `gain()`. """ # generate an audio clip using a sine wave originalDuration = 1.0 originalSampleRateHz = SAMPLE_RATE_48kHz audioClip = AudioClip.sine( duration=originalDuration, sampleRateHz=originalSampleRateHz, gain=0.8 ) # check if changing the sample rate results in a change in duration audioClip.sampleRateHz = SAMPLE_RATE_16kHz # should compute as longer as the same number of samples being sampled # slower should result in a longer duration assert audioClip.duration > originalDuration # check if the change in duration has the correct ratio given the new rate assert np.isclose(audioClip.duration, SAMPLE_RATE_48kHz / SAMPLE_RATE_16kHz) # check if setting samples works, just halve the number of samples and check # if the new duration is half as long audioClip.sampleRateHz = SAMPLE_RATE_48kHz # reset trimAt = int(audioClip.samples.shape[0] / 2.0) audioClip.samples = audioClip.samples[:trimAt, :] assert np.isclose(originalDuration / 2.0, audioClip.duration) # test if gain works, for our original data, not value should be above 0.8 assert np.max(audioClip.samples) <= 0.81 and \ np.min(audioClip.samples) >= -0.81 # apply gain to max and retest audioClip.gain(0.2) # 20% increase in gain assert np.max(audioClip.samples) <= 1.0 and \ np.min(audioClip.samples) >= -1.0 # give bad value to gain for the channel caughtChannelValueError = False try: audioClip.gain(1.0, channel=2) except ValueError: caughtChannelValueError = True assert caughtChannelValueError, \ "Failed to catch error be specifying wrong number to `channel` param " \ "in `.gain()`." @pytest.mark.audioclip def test_audioclip_concat(): """Test combining audio clips together. """ # durations to use for each segment dur1, dur2, dur3 = 0.2, 0.1, 0.7 totalDur = sum([dur1, dur2, dur3]) # create a bunch of clips to join clip1 = AudioClip.silence(duration=dur2, sampleRateHz=SAMPLE_RATE_48kHz) clip2 = AudioClip.whiteNoise(duration=dur1, sampleRateHz=SAMPLE_RATE_48kHz) clip3 = AudioClip.sine(duration=dur3, sampleRateHz=SAMPLE_RATE_48kHz) # concatenate clips using the `+` operator newClip1 = clip1 + clip2 + clip3 # check the new duration assert np.isclose(newClip1.duration, totalDur) assert np.isclose(newClip1.samples.shape[0], SAMPLE_RATE_48kHz) # do the same using the append() method newClip2 = (clip1.copy()).append(clip2).append(clip3) assert np.isclose(newClip2.duration, totalDur) assert np.isclose(newClip2.samples.shape[0], SAMPLE_RATE_48kHz) # assert that these two methods do the same thing assert np.allclose(newClip1.samples, newClip2.samples) # test copy newClip3 = clip1.copy() assert np.allclose(newClip3.samples, clip1.samples) # test inplace originalObjectId = id(newClip3) newClip3 += clip2 newClip3 += clip3 # make sure the object is the same in this case assert id(newClip3) == originalObjectId # check if samples are the same as above assert np.allclose(newClip3.samples, newClip2.samples) assert np.isclose(newClip3.samples.shape[0], SAMPLE_RATE_48kHz) # ensure that concatenation fails when sample rates are heterogeneous clipBad = AudioClip.whiteNoise( duration=dur1, sampleRateHz=SAMPLE_RATE_16kHz) caughtSampleRateError = False try: _ = clipBad + clip1 except AssertionError: caughtSampleRateError = True assert caughtSampleRateError, \ "Did not catch expected error when combining `AudioClip` objects " \ "with heterogeneous sample rates." # check what happens when clips are empty when combined emptyClip = AudioClip(np.zeros((0, 0)), sampleRateHz=SAMPLE_RATE_48kHz) # check if the empty clip contains the data from the other clipData = clip1.copy() newClip4 = emptyClip.append(clipData) assert np.allclose(clipData.samples, newClip4.samples) # other direction newClip4 = (clipData.copy()).append(emptyClip) assert np.allclose(clipData.samples, newClip4.samples) @pytest.mark.audioclip def test_audioclip_file(): """Test saving and loading audio samples from files. Checks the integrity of loaded data to ensure things are similar to the original. """ # generate samples np.random.seed(123456) rates = (SAMPLE_RATE_16kHz, SAMPLE_RATE_48kHz, SAMPLE_RATE_96kHz) for sampleRateHz in rates: for nChannels in (AUDIO_CHANNELS_MONO, AUDIO_CHANNELS_STEREO): audioClip = AudioClip.whiteNoise( duration=1.0, sampleRateHz=sampleRateHz, channels=nChannels) # create temporary folder for data testDir = mkdtemp(prefix='psychopy-tests-test_audioclip') # save as WAV file fname = os.path.join(testDir, 'test_audioclip_file.wav') audioClip.save(fname) # load it loadedAudioClip = AudioClip.load(fname) # check if they are the same, there is some error from quantization assert np.allclose( loadedAudioClip.samples, audioClip.samples, atol=1e-4) assert loadedAudioClip.channels == nChannels # save and load again loadedAudioClip.save(fname) loadedAudioClip2 = AudioClip.load(fname) # quantization applied, lossy but should be stable here assert np.allclose( loadedAudioClip.samples, loadedAudioClip2.samples) assert loadedAudioClip2.channels == nChannels @pytest.mark.audioclip def test_audioclip_rms(): """Test the RMS method of `AudioClip`. Just check if the function give back values that are correctly formatted given the input data. """ # test clip audioClipStereo = AudioClip.sine( duration=1.0, sampleRateHz=SAMPLE_RATE_48kHz, channels=AUDIO_CHANNELS_STEREO) # check error when channels are specified incorrectly caughtChannelParamError = False try: audioClipStereo.rms(-1) except AssertionError: caughtChannelParamError = True assert caughtChannelParamError, \ "Did not catch expected error related to specifying the wrong value " \ "when specifying `channel` to RMS." # should get back 2 values rmsResultStereo = audioClipStereo.rms() assert isinstance(rmsResultStereo, np.ndarray) and \ len(rmsResultStereo) == audioClipStereo.channels # make it mono, do it again audioClipMono = audioClipStereo.asMono() rmsResultMono = audioClipMono.rms() # should be float for one channel assert isinstance(rmsResultMono, np.float32) if __name__ == "__main__": # runs if this script is directly executed test_audioclip_create() test_audioclip_synth() test_audioclip_attrib() test_audioclip_concat() test_audioclip_file() test_audioclip_rms()
11,490
Python
.py
269
34
80
0.665293
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,512
test_hamming.py
psychopy_psychopy/psychopy/tests/test_sound/test_hamming.py
from psychopy.sound._base import apodize, HammingWindow from psychopy.constants import FINISHED from psychopy.exceptions import DependencyError import numpy as np import pytest import psychopy.sound.backend_ptb as ptb """ We need to test that the new block-by-block hamming works the same as the (simpler) method of adding the hamming window to the initial complete array (using the apodize function) """ sampleRate = 44100 thisFreq = 100 secs = 0.3 nSamples = int(secs * sampleRate) t = np.arange(0.0, 1.0, 1.0 / nSamples)*secs sndArray = np.sin(t*2*np.pi*thisFreq) plotting = False if plotting: import matplotlib.pyplot as plt @pytest.mark.needs_sound def test_HammingSmallBlock(): blockSize = 64 snd1 = apodize(sndArray, sampleRate) # is 5 ms sndDev = ptb.SoundPTB(thisFreq, sampleRate=sampleRate, secs=secs, hamming=True, blockSize=blockSize) snd2 = [] while sndDev.status != FINISHED: block = sndDev._nextBlock() snd2.extend(block) snd2 = np.array(snd2) if plotting: plt.subplot(2,1,1) plt.plot(snd1, 'b-') plt.plot(snd2, 'r--') plt.subplot(2,1,2) plt.plot(t, snd2[0:sampleRate*secs]-snd1) plt.show()
1,236
Python
.py
38
28.131579
75
0.70361
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,513
test_launch.py
psychopy_psychopy/psychopy/tests/test_iohub/test_launch.py
""" Test starting and stopping iohub server """ from psychopy.tests.test_iohub.testutil import startHubProcess, stopHubProcess def testDefaultServerLaunch(): """ """ io = startHubProcess() # check that a kb and mouse have been created keyboard=io.devices.keyboard mouse=io.devices.mouse exp = io.devices.experiment assert keyboard != None assert mouse != None assert exp != None stopHubProcess()
444
Python
.py
15
25.4
78
0.722353
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,514
test_event_get_and_clear.py
psychopy_psychopy/psychopy/tests/test_iohub/test_event_get_and_clear.py
""" Test getting events (experiment events only) and clearing event logic for 'global' and 'device' level event buffers. """ import pytest from psychopy.tests import skip_under_vm from psychopy.tests.test_iohub.testutil import startHubProcess, stopHubProcess, getTime @skip_under_vm def testGetEvents(): """ """ io = startHubProcess() exp = io.devices.experiment assert exp != None io.sendMessageEvent("Test Message 1") io.sendMessageEvent("Category Test", category="TEST") ctime = getTime() io.sendMessageEvent("Time Test",sec_time=ctime) events = io.getEvents() event_count = len(events) assert event_count == 3 m1, m2, m3 = events assert m1.text == "Test Message 1" assert m2.text == "Category Test" and m2.category == "TEST" assert m3.text == "Time Test" and m3.category == "" and m3.time == ctime assert len(io.getEvents()) == 0 assert len(exp.getEvents()) == 3 assert len(exp.getEvents()) == 0 stopHubProcess() @skip_under_vm def testGlobalBufferOnlyClear(): """ """ io = startHubProcess() exp = io.devices.experiment assert exp != None io.sendMessageEvent("Message Should Be Cleared Global Only") # clear only the global event buffer io.clearEvents(device_label=None) events = io.getEvents() assert len(events) == 0 exp_events = exp.getEvents() assert len(exp_events) == 1 assert exp_events[0].text == "Message Should Be Cleared Global Only" stopHubProcess() @skip_under_vm def testDeviceBufferOnlyClear(): """ """ io = startHubProcess() exp = io.devices.experiment assert exp != None io.sendMessageEvent("Message Should Be Cleared Device Level Only") exp.clearEvents() events = io.getEvents() assert len(events) == 1 assert events[0].text == "Message Should Be Cleared Device Level Only" exp_events = exp.getEvents() assert len(exp_events) == 0 stopHubProcess() @skip_under_vm def testAllBuffersClear(): """ """ io = startHubProcess() exp = io.devices.experiment assert exp != None io.sendMessageEvent("Message Should Be Cleared Everywhere") io.clearEvents('all') events = io.getEvents() assert len(events) == 0 exp_events = exp.getEvents() assert len(exp_events) == 0 stopHubProcess()
2,355
Python
.py
73
27.684932
87
0.684653
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,515
test_computer.py
psychopy_psychopy/psychopy/tests/test_iohub/test_computer.py
""" Test starting and stopping iohub server """ from psychopy.tests import skip_under_vm from psychopy.tests.test_iohub.testutil import startHubProcess, stopHubProcess, skip_not_completed from psychopy.iohub import Computer from psychopy.core import getTime @skip_under_vm class TestComputer(): """ Computer Device tests. """ @classmethod def setup_class(cls): """ setup any state specific to the execution of the given class (which usually contains tests). """ cls.io = startHubProcess() cls.computer = Computer @classmethod def teardown_class(cls): """ teardown any state that was previously setup with a call to setup_class. """ stopHubProcess() cls.io = None def test_getTime(self): ta = Computer.currentSec() tb = Computer.currentTime() tc = Computer.getTime() tp = getTime() assert ta <= tb <= tc <= tp assert tp - ta < 0.002 ta = getTime() tb = self.io.getTime() tc = self.io.getTime() tp = getTime() assert ta <= tb <= tc <= tp assert tp - ta < 0.01 def test_getProcesses(self): assert Computer.is_iohub_process is False assert Computer.psychopy_process == Computer.getCurrentProcess() assert Computer.current_process == Computer.psychopy_process assert Computer.iohub_process == Computer.getIoHubProcess() assert Computer.iohub_process.pid == Computer.iohub_process_id assert Computer.getCurrentProcess().is_running() assert Computer.getIoHubProcess().is_running() assert Computer.getIoHubProcess().parent() == Computer.getCurrentProcess() def test_processorCounts(self): get_puc = Computer.getProcessingUnitCount() cc = Computer.core_count puc = Computer.processing_unit_count assert puc == get_puc assert type(cc) is int assert type(puc) is int assert puc > 0 assert cc > 0 assert cc <= puc def test_procPriority(self): local_priority = Computer.getPriority() iohub_priority_rpc = self.io.getPriority() assert local_priority == 'normal' assert iohub_priority_rpc == 'normal' priority_level = Computer.setPriority('high', True) assert priority_level == 'high' priority_level = self.io.setPriority('high', True) assert priority_level == 'high' priority_level = Computer.setPriority('normal') assert priority_level == 'normal' priority_level = self.io.setPriority('normal') assert priority_level == 'normal' priority_level = Computer.setPriority('realtime') assert priority_level == 'realtime' priority_level = self.io.setPriority('realtime') assert priority_level == 'realtime' priority_level = Computer.setPriority('normal') assert priority_level == 'normal' priority_level = self.io.setPriority('normal') assert priority_level == 'normal' # >> Deprecated functionality tests psycho_proc = Computer.psychopy_process iohub_proc = Computer.getIoHubProcess() psycho_priority = Computer.getProcessPriority(psycho_proc) iohub_priority = Computer.getProcessPriority(iohub_proc) assert psycho_priority == 'normal' assert local_priority == psycho_priority assert iohub_priority == 'normal' assert iohub_priority == iohub_priority_rpc priority_change_ok = Computer.enableHighPriority() new_psycho_priority = Computer.getProcessPriority(psycho_proc) assert priority_change_ok == False or new_psycho_priority == 'high' priority_change_ok = self.io.enableHighPriority() new_io_priority = Computer.getProcessPriority(iohub_proc) assert priority_change_ok == False or new_io_priority == 'high' priority_change_ok = Computer.disableHighPriority() new_psycho_priority = Computer.getProcessPriority(psycho_proc) assert priority_change_ok == False or new_psycho_priority == 'normal' priority_change_ok = self.io.disableHighPriority() new_io_priority = Computer.getProcessPriority(iohub_proc) assert priority_change_ok == False or new_io_priority == 'normal' @skip_not_completed def test_procAffinity(self): pass
4,426
Python
.py
102
35.313725
98
0.663645
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,516
testutil.py
psychopy_psychopy/psychopy/tests/test_iohub/testutil.py
import pytest __author__ = 'Sol' import psutil, sys from psychopy.iohub import launchHubServer, Computer getTime = Computer.getTime from psychopy.tests import skip_under_vm @skip_under_vm def startHubProcess(): io = launchHubServer() assert io != None io_proc = Computer.getIoHubProcess() io_proc_pid = io_proc.pid assert io_proc != None and io_proc_pid > 0 return io @skip_under_vm def stopHubProcess(): from psychopy.iohub.client import ioHubConnection io = ioHubConnection.getActiveConnection() assert io != None io_proc = Computer.getIoHubProcess() io_proc_pid = io_proc.pid assert io_proc != None and psutil.pid_exists(io_proc_pid) # Stop iohub server, ending process. io.quit() # Enure iohub proc has terminated. assert not psutil.pid_exists(io_proc_pid) assert ioHubConnection.getActiveConnection() is None skip_not_completed = pytest.mark.skipif("True", reason="Cannot be tested until the test is completed.") skip_under_windoz = pytest.mark.skipif("sys.platform == 'win32'", reason="Cannot be tested under Windoz.") skip_under_linux = pytest.mark.skipif("sys.platform.startswith('linux')", reason="Cannot be tested under Linux.") skip_under_osx = pytest.mark.skipif("sys.platform == 'darwin'", reason="Cannot be tested under macOS.")
1,486
Python
.py
35
34.514286
94
0.662011
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,517
test_keyboard.py
psychopy_psychopy/psychopy/tests/test_iohub/test_keyboard.py
""" Test starting and stopping iohub server """ from psychopy.tests import skip_under_vm from psychopy.tests.test_iohub.testutil import startHubProcess, stopHubProcess @skip_under_vm class TestKeyboard(): """ Keyboard Device tests. Starts iohub server, runs test set, then stops iohub server. Since there is no way to currently automate keyboard event generation in a way that would actually test the iohub keyboard event processing logic, each test simply calls one of the device methods / properties and checks that the return type is as expected. Each method is called with no args; that should be improved. Following methods are not yet tested: addFilter enableFilters getConfiguration getCurrentDeviceState getModifierState removeFilter resetFilter resetState """ @classmethod def setup_class(cls): """ setup any state specific to the execution of the given class (which usually contains tests). """ cls.io = startHubProcess() cls.keyboard = cls.io.devices.keyboard @classmethod def teardown_class(cls): """ teardown any state that was previously setup with a call to setup_class. """ stopHubProcess() cls.io = None cls.keyboard = None def test_getEvents(self): evts = self.keyboard.getEvents() assert type(evts) in [list, tuple] def test_getKeys(self): evts = self.keyboard.getKeys() assert type(evts) in [list, tuple] def test_getPresses(self): evts = self.keyboard.getPresses() assert type(evts) in [list, tuple] def test_getReleases(self): evts = self.keyboard.getReleases() assert type(evts) in [list, tuple] def test_waitForKeys(self): evts = self.keyboard.waitForKeys(maxWait=0.05) assert type(evts) in [list, tuple] def test_waitForPresses(self): evts = self.keyboard.waitForPresses(maxWait=0.05) assert type(evts) in [list, tuple] def test_waitForReleases(self): evts = self.keyboard.waitForReleases(maxWait=0.05) assert type(evts) in [list, tuple] def test_clearEvents(self): self.keyboard.clearEvents() def test_state(self): kbstate = self.keyboard.state assert type(kbstate) is dict def test_reporting(self): reporting_state = self.keyboard.reporting assert reporting_state is True self.keyboard.reporting = False assert self.keyboard.isReportingEvents() is False self.keyboard.reporting = True assert self.keyboard.isReportingEvents() is True
2,744
Python
.py
72
30.402778
79
0.670939
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,518
test_Color.py
psychopy_psychopy/psychopy/tests/test_colors/test_Color.py
from psychopy import colors, visual, event, logging def test_readable(): """ Test method of Color which returns readable pairing for the given color. Currently no validation - just making sure the method runs without error. Commented out sections are for local use when previewing the colors to confirm, anecdotally, that they're readable. """ # win = visual.Window(size=(100, 100)) # text = visual.TextBox2( # win, # text="a", # units="norm", # size=(2, 2), # letterHeight=1, # fillColor=None # ) cases = [ {'val': (0, 0.00, 1.00, 0.50), 'space': "hsva"} ] # also test all named colors for name in colors.colorNames: cases.append( {'val': name, 'space': "named"} ) for case in cases: # create color object col = colors.Color(case['val'], space=case['space']) # get its contrasting color contr = col.getReadable() # # for local use: preview the color pairing on some text # win.color = col # text.color = contr # while not event.getKeys(): # text.draw() # win.flip()
1,200
Python
.py
36
26.75
77
0.583261
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,519
conftest.py
psychopy_psychopy/psychopy/tests/test_app/conftest.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 noet: """ py.test fixtures to create an instance of PsychoPyApp for testing """ import pytest from packaging.version import Version import psychopy.app as app from PIL import Image Image.DEBUG = False if Version(pytest.__version__) < Version('5'): class VersionError(Exception): pass raise VersionError("PsychoPy test suite requires pytest>=5.4") # this method seems to work on at least Pytest 5.4+ @pytest.mark.needs_wx @pytest.fixture(scope='session') def get_app(request): # set_up app.startApp(showSplash=False, testMode=True) # yield, to let all tests within the scope run _app = app.getAppInstance() yield _app # teasr_down: then clear table at the end of the scope app.quitApp() if __name__ == '__main__': pytest.main()
952
Python
.py
29
29.758621
92
0.70472
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,520
test_command_line.py
psychopy_psychopy/psychopy/tests/test_app/test_command_line.py
""" Test that PsychoPy can be initialised from the command line with all API options """ import sys import time from pathlib import Path from psychopy import core from psychopy.tests import utils def test_version_query(): """ Check that we can call the PsychoPy app with -v to get the version """ from psychopy import __version__ as ppyVersion cases = [ "-v", "--version", ] for case in cases: stderr = core.shellCall( [sys.executable, "-m", "psychopy.app", case], stderr=True ) assert ppyVersion in "\n".join(stderr) def test_help_query(): """ Check that we can call the PsychoPy app with -h to get the help text """ cases = [ "-h", "--help", ] for case in cases: stderr = core.shellCall( [sys.executable, "-m", "psychopy.app", case], stderr=True ) assert "PsychoPy" in "\n".join(stderr) def test_direct_run(): """ Check that we can directly run files by invoking psychopy.app with -x """ cases = [ {'tag': "-x", 'files': [str(Path(utils.TESTS_DATA_PATH) / "ghost_stroop.psyexp")]}, {'tag': "-x", 'files': [str(Path(utils.TESTS_DATA_PATH) / "test_basic_run.py")]}, {'tag': "-x", 'files': [ str(Path(utils.TESTS_DATA_PATH) / "ghost_stroop.psyexp"), str(Path(utils.TESTS_DATA_PATH) / "test_basic_run.py") ]}, ] # include --direct too for case in cases.copy(): case['tag'] = "--direct" cases.append(case) # run all cases for case in cases: stderr = core.shellCall( [sys.executable, "-m", "psychopy.app", case['tag']] + case['files'], stderr=True )
1,787
Python
.py
59
23.508475
91
0.571429
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,521
test_speed.py
psychopy_psychopy/psychopy/tests/test_app/test_speed.py
import sys import numpy from pathlib import Path from psychopy.tests.utils import TESTS_DATA_PATH, RUNNING_IN_VM import shutil from tempfile import mkdtemp import pytest import time from ... import logging class TestSpeed: def setup_method(self): self.tmp_dir = mkdtemp(prefix='psychopy-tests-app') # skip speed tests under vm if RUNNING_IN_VM: pytest.skip() def teardown_method(self): shutil.rmtree(self.tmp_dir, ignore_errors=True) @pytest.mark.usefixtures("get_app") def test_theme_change(self, get_app): """ Tests how fast the app can update its theme """ runs = [] for run in range(3): # Close any open frames for frame in get_app._allFrames: frame().Close() # Set theme get_app.theme = "PsychopyLight" # Open one of each frame get_app.newBuilderFrame() get_app.showCoder() get_app.newRunnerFrame() # Open some example files get_app.builder.fileOpen(filename=str( Path(TESTS_DATA_PATH) / "test_loops" / "testLoopsBlocks.psyexp" )) get_app.coder.fileOpen(filename=str( Path(TESTS_DATA_PATH) / "correctScript" / "python" / "correctKeyboardComponent.py" )) get_app.coder.fileOpen(filename=str( Path(TESTS_DATA_PATH) / "correctScript" / "js" / "correctKeyboardComponent.js" )) # Start timer start = time.time() # Change theme get_app.theme = "PsychopyDark" # Stop timer finish = time.time() # Store runtime runs.append(finish - start) # Check times avg = float(numpy.mean(runs)) # Log result logging.info(f"Average time to change theme: {avg} ({len(runs)} runs: {runs})") # <0.5 is the goal if avg >= 0.5: logging.warn( f"App took longer than expected to change theme, but not longer than is acceptable. Expected <0.4s, " f"got {avg}." ) # ...but anything <1 isn't worth failing the tests over assert avg < 1, ( f"App took longer than acceptable to change theme. Expected <0.4s, allowed <1s, got {avg}." ) @pytest.mark.usefixtures("get_app") def test_open_frame(self, get_app): # Close any open frames for frame in get_app._allFrames: frame().Close() # Set theme get_app.theme = "PsychopyLight" # Open one of each frame (to populate icon cache) get_app.newBuilderFrame() get_app.showCoder() get_app.newRunnerFrame() # Close frames again for frame in get_app._allFrames: frame().Close() # Open Builder frame start = time.time() get_app.newBuilderFrame() finish = time.time() dur = finish - start logging.info(f"Time to open builder frame: {dur}") # Check Builder frame load time assert dur < 10 # Open Coder frame start = time.time() get_app.showCoder() finish = time.time() dur = finish - start logging.info(f"Time to open coder frame: {dur}") # Check Coder frame load time assert dur < 10 # Open Runner frame start = time.time() get_app.newRunnerFrame() finish = time.time() dur = finish - start logging.info(f"Time to open runner frame: {dur}") # Check Runner frame load time assert dur < 10 def test_load_builder(self): # Load Builder dur = self._load_app("-b") logging.info(f"Time to open with -b tag: {dur}") # Check that it's within acceptable bounds assert dur < 10 def test_load_coder(self): # Load Coder dur = self._load_app("-c") logging.info(f"Time to open with -c tag: {dur}") # Check that it's within acceptable bounds assert dur < 10 def test_load_runner(self): # Load Runner dur = self._load_app("-r") logging.info(f"Time to with -r tag: {dur}") # Check that it's within acceptable bounds assert dur < 10 @staticmethod def _load_app(arg): # Test builder start = time.time() sys.argv.append(arg) from psychopy.app._psychopyApp import PsychoPyApp app = PsychoPyApp(0, testMode=True, showSplash=True) app.quit() finish = time.time() dur = finish - start return dur
4,701
Python
.py
132
26.106061
117
0.572464
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,522
test_BuilderFrame.py
psychopy_psychopy/psychopy/tests/test_app/test_builder/test_BuilderFrame.py
from os import path import shutil import py_compile from tempfile import mkdtemp import codecs import pytest import locale import time import psychopy.experiment from psychopy import prefs from psychopy.app.builder.dialogs import DlgComponentProperties from psychopy.experiment import Param # Jeremy Gray March 2011 # caveats when comparing files: # - dicts have no defined order, can load and save differently: use a # known-diff file to suppress boring errors. This situation was # addressed in 7e2c72a for stimOut by sorting the keys # - namespace.makeValid() can change var names from the orig demos, # but should not do so from a load-save-load because only the first # load should change things from psychopy.experiment.components.unknown import UnknownComponent allComponents = psychopy.experiment.getComponents(fetchIcons=False) import wx class Test_BuilderFrame(): """This test fetches all standard components and checks that, with default settings, they can be added to a Routine and result in a script that compiles """ def setup_method(self): self.here = path.abspath(path.dirname(__file__)) self.tmp_dir = mkdtemp(prefix='psychopy-tests-app') def teardown_method(self): shutil.rmtree(self.tmp_dir, ignore_errors=True) @pytest.mark.usefixtures("get_app") def test_BuilderFrame(self, get_app): """Tests of the Builder frame. We can call dialog boxes using a timeout (will simulate OK being pressed) """ builderView = get_app.newBuilderFrame() # self._app comes from requires_app expfile = path.join(prefs.paths['tests'], 'data', 'test001EntryImporting.psyexp') builderView.fileOpen(filename=expfile) builderView.setExperimentSettings(timeout=2000) builderView.isModified = False builderView.runFile() builderView.closeFrame() def _getCleanExp(self, app): """""" builder = app.newBuilderFrame() exp = builder.exp exp.addRoutine('testRoutine') testRoutine = exp.routines['testRoutine'] exp.flow.addRoutine(testRoutine, 0) return exp def _checkCompileWith(self, thisComp, app): """Adds the component to the current Routine and makes sure it still compiles """ filename = thisComp.params['name'].val+'.py' filepath = path.join(self.tmp_dir, filename) exp = self._getCleanExp(app) testRoutine = exp.routines['testRoutine'] testRoutine.addComponent(thisComp) #make sure the mouse code compiles # generate a script, similar to 'lastrun.py': buff = exp.writeScript() # is a StringIO object script = buff.getvalue() assert len(script) > 1500 # default empty script is ~2200 chars # save the script: f = codecs.open(filepath, 'w', 'utf-8') f.write(script) f.close() # compile the temp file to .pyc, catching error msgs (including no file at all): py_compile.compile(filepath, doraise=True) return filepath + 'c' def test_MessageDialog(self): """Test the message dialog """ from psychopy.app.dialogs import MessageDialog dlg = MessageDialog(message="Just a test", timeout=500) ok = dlg.ShowModal() assert ok == wx.ID_OK @pytest.mark.usefixtures("get_app") def test_ComponentDialogs(self, get_app): """Test the message dialog """ builderView = get_app.newBuilderFrame() # self._app comes from requires_app componsPanel = builderView.componentButtons for compBtn in list(componsPanel.compButtons): # simulate clicking the button for each component assert compBtn.onClick(timeout=500) builderView.isModified = False builderView.closeFrame() del builderView, componsPanel @pytest.mark.usefixtures("get_app") def test_param_validator(self, get_app): """Test the code validator for component parameters""" builderView = get_app.newBuilderFrame() # Make experiment with a component exp = self._getCleanExp(get_app) comp = UnknownComponent(exp, "testRoutine", "testComponent") exp.routines['testRoutine'].append(comp) # Define 'tykes' - combinations of values likely to cause an error if certain features aren't working tykes = [ {'fieldName': "brokenCode", 'param': Param(val="for + :", valType="code"), 'msg': "Python syntax error in field `{fieldName}`: {param.val}"}, # Make sure it's picking up clearly broken code {'fieldName': "variableDef", 'param': Param(val="visual = 1", valType="code"), 'msg': "Variable name $visual is in use (by Psychopy module). Try another name."}, {'fieldName': "correctAns", 'param': Param(val="'space'", valType="code"), 'msg': ""}, # Single-element lists should not cause warning ] for case in tykes: # Give each param a label case['param'].label = case['fieldName'] # Add each param to the component comp.params[case['fieldName']] = case['param'] # Test component dlg dlg = DlgComponentProperties( frame=builderView, element=comp, experiment=exp, timeout=500) # Does the message delivered by the validator match what is expected? for case in tykes: if case['msg']: assert case['msg'].format(**case) in dlg.warnings.messages, ( "Error for param {fieldName} with value `{val}` should include:\n" "'{msg}'\n" "but instead was:\n" "{actual}\n" ).format(**case, val=case['param'].val.format(**case), actual=dlg.warnings.messages) # Cleanup dlg.Destroy()
5,938
Python
.py
129
37.697674
202
0.654225
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,523
test_CompileFromBuilder.py
psychopy_psychopy/psychopy/tests/test_app/test_builder/test_CompileFromBuilder.py
import pytest import shutil from tempfile import mkdtemp import os """Each test class creates a context subclasses _baseVisualTest to run a series of tests on a single graphics context (e.g. pyglet with shaders) To add a new stimulus test use _base so that it gets tested in all contexts """ import psychopy from psychopy import experiment from psychopy.app import getAppInstance import psychopy.scripts.psyexpCompile as psyexpCompile import codecs from pathlib import Path keepFiles = False thisDir = Path(__file__).parent psychoRoot = Path(psychopy.__file__).parent demosDir = psychoRoot / 'demos' testsDataDir = psychoRoot/'tests/data' class Test_PsychoJS_from_Builder(): """Some tests just for the window - we don't really care about what's drawn inside it """ @pytest.mark.usefixtures("get_app") def setup_class(self): if keepFiles: self.temp_dir = Path.home() / "Desktop" / "tmp" else: self.temp_dir = Path(mkdtemp(prefix='psychopy-test_psychojs')) self.builderView = getAppInstance().newBuilderFrame() # self._app comes from requires_app def teardown_class(self): if not keepFiles: shutil.rmtree(self.temp_dir) def writeScript(self, exp, outFolder): script = exp.writeScript(expPath=outFolder, target="PsychoJS") with codecs.open(outFolder/'index.html', 'w', encoding='utf-8-sig') as f: f.write(script) def compileScript(self, infile=None, version=None, outfile=None): """ Compile script used to test whether JS modular files are written :param infile: psyexp file :param version: Version to use :param outfile: For testing JS filename :return: True """ psyexpCompile.compileScript(infile, version, outfile) return True def test_stroop(self): #load experiment exp = experiment.Experiment() exp.loadFromXML(demosDir/'builder'/'Experiments'/'stroop'/'stroop.psyexp') # try once packaging up the js libs exp.settings.params['JS libs'].val = 'remote' outFolder = self.temp_dir/'stroopJS_remote/html' os.makedirs(outFolder) self.writeScript(exp, outFolder) def test_blocked(self): # load experiment exp = experiment.Experiment() exp.loadFromXML(demosDir/'builder'/'Design Templates'/'randomisedBlocks'/'randomisedBlocks.psyexp') # try once packaging up the js libs exp.settings.params['JS libs'].val = 'packaged' outFolder = self.temp_dir/'blocked_packaged/html' os.makedirs(outFolder) self.writeScript(exp, outFolder) print("files in {}".format(outFolder)) def test_JS_script_output(self): # Load experiment exp = experiment.Experiment() exp.loadFromXML(demosDir/'builder'/'Experiments'/'stroop'/'stroop.psyexp') outFolder = self.temp_dir/'stroopJS_output/html' outFile = outFolder/'stroop.js' os.makedirs(outFolder) # Compile scripts assert(self.compileScript(infile=exp, version=None, outfile=str(outFile))) # Test whether files are written assert(os.path.isfile(os.path.join(outFolder, 'stroop.js'))) assert(os.path.isfile(os.path.join(outFolder, 'stroop-legacy-browsers.js'))) assert(os.path.isfile(os.path.join(outFolder, 'index.html'))) assert(os.path.isdir(os.path.join(outFolder, 'resources'))) def test_getHtmlPath(self): """Test retrieval of html path""" self.temp_dir = mkdtemp(prefix='test') fileName = os.path.join(self.temp_dir, 'testFile.psyexp') htmlPath = os.path.join(self.temp_dir, self.builderView.exp.htmlFolder) assert self.builderView._getHtmlPath(fileName) == htmlPath def test_getExportPref(self): """Test default export preferences""" assert self.builderView._getExportPref('on Sync') assert not self.builderView._getExportPref('on Save') assert not self.builderView._getExportPref('manually') with pytest.raises(ValueError): self.builderView._getExportPref('DoesNotExist') def test_onlineExtraResources(self): """Open an experiment with resources in the format of 2020.5 (i.e. broken with \\ and with .. at start)""" expFile = (testsDataDir / 'broken2020_2_5_resources/broken_resources.psyexp') exp = experiment.Experiment() exp.loadFromXML(expFile) resList = exp.settings.params['Resources'].val print(resList) assert type(resList) == list assert (not resList[0].startswith('..')) if __name__ == '__main__': cls = Test_PsychoJS_from_Builder() cls.setup_class() cls.test_stroop() cls.test_blocked() cls.test_JS_script_output() cls.test_onlineExtraResources() cls.teardown_class()
4,962
Python
.py
113
36.265487
107
0.66936
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,524
test_ComponentDialogs.py
psychopy_psychopy/psychopy/tests/test_app/test_builder/test_ComponentDialogs.py
import pytest from psychopy import experiment from psychopy.app.builder.dialogs import DlgCodeComponentProperties from psychopy.experiment.components.code import CodeComponent class TestComponentDialogs: def setup_method(self): # Create experiment self.exp = experiment.Experiment() self.exp.addRoutine( "testRoutine", experiment.routines.Routine("testRoutine", self.exp) ) @pytest.mark.usefixtures("get_app") def test_code_component_changed_marking(self, get_app): """ Tests that, when opening a Code component dialog, the correct tabs are marked based on the contents """ _nl = "\n" # Create frame frame = get_app.newBuilderFrame() # Define cases by which fields are populated, which tab should be open first and which tabs should be starred cases = [ # JS populated then py {'params': ["Begin JS Routine", "Each Frame"], 'first': "Begin Routine", 'starred': ["Begin Routine", "Each Frame"]}, # JS populated then both then py {'params': ["Begin JS Routine", "Each Frame", "Each JS Frame", "End Routine"], 'first': "Begin Routine", 'starred': ["Begin Routine", "Each Frame", "End Routine"]}, # Py populated then both then js {'params': ["Begin Routine", "Each Frame", "Each JS Frame", "End JS Routine"], 'first': "Begin Routine", 'starred': ["Begin Routine", "Each Frame", "End Routine"]}, # Py populated then js {'params': ["Begin Routine", "Each JS Frame"], 'first': "Begin Routine", 'starred': ["Begin Routine", "Each Frame"]}, # All populated {'params': ["Before Experiment", "Before JS Experiment", "Begin Experiment", "Begin JS Experiment", "Begin Routine", "Begin JS Routine", "Each Frame", "Each JS Frame", "End Routine", "End JS Routine", "End Experiment", "End JS Experiment"], 'first': "Before Experiment", 'starred': ["Before Experiment", "Begin Experiment", "Begin Routine", "Each Frame", "End Routine", "End Experiment"]}, # None populated {'params': [], 'first': "Begin Experiment", 'starred': []}, ] # For each case... for case in cases: # Create Code component comp = CodeComponent( exp=self.exp, parentName="testRoutine", codeType="Both" ) # Assign values from case for param in case['params']: comp.params[param].val = "x = 1" # Dummy code just so there's some valid content # Make dialog dlg = DlgCodeComponentProperties( frame=frame, element=comp, experiment=self.exp, timeout=200 ) # Check that correct tab is shown first pg = dlg.codeNotebook.GetCurrentPage() i = dlg.codeNotebook.FindPage(pg) tabLabel = dlg.codeNotebook.GetPageText(i) assert case['first'].lower() in tabLabel.lower(), ( f"Tab {case['first']} should be opened first when the following fields are populated:\n" f"{_nl.join(case['params'])}\n" f"Instead, first tab open was {tabLabel}" ) # Check that correct tabs are starred for i in range(dlg.codeNotebook.GetPageCount()): tabLabel = dlg.codeNotebook.GetPageText(i) populated = any(name.lower() in tabLabel.lower() for name in case['starred']) if populated: assert "*" in tabLabel, ( f"Tab '{tabLabel}' should include a * when the following fields are populated:\n" f"{_nl.join(case['params'])}" ) else: assert "*" not in tabLabel, ( f"Tab '{tabLabel}' should not include a * when the following fields are populated:\n" f"{_nl.join(case['params'])}" ) # Close frame frame.closeFrame()
4,356
Python
.py
91
34.472527
117
0.545796
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,525
test_RunnerFrame.py
psychopy_psychopy/psychopy/tests/test_app/test_runner/test_RunnerFrame.py
import sys import pytest import os import time from psychopy import prefs import wx from psychopy.app import psychopyApp class Test_RunnerFrame: """ This test opens Runner, and several processes. """ def setup_method(self): self.tempFile = os.path.join( prefs.paths['tests'], 'data', 'test001EntryImporting.psyexp') def _getRunnerView(self, app): runner = app.newRunnerFrame() runner.clearTasks() return runner @pytest.mark.usefixtures("get_app") def test_RunnerFrame(self, get_app): app = get_app app.showRunner() @pytest.mark.usefixtures("get_app") def test_addFile(self, get_app): runner = self._getRunnerView(get_app) runner.addTask(fileName=self.tempFile) assert runner.panel.expCtrl.FindItem(-1, self.tempFile) @pytest.mark.usefixtures("get_app") def test_removeTask(self, get_app): runner = self._getRunnerView(get_app) runner.removeTask(runner.panel.currentSelection) assert runner.panel.expCtrl.FindItem(-1, self.tempFile) == -1 @pytest.mark.usefixtures("get_app") def test_clearItems(self, get_app): runner = self._getRunnerView(get_app) runner.addTask(fileName=self.tempFile) runner.clearTasks() assert runner.panel.expCtrl.FindItem(-1, self.tempFile) == -1 @pytest.mark.usefixtures("get_app") def test_runLocal(self, get_app): """Run a local experiment file. Tests the `Job` module and expands coverage. """ if sys.platform == 'linux': # skip on GTK+, manually tested for now return runner = self._getRunnerView(get_app) runner.Raise() # get panel with controls runnerPanel = runner.panel # add task runner.addTask(fileName=self.tempFile) runner.panel.expCtrl.Select(0) # select only item # --- # Run a Builder experiment locally without interruption, check if the # UI is correctly updated. # --- # check button states before running the file assert runnerPanel.toolbar.buttons['runBtn'].Enabled, ( "Incorrect button state for `Runner.panel.runBtn` at start of " "experiment.") assert not runnerPanel.toolbar.buttons['stopBtn'].Enabled, ( "Incorrect button state for `Runner.panel.stopBtn` at start of " "experiment.") # issue a button click event to run the file wx.PostEvent( runnerPanel.toolbar.buttons['runBtn'].GetEventHandler(), wx.PyCommandEvent(wx.EVT_BUTTON.typeId, runnerPanel.toolbar.buttons['runBtn'].GetId()) ) # wait until the subprocess wakes up timeoutCounter = 0 while runnerPanel.scriptProcess is None: # give a minute to start, raise exception otherwise assert timeoutCounter < 6000, ( "Timeout starting subprocess. Process took too long to start.") time.sleep(0.01) timeoutCounter += 1 wx.YieldIfNeeded() # check button states during experiment assert not runnerPanel.toolbar.buttons['runBtn'].Enabled, ( "Incorrect button state for `runnerPanel.toolbar.buttons['runBtn']` " "during experiment.") assert runnerPanel.toolbar.buttons['stopBtn'].Enabled, ( "Incorrect button state for `runnerPanel.toolbar.buttons['stopBtn']` " "experiment.") # wait until the subprocess ends timeoutCounter = 0 while runnerPanel.scriptProcess is not None: # give a minute to stop, raise exception otherwise assert timeoutCounter < 6000, ( "Timeout stopping subprocess. Process took too long to end.") time.sleep(0.01) timeoutCounter += 1 wx.YieldIfNeeded() # check button states after running the file, make sure they are # correctly restored assert not runnerPanel.toolbar.buttons['stopBtn'].Enabled, ( "Incorrect button state for `runnerPanel.toolbar.buttons['stopBtn']` " "experiment.") # --- # Run a Builder experiment locally, but interrupt it to see how well # the UI can handle that. # --- runner.panel.expCtrl.Select(0) # again, start the process using the run event wx.PostEvent( runnerPanel.toolbar.buttons['runBtn'].GetEventHandler(), wx.PyCommandEvent(wx.EVT_BUTTON.typeId, runnerPanel.toolbar.buttons['runBtn'].GetId()) ) # wait until the subprocess wakes up timeoutCounter = 0 while runnerPanel.scriptProcess is None: assert timeoutCounter < 6000, ( "Timeout starting subprocess. Process took too long to start.") time.sleep(0.01) timeoutCounter += 1 wx.YieldIfNeeded() # kill the process a bit through it wx.PostEvent( runnerPanel.toolbar.buttons['stopBtn'].GetEventHandler(), wx.PyCommandEvent(wx.EVT_BUTTON.typeId, runnerPanel.toolbar.buttons['stopBtn'].GetId()) ) # wait until the subprocess ends timeoutCounter = 0 while runnerPanel.scriptProcess is not None: assert timeoutCounter < 6000, ( "Timeout stopping subprocess. Process took too long to end.") time.sleep(0.01) timeoutCounter += 1 wx.YieldIfNeeded() # check button states after running the file, make sure they are # correctly restored assert not runnerPanel.toolbar.buttons['stopBtn'].Enabled, ( "Incorrect button state for `runnerPanel.toolbar.buttons['stopBtn']` " "experiment.") runner.clearTasks() # clear task list
5,975
Python
.py
138
33.181159
82
0.625925
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,526
test_icons.py
psychopy_psychopy/psychopy/tests/test_app/test_themes/test_icons.py
import pytest from pathlib import Path from psychopy.app.themes import icons from psychopy.experiment.components.unknown import UnknownComponent class TestIcons: @pytest.mark.usefixtures("get_app") def test_button_icons(self, get_app): exemplars = [ # File open, 32px (icons.ButtonIcon("fileopen", size=32), icons.ButtonIcon("fileopen", size=32)), # Clear, 16px (icons.ButtonIcon("clear", size=32), icons.ButtonIcon("clear", size=32)), ] tykes = [ # File open, no size (icons.ButtonIcon("fileopen", size=32), icons.ButtonIcon("fileopen", size=32)), # File open, wrong size (icons.ButtonIcon("fileopen", size=48), icons.ButtonIcon("fileopen", size=48)), ] for case in exemplars + tykes: # Ensure that the underlying bitmap of each button is the same object assert case[0].bitmap is case[1].bitmap @pytest.mark.usefixtures("get_app") def test_component_icons(self, get_app): exemplars = [ # Unknown component, 48px (icons.ComponentIcon(UnknownComponent, size=48), icons.ComponentIcon(UnknownComponent, size=48)), ] tykes = [ # Unknown component, no size (icons.ComponentIcon(UnknownComponent, size=48), icons.ComponentIcon(UnknownComponent, size=48)), # Unknown component, wrong size (icons.ComponentIcon(UnknownComponent, size=32), icons.ComponentIcon(UnknownComponent, size=32)), ] for case in exemplars + tykes: # Ensure that the underlying bitmap of each button is the same object assert case[0].bitmap is case[1].bitmap def testIconParity(self): """ Test that the same icons exist for all themes """ # Get root icons folder from psychopy.app.themes.icons import resources as root # Iterate through all png files in light for file in (root / "light").glob("**/*.png"): # Ignore @2x if file.stem.endswith("@2x"): file = file.parent / (file.stem[:-3] + ".png") # Ignore size numbers while file.stem[-1].isnumeric(): file = file.parent / (file.stem[:-1] + ".png") # Get location relative to light folder file = file.relative_to(root / "light") # Create versions of file with size suffices variants = [ file, file.parent / (file.stem + "16.png"), file.parent / (file.stem + "32.png"), file.parent / (file.stem + "48.png"), ] # Check that equivalent file exists in all themes for theme in ("light", "dark", "classic"): # Check that file or variant exists assert any( (root / theme / v).is_file() for v in variants ), f"Could not find file '{file}' for theme '{theme}'"
3,131
Python
.py
73
31.410959
81
0.565858
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,527
test_gammasci.py
psychopy_psychopy/psychopy/tests/test_hardware/test_gammasci.py
import math from unittest.mock import patch from psychopy import hardware @patch('serial.Serial') def test_S470(MockSerial): """ Test the photometer class without the device by mocking the serial connection.""" # Test setup Photometer = hardware.getPhotometerByName('S470') if Photometer is None: print( 'Photometer not found, make sure `psychopy-gammasci` is installed.') return # assert Photometer is not None photometer = Photometer('/dev/DUMMY') # Test single measures photometer = Photometer('/dev/DUMMY', n_repeat=1) photometer.com.read_until.side_effect = [b"\r\n", b"0.5\r\n"] assert photometer.getLum() == 0.5 photometer.com.write.assert_called_with(b"REA\r\n") # Test repeated measures photometer = Photometer('/dev/DUMMY', n_repeat=3) photometer.com.read_until.side_effect = [b"\r\n", b"0.3\r\n", b"0.5\r\n", b"0.4\r\n"] assert math.isclose(photometer.getLum(), 0.4) photometer.com.write.assert_called_with(b"REA 3\r\n") # Test clean-up serial = photometer.com del photometer serial.close.assert_called()
1,140
Python
.py
28
35.285714
89
0.691606
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,528
test_keyboard_events.py
psychopy_psychopy/psychopy/tests/test_hardware/test_keyboard_events.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from psychopy import event, core from psychopy.preferences import prefs from psychopy.visual import Window from pyglet.window.key import (MOD_SHIFT, MOD_CTRL, MOD_ALT, MOD_CAPSLOCK, MOD_NUMLOCK, MOD_WINDOWS, MOD_COMMAND, MOD_OPTION, MOD_SCROLLLOCK) @pytest.mark.keyboard class TestKeyboardEvents(): def test_keyname(self): """Test that a key name is correctly returned.""" event._onPygletKey('a', 0, emulated=True) keys = event.getKeys() assert len(keys) == 1 assert keys[0] == 'a' def test_modifiers(self): """Test that key modifier flags are correctly returned""" event._onPygletKey('a', MOD_CTRL|MOD_SHIFT, emulated=True) keys = event.getKeys(modifiers=True) assert len(keys) == 1 assert len(keys[0]) == 2 assert keys[0][0] == 'a' assert keys[0][1]['ctrl'] assert keys[0][1]['shift'] assert not keys[0][1]['alt'] def test_timestamp(self): """Test that a keypress timestamp is correctly returned""" event._onPygletKey('a', 0, emulated=True) keys = event.getKeys(timeStamped=True) assert len(keys) == 1 assert len(keys[0]) == 2 assert keys[0][0] == 'a' assert isinstance(keys[0][1], float) assert keys[0][1] > 0.0 def test_modifiers_and_timestamp(self): """Test that both key modifiers and timestamp are returned""" event._onPygletKey('a', MOD_ALT, emulated=True) keys = event.getKeys(modifiers=True, timeStamped=True) assert len(keys) == 1 assert len(keys[0]) == 3 assert keys[0][0] == 'a' assert keys[0][1]['alt'] assert isinstance(keys[0][2], float) def test_invalid_modifiers(self): """Modifiers must be integers.""" key = 'a' modifiers = None with pytest.raises(ValueError): event._onPygletKey(key, modifiers, emulated=True) def test_german_characters(self): """Test that event can handle German characters""" # 824633720832 = ö as pyglet symbol string # need to use emulated = False to execute the lines that actually # fix the German characters handling event._onPygletKey(824633720832, 0, emulated=False) event._onPygletText('ö', emulated=True) keys = event.getKeys(modifiers=False, timeStamped=True) assert len(keys) == 1 assert len(keys[0]) == 2 assert keys[0][0] == 'ö' assert isinstance(keys[0][1], float) def test_german_characters_with_modifiers(self): """Test that event can handle German characters with modifiers""" # 824633720832 = ö as pyglet symbol string # need to use emulated = False to execute the lines that actually # fix the German characters handling event._onPygletKey(824633720832, MOD_SHIFT | MOD_SCROLLLOCK, emulated=False) event._onPygletText('ö', emulated=True) keys = event.getKeys(modifiers=True, timeStamped=True) assert len(keys) == 1 assert len(keys[0]) == 3 assert keys[0][0] == 'ö' assert keys[0][1]['shift'] assert keys[0][1]['scrolllock'] assert isinstance(keys[0][2], float) @pytest.mark.keyboard class TestGLobalEventKeys(): @classmethod def setup_class(self): self.win = Window([128, 128], winType='pyglet', pos=[50, 50], autoLog=False) @classmethod def teardown_class(self): self.win.close() def setup_method(self, test_method): # Disable auto-creation of shutdown key. prefs.general['shutdownKey'] = '' def _func(self, *args, **kwargs): return [args, kwargs] def test_shutdownKey_prefs(self): key = 'escape' modifiers = ('ctrl', 'alt') prefs.general['shutdownKey'] = key prefs.general['shutdownKeyModifiers'] = modifiers global_keys = event._GlobalEventKeys() e = list(global_keys)[0] assert key, modifiers == e assert global_keys[e].func == core.quit def test_add(self): key = 'a' func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func) assert global_keys[key, ()].func == func assert global_keys[key, ()].name == func.__name__ def test_add_key_twice(self): key = 'a' func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func) with pytest.raises(ValueError): global_keys.add(key=key, func=func) def test_add_name(self): key = 'a' name = 'foo' func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func, name=name) assert global_keys[key, ()].name == name def test_add_args(self): key = 'a' func = self._func args = (1, 2, 3) global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func, func_args=args) assert global_keys[key, ()].func_args == args def test_add_kwargs(self): key = 'a' func = self._func kwargs = dict(foo=1, bar=2) global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func, func_kwargs=kwargs) assert global_keys[key, ()].func_kwargs == kwargs def test_add_args_and_kwargs(self): key = 'a' func = self._func args = (1, 2, 3) kwargs = dict(foo=1, bar=2) global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func, func_args=args, func_kwargs=kwargs) assert global_keys[key, ()].func_args == args assert global_keys[key, ()].func_kwargs == kwargs def test_add_invalid_key(self): key = 'foo' func = self._func global_keys = event._GlobalEventKeys() with pytest.raises(ValueError): global_keys.add(key=key, func=func) def test_add_invalid_modifiers(self): key = 'a' modifiers = ('foo', 'bar') func = self._func global_keys = event._GlobalEventKeys() with pytest.raises(ValueError): global_keys.add(key=key, modifiers=modifiers, func=func) def test_remove(self): keys = ['a', 'b', 'c'] modifiers = ('ctrl',) func = self._func global_keys = event._GlobalEventKeys() [global_keys.add(key=key, modifiers=modifiers, func=func) for key in keys] global_keys.remove(keys[0], modifiers) with pytest.raises(KeyError): _ = global_keys[keys[0], modifiers] def test_remove_modifiers_list(self): key = 'a' modifiers = ['ctrl', 'alt'] func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, modifiers=modifiers, func=func) global_keys.remove(key, modifiers) with pytest.raises(KeyError): _ = global_keys[key, modifiers] def test_remove_invalid_key(self): key = 'a' global_keys = event._GlobalEventKeys() with pytest.raises(KeyError): global_keys.remove(key) def test_remove_all(self): keys = ['a', 'b', 'c'] func = self._func global_keys = event._GlobalEventKeys() [global_keys.add(key=key, func=func) for key in keys] global_keys.remove('all') assert len(global_keys) == 0 def test_getitem(self): key = 'escape' modifiers = ('ctrl', 'alt') func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, modifiers=modifiers, func=func) assert global_keys[key, modifiers] == global_keys._events[key, modifiers] def test_getitem_string(self): key = 'escape' func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func) assert global_keys[key] == global_keys._events[key, ()] def test_getitem_modifiers_list(self): key = 'escape' modifiers = ['ctrl', 'alt'] func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, modifiers=modifiers, func=func) assert (global_keys[key, modifiers] == global_keys._events[key, tuple(modifiers)]) def test_setitem(self): keys = 'a' modifiers = () global_keys = event._GlobalEventKeys() with pytest.raises(NotImplementedError): global_keys[keys, modifiers] = None def test_delitem(self): key = 'escape' modifiers = ('ctrl', 'alt') func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, modifiers=modifiers, func=func) del global_keys[key, modifiers] with pytest.raises(KeyError): _ = global_keys[key, modifiers] def test_delitem_string(self): key = 'escape' func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, func=func) del global_keys[key] with pytest.raises(KeyError): _ = global_keys[key] def test_len(self): prefs.general['shutdownKey'] = '' key = 'escape' func = self._func global_keys = event._GlobalEventKeys() assert len(global_keys) == 0 global_keys.add(key=key, func=func) assert len(global_keys) == 1 del global_keys[key, ()] assert len(global_keys) == 0 def test_event_processing(self): key = 'a' modifiers = 0 func = self._func args = (1, 2, 3) kwargs = dict(foo=1, bar=2) event.globalKeys.add(key=key, func=func, func_args=args, func_kwargs=kwargs) r = event._process_global_event_key(key, modifiers) assert r[0] == args assert r[1] == kwargs def test_index_keys(self): key = 'escape' modifiers = ('ctrl', 'alt') func = self._func global_keys = event._GlobalEventKeys() global_keys.add(key=key, modifiers=modifiers, func=func) index_key = list(global_keys.keys())[-1] assert index_key.key == key assert index_key.modifiers == modifiers def test_numlock(self): key = 'a' modifiers = ('numlock',) func = self._func global_keys = event._GlobalEventKeys() with pytest.raises(ValueError): global_keys.add(key=key, modifiers=modifiers, func=func) if __name__ == '__main__': import pytest pytest.main()
10,995
Python
.py
278
30.133094
84
0.586807
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,529
test_ports.py
psychopy_psychopy/psychopy/tests/test_hardware/test_ports.py
import psychopy.hardware as hw import pytest try: import mock except Exception: def require_mock(fn): def _inner(): pytest.skip("Can't test without Mock") _inner.__name__ = fn.__name__ return _inner else: def require_mock(fn): return fn try: from collections.abc import Iterable except ImportError: from collections import Iterable try: from contextlib import nested # Python 2 except ImportError: from contextlib import ExitStack, contextmanager @contextmanager def nested(*contexts): """ Reimplementation of nested in python 3. """ with ExitStack() as stack: for ctx in contexts: stack.enter_context(ctx) yield contexts def globMock(expr): if "?" in expr: return [expr.replace("?","1")] elif "*" in expr: return [expr.replace(r"*","MOCK1")] else: return [expr] def assertPorts(expected,actual): actual = list(actual) # ensure list for port in expected: assert port in actual @require_mock def test_getWindowsSerialPorts(): should_have = ["COM0","COM5","COM10"] with mock.patch("sys.platform","win32"): assertPorts(should_have,hw.getSerialPorts()) @require_mock def test_getLinuxSerialPorts(): should_have = ["/dev/ttyS1","/dev/ttyACM1","/dev/ttyUSB1"] with nested(mock.patch("sys.platform","linux2"), mock.patch("glob.iglob",globMock)): assertPorts(should_have,hw.getSerialPorts()) @require_mock def test_getDarwinSerialPorts(): should_have = ["/dev/tty.USAMOCK1","/dev/tty.KeyMOCK1","/dev/tty.modemMOCK1","/dev/cu.usbmodemMOCK1"] with nested(mock.patch("sys.platform","darwin"), mock.patch("glob.iglob",globMock)): assertPorts(should_have,hw.getSerialPorts()) @require_mock def test_getCygwinSerialPorts(): should_have = ["/dev/ttyS1"] with nested(mock.patch("sys.platform","cygwin"), mock.patch("glob.iglob",globMock)): assertPorts(should_have,hw.getSerialPorts()) @require_mock def test_getCRSPhotometers(): try: with mock.patch.dict("sys.modules",{"psychopy.hardware.crs": object()}): photoms = list(hw.getAllPhotometers()) for p in photoms: assert p.longName != "CRS ColorCAL" assert isinstance(photoms, Iterable) # missing crs shouldn't break it assert len(photoms) > 0 except (AssertionError, ImportError): """ I was able to do this fine from a shell: >>> from psychopy.hardware import crs or >>> import psychopy.hardware.crs but kept getting an ImportError when running the test locally: from . import minolta, pr > from psychopy.hardware import crs E ImportError: cannot import name crs hardware/__init__.py:60: ImportError or an assert error on travis-ci > assert p.longName != "CRS ColorCAL" E assert 'CRS ColorCAL' != 'CRS ColorCAL' E + where 'CRS ColorCAL' = <class psychopy.hardware.crs.colorcal.ColorCAL at 0x79b8738>.longName """ pytest.skip() # This allows us to test our logic even when pycrsltd is missing faked = type("MockColorCAL",(object,),{}) with mock.patch("psychopy.hardware.crs.ColorCAL", faked, create=True): photoms = list(hw.getAllPhotometers()) assert faked in photoms # I wish our PR650 would behave like this ;-) _MockPhotometer = type("MockPhotometer",(),{"OK": True,"type": "MockPhotometer"}) _workingPhotometer = lambda port: _MockPhotometer def _exceptionRaisingPhotometer(port): raise Exception("Exceptional quality they said...") def test_findPhotometer(): # findPhotometer with no ports should return None assert (hw.findPhotometer(ports=[]) is None) # likewise, if an empty device list is used return None assert (hw.findPhotometer(device=[]) is None) # even when both are empty assert (hw.findPhotometer(device=[],ports=[]) is None) # non-existent photometers return None, for now assert (hw.findPhotometer(device="thisIsNotAPhotometer!") is None) # if the photometer raises an exception don't crash, return None assert (hw.findPhotometer(device=[_exceptionRaisingPhotometer],ports="foobar") is None) # specifying a photometer should work assert hw.findPhotometer(device=[_workingPhotometer],ports="foobar") == _MockPhotometer # one broken, one working device = [_exceptionRaisingPhotometer,_workingPhotometer] assert hw.findPhotometer(device=device,ports="foobar") == _MockPhotometer
4,747
Python
.py
117
33.931624
120
0.6637
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,530
test_emulator.py
psychopy_psychopy/psychopy/tests/test_hardware/test_emulator.py
"""Tests for psychopy.hardware.emulator""" # covers most lines of code but does not test all possible logic # py.test -k emulator --cov-report term-missing --cov hardware/emulator.py tests/test_hardware import os, sys import pytest from psychopy import visual, core, event from psychopy.hardware import emulator from psychopy.hardware.emulator import * # launchScan sound is not tested, nor included coverage from psychopy.tests import skip_under_vm BASE_MR_SETTINGS = { 'TR': 0.5, # duration (sec) per volume 'volumes': 3, # number of whole-brain 3D volumes / frames 'sync': '5', # character to use as the sync timing event; assumed to come at start of a volume 'skip': 1 # number of volumes lacking a sync pulse at start of scan (for T1 stabilization) } @pytest.mark.emulator class TestLaunchScan(): '''A base class to test launchScan with different MR_settings''' def setup_method(self): self.win = visual.Window(fullscr=False, autoLog=False) self.globalClock = core.Clock() self.MR_settings = BASE_MR_SETTINGS.copy() def test_launch_scan(self): '''Test that launchScan successfully adds sync keys to the buffer.''' MR_settings = self.MR_settings # Initialize onsets with 0; the first onset is used to 0 the clock and is not reported by launchScan onsets = [0.0] sync_key = MR_settings['sync'] # Call launchScan with MR Settings from test classes, in 'Test' mode with a short timeout. vol = launchScan(self.win, MR_settings, globalClock=self.globalClock, mode='Test', wait_timeout=5, log=False) assert 0 < self.globalClock.getTime() < .05 # should get zeroed upon launch duration = MR_settings['volumes'] * MR_settings['TR'] while self.globalClock.getTime() < duration: allKeys = event.getKeys(timeStamped=True) # detect sync or infer it should have happened: for key_tuple in allKeys: if key_tuple[0] == sync_key: vol += 1 onsets.append(key_tuple[1]) assert vol == MR_settings['volumes'] == len(onsets) def test_no_mode(self): #pytest.skip() event.clearEvents() ResponseEmulator(simResponses=[(0.5, 'escape')]).run() vol = launchScan(self.win, BASE_MR_SETTINGS.copy(), globalClock=self.globalClock, wait_timeout=1, log=False) # no mode, so a RatingScale will be displayed; return to select value # the key event is not being detected here core.wait(1, 0) #event._onPygletKey(symbol='escape', modifiers=None, emulated=True) #core.wait(1, 0) def test_sync_generator(self): with pytest.raises(ValueError): s = SyncGenerator(TR=0.01) s = SyncGenerator(TR=0.1) s.start() s.stop() def test_response_emulator(self): # logs error but does not raise: ResponseEmulator(simResponses=[(.1, 0.123)]).run() r = ResponseEmulator() r.start() r.stop() core.wait(.1, 0) @skip_under_vm def test_misc(self): MR_settings = BASE_MR_SETTINGS.copy() MR_settings.update({'sync': 'equal'}) vol = launchScan(self.win, MR_settings, globalClock=self.globalClock, simResponses=[(0.1,'a'), (.2, 1)], mode='Test', log=False) # test replace missing defaults: min_MR_settings = { 'TR': 0.2, # duration (sec) per volume 'volumes': 3} vol = launchScan(self.win, min_MR_settings, globalClock=self.globalClock, mode='Test', log=False) core.wait(1, 0) def test_wait_timeout(self): '''Ensure that the wait_timeout happily rejects bad values.''' with pytest.raises(RuntimeError): vol = launchScan(self.win, BASE_MR_SETTINGS, wait_timeout=.1, mode='Scan', log=False) with pytest.raises(ValueError): vol = launchScan(self.win, self.MR_settings, wait_timeout='cant_coerce_me!', mode='Test', log=False)
4,227
Python
.py
88
38.477273
108
0.622422
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,531
test_keyboard.py
psychopy_psychopy/psychopy/tests/test_hardware/test_keyboard.py
import sys from psychopy.hardware import keyboard import pytest import time from psychopy import logging from psychopy.tests.utils import RUNNING_IN_VM class _TestBaseKeyboard: """ Tests for the general functionality which should exist across Keyboard backends. """ def testReceiveGeneratedKeypress(self): """ Test that `KeyboardDevice.receiveMessage` can receive and interpret a KeyPress object correctly, even when that object isn't linked to a physical keypress. """ # list of events to fake, time to fake them and state of getKeys outputs afterwards cases = [ {'val': "a", 't': 0.1, 'len': 1}, {'val': "b", 't': 0.2, 'len': 1}, ] for case in cases: evt = self.kb.makeResponse(tDown=case['t'], code=case['val']) keys = self.kb.getKeys(waitRelease=False, clear=True) assert len(keys) == case['len'] assert keys[-1] is evt assert keys[-1].value == case['val'] def testAcceptDuplicateResponses(self): """ Test that KeyboardDevice can receive multiple presses of the same key without accepting genuine duplicates (e.g. KeyPress objects added twice, or the same object added for press and release) """ # clear self.kb.clearEvents() # press space twice and don't release resp1 = self.kb.makeResponse(tDown=0.1, code="space") resp2 = self.kb.makeResponse(tDown=0.2, code="space") # make sure we only have 2 press objects keys = self.kb.getKeys(waitRelease=False, clear=False) assert len(keys) == 2 # simulate a release resp1.duration = 0.2 resp2.duration = 0.1 self.kb.responses += [resp1, resp2] # we should still only have 2 press objects (as these are duplicates) keys = self.kb.getKeys(waitRelease=True, clear=False) assert len(keys) == 2 # add the same objects again for no good reason self.kb.responses += [resp1, resp2] # we should STILL only have 2 press objects keys = self.kb.getKeys(waitRelease=True, clear=False) assert len(keys) == 2 def testMuteOutsidePsychopyNotSlower(self): """ Test that responses aren't worryingly slower when using muteOutsidePsychopy """ # skip this test on Linux (as MOP *is* slower due to having to use subprocess) if sys.platform == "linux": pytest.skip() # skip speed tests under vm if RUNNING_IN_VM: pytest.skip() # array to store times times = {} # number of responses to make nResps = 10000 for mop in (True, False): # make new keyboard with muteOutsidePsychopy set as desired self.kb.muteOutsidePsychopy = mop # start timer start = time.time() # make 10000 responses for n in range(nResps): self.kb.makeResponse( code="a", tDown=0 ) # get time times[mop] = time.time() - start # work out average difference per-response avg = (times[True] - times[False]) / nResps # make sure average difference will still be less than a frame on high performance monitors assert avg < 1/240 def teardown_method(self): # clear any keypresses self.kb.getKeys(clear=True) # set mute outside psychopy back to False self.kb.muteOutsidePsychopy = False class _MillikeyMixin: """ Mixin to add tests which use a Millikey device to generate keypresses. If no such device is connected, these tests will all skip. """ # this attribute should be overwritten when setup_class is called millikey = None def setup_class(self): """ Create a serial object to interface with a Millikey device, """ from psychopy.hardware.serialdevice import SerialDevice from psychopy.tools import systemtools as st # systemtools only works on Windows so skip millikey-dependent tests on other OS's if sys.platform != "win32": return # use systemtools to find millikey port for profile in st.systemProfilerWindowsOS(classname="Ports", connected=True): # identify by driver name if "usbser.inf" not in profile['Driver Name']: continue # find "COM" in profile description desc = profile['Device Description'] start = desc.find("COM") + 3 end = desc.find(")", start) # if there's no reference to a COM port, skip if -1 in (start, end): continue # get COM port number num = desc[start:end] # if we've got this far, create device self.millikey = SerialDevice(f"COM{num}", baudrate=128000) # stop looking once we've got one break def teardown_class(self): """ Close Millikey before finishing tests. """ if self.millikey is not None: self.millikey.close() def assertMillikey(self): """ Make sure a Millikey device is connected (and skip the current test if not) """ # if we didn't find a device, skip current test if self.millikey is None: pytest.skip() def makeMillikeyKeypress(self, key, duration, delay=0): """ Send a trigger to the Millikey device telling to to press a particular key. Parameters ---------- key : str Key to press duration : int Duration (ms) of the keypress delay : int Delay (ms) before making the keypress """ # make sure we have a millikey device self.assertMillikey() # construct command (see https://blog.labhackers.com/?p=285) cmd = "KGEN {} {} {}".format(key, duration, delay) # send self.millikey.sendMessage(cmd) # read any resp1 return self.millikey.getResponse() def testReceivePhysicalKeypress(self): """ Test that physical keypresses are detected. Requires a Millikey device to run. """ self.makeMillikeyKeypress(key="a", duration=10, delay=10) # get last message resp = self.kb.getKeys()[-1] # check whether the created press was received assert resp.name == "a" def testPhysicalKeypressTiming(self): """ Test that timing (tDown, rt, etc.) on KeyPress objects received via a physical key press are correct. Requires a Millikey device to run. """ # define tolerance (ms) for this test tolerance = 4 # try a few times to make sure times aren't cumulative for ans, dur, rt in [ ("a", 123, 456), ("b", 456, 123), ("c", 123, 123), ("d", 456, 456), ]: # reset keyboard clock self.kb.clock.reset() # wait for rt time.sleep(rt / 1000) # store start time start = logging.defaultClock.getTime() # make a keypress self.makeMillikeyKeypress(key=ans, duration=dur) # wait for press to finish time.sleep(dur / 500) # get last message resp = self.kb.getKeys()[-1] # check correct key assert resp.name == ans # check correct rt assert abs(resp.rt - rt / 1000) <= tolerance / 1000 # check correct duration assert abs(resp.duration - dur / 1000) <= tolerance / 1000 # check correct start time assert abs(resp.tDown - start) <= tolerance / 1000 class TestIohubKeyboard(_TestBaseKeyboard, _MillikeyMixin): def setup_method(self): self.kb = keyboard.KeyboardDevice(backend="iohub", muteOutsidePsychopy=False) class TestPtbKeyboard(_TestBaseKeyboard, _MillikeyMixin): def setup_method(self): self.kb = keyboard.KeyboardDevice(backend="ptb", muteOutsidePsychopy=False) def teardown_method(self): self.kb.getKeys(clear=True) class TestEventKeyboard(_TestBaseKeyboard, _MillikeyMixin): def setup_method(self): self.kb = keyboard.KeyboardDevice(backend="event", muteOutsidePsychopy=False) def teardown_method(self): self.kb.getKeys(clear=True)
8,566
Python
.py
212
30.778302
99
0.605886
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,532
test_device_manager.py
psychopy_psychopy/psychopy/tests/test_hardware/test_device_manager.py
from psychopy.hardware import manager from psychopy.tests import skip_under_vm class TestDeviceManager: def setup_class(cls): cls.mgr = manager.getDeviceManager() @skip_under_vm def test_all_devices(self): devices = ( "psychopy.hardware.keyboard.KeyboardDevice", "psychopy.hardware.microphone.MicrophoneDevice", "psychopy.hardware.serialdevice.SerialDevice", # "psychopy_bbtk.tpad.TPadPhotodiodeGroup", # uncomment when running locally with a BBTK ) for device in devices: self._test_device(device) def _test_device(self, deviceType): # test available getter available = self.mgr.getAvailableDevices(deviceType) # if no devices are available, just return if not len(available): return # create device _device = self.mgr.addDevice(**available[0]) # get device name = available[0]['deviceName'] device = self.mgr.getDevice(name) assert device == _device # check it's in list of registered devices devices = self.mgr.getInitialisedDevices(deviceType) assert name in devices assert devices[name] == device
1,240
Python
.py
31
31.354839
101
0.656146
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,533
test_photodiode.py
psychopy_psychopy/psychopy/tests/test_hardware/test_photodiode.py
import pytest from psychopy import core, visual from psychopy.tests.utils import RUNNING_IN_VM from psychopy.hardware.photodiode import BasePhotodiodeGroup, PhotodiodeResponse class DummyPhotodiode(BasePhotodiodeGroup): def __init__(self, channels=1, threshold=None, pos=None, size=None, units=None): # make a basic timer self.timer = core.Clock() # queue of messages that can be manually added self.queue = [] # initialise base BasePhotodiodeGroup.__init__( self, channels=channels, threshold=threshold, pos=pos, size=size, units=units ) def dispatchMessages(self): for msg in self.queue: self.responses = self.parseMessage(msg) def parseMessage(self, message): """ Parameters ---------- message : tuple[float, bool, int, float] Raw message, in the format: - float: Timestamp - bool: True/False photodiode state - int: Channel in question Returns ------- PhotodiodeResponse Photodiode response """ # split message t, value, channel = message # make obj return PhotodiodeResponse( t, value, channel, threshold=self.threshold[channel] ) def _setThreshold(self, threshold, channel): self.threshold[channel] = threshold def resetTimer(self, clock=None): self.timer.reset() class TestPhotodiode: def setup_class(self): self.photodiode = DummyPhotodiode() self.win = visual.Window() def test_handle_no_response(self): """ If no response (as will be the case here), should try n times and then give up. """ # this one takes a while and isn't all that helpful if you can't watch it, so skip under vm if RUNNING_IN_VM: pytest.skip() # try to find the photodiode, knowing full well it'll get nothing as this is a dummy self.photodiode.findPhotodiode(win=self.win, retryLimit=2)
2,088
Python
.py
54
29.907407
99
0.63051
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,534
test_projections_interactive.py
psychopy_psychopy/psychopy/tests/test_visual/test_projections_interactive.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pyglet.window import key from psychopy.visual import * from psychopy.visual.windowwarp import * from psychopy.visual.windowframepack import * foregroundColor=[-1,-1,-1] backgroundColor=[1,1,1] class ProjectionsLinesAndCircles(): """ Test jig for projection warping. Switch between warpings by pressing a key 'S'pherical, 'C'ylindrical, 'N'one, warp'F'ile. Click the mouse to set the eyepoint X, Y. Up / Down arrow or mousewheel to move eyepoint in and out. """ def __init__(self, window, warper): self.window = window self.warper = warper self.stimT = TextStim(self.window, text='Null warper', units = 'pix', pos=(0, -140), height=20) self.bl = -window.size / 2.0 self.tl = (self.bl[0], -self.bl[1]) self.tr = window.size / 2.0 self.stims = [] self.degrees = 120 nLines = 12 for x in range(-nLines, nLines+1): t = GratingStim(window,tex=None,units='deg',size=[2,window.size[1]],texRes=128,color=foregroundColor, pos=[float(x) / nLines * self.degrees,0]) self.stims.append (t) for y in range(-nLines, nLines+1): t = GratingStim(window,tex=None,units='deg',size=[window.size[0],2],texRes=128,color=foregroundColor,pos=[0,float(y)/nLines * self.degrees]) self.stims.append (t) for c in range(1, nLines+1): t = Circle(window, radius=c * 10, edges=128, units='deg', lineWidth=4) self.stims.append (t) self.updateInfo() self.keys = key.KeyStateHandler() window.winHandle.push_handlers(self.keys) self.mouse = event.Mouse(win=self.window) def updateFrame(self, i): """ Updates frame with any item that is to be modulated per frame. """ for s in self.stims: s.draw() self.stimT.draw() def update_sweep(self,i): """ Update function for sweeps. Input is in domain units. """ self.updateFrame(i) self.check_keys() self._handleMouse() self.window.flip() def updateInfo(self): try: self.stimT.setText ("%s \n eyePoint: %.3f, %.3f \n eyeDistance: %.2f\n\nProjection: [s]pherical, [c]ylindrical, [n]one, warp[f]ile\nFlip: [h]orizontal, [v]ertical\nMouse: wheel = eye distance, click to set eyepoint\n[q]uit" % ( self.warper.warp, self.warper.eyepoint[0], self.warper.eyepoint[1], self.warper.dist_cm)) except Exception: pass def check_keys(self): """Checks key input""" for keys in event.getKeys(timeStamped=True): k = keys[0] if k in ['escape', 'q']: self.window.close() sys.exit() elif k in ['space']: for c in range (1,2): t = Circle(self.window, radius=c) self.stims.append (t) #for c in range (1,2): # t = RadialStim(self.window) # self.stims.append(t) # handle projections elif k in ['s']: self.warper.changeProjection ('spherical', None, (0.5,0.5)) elif k in ['c']: self.warper.changeProjection ('cylindrical', None, (0.5,0.5)) elif k in ['n']: self.warper.changeProjection (None, None, (0.5,0.5)) elif k in ['f']: self.warper.changeProjection ('warpfile', #r'C:\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\Lib\site-packages\aibs\Projector\Calibration\standard_4x3.data', r'C:\Users\jayb\Documents\Stash\aibs\Projector\Calibration\InteriorProject24inDome6inMirrorCenter.meshwarp.data', #r'C:\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\Lib\site-packages\aibs\Projector\Calibration\standard_16x9.data', (0.5,0.5)) # flip horizontal and vertical elif k in ['h']: self.warper.changeProjection(self.warper.warp, self.warper.warpfile, flipHorizontal = not self.warper.flipHorizontal) elif k in ['v']: self.warper.changeProjection(self.warper.warp, self.warper.warpile, flipVertical = not self.warper.flipVertical) # move eyepoint elif k in ['down']: if (self.warper.dist_cm > 1): self.warper.dist_cm -= 1 self.warper.changeProjection (self.warper.warp, None, self.warper.eyepoint) elif k in ['up']: if (self.warper.dist_cm < 200): self.warper.dist_cm += 1 self.warper.changeProjection (self.warper.warp, None, self.warper.eyepoint) elif k in ['right']: if (self.warper.eyepoint[0] < 0.9): self.warper.eyepoint = (self.warper.eyepoint[0] + 0.1, self.warper.eyepoint[1]) self.warper.changeProjection (self.warper.warp, None, self.warper.eyepoint) elif k in ['left']: if (self.warper.eyepoint[0] > 0.1): self.warper.eyepoint = (self.warper.eyepoint[0] - 0.1, self.warper.eyepoint[1]) self.warper.changeProjection (self.warper.warp, None, self.warper.eyepoint) self.updateInfo() def _handleMouse(self): x, y = self.mouse.getWheelRel() if y != 0: self.warper.dist_cm += y self.warper.dist_cm = max (1, min (200, self.warper.dist_cm)) self.warper.changeProjection (self.warper.warp, self.warper.warpfile, self.warper.eyepoint) self.updateInfo() pos = (self.mouse.getPos() + 1) / 2 leftDown = self.mouse.getPressed()[0] if leftDown: self.warper.changeProjection (self.warper.warp, self.warper.warpfile, pos) self.updateInfo() def mainProjectionsLinesAndCircles(params=None): """ ProjectionsLinesAndCircles test runner to test projections """ if not params: params = {'testlength': 400} win = Window(monitor='LightCrafter4500', screen=1, fullscr=True, color='gray', useFBO = True, autoLog=False) warper = Warper (win, warp='spherical', warpfile = "", warpGridsize = 128, eyepoint = [0.5, 0.5], flipHorizontal = False, flipVertical = False) # frame packer is used with DLP projectors to create 180Hz monochrome stimuli #framePacker = ProjectorFramePacker(win) g = ProjectionsLinesAndCircles(win, warper) for i in range(int(params['testlength'] * 60)): g.update_sweep(i) win.close() if __name__ == "__main__": mainProjectionsLinesAndCircles()
6,780
Python
.py
136
38.551471
243
0.591053
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,535
test_brush.py
psychopy_psychopy/psychopy/tests/test_visual/test_brush.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from psychopy import event from psychopy.visual.window import Window from psychopy.visual.brush import Brush from psychopy.visual.shape import ShapeStim class Test_Brush(): """Test suite for Brush component""" def setup_class(self): self.win = Window([128,128], pos=[50,50], allowGUI=False, autoLog=False) def teardown_class(self): self.win.close() def test_line_color(self): colors = ['black', 'red'] for color in colors: testBrush = Brush(self.win, lineColor=color) assert testBrush.lineColor == color def test_line_width(self): widths = [1, 5] for width in widths: testBrush = Brush(self.win, lineWidth=width) assert testBrush.lineWidth == width def test_close_shape(self): testBrush = Brush(self.win) assert testBrush.closeShape == False def test_create_stroke(self): testBrush = Brush(self.win) testBrush._createStroke() assert len(testBrush.shapes) == 1 assert isinstance(testBrush.shapes[0], ShapeStim) def test_brush_down(self): testBrush = Brush(self.win) testMouse = event.Mouse() assert testBrush.brushDown == testMouse.getPressed()[0] def test_brush_vertices(self): testBrush = Brush(self.win) assert testBrush.brushPos == [] def test_at_start_point(self): testBrush = Brush(self.win) assert testBrush.atStartPoint == False def test_current_shape(self): testBrush = Brush(self.win) testBrush._createStroke() assert testBrush.currentShape == 0 def test_reset(self): testBrush = Brush(self.win) testBrush._createStroke() testBrush.reset() assert testBrush.shapes == [] assert testBrush.atStartPoint == False
1,982
Python
.py
54
28.222222
63
0.626437
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,536
test_window.py
psychopy_psychopy/psychopy/tests/test_visual/test_window.py
import importlib from copy import copy from pathlib import Path from psychopy import visual, colors from psychopy.tests import utils from psychopy.tests.test_visual.test_basevisual import _TestColorMixin from psychopy.tools.stimulustools import serialize from psychopy import colors class TestWindow: def test_serialization(self): # make window win = visual.Window() # serialize window params = serialize(win, includeClass=True) # get class mod = importlib.import_module(params.pop('__module__')) cls = getattr(mod, params.pop('__class__')) # check class is Window assert isinstance(win, cls) # recreate win from params dupe = cls(**params) # delete duplicate dupe.close() def test_background_image_fit(self): _baseCases = [ # no fitting {"fit": None, "image": "default.png", "sizes": {'wide': 256, 'tall': 256, 'large': 256, 'small': 256}}, # cover {"fit": "cover", "image": "default.png", "sizes": {'wide': 500, 'tall': 500, 'large': 500, 'small': 200}}, # contain {"fit": "contain", "image": "default.png", "sizes": {'wide': 200, 'tall': 200, 'large': 500, 'small': 200}}, # fill {"fit": "fill", "image": "default.png", "sizes": {'wide': "fill", 'tall': "fill", 'large': 500, 'small': 200}}, # scaleDown {"fit": "scaleDown", "image": "default.png", "sizes": {'wide': 200, 'tall': 200, 'large': 256, 'small': 200}}, ] cases = [] # Create version of each case with different units for units in ["pix", "height", "norm"]: theseCases = copy(_baseCases) for case in theseCases: case['units'] = units cases.append(case) # Additional level of variation: window sizes sizes = { "wide": (500, 200), "tall": (200, 500), "large": (500, 500), "small": (200, 200), } for sizeTag, size in sizes.items(): win = visual.Window(size=size) for case in cases: # Set image and fit win.backgroundFit = case['fit'] win.backgroundImage = case['image'] win.flip() # Compare imgName = Path(case['image']).stem filename = f"test_win_bg_{sizeTag}_{case['sizes'][sizeTag]}_{imgName}.png" # win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) try: utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, win, crit=7) except AssertionError as err: raise AssertionError(f"Window did not look as expected when:\n" f"backgroundImage={case['image']},\n" f"backgroundFit={case['fit']},\n" f"size={sizeTag},\n" f"units={case['units']}\n" f"\n" f"Original error:" f"{err}") # Close win.close() def test_win_color_with_image(self): """ Test that the window color is still visible under the background image """ cases = [ "red", "blue", "green", ] win = visual.Window(size=(200, 200), backgroundImage="default.png", backgroundFit="contain") for case in cases: # Set window color win.color = case # Draw with background win.flip() # Check filename = f"test_win_bgcolor_{case}.png" # win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, win, crit=10) def test_window_colors(self): win = visual.Window(size=(200, 200)) for case in _TestColorMixin.colorTykes + _TestColorMixin.colorExemplars: # Go through all TestColorMixin cases for colorSpace, color in case.items(): # Make color to compare against target = colors.Color(color, colorSpace) # Set each colorspace/color combo win.colorSpace = colorSpace win.color = color win.flip() # Check that the middle pixel is this color utils.comparePixelColor( win, target, coord=(0, 0), context=f"win_{color}_{colorSpace}")
4,891
Python
.py
114
29.254386
100
0.510384
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,537
test_progress.py
psychopy_psychopy/psychopy/tests/test_visual/test_progress.py
from psychopy import visual from .test_basevisual import _TestColorMixin, _TestUnitsMixin, _TestSerializationMixin from psychopy.tests.test_experiment.test_component_compile_python import _TestBoilerplateMixin from psychopy.tests import utils from pathlib import Path class TestProgress(_TestColorMixin, _TestUnitsMixin, _TestBoilerplateMixin, _TestSerializationMixin): @classmethod def setup_class(cls): cls.win = visual.Window([128,128], pos=[50,50], monitor="testMonitor", allowGUI=False, autoLog=False) cls.obj = visual.Progress(cls.win, pos=(0, 0), size=(128, 64), anchor="center", units="pix", foreColor="red", backColor="green", lineColor="blue", opacity=1, lineWidth=10) # Pixel which is the border color cls.borderPoint = (30, 64) cls.borderUsed = True # Pixel which is the fill (back) color cls.fillPoint = (64, 16) cls.fillUsed = True # Pixel which is the fore color cls.forePoint = (64, 64) cls.foreUsed = True def setup_method(self): # Set progress mid way at start of each test self.obj.progress = 0.5 # Set direction to horizontal self.obj.direction = "horizontal" # Set colors self.obj.colorSpace = "rgb" self.obj.foreColor = "red" self.obj.backColor = "green" self.obj.lineColor = "blue" self.obj.opacity = 1 # Set position self.obj.units = "pix" self.obj.pos = (0, 0) self.obj.size = (128, 64) def test_value(self): """ Check that setting the value of progress has the desired effect """ # Values to test vals = [0, 0.3, 0.6, 1] # Layouts to test them in layouts = [ {'anchor': "left center", 'direction': "horizontal"}, {'anchor': "center center", 'direction': "horizontal"}, {'anchor': "right center", 'direction': "horizontal"}, {'anchor': "top center", 'direction': "vertical"}, {'anchor': "center center", 'direction': "vertical"}, {'anchor': "bottom center", 'direction': "vertical"}, ] # Create cases list cases = [] for val in vals: for lo in layouts: lo = lo.copy() lo.update({'val': val}) cases.append(lo) # Test each case for case in cases: # Prepare window self.win.flip() # Set anchor from case self.obj.anchor = case['anchor'] # Set pos so it's always centred pos = [0, 0] if "left" in case['anchor']: pos[0] = -64 if "right" in case['anchor']: pos[0] = 64 if "bottom" in case['anchor']: pos[1] = -32 if "top" in case['anchor']: pos[1] = 32 self.obj.pos = pos # Set direction and progress from case self.obj.direction = case['direction'] self.obj.progress = case['val'] # Draw self.obj.draw() # Compare screenshot if case['val'] not in (0, 1): filename = f"{self.__class__.__name__}_testValue_%(direction)s_%(anchor)s_%(val)s.png" % case else: filename = f"{self.__class__.__name__}_testValue_minmax_%(val)s.png" % case # self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) utils.compareScreenshot(filename, self.win, crit=8)
3,699
Python
.py
88
30.693182
109
0.547599
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,538
test_slider.py
psychopy_psychopy/psychopy/tests/test_visual/test_slider.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path from psychopy.tests import utils from psychopy.tests.test_visual.test_basevisual import _TestColorMixin, _TestSerializationMixin from psychopy.tests.test_experiment.test_component_compile_python import _TestBoilerplateMixin from psychopy.visual.window import Window from psychopy.visual.slider import Slider from psychopy.visual.elementarray import ElementArrayStim from psychopy.visual.shape import ShapeStim from psychopy.visual.rect import Rect from psychopy import constants from numpy import array_equal import random class Test_Slider(_TestColorMixin, _TestBoilerplateMixin, _TestSerializationMixin): def setup_class(self): # Make a Window self.win = Window([128,128], pos=[50,50], monitor="testMonitor", allowGUI=False, autoLog=False) # Create a Slider self.obj = Slider(self.win, units="height", size=(1, 0.1), pos=(0, 0.5), style='radio') # Set the Marker position to 0 self.obj.markerPos = 0 # Pixel which is the border color self.borderPoint = (0, 127) self.borderUsed = True # Pixel which is the fill color self.fillPoint = (0, 0) self.fillUsed = True # Pixel which is the fore color self.forePoint = (0, 0) self.foreUsed = False def teardown_class(self): # Delete created object self.win.close() def test_horiz(self): # Define cases exemplars = [ {'size': (1, 0.2), 'ori': 0, 'horiz': True, 'tag': 'horiz'}, # Wide slider, no rotation {'size': (0.2, 1), 'ori': 0, 'horiz': False, 'tag': 'vert'}, # Tall slider, no rotation {'size': (1, 0.2), 'ori': 90, 'horiz': False, 'tag': 'vert'}, # Wide slider, 90deg rotation {'size': (0.2, 1), 'ori': 90, 'horiz': True, 'tag': 'horiz'}, # Tall slider, 90deg rotation ] tykes = [ {'size': (1, 0.2), 'ori': 25, 'horiz': True, 'tag': 'accute_horiz'}, # Wide slider, accute rotation {'size': (0.2, 1), 'ori': 25, 'horiz': False, 'tag': 'accute_vert'}, # Tall slider, accute rotation {'size': (1, 0.2), 'ori': 115, 'horiz': False, 'tag': 'obtuse_horiz'}, # Wide slider, obtuse rotation {'size': (0.2, 1), 'ori': 115, 'horiz': True, 'tag': 'obtuse_vert'}, # Tall slider, obtuse rotation ] # Try each case self.win.flip() for case in exemplars + tykes: # Make sure horiz is set as intended obj = Slider(self.win, labels=["a", "b", "c", "d"], ticks=[1, 2, 3, 4], labelHeight=0.2, labelColor='red', size=case['size'], ori=case['ori']) assert obj.horiz == case['horiz'] # Make sure slider looks as intended obj.draw() # Filename to a png file with the tag for this case filename = f"test_slider_horiz_{case['tag']}.png" # self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) # Compare the created slider to a screenshot of what we expect to see tests/data folder for screenshots utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, self.win, crit=10) self.win.flip() def test_reset(self): # Test reset function of the slider s = Slider(self.win, size=(1, 0.1)) # Set up the slider with some default vals s.markerPos = 1 s.history = [1] s.rating = 1 s.rt = 1 s.status = constants.STARTED # Call the reset function s.reset() assert s.markerPos == None assert s.history == [] assert s.rating == None assert s.rt == None assert s.status == constants.NOT_STARTED def test_elements(self): # Test slider elements # Create the slider (s) s = Slider(self.win, size=(1, 0.1)) assert type(s.line) == type(Rect(self.win)) # Check the line is a rectangle assert type(s.tickLines) == type(ElementArrayStim(self.win)) # Check the ticklines are element array stim assert type(s.marker) == type(ShapeStim(self.win)) # Check marker is ShapeStim assert type(s.validArea) == type(Rect(self.win)) def test_pos(self): # Test slider position # Create the slider (s) s = Slider(self.win, size=(1, 0.1)) # List of positions to test positions = [(.05, .05),(0.2, .2)] # For each position in list for newPos in positions: s.pos = newPos assert array_equal(s.pos, newPos) # Check that the position updates def test_triangle_marker(self): # Test with triangular marker # Test all combinations of horiz and flip cases = [ {"horiz": True, "flip": True}, {"horiz": True, "flip": False}, {"horiz": False, "flip": True}, {"horiz": False, "flip": False}, ] # Create slider s = Slider(self.win, units="height", pos=(0, 0), ticks=(0, 1, 2), styleTweaks=["triangleMarker"]) s.rating = 1 # Try each case for case in cases: # Make horizontal/vertical if case['horiz']: s.size = (1, 0.1) else: s.size = (0.1, 1) # Flip or not s.flip = case['flip'] # Compare s.draw() filename = "test_slider_triangle_horiz_%(horiz)s_flip_%(flip)s.png" % case #self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) # Compare the created slider to a screenshot of what we expect to see tests/data folder for screenshots utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, self.win) self.win.flip() def test_ratingToPos(self): # Test translationg between rating and marker positions # Create the slider (s) s = Slider(self.win, size=(1, 0.1), ) assert s._ratingToPos(3)[0] == 0 # check a rating of 3 is central position assert s._ratingToPos(1)[0] == -.5 # check a rating of 1 is furthest left assert s._ratingToPos(5)[0] == .5 # check a rating of 5 is furthest right def test_posToRatingToPos(self): # Test translationg between marker position and ratings # Create the slider (s) s = Slider(self.win, size=(1, 0.1), ) assert s._posToRating((0, 0)) == 3 # check central position is a rating of 3 assert s._posToRating((-.5, 0)) == 1 # check furthest left is a rating of 1 assert s._posToRating((.5, 0)) == 5 # check furthest right is a rating of 5 def test_tick_and_label_locs(self): # Test ticks an label locations exemplars = [ {'ticks': [1, 2, 3, 4, 5], 'labels': ["a", "b", "c", "d", "e"], 'tag': "simple"}, {'ticks': [1, 2, 3, 9, 10], 'labels': ["a", "b", "c", "d", "e"], 'tag': "clustered"}, {'ticks': [1, 2, 3, 4, 5], 'labels': ["", "b", "c", "d", ""], 'tag': "blanks"}, {'ticks': None, 'labels': ["a", "b", "c", "d", "e"], 'tag': "noticks"}, {'ticks': [1, 2, 3, 4, 5], 'labels': None, 'tag': "nolabels"}, ] tykes = [ {'ticks': [1, 2, 3], 'labels': ["a", "b", "c", "d", "e"], 'tag': "morelabels"}, {'ticks': [1, 2, 3, 4, 5], 'labels': ["a", "b", "c"], 'tag': "moreticks"}, {'ticks': [1, 9, 10], 'labels': ["a", "b", "c", "d", "e"], 'tag': "morelabelsclustered"}, {'ticks': [1, 7, 8, 9, 10], 'labels': ["a", "b", "c", "d"], 'tag': "moreticksclustered"}, ] # Test all cases self.win.flip() for case in exemplars + tykes: # Make vertical slider vert = Slider(self.win, size=(0.1, 0.5), pos=(-0.25, 0), units="height", labels=case['labels'], ticks=case['ticks']) vert.draw() # Make horizontal slider horiz = Slider(self.win, size=(0.5, 0.1), pos=(0.2, 0), units="height", labels=case['labels'], ticks=case['ticks']) horiz.draw() # Compare screenshot filename = "test_slider_ticklabelloc_%(tag)s.png" % case #self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) # Compare the created slider to a screenshot of what we expect to see tests/data folder for screenshots utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, self.win) self.win.flip() def test_granularity(self): # Test granularity of Slider works as expected # Create the slider (s) s = Slider(self.win, size=(1, 0.1), granularity=1) # Set minimum and maximum ratings minRating, maxRating = 1, 5 assert s.granularity == 1 # Check granulariy is 1 assert s._granularRating(1) == minRating assert s._granularRating(5) == maxRating assert s._granularRating(0) == minRating assert s._granularRating(6) == maxRating def test_rating(self): # Test rating sets and updates as expected # Create the slider (s) s = Slider(self.win, size=(1, 0.1)) # Set minimum and maximum ratings minRating, maxRating = 1, 5 s.rating = 1 # Set to minimum rating assert s.rating == minRating # Check it is minimum rating s.rating = 5 # Set to maximum rating assert s.rating == maxRating # Check it is maximum rating s.rating = 0 # Set below minimum rating assert s.rating == minRating # Check it is minimum rating s.rating = 6 # Set above maximum rating assert s.rating == maxRating # Check it is maximum rating def test_markerPos(self): # Test marker value sets and updates as expected # Create the slider (s) s = Slider(self.win, size=(1, 0.1)) s._updateMarkerPos = False # Set minimum and maximum positions minPos, maxPos = 1, 5 assert s._updateMarkerPos != True s.markerPos = 1 # Set to minimum position assert s.markerPos == minPos # Check it is minimum position s.markerPos = 5 # Set to maximum position assert s.markerPos == maxPos # Check it is maximum position s.markerPos = 0 # Set below minimum position assert s.markerPos == minPos# Check it is minimum position s.markerPos = 6 # Set above maximum position assert s.markerPos == maxPos # Check it is maximum position assert s._updateMarkerPos == True def test_recordRating(self): # Test recording of rating values # Create the slider (s) s = Slider(self.win, size=(1, 0.1)) # Provide a minRating and a maxRating minRating, maxRating = 1, 5 counter = 0 for rates in range(0,7): s.recordRating(rates, random.random()) # "rates" will be rating random.random() generates random response time val counter +=1 # Get a list of ratings and response times for all ratings made ratings = [rating[0] for rating in s.history] RT = [rt[1] for rt in s.history] assert len(s.history) == counter assert len(ratings) == counter # Check the number of ratings is equal to expected assert min(ratings) == minRating # Check ratings never go below minimum cap assert max(ratings) == maxRating # Check ratings never go above maximum cap assert len(RT) == counter # Check the number of rts is equal to expected assert max(RT) <= 1 # check the max RT is less than or equal to 1 assert min(RT) >= 0 # check the min RT is greater than or equal to 1 def test_getRating(self): # Test fetching of the rating data e.g. that minRating and maxRating caps the ratings as expected # Create the slider (s) s = Slider(self.win, size=(1, 0.1)) # Provide a minRating and a maxRating minRating, maxRating = 1, 5 s.rating = 1 # Set a rating value that is the minimum rating assert s.getRating() == minRating # Check getRating() is the minRating - expect return True s.rating = 5 # Set a rating value that is the maximum rating assert s.getRating() == maxRating # Check getRating() is the maxRating - expect return True s.rating = 0 # Set a rating value that is below the minimum rating assert s.getRating() == minRating # Check getRating() is the minRating - expect return True s.rating = 6 # Set a rating value that is above the maximum rating assert s.getRating() == maxRating # Check getRating() is the maxRating - expect return True def test_getRT(self): # Test fetching of the response time data # Create the slider (s) s = Slider(self.win, size=(1, 0.1)) # Provide example response time testRT = .89 # Give the response time to the Slider s.recordRating(2, testRT) assert s.history[-1][1] == s.getRT() assert type(s.getRT()) == float # Check thet getRT() returns a float (as expected) assert s.getRT() == testRT # Check that getRT() returns the provided testRT
13,483
Python
.py
261
41.555556
126
0.590795
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,539
test_winFlipTiming.py
psychopy_psychopy/psychopy/tests/test_visual/test_winFlipTiming.py
import sys from psychopy import visual, clock import pytest import numpy as np try: from psychtoolbox import GetSecs havePTB = True except ImportError: havePTB = False class Test_WinFlipTiming(): def setup_class(self): self.win = visual.Window(size=(200, 200), units='pix', allowGUI=False, autoLog=False, waitBlanking=True) self.rate = self.win.getActualFrameRate() if self.rate and 40<self.rate<160: self.testOutputs = True else: self.testOutputs = False def teardown_class(self): self.win.close() def _runSeriesOfFlips(self, usePTB): if usePTB: getTime = GetSecs clk = 'ptb' else: getTime = clock.monotonicClock.getTime clk = clock.monotonicClock self.win.flip() now = clock.monotonicClock.getTime() next = self.win.getFutureFlipTime(clock=clk) self.win.flip() errsNext = [] # check nextFrame against reality for 10 frames for frameN in range(10): self.win.flip() this = getTime() # print('this', this) # print('err', next-this) errsNext.append(next-this) #then update next next = self.win.getFutureFlipTime(clock=clk) # print('next', next) return errsNext def test_winFutureFlip(self): """test window.viewScale and .viewPos simultaneous negative-going scale should mirror-reverse, and position should account for that visually, the green square/rect should move clockwise around the text Non-zero viewOri would not currently pass with a nonzero viewPos """ self.win.flip() now = clock.monotonicClock.getTime() next = self.win._frameTimes[-1] + self.win.monitorFramePeriod errs = self._runSeriesOfFlips(usePTB=False) print() print('getFutureFlipTime(0): mean={:.6f}, std={:6f}, all={}' .format(np.mean(errs), np.std(errs), errs)) if self.testOutputs: assert np.mean(errs)<0.005 # checks for any systematic bias if havePTB: errs = self._runSeriesOfFlips(usePTB=True) print('PTB getFutureFlipTime(0): mean={:.6f}, std={:6f}, all={}' .format(np.mean(errs), np.std(errs), errs)) if self.testOutputs: assert np.mean(errs)<0.005 # checks for any systematic bias now = clock.monotonicClock.getTime() predictedFrames = [] print('now={:.5f}, lastFrame={:.5f}'.format(now, self.win._frameTimes[-1])) print('delay requestT expectT diff'.format(now, self.win._frameTimes[-1])) for requested in np.arange(0, 0.04, 0.001): expect = self.win.getFutureFlipTime(requested) diff = expect-(now+requested) print("{:.4f}, {:.5f} {:.5f} {:.5f}".format(requested, requested, expect, diff)) # should always be within 1/2 frame if self.testOutputs and sys.platform != 'darwin': assert abs(diff) < self.win.monitorFramePeriod/2.0 if __name__ == "__main__": pytest.main(__file__)
3,275
Python
.py
79
31.367089
92
0.596226
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,540
test_circle.py
psychopy_psychopy/psychopy/tests/test_visual/test_circle.py
from pathlib import Path import pytest from psychopy import visual from .test_basevisual import _TestColorMixin, _TestUnitsMixin, _TestSerializationMixin from psychopy.tests.test_experiment.test_component_compile_python import _TestBoilerplateMixin from .. import utils class TestCircle(_TestColorMixin, _TestUnitsMixin, _TestBoilerplateMixin, _TestSerializationMixin): @classmethod def setup_class(self): self.win = visual.Window([128,128], pos=[50,50], allowGUI=False, autoLog=False) self.obj = visual.Circle(self.win, units="pix", pos=(0, 0), size=(128, 128), lineWidth=3) # Pixel which is the border color self.borderPoint = (64, 0) self.borderUsed = True # Pixel which is the fill color self.fillPoint = (64, 64) self.fillUsed = True # Shape has no foreground color self.foreUsed = False def test_radius(self): # Define some use cases cases = [ {'size': [.1, .1], 'radius': 1, 'units': 'height', 'minvertices': [-.1, -.1], 'maxvertices': [.1, .1], 'label': ".1height"}, {'size': [.1, .1], 'radius': 2, 'units': 'height', 'minvertices': [-.2, -.2], 'maxvertices': [.2, .2], 'label': ".2height"}, {'size': [.2, .2], 'radius': 0.5, 'units': 'height', 'minvertices': [-.1, -.1], 'maxvertices': [.1, .1], 'label': ".1height"}, {'size': [10, 10], 'radius': 1, 'units': 'pix', 'minvertices': [-10, -10], 'maxvertices': [10, 10], 'label': "10pix"}, {'size': [10, 10], 'radius': 2, 'units': 'pix', 'minvertices': [-20, -20], 'maxvertices': [20, 20], 'label': "20pix"}, {'size': [20, 20], 'radius': 0.5, 'units': 'pix', 'minvertices': [-10, -10], 'maxvertices': [10, 10], 'label': "10pix"}, ] # Test each case for case in cases: self.win.flip() # Apply units, size and radius self.obj.units = case['units'] self.obj.radius = case['radius'] self.obj.size = case['size'] # Check that this results in correct vertices verts = getattr(self.obj._vertices, case['units']) for i in [0, 1]: assert min(verts[:, i]) == case['minvertices'][i] assert max(verts[:, i]) == case['maxvertices'][i] # Check that vertices are drawn correctly filename = f"test_circle_radius_{case['label']}.png" self.obj.draw() # self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) # utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, self.win, crit=20)
2,815
Python
.py
58
37.948276
99
0.550382
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,541
test_textbox.py
psychopy_psychopy/psychopy/tests/test_visual/test_textbox.py
from pathlib import Path import numpy as np from psychopy import layout from psychopy.alerts import addAlertHandler from psychopy.alerts._errorHandler import _BaseErrorHandler from psychopy.tests.test_visual.test_basevisual import _TestColorMixin, _TestUnitsMixin, _TestSerializationMixin from psychopy.tests.test_experiment.test_component_compile_python import _TestBoilerplateMixin from psychopy.visual import Window from psychopy.visual import TextBox2 from psychopy.tools.fontmanager import FontManager import pytest from psychopy.tests import utils # cd psychopy/psychopy # py.test -k textbox --cov-report term-missing --cov visual/textbox @pytest.mark.textbox class Test_textbox(_TestColorMixin, _TestUnitsMixin, _TestBoilerplateMixin, _TestSerializationMixin): def setup_method(self): self.win = Window((128, 128), pos=(50, 50), monitor="testMonitor", allowGUI=False, autoLog=False) self.error = _BaseErrorHandler() addAlertHandler(self.error) self.textbox = TextBox2(self.win, "A PsychoPy zealot knows a smidge of wx, but JavaScript is the question.", placeholder="Placeholder text", font="Noto Sans", alignment="top left", lineSpacing=1, padding=0.05, pos=(0, 0), size=(1, 1), units='height', letterHeight=0.1, colorSpace="rgb") self.obj = self.textbox # point to textbox for mixin tests # Pixel which is the border color self.borderPoint = (0, 0) self.borderUsed = True # Pixel which is the fill color self.fillPoint = (2, 2) self.fillUsed = True # Textbox foreground is too unreliable due to fonts for pixel analysis self.foreUsed = False def teardown_method(self): self.win.close() def test_glyph_rendering(self): # Prepare textbox self.textbox.colorSpace = 'rgb' self.textbox.color = 'white' self.textbox.fillColor = (0, 0, 0) self.textbox.borderColor = None self.textbox.opacity = 1 # Add all Noto Sans fonts to cover widest possible base of handles characters for font in ["Noto Sans", "Noto Sans HK", "Noto Sans JP", "Noto Sans KR", "Noto Sans SC", "Noto Sans TC", "Niramit", "Indie Flower"]: self.textbox.fontMGR.addGoogleFont(font) # Some exemplar text to test basic TextBox rendering exemplars = [ # An English pangram {"text": "A PsychoPy zealot knows a smidge of wx, but JavaScript is the question.", "font": "Noto Sans", "size": 16, "screenshot": "exemplar_1.png"}, # The same pangram in IPA {"text": "ə saɪkəʊpaɪ zɛlət nəʊz ə smidge ɒv wx, bʌt ˈʤɑːvəskrɪpt ɪz ðə ˈkwɛsʧən", "font": "Noto Sans", "size": 16, "screenshot": "exemplar_2.png"}, # The same pangram in Hangul {"text": "아 프시초피 제알롣 크노W스 아 s믿게 오f wx, 붇 자v앗c립t 잇 테 q왯디온", "font": "Noto Sans KR", "size": 16, "screenshot": "exemplar_3.png"}, # A noticeably non-standard font {"text": "A PsychoPy zealot knows a smidge of wx, but JavaScript is the question.", "font": "Indie Flower", "size": 16, "screenshot": "exemplar_4.png", } ] # Some text which is likely to cause problems if something isn't working tykes = [ # Text which doesn't render properly on Mac (Issue #3203) {"text": "कोशिकायें", "font": "Noto Sans", "size": 16, "screenshot": "tyke_1.png"}, # Thai text which old Text component couldn't handle due to Pyglet {"text": "ขาว แดง เขียว เหลือง ชมพู ม่วง เทา", "font": "Niramit", "size": 16, "screenshot": "tyke_2.png" }, # Text which had the top cut off {"text": "โฬิปื้ด็ลู", "font": "Niramit", "size": 36, "screenshot": "cutoff_top.png"}, ] # Test each case and compare against screenshot for case in exemplars + tykes: self.textbox.reset() self.textbox.fontMGR.addGoogleFont(case['font']) self.textbox.letterHeight = layout.Size(case['size'], "pix", self.win) self.textbox.font = case['font'] self.textbox.text = case['text'] self.win.flip() self.textbox.draw() if case['screenshot']: # Uncomment to save current configuration as desired filename = "textbox_{}_{}".format(self.textbox._lineBreaking, case['screenshot']) #self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, self.win, crit=20) def test_ori(self): # setup textbox self.textbox.color = "black" self.textbox.fillColor = "white" self.textbox.units = "pix" self.textbox.size = (100, 50) self.textbox.pos = (0, 0) self.textbox.letterHeight = 5 # define params to use orientations = [ 0, 120, 180, 240, ] anchors = [ "top left", "center", "bottom right", ] # try each combination for ori in orientations: for anchor in anchors: # flip self.win.flip() # set params self.textbox.ori = ori self.textbox.anchor = anchor self.textbox._layout() # draw self.textbox.draw() # construct exemplar filename exemplar = f"test_ori_{ori}_{anchor}.png" # check/make exemplar # self.win.getMovieFrame(buffer='back').save( # Path(utils.TESTS_DATA_PATH) / "Test_textbox" / exemplar # ) utils.compareScreenshot( Path(utils.TESTS_DATA_PATH) / "Test_textbox" / exemplar, self.win, crit=20 ) def test_colors(self): # Do base tests _TestColorMixin.test_colors(self) # Do own custom tests self.textbox.text = "A PsychoPy zealot knows a smidge of wx, but JavaScript is the question." # Some exemplar text to test basic colors exemplars = [ # White on black in rgb {"color": (1, 1, 1), "fillColor": (-1,-1,-1), "borderColor": (-1,-1,-1), "space": "rgb", "screenshot": "colors_WOB.png"}, # White on black in named {"color": "white", "fillColor": "black", "borderColor": "black", "space": "rgb", "screenshot": "colors_WOB.png"}, # White on black in hex {"color": "#ffffff", "fillColor": "#000000", "borderColor": "#000000", "space": "hex", "screenshot": "colors_WOB.png"}, {"color": "red", "fillColor": "yellow", "borderColor": "blue", "space": "rgb", "screenshot": "colors_exemplar1.png"}, {"color": "yellow", "fillColor": "blue", "borderColor": "red", "space": "rgb", "screenshot": "colors_exemplar2.png"}, {"color": "blue", "fillColor": "red", "borderColor": "yellow", "space": "rgb", "screenshot": "colors_exemplar3.png"}, ] # Some colors which are likely to cause problems if something isn't working tykes = [ # Text only {"color": "white", "fillColor": None, "borderColor": None, "space": "rgb", "screenshot": "colors_tyke1.png"}, # Fill only {"color": None, "fillColor": "white", "borderColor": None, "space": "rgb", "screenshot": "colors_tyke2.png"}, # Border only {"color": None, "fillColor": None, "borderColor": "white", "space": "rgb", "screenshot": "colors_tyke3.png"}, ] # Test each case and compare against screenshot for case in exemplars + tykes: # Raise error if case spec does not contain all necessary keys if not all(key in case for key in ["color", "fillColor", "borderColor", "space", "screenshot"]): raise KeyError(f"Case spec for test_colors in class {self.__class__.__name__} ({__file__}) invalid, test cannot be run.") # Apply params from case spec self.textbox.colorSpace = case['space'] self.textbox.color = case['color'] self.textbox.fillColor = case['fillColor'] self.textbox.borderColor = case['borderColor'] for lineBreaking in ('default', 'uax14'): self.win.flip() self.textbox.draw() if case['screenshot']: # Uncomment to save current configuration as desired filename = "textbox_{}_{}".format(self.textbox._lineBreaking, case['screenshot']) # self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, self.win, crit=20) def test_char_colors(self): cases = [ # Named color {'text': "<c=white>Hello</c> there", 'space': "rgb", 'base': "black", 'screenshot': "white_hello_black_there"}, # Hex color {'text': "<c=#ffffff>Hello</c> there", 'space': "rgb", 'base': "black", 'screenshot': "white_hello_black_there"}, # RGB color {'text': "<c=(1, 1, 1)>Hello</c> there", 'space': "rgb", 'base': "black", 'screenshot': "white_hello_black_there"}, # RGB255 color {'text': "<c=(255, 255, 255)>Hello</c> there", 'space': "rgb255", 'base': "black", 'screenshot': "white_hello_black_there"}, # Rainbow {'text': ( "<c=red>R</c><c=orange>o</c><c=yellow>y</c> <c=green>G.</c> " "<c=blue>B</c><c=indigo>i</c><c=violet>v</c> is a colorful man and he proudly stands at " "the rainbow's end" ), 'space': "rgb", 'base': "white", 'screenshot': "roygbiv"}, ] for case in cases: # Set attributes from test cases self.textbox.colorSpace = case['space'] self.textbox.color = case['base'] self.textbox.text = case['text'] # Draw self.win.flip() self.textbox.draw() # Compare screenshot filename = "textbox_charcolors_{}_{}.png".format(self.textbox._lineBreaking, case['screenshot']) #self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, self.win, crit=20) def test_caret_position(self): # Identify key indices to test indices = ( 4, # first line 30, # wrapping line 64 # newline line ) # One array for anchor and alignment as they use the same allowed vals anchalign = ( 'center', 'top-center', 'bottom-center', 'center-left', 'center-right', 'top-left', 'top-right', 'bottom-left', 'bottom-right', ) # Try with all anchors for anchor in anchalign: # Try with all alignments for align in anchalign: # Try flipped horiz and unflipped for flipHoriz in (True, False): # Try flipped vert and unflipped for flipVert in (True, False): # Create a textbox with multiple lines of differing length from both wrapping and a newline char textbox = TextBox2( self.win, text="A PsychoPy zealot knows a smidge of wx, but JavaScript is the \nquestion.", size=(128, 64), pos=(0, 0), units='pix', anchor=anchor, alignment=align, flipHoriz=flipHoriz, flipVert=flipVert ) # Check that caret position at key indices matches character positions for i in indices: # Set caret index textbox.caret.index = i # Draw textbox to refresh verts textbox.draw() textbox.caret.draw() # Compare bottom vert of caret to bottom right vert of character (within 1 px) caretVerts = textbox.caret.vertices charVerts = textbox._vertices.pix[range((i-1) * 4, (i-1) * 4 + 4)] assert all(np.isclose(caretVerts[0], charVerts[2], 1)), ( f"Textbox caret at index {i} didn't align with bottom right corner of " f"matching char when:\n" f"anchor={anchor}, alignment={align}, flipHoriz={flipHoriz}, flipVert={flipVert}.\n" f"Caret vertices were:\n" f"{caretVerts}\n" f"Char verts were \n" f"{charVerts}\n" ) def test_typing(self): """Check that continuous typing doesn't break anything""" # Make sure the textbox has the right colours self.textbox.color = "white" self.textbox.fillColor = None self.textbox.borderColor = None # Make textbox editable wasEditable = self.textbox.editable self.textbox.editable = True # Define some cases exemplars = [ {"text": "", "font": "Noto Sans", "screenshot": "textbox_typing_blank.png"}, # No text {"text": "test←←←←", "font": "Noto Sans", "screenshot": "textbox_typing_blank.png"}, # Make some text then delete it {"text": "A PsychoPy zealot knows a smidge of wx, but JavaScript is the question.", "font": "Noto Sans", "screenshot": "textbox_typing_pangram.png"}, # Pangram {"text": "ther◀◀◀◀Hello ▶▶▶▶e", "font": "Noto Sans", "screenshot": "textbox_typing_navLR.png"}, # Try moving left/rght {"text": "Hello←o there←e◀◀◀→e", "font": "Noto Sans", "screenshot": "textbox_typing_navDel.png"}, # Try backspace/delete {"text": "Hello\nthere", "font": "Noto Sans", "screenshot": "textbox_typing_newline.png"}, # Try with a new line ] tykes = [ # { # "text": "엹 씨쓹촜 둪 캡탃뉸퀑띱 땀 젲깷굨텕하성쪟 뗸엦붊즈눂죿헶맕흁 윸끱뫏폒튯븇 땪샒죳웘핱 쑁뻸귣퀤늾녻늈냽쉜늌륝씑혅앴 잏 콡뒘 ᇵ쮣둿녩욀범 ᇖ됶쟤햔쬷쓃늅뤛섳퉃 킡 쎺뫙썛륆 뇲 짭 핫챦 켘횧뤠휦뺵촯끙 푓킘 휳잛딀꼄죘 텏룧쟨솎쿍 캋앦 ᆲ뙝뎛 낀 멟칾랟녇뙥쐊 쬻틇듥 듫엮씡붞 겡 뽕 썦썓 땤껪픐뫾툆폅륿캯 멄퇓뱫쫵 쪊쁐 픍풼뺖샷 묚볥 쟃 국땗푋믋쬩륶쩔꽆겋럛귛뤄랳 랧뉄쓠떸 놲 낟싸쑆썹 옰겏 듇쏮 쭟 럕룚뮤급윲흹뤙셄뒴뷃쁯큹뵫 톤싟뽰뾆ᆛ탠촻퀘퇅휙뚘팛모찈툣귟뺕쬸뻜 뉭뱳튯뉸 봯즉젊 령즼넃훵쏂쿼좷힆펯좲췟럥쿮 묘퀱녌됮퀟뀲텚뾠퐂놆틷궞몶챁뤩깜쉺톚 쿄빈궁 끵쿤쵨슳벥풂걊뮽 찪 볼 윚곭쑒촢ᄯ뛺 롄틴얕쫻쪠랼묥륾걅쁄퍱쨍액쩕 꽇텳쌔꺓끮봛굔쿻칡훳쒹촲볂댘얄떸밢극뿩뉳 툲굹 갰삭 첁긇꿊댠퉄캫옵즈새륳뷂봇쁆겈럵ᆬ 쓝쯙뙶벗덆뛫걾캆놫왛젂밃힑뜾뱝듉뾱껆펢끽룓 뛓 퍯볍 뵁ᇉᆚ슙 봉ᅧ민픋귲컬쵾찁뵜쇃츻ᇶ띉 쬢홀촑뇢폯 뼻릯쵊 뎴딆 퉁섀벌즿앀 몴 틮 뤗뵱 뉋쐤얇양뜴꽫 껣룮ᇂ쭉울횰 쌀툛ᄵ쉰떩쑉틱꾽횧 퐍 뙿쀎붎쳧풃멩짓뭼 봜꼦 팘둅났 ᅛ꽷쬣 믾뺠뼯쨵둎퀲캢츤절쳴 땏 깦픦힗섙 웫윆읨콭믰뀭턟쨁 쫺즽륉팂쎴 돔쪏ᆽ뿚쮩넶쥲꼱튪떍꼽 칤 튉쉷턏 첫냮됏뢤 퇘촷펆뒲팀 좊강껽옳팠숷촑뗻 랓톀 녥쌐껙 짱뚦 쇯럶브 핛 퀪뷌살턴쫕쯌헥횚픥쾅슅옉떓듻쁡꾛싟쇑뺦긜땨혽 꽬 곞쉮 쟮딦햰 뱣롱뢓튜귪땟붖 먻룃쬿쎇랍꺽핊줌켝뙩쪜럵먨녆뚨퀈깋눷떵꿛한 풪컳멸뉉썛땸캭닊걵탞 샋훪떗묭젽븀릑ᇇ웿랯튇 슌별뉅켮얤롲펫뉋흖굈렷뚞 즥쌬꾪셼쟌뽪텛쁗쨳 꺌퍎졮츑 웳 돛빳땭펃륄 쀣 씍측 뗗꿢줋쿲삙퇖쵤놻컝붐닆싷쒓킏냆뢣과캢큘랝뫖림롦쓬싡볍킍쾃숢힂덁껖녷흂냇꽙빸꼿졗밭똒ᆿ핮럹펏 풰럗쬻뾦겡톟쫱퐄슩겧솵꾔굛퉚읚왒븚얞놨껭뭨딃욵릡흇쟗콡롡뢈펞픤촀엞 퇙땨밹귥직턣탂탂큨뽇ᄞ숀턢쁻츕 샼졒쁷웚퀭엡겙 끴컍 뱟쯮뉖펼읲뛓꿢쿤쟢얫 쟳랷ᅵ눙뫂 늚 냋츤킓팝꿂윮쥮힓윾럯턏몄픮뙜컉꼕폄 좁쇋쳠딃좡슦췃킙옅얷쇇짗탻뮏곞킣능쁕췉챖집됂 클똁 뒦잳층먯ᄁ쪂 쥄겸 굇넢뛞 맶췠챳츖귦뤔솀엸빲뾎뫜냃겱낾뭾뮑 뙹갾뗪뱐두ᄇ겈꿂솫 쎎뿽 얓믡썕췠핁혎 ᆆ헮륎촀몭덙쨄딀쵂 볋쭨볃 볌휣ᇣ ᆫ킩쪕햭퇽멂볾쵁 똺넡뗨잺 뵁귓퐽멪뽪 횉 쥋궾셺벊녁밊 ", # "font": "Noto Sans KR", # "screenshot": "textbox_typing_longKoeran.png" # }, # https://discourse.psychopy.org/t/textbox2-crashes-when-korean-input-exceed-certain-length/22717/6 { "text": "i need a word which will go off the page, antidisestablishmentarianism is a very long word", "font": "Open Sans", "screenshot": "textbox_typing_longWord.png" }, # Check that lines wrap correctly when there's a very long word, rather than as described in https://github.com/psychopy/psychopy/issues/3892 ] for case in exemplars + tykes: self.textbox.font = case['font'] self.textbox.text = "" for letter in case['text']: # Handle cursor key placeholders if letter == '◀': self.textbox._onCursorKeys('MOTION_LEFT') elif letter == '▶': self.textbox._onCursorKeys('MOTION_RIGHT') elif letter == '←': self.textbox._onCursorKeys('MOTION_BACKSPACE') elif letter == '→': self.textbox._onCursorKeys('MOTION_DELETE') else: # Input text self.textbox._onText(letter) self.textbox.draw() self.win.flip() if case['screenshot']: self.win.flip() self.textbox.draw() # Force caret to draw for consistency self.textbox.caret.draw(override=True) #self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / case['screenshot']) utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / case['screenshot'], self.win, crit=20) # Set editable back to start value self.textbox.editable = wasEditable def test_basic(self): pass def test_editable(self): # Make textbox editable self.textbox.editable = True # Make a second textbox, which is editable from init textbox2 = TextBox2(self.win, "", "Noto Sans", pos=(0.5, 0.5), size=(1, 1), units='height', letterHeight=0.1, colorSpace="rgb", editable=True) # Check that both are editable children of the window editables = [] for ref in self.win._editableChildren: editables.append(ref()) # Actualise weakrefs assert self.textbox in editables assert textbox2 in editables # Set current editable to textbox 1 self.win.currentEditable = self.textbox # Make sure next editable is textbox 2 self.win.nextEditable() assert self.win.currentEditable == textbox2 # Make each textbox no longer editable self.textbox.editable = False textbox2.editable = False # Make sure they are no longer editable children of the window editables = [] for ref in self.win._editableChildren: editables.append(ref()) # Actualise weakrefs assert self.textbox not in editables assert textbox2 not in editables # Cleanup del textbox2 def test_alignment(self): # Define classic use cases exemplars = [ "top left", "top center", "top right", "center left", "center center", "center right", "bottom left", "bottom center", "bottom right", ] # Some potentially problematic use cases which should be handled tykes = [ "center", "centre", "centre centre", "someword", "more than two words", ] # Get intial textbox params initParams = {} for param in ["units", "fillColor", "color", "padding", "letterHeight", "alignment", "text"]: initParams[param] = getattr(self.textbox, param) # Test for case in exemplars + tykes: for units in layout.unitTypes: # Setup textbox self.textbox.text = "A PsychoPy zealot knows a smidge of wx but JavaScript is the question." self.textbox.fillColor = "white" self.textbox.color = "black" self.textbox.padding = 0 self.textbox.letterHeight = layout.Size((0, 10), units="pix", win=self.win) # Set test attributes self.textbox.units = units self.textbox.alignment = case # Draw and compare self.textbox.draw() #self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / f"textbox_{self.textbox._lineBreaking}_align_{case.replace(' ', '_')}.png") utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / f"textbox_{self.textbox._lineBreaking}_align_{case.replace(' ', '_')}.png", self.win, crit=20) self.win.flip() # Reset initial params for param, value in initParams.items(): setattr(self.textbox, param, value) def test_speechpoint(self): self.obj.size = (0.5, 0.5) self.obj.fillColor = "red" # Create list of points to test cases = [ (-3/8, 0), (3/8, 0), (0, -3/8), (0, 3/8) ] for x, y in cases: # Prepare window self.win.flip() # Set from case self.obj.speechPoint = (x, y) # Draw self.obj.draw() # Compare screenshots filename = f"{self.__class__.__name__}_testSpeechpoint_{int(x*8)}ovr8_{int(y*8)}ovr8.png" # self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) utils.compareScreenshot(filename, self.win, crit=8) self.obj.speechPoint = None def test_alerts(self): noFontTextbox = TextBox2(self.win, "", font="Raleway Dots", bold=True) assert (self.error.alerts[0].code == 4325) def test_letter_spacing(self): cases = (0.6, 0.8, 1, None, 1.2, 1.4, 1.6, 1.8, 2.0) for case in cases: self.win.flip() # Set letter spacing self.obj.letterSpacing = case # Draw self.obj.draw() # Compare nameSafe = str(case).replace(".", "p") filename = Path(utils.TESTS_DATA_PATH) / f"TestTextbox_testLetterSpacing_{nameSafe}.png" self.win.getMovieFrame(buffer='back').save(filename) utils.compareScreenshot(filename, self.win, crit=20) def test_font_manager(): # Create a font manager mgr = FontManager() # Check that it finds fonts which should be pre-packaged with PsychoPy in the resources folder assert bool(mgr.getFontNamesSimilar("Open Sans")) # Check that it doesn't find fonts which aren't installed as default assert not bool(mgr.getFontNamesSimilar("Dancing Script")) # Check that it can install fonts from Google mgr.addGoogleFont("Hanalei") # Check that these fonts are found once installed assert bool(mgr.getFontNamesSimilar("Hanalei")) @pytest.mark.uax14 class Test_uax14_textbox(Test_textbox): """Runs the same tests as for Test_textbox, but with the textbox set to uax14 line breaking""" def setup_method(self): Test_textbox.setup_method(self) self.textbox._lineBreaking = 'uax14'
25,750
Python
.py
482
36.390041
1,029
0.55982
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,542
test_basevisual.py
psychopy_psychopy/psychopy/tests/test_visual/test_basevisual.py
import json import pytest import importlib from copy import copy from pathlib import Path from psychopy import visual, layout, event, colors from psychopy.tools.stimulustools import serialize, actualize from psychopy.monitors import Monitor from psychopy.tests import utils class _TestSerializationMixin: """ Tests that stimuli can be serialized and recreated from serialized form. """ # placeholders for object and window obj = None win = None def test_serialization(self): # skip if we don't have an object if self.obj is None or self.win is None: pytest.skip() # start by flipping the window self.win.flip() # serialize object params = serialize(self.obj, includeClass=True) # substitute win params['win'] = self.win # recreate object from params dupe = actualize(params) # check object is same class assert isinstance(dupe, type(self.obj)) # delete duplicate del dupe class _TestColorMixin: # Define expected values for different spaces colorExemplars = [ {'rgb': (1.00, 1.00, 1.00), 'rgb255': (255, 255, 255), 'hsv': (0, 0.00, 1.00), 'hex': '#ffffff', 'named': 'white'}, # Pure white {'rgb': (0.00, 0.00, 0.00), 'rgb255': (128, 128, 128), 'hsv': (0, 0.00, 0.50), 'hex': '#808080', 'named': 'gray'}, # Mid grey {'rgb': (-1.00, -1.00, -1.00), 'rgb255': (0, 0, 0), 'hsv': (0, 0.00, 0.00), 'hex': '#000000', 'named': 'black'}, # Pure black {'rgb': (1.00, -1.00, -1.00), 'rgb255': (255, 0, 0), 'hsv': (0, 1.00, 1.00), 'hex': '#ff0000', 'named': 'red'}, # Pure red {'rgb': (-1.00, 1.00, -1.00), 'rgb255': (0, 255, 0), 'hsv': (120, 1.00, 1.00), 'hex': '#00ff00', 'named': 'lime'}, # Pure green {'rgb': (-1.00, -1.00, 1.00), 'rgb255': (0, 0, 255), 'hsv': (240, 1.00, 1.00), 'hex': '#0000ff', 'named': 'blue'}, # Pure blue # Psychopy colours {'rgb': (-0.20, -0.20, -0.14), 'rgb255': (102, 102, 110), 'hsv': (240, 0.07, 0.43), 'hex': '#66666e'}, # grey {'rgb': (0.35, 0.35, 0.38), 'rgb255': (172, 172, 176), 'hsv': (240, 0.02, 0.69), 'hex': '#acacb0'}, # light grey {'rgb': (0.90, 0.90, 0.90), 'rgb255': (242, 242, 242), 'hsv': (0, 0.00, 0.95), 'hex': '#f2f2f2'}, # offwhite {'rgb': (0.90, -0.34, -0.29), 'rgb255': (242, 84, 91), 'hsv': (357, 0.65, 0.95), 'hex': '#f2545b'}, # red {'rgb': (-0.98, 0.33, 0.84), 'rgb255': (2, 169, 234), 'hsv': (197, 0.99, 0.92), 'hex': '#02a9ea'}, # blue {'rgb': (-0.15, 0.60, -0.09), 'rgb255': (108, 204, 116), 'hsv': (125, 0.47, 0.80), 'hex': '#6ccc74'}, # green {'rgb': (0.85, 0.18, -0.98), 'rgb255': (236, 151, 3), 'hsv': (38, 0.99, 0.93), 'hex': '#ec9703'}, # orange {'rgb': (0.89, 0.65, -0.98), 'rgb255': (241, 211, 2), 'hsv': (52, 0.99, 0.95), 'hex': '#f1d302'}, # yellow {'rgb': (0.53, 0.49, 0.94), 'rgb255': (195, 190, 247), 'hsv': (245, 0.23, 0.97), 'hex': '#c3bef7'}, # violet ] # A few values which are likely to mess things up colorTykes = [ {'rgba': (1.00, 1.00, 1.00, 0.50), 'rgba255': (255, 255, 255, 0.50), 'hsva': (0, 0.00, 1.00, 0.50)}, # Make sure opacities work in every space {'rgba': "white", 'rgba255': "white", "hsva": "white", "hex": "white", "rgb255": "#ffffff"}, # Overriding colorSpace with hex or named values {'rgba': None, 'named': None, 'hex': None, 'hsva': None}, # None as a value ] # Pixel which is the border color borderPoint = (0, 0) borderUsed = False # Pixel which is the fill color fillPoint = (50, 50) fillUsed = False # Pixel which is the fore color forePoint = (50, 50) foreUsed = False # Placeholder for testing object and window obj = None win = None def test_colors(self): # If this test object has no obj, skip if not self.obj: return # Test each case for case in self.colorTykes + self.colorExemplars: for space, color in case.items(): # Make color to compare against target = colors.Color(color, space) # Prepare object self.obj.colorSpace = space self.obj.fillColor = 'white' self.obj.foreColor = 'white' self.obj.borderColor = 'white' self.obj.opacity = 1 if hasattr(self.obj, "text"): self.obj.text = "A PsychoPy zealot knows a smidge of wx, but JavaScript is the question." # Prepare window self.win.flip() # Test fill color if self.fillUsed: # Set fill self.obj.fillColor = color self.obj.opacity = 1 self.obj.draw() if color is not None: # Make sure fill is set utils.comparePixelColor(self.win, target, coord=self.fillPoint, context=f"{self.__class__.__name__}_fill") # Make sure border is not if self.borderUsed: utils.comparePixelColor(self.win, colors.Color('white'), coord=self.borderPoint, context=f"{self.__class__.__name__}_fill") # Make sure fore is not if self.foreUsed: utils.comparePixelColor(self.win, colors.Color('white'), coord=self.forePoint, context=f"{self.__class__.__name__}_fill") # Reset fill self.obj.fillColor = 'white' self.obj.opacity = 1 # Test border color if self.borderUsed: # Set border self.obj.borderColor = color self.obj.opacity = 1 self.obj.draw() if color is not None: # Make sure border is set utils.comparePixelColor(self.win, target, coord=self.borderPoint, context=f"{self.__class__.__name__}_border") # Make sure fill is not if self.fillUsed: utils.comparePixelColor(self.win, colors.Color('white'), coord=self.fillPoint, context=f"{self.__class__.__name__}_border") # Make sure fore is not if self.foreUsed: utils.comparePixelColor(self.win, colors.Color('white'), coord=self.forePoint, context=f"{self.__class__.__name__}_border") # Reset border self.obj.borderColor = 'white' self.obj.opacity = 1 # Test fore color if self.foreUsed: # Set fore self.obj.foreColor = color self.obj.opacity = 1 self.obj.draw() if color is not None: # Make sure fore is set utils.comparePixelColor(self.win, target, coord=self.forePoint, context=f"{self.__class__.__name__}_fore") # Make sure fill is not if self.fillUsed: utils.comparePixelColor(self.win, colors.Color('white'), coord=self.fillPoint, context=f"{self.__class__.__name__}_fore") # Make sure border is not if self.borderUsed: utils.comparePixelColor(self.win, colors.Color('white'), coord=self.borderPoint, context=f"{self.__class__.__name__}_fore") # Reset fore self.obj.foreColor = 'white' self.obj.opacity = 1 def test_legacy_setters(self): # If this test object has no obj, skip if not self.obj: return # Test each case for case in self.colorTykes + self.colorExemplars: for space, color in case.items(): if color is None: continue # Make color to compare against target = colors.Color(color, space) # Prepare object self.obj.colorSpace = space self.obj.fillColor = 'white' self.obj.foreColor = 'white' self.obj.borderColor = 'white' self.obj.opacity = 1 if hasattr(self.obj, "text"): self.obj.text = "A PsychoPy zealot knows a smidge of wx, but JavaScript is the question." # Test property aliases: # color == foreColor self.obj.color = color assert self.obj._foreColor == target self.obj.color = colors.Color('white') self.obj.opacity = 1 # backColor == fillColor self.obj.backColor = color assert self.obj._fillColor == target self.obj.backColor = colors.Color('white') self.obj.opacity = 1 # lineColor == borederColor self.obj.lineColor = color assert self.obj._borderColor == target self.obj.lineColor = colors.Color('white') self.obj.opacity = 1 if space == 'rgb': # Test RGB properties # foreRGB self.obj.foreRGB = color assert self.obj._foreColor == target self.obj.foreRGB = colors.Color('white') self.obj.opacity = 1 # RGB self.obj.RGB = color assert self.obj._foreColor == target self.obj.RGB = colors.Color('white') self.obj.opacity = 1 # fillRGB self.obj.fillRGB = color assert self.obj._fillColor == target self.obj.fillRGB = colors.Color('white') self.obj.opacity = 1 # backRGB self.obj.backRGB = color assert self.obj._fillColor == target self.obj.backRGB = colors.Color('white') self.obj.opacity = 1 # borderRGB self.obj.borderRGB = color assert self.obj._borderColor == target self.obj.borderRGB = colors.Color('white') self.obj.opacity = 1 # lineRGB self.obj.lineRGB = color assert self.obj._borderColor == target self.obj.lineRGB = colors.Color('white') self.obj.opacity = 1 # Test RGB methods # setRGB self.obj.setRGB(color) assert self.obj._foreColor == target self.obj.setRGB('white') self.obj.opacity = 1 # setFillRGB self.obj.setFillRGB(color) assert self.obj._fillColor == target self.obj.setFillRGB('white') self.obj.opacity = 1 # setBackRGB self.obj.setBackRGB(color) assert self.obj._fillColor == target self.obj.setBackRGB('white') self.obj.opacity = 1 # setBorderRGB self.obj.setBorderRGB(color) assert self.obj._borderColor == target self.obj.setBorderRGB('white') self.obj.opacity = 1 # setLineRGB self.obj.setLineRGB(color) assert self.obj._borderColor == target self.obj.setLineRGB('white') self.obj.opacity = 1 # Test methods: # setForeColor self.obj.setForeColor(color) assert self.obj._foreColor == target self.obj.setForeColor('white') self.obj.opacity = 1 # setColor self.obj.setColor(color) assert self.obj._foreColor == target self.obj.setColor('white') self.obj.opacity = 1 # setFillColor self.obj.setFillColor(color) assert self.obj._fillColor == target self.obj.setFillColor('white') self.obj.opacity = 1 # setBackColor self.obj.setBackColor(color) assert self.obj._fillColor == target self.obj.setBackColor('white') self.obj.opacity = 1 # setBorderColor self.obj.setBorderColor(color) assert self.obj._borderColor == target self.obj.setBorderColor('white') self.obj.opacity = 1 # setLineColor self.obj.setLineColor(color) assert self.obj._borderColor == target self.obj.setLineColor('white') self.obj.opacity = 1 # Test old color space setters # foreColorSpace self.obj.foreColorSpace = space assert self.obj.colorSpace == space self.obj.foreColorSpace = 'named' # fillColorSpace self.obj.fillColorSpace = space assert self.obj.colorSpace == space self.obj.fillColorSpace = 'named' # backColorSpace self.obj.backColorSpace = space assert self.obj.colorSpace == space self.obj.backColorSpace = 'named' # borderColorSpace self.obj.borderColorSpace = space assert self.obj.colorSpace == space self.obj.borderColorSpace = 'named' # lineColorSpace self.obj.lineColorSpace = space assert self.obj.colorSpace == space self.obj.lineColorSpace = 'named' class _TestUnitsMixin: """ Base tests for all objects which use units """ # Define exemplar positions (assumes win.pos = (256, 128) and 1cm = 64 pix) posExemplars = [ {'suffix': "center_center", 'norm': (0, 0), 'height': (0, 0), 'pix': (0, 0), 'cm': (0, 0)}, {'suffix': "bottom_left", 'norm': (-1, -1), 'height': (-1, -0.5), 'pix': (-128, -64), 'cm': (-2, -1)}, {'suffix': "top_left", 'norm': (-1, 1), 'height': (-1, 0.5), 'pix': (-128, 64), 'cm': (-2, 1)}, {'suffix': "bottom_right", 'norm': (1, -1), 'height': (1, -0.5), 'pix': (128, -64), 'cm': (2, -1)}, {'suffix': "top_right", 'norm': (1, 1), 'height': (1, 0.5), 'pix': (128, 64), 'cm': (2, 1)}, ] posTykes = [] # Define exemplar sizes (assumes win.pos = (256, 128) and 1cm = 64 pix) sizeExemplars = [ {'suffix': "w128h128", 'norm': (1, 2), 'height': (1, 1), 'pix': (128, 128), 'cm': (2, 2)}, {'suffix': "w128h64", 'norm': (1, 1), 'height': (1, 0.5), 'pix': (128, 64), 'cm': (2, 1)}, {'suffix': "w64h128", 'norm': (0.5, 2), 'height': (0.5, 1), 'pix': (64, 128), 'cm': (1, 2)}, {'suffix': "w64h64", 'norm': (0.5, 1), 'height': (0.5, 0.5), 'pix': (64, 64), 'cm': (1, 1)}, ] sizeTykes = [] # Placeholder for testing object and window obj = None win = None def test_pos_size(self): # If this test object has no obj, skip if not self.obj: return # Setup window for this test monitor = Monitor("testMonitor") monitor.setSizePix((256, 128)) monitor.setWidth(4) monitor.setDistance(50) win = visual.Window(size=(256, 128), monitor=monitor) win.useRetina = False # Setup object for this test obj = copy(self.obj) obj.win = win if hasattr(obj, "fillColor"): obj.fillColor = 'red' if hasattr(obj, "foreColor"): obj.foreColor = 'blue' if hasattr(obj, 'borderColor'): obj.borderColor = 'green' if hasattr(obj, 'opacity'): obj.opacity = 1 # Run positions through each size exemplar for size in self.sizeExemplars + self.sizeTykes: for pos in self.posExemplars + self.posTykes: for units in set(list(pos) + list(size)): if units == 'suffix': continue # Set pos and size obj.units = units obj.size = size[units] obj.pos = pos[units] # Draw obj.draw() # Compare screenshot filename = f"{self.__class__.__name__}_{size['suffix']}_{pos['suffix']}.png" #win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) utils.compareScreenshot(filename, win, crit=8) win.flip() # Cleanup win.close() del obj del win # def test_wh_setters(self): # """ # Test that the width and height setters function the same as using the size setter # """ # # Define some sizes to try out # cases = [ # {'size': 100, # 'units': 'pix'}, # {'size': 200, # 'units': 'pix'}, # ] # # Create duplicate of object for safety # obj = copy(self.obj) # # Try each case # for case in cases: # # Set units # obj.units = case['units'] # # Set width and height using setters # obj.width = case['size'] # obj.height = case['size'] # # Check that the resulting size is as desired # assert all(obj.size == case['size']) def test_unit_mismatch(self): """ Test that a given stimulus can be drawn without error in all combinations of stimulus units x window units and checking that it looks the same as when both units are pix. """ # Test all unit types apart from None and "" unitTypes = layout.unitTypes[2:] # Create window (same size as was used for other tests) win = visual.Window(self.obj.win.size, pos=self.obj.win.pos, monitor="testMonitor") # Create object obj = copy(self.obj) obj.win = win # Create model image (pix units for both) win.units = 'pix' obj.units = 'pix' obj.draw() filename = Path(utils.TESTS_DATA_PATH) / "test_unit_mismatch.png" win.getMovieFrame(buffer='back').save(filename) if hasattr(obj, "_size"): # Get model sizes targetSizes = {units: getattr(obj._size, units) for units in unitTypes} # Flip screen win.flip() # Iterate through window and object units for winunits in unitTypes: for objunits in unitTypes: # Create a window and object win.units = winunits obj.units = objunits # Draw object obj.draw() # Compare appearance utils.compareScreenshot(filename, win, tag=f"{winunits}X{objunits}") if hasattr(obj, "_size"): # Compare reported size assert layout.Size(obj.size, obj.units, obj.win) == layout.Size(targetSizes[objunits], objunits, obj.win), ( f"Object size ({obj.size}, in {obj.units}) did not match desired size ({targetSizes[objunits]} " f"in {objunits} when window was {obj.win.size}px in {winunits}." ) # Flip screen win.flip() # Close window win.close() # Delete model image filename.unlink() def test_manual(self): """ For local use only: Uncomment desired manual tests to have them picked up by the test suite when you next run it. Useful as it means you can actually interact with the stimulus to make sure it behaves right, rather than relying on static screenshot comparisons. IMPORTANT: Comment them back out before committing, otherwise the test suite will stall! """ # self.manual_unit_mismatch() def manual_unit_mismatch(self): """ For manually testing stimulus x window unit mismatches. Won't be run by the test suite but can be useful to run yourself as it allows you to interact with the stimulus to make sure it's working as intended. """ # Test all unit types apart from None and "" unitTypes = layout.unitTypes[2:] # Load / create file to store reference to combinations which are marked as good (saves time) goodPath = Path(utils.TESTS_DATA_PATH) / "manual_unit_test_good_local.json" if goodPath.is_file(): # Load good file if present with open(goodPath, "r") as f: good = json.loads(f.read()) else: # Create good file if not good = [] with open(goodPath, "w") as f: f.write("[]") # Iterate through window and object units for winunits in unitTypes: for objunits in unitTypes: # If already marked as good, skip this combo if [winunits, objunits] in good: continue try: # Create a window and object win = visual.Window(monitor="testMonitor", units=winunits) win.monitor.setSizePix((256, 128)) win.monitor.setWidth(4) win.monitor.setDistance(50) obj = copy(self.obj) obj.win = win obj.units = objunits # Add a label for the units label = visual.TextBox2(win, text=f"Window: {winunits}, Slider: {objunits}", font="Open Sans", anchor="top-center", alignment="center top", padding=0.05, units="norm", pos=(0, 1)) # Add instructions instr = visual.TextBox2(win, text=( f"Press ENTER if object is functioning as intended, otherwise press " f"any other key." ), font="Open Sans", anchor="top-center", alignment="center bottom", padding=0.05, units="norm", pos=(0, -1)) # Draw loop until button is pressed keys = [] while not keys: keys = event.getKeys() obj.draw() label.draw() instr.draw() win.flip() if 'return' in keys: # If enter was pressed, mark as good good.append([winunits, objunits]) with open(goodPath, "w") as f: f.write(json.dumps(good)) else: # If any other key was pressed, mark as bad raise AssertionError( f"{self.obj.__class__.__name__} marked as bad when its units were {objunits} and window " f"units were {winunits}" ) win.close() except BaseException as err: err.args = err.args + ([winunits, objunits],) raise err def test_default_units(self): for units in layout.unitTypes: if units in [None, "None", "none", ""]: continue # Create a window with given units win = visual.Window(monitor="testMonitor", units=units) win.monitor.setSizePix((256, 128)) win.monitor.setWidth(4) win.monitor.setDistance(50) # When setting units to None with win, does it inherit units? self.obj.win = win self.obj.units = None assert self.obj.units == units # Cleanup win.close() del win # Reset obj win self.obj.win = self.win
24,981
Python
.py
533
32.037523
151
0.497727
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,543
test_gamma.py
psychopy_psychopy/psychopy/tests/test_visual/test_gamma.py
from psychopy import visual, monitors import numpy from psychopy.tests import skip_under_vm @skip_under_vm(reason="Cannot test gamma in a virtual machine") def test_low_gamma(): """setting gamma low (dark screen)""" win = visual.Window([600,600], gamma=0.5, autoLog=False) # should make the entire screen bright for n in range(5): win.flip() assert win.useNativeGamma == False win.close() @skip_under_vm(reason="Cannot test gamma in a virtual machine") def test_mid_gamma(): """setting gamma high (bright screen)""" win = visual.Window([600,600], gamma=2.0, autoLog=False)#should make the entire screen bright for n in range(5): win.flip() assert win.useNativeGamma==False win.close() @skip_under_vm(reason="Cannot test gamma in a virtual machine") def test_high_gamma(): """setting gamma high (bright screen)""" win = visual.Window([600,600], gamma=4.0, autoLog=False)#should make the entire screen bright for n in range(5): win.flip() assert win.useNativeGamma==False win.close() @skip_under_vm(reason="Cannot test gamma in a virtual machine") def test_no_gamma(): """check that no gamma is used if not passed""" win = visual.Window([600,600], autoLog=False)#should not change gamma assert win.useNativeGamma==True win.close() """Or if gamma is provided but by a default monitor?""" win = visual.Window([600,600], monitor='blaah', autoLog=False)#should not change gamma assert win.useNativeGamma==True win.close() @skip_under_vm(reason="Cannot test gamma in a virtual machine") def test_monitorGetGamma(): #create our monitor object gammaVal = [2.2, 2.2, 2.2] mon = monitors.Monitor('test') mon.setGamma(gammaVal) #create window using that monitor win = visual.Window([100,100], monitor=mon, autoLog=False) assert numpy.alltrue(win.gamma==gammaVal) win.close() @skip_under_vm(reason="Cannot test gamma in a virtual machine") def test_monitorGetGammaGrid(): #create (outdated) gamma grid (new one is [4,6]) newGrid = numpy.array([[0,150,2.0],#lum [0,30,2.0],#r [0,110,2.0],#g [0,10,2.0]],#b ) mon = monitors.Monitor('test') mon.setGammaGrid(newGrid) win = visual.Window([100,100], monitor=mon, autoLog=False) assert numpy.alltrue(win.gamma==numpy.array([2.0, 2.0, 2.0])) win.close() @skip_under_vm(reason="Cannot test gamma in a virtual machine") def test_monitorGetGammaAndGrid(): """test what happens if gamma (old) and gammaGrid (new) are both present""" #create (outdated) gamma grid (new one is [4,6]) newGrid = numpy.array([[0,150,2.0],#lum [0,30,2.0],#r [0,110,2.0],#g [0,10,2.0]],#b ) mon = monitors.Monitor('test') mon.setGammaGrid(newGrid) mon.setGamma([3,3,3]) #create window using that monitor win = visual.Window([100,100], monitor=mon, autoLog=False) assert numpy.alltrue(win.gamma==numpy.array([2.0, 2.0, 2.0])) win.close() @skip_under_vm(reason="Cannot test gamma in a virtual machine") def test_setGammaRamp(): """test that the gamma ramp is set as requested""" testGamma = 2.2 win = visual.Window([600,600], autoLog=False) desiredRamp = numpy.tile( visual.gamma.createLinearRamp( rampSize=win.backend.getGammaRampSize(), driver=win.backend._driver ), (3, 1) ) if numpy.all(testGamma == 1.0) == False: # correctly handles 1 or 3x1 gamma vals desiredRamp = desiredRamp**(1.0/numpy.array(testGamma)) win.gamma = testGamma for n in range(5): win.flip() setRamp = win.backend.getGammaRamp() win.close() assert numpy.allclose(desiredRamp, setRamp, atol=1.0 / desiredRamp.shape[1]) @skip_under_vm(reason="Cannot test gamma in a virtual machine") def test_gammaSetGetMatch(): """test that repeatedly getting and setting the gamma table has no cumulative effect.""" startGammaTable = None n_repeats = 2 for _ in range(n_repeats): win = visual.Window([600, 600], autoLog=False) for _ in range(5): win.flip() if startGammaTable is None: startGammaTable = win.backend.getGammaRamp() else: currGammaTable = win.backend.getGammaRamp() assert numpy.all(currGammaTable == startGammaTable) win.close() if __name__=='__main__': test_high_gamma()
4,645
Python
.py
115
33.330435
100
0.643223
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,544
test_target.py
psychopy_psychopy/psychopy/tests/test_visual/test_target.py
from psychopy import visual, layout from .test_basevisual import _TestColorMixin, _TestUnitsMixin, _TestSerializationMixin class TestTarget(_TestUnitsMixin, _TestSerializationMixin): # Pixel which is the border color borderPoint = (0, 55) borderUsed = True # Pixel which is the fill color fillPoint = (0, 30) fillUsed = False # Pixel which is the fore color forePoint = (0, 0) foreUsed = False @classmethod def setup_class(cls): cls.win = visual.Window(size=(128, 128)) cls.obj = visual.TargetStim(cls.win, "TargetStim", units='pix', pos=(-64, 64), innerRadius=20, radius=60, lineWidth=10, innerLineWidth=5) def test_radius(self): # Define some cases to test cases = [ {"outer": 1, "inner": 0.5, "units": "height"}, {"outer": 100, "inner": 50, "units": "pix"}, ] for case in cases: # Set radiae (radiuses?) and units self.obj.units = case['units'] self.obj.outerRadius = case['outer'] self.obj.innerRadius = case['inner'] # Check that the target's size is set to twice the radius value assert self.obj.outer._size == layout.Size(case['outer']*2, case['units'], self.win) assert self.obj.inner._size == layout.Size(case['inner']*2, case['units'], self.win)
1,400
Python
.py
31
36.290323
96
0.608059
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,545
test_form.py
psychopy_psychopy/psychopy/tests/test_visual/test_form.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from pathlib import Path import pytest from pandas import DataFrame from psychopy.tests.test_visual.test_basevisual import _TestColorMixin, _TestSerializationMixin from psychopy.tests.test_experiment.test_component_compile_python import _TestBoilerplateMixin from psychopy.visual.window import Window from psychopy.visual.form import Form from psychopy.visual.textbox2.textbox2 import TextBox2 from psychopy.visual.slider import Slider from psychopy.tests import utils import shutil from tempfile import mkdtemp import numpy as np class Test_Form(_TestColorMixin, _TestBoilerplateMixin, _TestSerializationMixin): """Test suite for Form component""" def setup_class(self): # Store different response types self.respTypes = ['heading', 'description', 'rating', 'slider', 'free text', 'choice', 'radio'] # Create temp files for storing items self.temp_dir = mkdtemp() self.fileName_xlsx = os.path.join(self.temp_dir, 'items.xlsx') self.fileName_csv = os.path.join(self.temp_dir, 'items.csv') # create some questions self.questions = [] self.genderItem = {"questionText": "What is your gender?", "questionWidth": 0.7, "type": "radio", "responseWidth": 0.3, "options": "Male, Female, Other", "layout": 'vert', "index": 0, "questionColor": "white", "responseColor": "white" } self.questions.append(self.genderItem) # then a set of ratings items = ["running", "cake", "programming"] for idx, item in enumerate(items): entry = {"questionText": "How much you like {}".format(item), "questionWidth": 0.7, "type": "rating", "responseWidth": 0.3, "options":"Lots, some, Not a lot, Longest Option", "layout": 'horiz', "index": idx+1, "questionColor": "white", "responseColor": "white" } self.questions.append(entry) self.win = Window(units='height', allowStencil=True, autoLog=False) self.survey = Form(self.win, items=self.questions, size=(1.0, 0.3), pos=(0.0, 0.0), autoLog=False) self.obj = self.survey # Pixel coord of top left corner tl = (round(self.obj.win.size[0]/2 - 1*self.obj.win.size[1]/2), round(self.obj.win.size[1]/2 - 0.3*self.obj.win.size[1]/2)) # Pixel which is the border color self.obj.border.lineWidth = 2 self.borderPoint = (tl[1], tl[0]) self.borderUsed = True # Pixel which is the fill color self.fillPoint = (tl[1]+4, tl[0]+4) self.fillUsed = True # Create datafiles df = DataFrame(self.questions) df.to_excel(self.fileName_xlsx, index=False) df.to_csv(self.fileName_csv, index=False) def test_importItems(self): wrongFields = [{"a": "What is your gender?", "b": 0.7, "c": "radio", "d": 0.3, "e": "Male, Female, Other", "f": 'vert', "g": "white", "h": "white" }] # this doesn't include a itemText or questionText so should get an err missingHeader = [{"qText": "What is your gender?", "questionWidth": 0.7, "type": "radio", "responseWidth": 0.3, "options": "Other", "layout": 'vert', "index": 0, "questionColor": "white", "responseColor": "white"}] # Check options for list of dicts with pytest.raises(ValueError): self.survey = Form(self.win, items=missingHeader, size=(1.0, 0.3), pos=(0.0, 0.0), autoLog=False) # Check csv self.survey = Form(self.win, items=self.fileName_csv, size=(1.0, 0.3), pos=(0.0, 0.0), autoLog=False) # Check Excel self.survey = Form(self.win, items=self.fileName_xlsx, size=(1.0, 0.3), pos=(0.0, 0.0), randomize=False, autoLog=False) def test_combinations(self): """ Test that question options interact well """ # Define sets of each option exemplars = { 'bigResp': [ # Resp is bigger than item { 'index': 1, 'itemText': "A PsychoPy zealot knows a smidge of wx but JavaScript is the question", 'options': [1, "a", "multiple word"], 'ticks': [1, 2, 3], 'layout': 'vert', 'itemColor': 'darkslateblue', 'itemWidth': 0.3, 'responseColor': 'darkred', 'responseWidth': 0.7, 'font': 'Open Sans', }, { 'index': 0, 'itemText': "A PsychoPy zealot knows a smidge of wx but JavaScript is the question", 'options': [1, "a", "multiple word"], 'ticks': [1, 2, 3], 'layout': 'horiz', 'itemColor': 'darkred', 'itemWidth': 0.3, 'responseColor': 'darkslateblue', 'responseWidth': 0.7, 'font': 'Open Sans', }, ], 'bigItem': [ # Item is bigger than resp { 'index': 1, 'itemText': "A PsychoPy zealot knows a smidge of wx but JavaScript is the question", 'options': [1, "a", "multiple word"], 'ticks': [1, 2, 3], 'layout': 'vert', 'itemColor': 'darkslateblue', 'itemWidth': 0.7, 'responseColor': 'darkred', 'responseWidth': 0.3, 'font': 'Open Sans', }, { 'index': 0, 'itemText': "A PsychoPy zealot knows a smidge of wx but JavaScript is the question", 'options': [1, "a", "multiple word"], 'ticks': [1, 2, 3], 'layout': 'horiz', 'itemColor': 'darkred', 'itemWidth': 0.7, 'responseColor': 'darkslateblue', 'responseWidth': 0.3, 'font': 'Open Sans', }, ], } tykes = { 'bigRespOverflow': [ # Resp is bigger than item, both together flow over form edge { 'index': 1, 'itemText': "A PsychoPy zealot knows a smidge of wx but JavaScript is the question", 'options': [1, "a", "multiple word"], 'ticks': [1, 2, 3], 'layout': 'vert', 'itemColor': 'darkslateblue', 'itemWidth': 0.4, 'responseColor': 'darkred', 'responseWidth': 0.8, 'font': 'Open Sans', }, { 'index': 0, 'itemText': "A PsychoPy zealot knows a smidge of wx but JavaScript is the question", 'options': [1, "a", "multiple word"], 'ticks': [1, 2, 3], 'layout': 'horiz', 'itemColor': 'darkred', 'itemWidth': 0.4, 'responseColor': 'darkslateblue', 'responseWidth': 0.8, 'font': 'Open Sans', }, ], 'bigItemOverflow': [ # Item is bigger than resp, both together flow over form edge { 'index': 1, 'itemText': "A PsychoPy zealot knows a smidge of wx but JavaScript is the question", 'options': [1, "a", "multiple word"], 'ticks': [1, 2, 3], 'layout': 'vert', 'itemColor': 'darkslateblue', 'itemWidth': 0.8, 'responseColor': 'darkred', 'responseWidth': 0.4, 'font': 'Open Sans', }, { 'index': 0, 'itemText': "A PsychoPy zealot knows a smidge of wx but JavaScript is the question", 'options': [1, "a", "multiple word"], 'ticks': [1, 2, 3], 'layout': 'horiz', 'itemColor': 'darkred', 'itemWidth': 0.8, 'responseColor': 'darkslateblue', 'responseWidth': 0.4, 'font': 'Open Sans', }, ], } cases = exemplars.copy() cases.update(tykes) # Test every case self.win.flip() for name, case in cases.items(): # Test it for each type for thisType in self.respTypes: # Set type for i, q in enumerate(case): case[i]['type'] = thisType # Make form survey = Form(self.win, units="height", size=(1, 1), fillColor="white", items=case) survey.draw() # Get name of answer file filename = f"test_form_combinations_{thisType}_{name}.png" # Do comparison #self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, self.win, crit=20) self.win.flip() def test_reset(self): """ Test that the reset function can reset all types of form item """ items = [] # Add an item of each type for thisType in self.respTypes: items.append({ 'type': thisType, 'itemText': "A PsychoPy zealot knows a smidge of wx but JavaScript is the question", 'options': [1, "a", "multiple word"], 'ticks': [1, 2, 3], 'layout': 'vert', 'itemColor': 'darkslateblue', 'itemWidth': 0.7, 'responseColor': 'darkred', 'responseWidth': 0.3, 'font': 'Open Sans', }) # Create form survey = Form(self.win, units="height", size=(1, 1), fillColor="white", items=items) # Reset form to check it doesn't error survey.reset() def test_scrolling(self): # Define basic question to test with item = [{ 'type': 'slider', 'itemText': "A PsychoPy zealot knows a smidge of wx but JavaScript is the question", 'options': [1, "a", "multiple word"], 'ticks': [1, 2, 3], 'layout': 'vert', 'itemColor': 'darkslateblue', 'itemWidth': 0.7, 'responseColor': 'darkred', 'responseWidth': 0.3, 'font': 'Open Sans', }] # Typical points on slider to test exemplars = [ 0, 0.5, 1 ] # Problem cases which should be handled tykes = [ ] # Try with questions smaller than form, the same size as and much bigger for nItems in (1, 3, 10): # Make form items = [] for i in range(nItems): items.append(item[0].copy()) # Append index to item text so it's visible in artefacts items[i]['itemText'] = str(i) + items[i]['itemText'] survey = Form(self.win, units="height", size=(1, 0.5), fillColor="white", items=items) for case in exemplars + tykes: # Set scrollbar survey.scrollbar.rating = case survey.draw() # Compare screenshot filename = f"TestForm_scrolling_nq{nItems}_s{case}.png" self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) #utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, self.win, crit=20) self.win.flip() def test_set_scroll_speed(self): items = 2 for multipliers in [1,2,3,4]: assert self.survey.setScrollSpeed([0] * items, multipliers) == items * multipliers assert self.survey.setScrollSpeed([0] * items, multipliers) == items * multipliers assert self.survey.setScrollSpeed([0] * items, multipliers) == items * multipliers def test_response_text_wrap(self): options = ['a', 'b', 'c'] for size in [.2, .3, .4]: item = {"responseWidth": size, "options": options} def test_set_questions(self): survey = Form(self.win, items=[self.genderItem], size=(1.0, 0.3), pos=(0.0, 0.0), autoLog=False) ctrl, h, w = survey._setQuestion(self.genderItem) assert type(ctrl) == TextBox2 assert type(h) in [float, np.float64] assert type(w) in [float, np.float64] def test_set_response(self): survey = Form(self.win, items=[self.genderItem], size=(1.0, 0.3), pos=(0.0, 0.0), autoLog=False) ctrl, h, w = survey._setQuestion(self.genderItem) sliderStim, respHeight = survey._setResponse(self.genderItem) assert type(sliderStim) == Slider assert type(respHeight) in [float, np.float64] def test_form_size(self): assert self.survey.size[0] == (1.0, 0.3)[0] # width assert self.survey.size[1] == (1.0, 0.3)[1] # height def test_aperture_size(self): assert self.survey.aperture.size[0] == self.survey.size[0] assert self.survey.aperture.size[1] == self.survey.size[1] def test_border_limits(self): survey = self.survey assert survey.leftEdge == survey.pos[0] - survey.size[0]/2.0 assert survey.rightEdge == survey.pos[0] + survey.size[0]/2.0 assert survey.topEdge == survey.pos[1] + survey.size[1]/2.0 def test_text_height(self): assert self.survey.textHeight == 0.02 def test_font(self): exemplars = [ {"file": "form_font_demographics.xlsx", "font": "Open Sans", "screenshot": "form_font_demographics.png"}, ] tykes = [ {"file": "form_font_demographics.xlsx", "font": "Indie Flower", "screenshot": "form_font_nonstandard.png"}, {"file": "form_font_languages.xlsx", "font": "Rubrik", "screenshot": "form_font_languages.png"}, ] for case in exemplars + tykes: survey = Form(self.win, items=str(Path(utils.TESTS_DATA_PATH) / case['file']), size=(1, 1), font=case['font'], fillColor=None, borderColor=None, itemColor="white", responseColor="white", markerColor="red", pos=(0, 0), autoLog=False) survey.draw() self.win.flip() # self.win.getMovieFrame(buffer='front').save(Path(utils.TESTS_DATA_PATH) / case['screenshot']) utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / case['screenshot'], self.win, crit=20) def test_item_padding(self): assert self.survey.itemPadding == 0.05 def test_form_units(self): assert self.survey.units == 'height' def test_screen_status(self): """Test whether the object is visible""" assert self.survey._inRange(self.survey.items[0]['itemCtrl']) def test_get_data(self): self.survey = Form(self.win, items=self.questions, size=(1.0, 0.3), pos=(0.0, 0.0), autoLog=False) data = self.survey.getData() Qs = [this['itemText'] for this in data] indices = [item['index'] for item in data] assert Qs == ['What is your gender?', 'How much you like running', 'How much you like cake', 'How much you like programming',] assert all([item['response'] is None for item in data]) assert all([item['rt'] is None for item in data]) assert list(indices) == list(range(4)) def teardown_class(self): shutil.rmtree(self.temp_dir) self.win.close() if __name__ == "__main__": test = Test_Form() test.setup_class() test.test_get_data() test.teardown_class()
17,071
Python
.py
378
30.791005
122
0.501351
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,546
measure_parity.py
psychopy_psychopy/psychopy/tests/test_visual/measure_parity.py
import ast from collections import OrderedDict import esprima import pandas as pd from copy import deepcopy from pathlib import Path def measure_js_parity(pypath, jspath, outpath=None): """ Get all methods and attributes for classes in psychopy.visual and psychojs.visual, for comparison """ def _listcomp(a, b): """ Convenience function for quickly getting arrays of differences between two lists (a and b). Returns === justa : list Elements only present in list a justb : list Elements only present in b both : list Elements present in both lists """ # Get as sets a = set(a) b = set(b) # Do comparison justa = list(a.difference(b)) justb = list(b.difference(a)) both = list(a & b) either = list(a | b) return justa, justb, both, either # Pathify paths pypath = Path(pypath) jspath = Path(jspath) # Dict with classes & filenames for visual components which exist in PsychoPy and PsychoJS attrs = { "ButtonStim": { 'js': {'file': 'ButtonStim.js', 'cls': "ButtonStim"}, 'py': {'file': 'button.py', 'cls': "ButtonStim"}, }, "Form": { 'js': {'file': 'Form.js', 'cls': "Form"}, 'py': {'file': 'form.py', 'cls': "Form"}, }, "ImageStim": { 'js': {'file': 'ImageStim.js', 'cls': "ImageStim"}, 'py': {'file': 'image.py', 'cls': "ImageStim"}, }, "MovieStim3": { 'js': {'file': 'MovieStim.js', 'cls': "MovieStim"}, 'py': {'file': 'movie3.py', 'cls': "MovieStim3"}, }, "Polygon": { 'js': {'file': 'Polygon.js', 'cls': "Polygon"}, 'py': {'file': 'polygon.py', 'cls': "Polygon"} }, "Rect": { 'js': {'file': 'Rect.js', 'cls': "Rect"}, 'py': {'file': 'rect.py', 'cls': "Rect"} }, "ShapeStim": { 'js': {'file': 'ShapeStim.js', 'cls': "ShapeStim"}, 'py': {'file': 'shape.py', 'cls': "ShapeStim"} }, "Slider": { 'js': {'file': 'Slider.js', 'cls': "Slider"}, 'py': {'file': 'slider.py', 'cls': "Slider"} }, "TextBox2": { 'js': {'file': 'TextBox.js', 'cls': "TextBox"}, 'py': {'file': 'textbox2/textbox2.py', 'cls': "TextBox2"} }, "TextStim": { 'js': {'file': 'TextStim.js', 'cls': "TextStim"}, 'py': {'file': 'text.py', 'cls': "TextStim"} }, "BaseVisualStim": { 'js': {'file': 'VisualStim.js', 'cls': "VisualStim"}, 'py': {'file': 'basevisual.py', 'cls': "BaseVisualStim"} }, } # Create blank output arrays for name in attrs: # Create output array arr = {'init': [], 'methods': {}, 'attribs': {}} # Append to js and py attrs[name]['js'].update(deepcopy(arr)) attrs[name]['py'].update(deepcopy(arr)) # For each class, get dicts of methods and attributes for name in attrs: # --- Parse JS file --- with open(jspath / attrs[name]['js']['file'], 'r') as f: code = f.read() tree = esprima.parse(code, sourceType='module') # Get class def cls = None for node in tree.body: if node.type == "ExportNamedDeclaration": if node.declaration.type == "ClassDeclaration" and node.declaration.id.name == attrs[name]['js']['cls']: cls = node if cls is None: raise ValueError(f"Could not find class def for {attrs[name]['js']['cls']} in {attrs[name]['js']['file']}") # Get methods & properties for node in cls.declaration.body.body: if node.value.type == "FunctionExpression": # Get flattened list of params paramNames = [] for param in node.value.params: if param.type == "AssignmentPattern": # If parameter is a dict style assignment pattern, break it apart if param.left.type == "ObjectPattern": for prop in param.left.properties: paramNames.append(prop.key.name) # If parameter is an expression, store name elif param.left.type == "Identifier": paramNames.append(param.left.name) elif param.type == "Identifier": paramNames.append(param.name) # Skip protected methods if node.key.name is None or node.key.name.startswith("_"): continue # If it's the constructor method, store params if node.kind == "constructor": attrs[name]['js']['init'] = paramNames # If it's a getter, store its name & whether it's settable elif node.kind == "get": attrs[name]['js']['attribs'][node.key.name] = node.key.name in attrs[name]['js']['attribs'] # If it's a setter, store its name & the fact that it's settable elif node.kind == "set": attrs[name]['js']['attribs'][node.key.name] = True # If it's regular method, store its name and params elif node.kind == "method": attrs[name]['js']['methods'][node.key.name] = paramNames # --- Parse Py file --- with open(pypath / attrs[name]['py']['file'], 'r') as f: code = f.read() tree = ast.parse(code) # Get class def cls = None for node in tree.body: if isinstance(node, ast.ClassDef) and node.name == attrs[name]['py']['cls']: cls = node if cls is None: raise ValueError(f"Could not find class def for {attrs[name]['py']['cls']} in {attrs[name]['py']['file']}") # Get methods and attributes for node in cls.body: if isinstance(node, ast.FunctionDef): # Get flattened list of params paramNames = [] for param in node.args.args: if param.arg == "self": continue paramNames.append(param.arg) # Get string list of decorators decorators = [] for dec in node.decorator_list: if isinstance(dec, ast.Name): decorators.append(dec.id) if isinstance(dec, ast.Attribute): decorators.append(dec.attr) # If it's the constructor method, store params if node.name == "__init__": attrs[name]['py']['init'] = paramNames # Skip protected methods elif node.name is None or node.name.startswith("_"): continue # If it's a getter, store its name & whether it's settable elif "property" in decorators: attrs[name]['py']['attribs'][node.name] = node.name in attrs[name]['py']['attribs'] # If it's a setter, store its name & the fact that it's settable elif "setter" in decorators: attrs[name]['py']['attribs'][node.name] = True # If it's regular method, store its name and params else: attrs[name]['py']['methods'][node.name] = paramNames # --- Compare --- compr = {} # Iterate through components for name in attrs: # Add field to comparison dict compr[name] = OrderedDict({}) # Compare init params, attributes and method names for key in ('init', 'attribs', 'methods'): # Get lists py = attrs[name]['py'][key] js = attrs[name]['js'][key] # Do comparison justpy, justjs, both, either = _listcomp(py, js) # Store in dict compr[name][f'{key}_both'] = both compr[name][f'{key}_py'] = justpy compr[name][f'{key}_js'] = justjs # Add empty column compr[name]['|||'] = [] # Compare params for each method for key in compr[name][f'methods_both']: # Get lists py = attrs[name]['py']['methods'][key] js = attrs[name]['js']['methods'][key] # Do comparison justpy, justjs, both, either = _listcomp(py, js) # Store in dict compr[name][f'{key}_both'] = both compr[name][f'{key}_py'] = justpy compr[name][f'{key}_js'] = justjs # If asked to, save to a table if outpath: # Pathify output path outpath = Path(outpath) # Save csv's for name, data in compr.items(): # Pad columns to max ncols = max([len(val) for val in data.values()]) for n in range(ncols): for key in data: while len(data[key]) < ncols: data[key].append(None) # Make a pandas dataframe df = pd.DataFrame(data) # Write to csv df.to_csv(outpath / f"{name}.csv") return attrs, compr
9,550
Python
.py
222
30.085586
120
0.498332
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,547
test_image.py
psychopy_psychopy/psychopy/tests/test_visual/test_image.py
from pathlib import Path from psychopy import visual, colors, core from .test_basevisual import _TestUnitsMixin, _TestSerializationMixin from psychopy.tests.test_experiment.test_component_compile_python import _TestBoilerplateMixin from psychopy.tests import utils import pytest class TestImage(_TestUnitsMixin, _TestBoilerplateMixin, _TestSerializationMixin): """ Test that images render as expected. Note: In BaseVisual tests, image colors will look different than seems intuitive as foreColor will be set to `"blue"`. """ def setup_method(self): self.win = visual.Window() self.obj = visual.ImageStim( self.win, str(Path(utils.TESTS_DATA_PATH) / 'testimage.jpg'), colorSpace='rgb1', ) def test_anchor_flip(self): """ Check that flipping the image doesn't flip the direction of the anchor """ # Setup obj self.obj.units = "height" self.obj.pos = (0, 0) self.obj.size = (0.5, 0.5) self.obj.anchor = "bottom left" # Flip vertically self.obj.flipVert = True self.obj.flipHoriz = False # Check self.win.flip() self.obj.draw() # self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / "test_image_flip_anchor_vert.png") utils.compareScreenshot("test_image_flip_anchor_vert.png", self.win, crit=7) # Flip horizontally self.obj.flipVert = False self.obj.flipHoriz = True # Check self.win.flip() self.obj.draw() # self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / "test_image_flip_anchor_horiz.png") utils.compareScreenshot("test_image_flip_anchor_horiz.png", self.win, crit=7) def test_aspect_ratio(self): """ Test that images set with one or both dimensions as None maintain their aspect ratio """ cases = [ # norm 1:1 {"img": "default.png", "aspect": (1, 1), "size": (None, 2), "units": "norm", "tag": "default_xNone_yFull"}, {"img": "default.png", "aspect": (1, 1), "size": (2, None), "units": "norm", "tag": "default_xFull_yNone"}, {"img": "default.png", "aspect": (1, 1), "size": (None, None), "units": "norm", "tag": "default_xNone_yNone"}, {"img": "default.png", "aspect": (1, 1), "size": None, "units": "norm", "tag": "default_None"}, # height 1:1 {"img": "default.png", "aspect": (1, 1), "size": (None, 1), "units": "height", "tag": "default_xNone_yFull"}, {"img": "default.png", "aspect": (1, 1), "size": (1 / self.win.size[1] * self.win.size[0], None), "units": "height", "tag": "default_xFull_yNone"}, {"img": "default.png", "aspect": (1, 1), "size": (None, None), "units": "height", "tag": "default_xNone_yNone"}, {"img": "default.png", "aspect": (1, 1), "size": None, "units": "height", "tag": "default_None"}, # pix 1:1 {"img": "default.png", "aspect": (1, 1), "size": (None, self.win.size[1]), "units": "pix", "tag": "default_xNone_yFull"}, {"img": "default.png", "aspect": (1, 1), "size": (self.win.size[0], None), "units": "pix", "tag": "default_xFull_yNone"}, {"img": "default.png", "aspect": (1, 1), "size": (None, None), "units": "pix", "tag": "default_xNone_yNone"}, {"img": "default.png", "aspect": (1, 1), "size": None, "units": "pix", "tag": "default_None"}, ] for case in cases: # Set image self.obj.image = case['img'] # Set size self.obj.units = case['units'] self.obj.size = case['size'] # Check that aspect ratio is still correct assert self.obj.aspectRatio == case['aspect'] # Check that image looks as expected self.obj.draw() filename = f"test_image_aspect_{case['tag']}.png" # self.win.getMovieFrame(buffer='back').save(Path(utils.TESTS_DATA_PATH) / filename) utils.compareScreenshot(Path(utils.TESTS_DATA_PATH) / filename, self.win, crit=7) self.win.flip() class TestImageAnimation: """ Tests for using ImageStim to create frame animations """ @classmethod def setup_class(cls): nFrames = 16 # Define array of sizes/desired frame rates cls.cases = [ {'size': 6 ** 2, 'fps': 16}, {'size': 8 ** 2, 'fps': 16}, {'size': 10 ** 2, 'fps': 8}, {'size': 12 ** 2, 'fps': 2}, ] # Create frames for i, case in enumerate(cls.cases): size = case['size'] # Create window and shapes win = visual.Window(size=(size, size), color='purple') shape1 = visual.ShapeStim(win, pos=(0.2, 0.2), size=(0.5, 0.5), lineWidth=size * 0.1, fillColor='red', lineColor='green', ) shape2 = visual.ShapeStim(win, pos=(-0.2, -0.2), size=(0.5, 0.5), lineWidth=size * 0.1, fillColor='blue', lineColor='yellow' ) frames = [] for thisFrame in range(nFrames): # Cycle window hue win.color = colors.Color( (win._color.hsv[0] + 360 * thisFrame / nFrames, win._color.hsv[1], win._color.hsv[2]), 'hsv' ) # Cycle shape hues shape1._fillColor.hsv = ( shape1._fillColor.hsv[0] + 360 * thisFrame / nFrames, shape1._fillColor.hsv[1], shape1._fillColor.hsv[2] ) shape1._borderColor.hsv = ( shape1._borderColor.hsv[0] - 360 * thisFrame / nFrames, shape1._borderColor.hsv[1], shape1._borderColor.hsv[2] ) shape2._fillColor.hsv = ( shape2._fillColor.hsv[0] + 360 * thisFrame / nFrames, shape2._fillColor.hsv[1], shape2._fillColor.hsv[2] ) shape2._borderColor.hsv = ( shape2._borderColor.hsv[0] - 360 * thisFrame / nFrames, shape2._borderColor.hsv[1], shape2._borderColor.hsv[2] ) # Rotate shapes shape1.ori = shape1.ori + 360 * thisFrame / nFrames shape2.ori = shape2.ori - 360 * thisFrame / nFrames # Render win.flip() shape1.draw() shape2.draw() # Get frame frame = win.getMovieFrame(buffer='back') frames.append( frame ) # Cleanup win.close() del shape1 del shape2 # Update case cls.cases[i]['frames'] = frames def test_fps(self): """ Check that images can be updated sufficiently fast to create frame animations """ # skip speed tests under vm if utils.RUNNING_IN_VM: pytest.skip() # Create clock clock = core.Clock() # Try at each size for case in self.cases: size = case['size'] # Make window and image win = visual.Window(size=(size, size)) img = visual.ImageStim(win, units='pix', size=(size, size)) # Iterate through frames refr = [] for frame in case['frames']: # Reset clock clock.reset() # Set image contents img.image = frame # Update img.draw() win.flip() # Store time taken refr.append(clock.getTime()) # Print frame rate for this size fps = round(1 / max(refr)) assert fps > case['fps'], ( f"Max frame rate for {size}x{size} animations should be at least {case['fps']}, but was {fps}" ) # Cleanup win.close() del img
8,727
Python
.py
208
28.5625
118
0.493233
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,548
test_all_stimuli.py
psychopy_psychopy/psychopy/tests/test_visual/test_all_stimuli.py
import sys, os, copy from pathlib import Path from psychopy import visual, monitors, prefs, constants from psychopy.visual import filters from psychopy.tools.coordinatetools import pol2cart from psychopy.tests import utils import numpy import pytest import shutil from tempfile import mkdtemp """Each test class creates a context subclasses _baseVisualTest to run a series of tests on a single graphics context (e.g. pyglet with shaders) To add a new stimulus test use _base so that it gets tested in all contexts """ from psychopy.tests import skip_under_vm, requires_plugin from psychopy.tools import systemtools class Test_Window(): """Some tests just for the window - we don't really care about what's drawn inside it """ def setup_class(self): self.temp_dir = mkdtemp(prefix='psychopy-tests-test_window') self.win = visual.Window([128,128], pos=[50,50], allowGUI=False, autoLog=False) def teardown_class(self): shutil.rmtree(self.temp_dir) def test_captureMovieFrames(self): stim = visual.GratingStim(self.win, dkl=[0,0,1]) stim.autoDraw = True for frameN in range(3): stim.phase += 0.3 self.win.flip() self.win.getMovieFrame() self.win.saveMovieFrames(os.path.join(self.temp_dir, 'junkFrames.png')) self.win.saveMovieFrames(os.path.join(self.temp_dir, 'junkFrames.gif')) region = self.win._getRegionOfFrame() def test_multiFlip(self): self.win.recordFrameIntervals = False #does a reset self.win.recordFrameIntervals = True self.win.multiFlip(3) self.win.multiFlip(3,clearBuffer=False) self.win.saveFrameIntervals(os.path.join(self.temp_dir, 'junkFrameInts')) fps = self.win.fps() def test_callonFlip(self): def assertThisIs2(val): assert val==2 self.win.callOnFlip(assertThisIs2, 2) self.win.flip() def test_resetViewport(self): # Check if the `Window.resetViewport()` method works correctly. Not # checking if the OpenGL state is correct here, just if the property # setter `Window.viewport` updates accordingly. # # bugfix: https://github.com/psychopy/psychopy/issues/5135 # viewportOld = self.win.viewport.copy() # store old viewport value # Create a new viewport, ensure that the test value never equals the # windows size. viewportNew = [0, 0] + [max(int(v / 2.0), 1) for v in viewportOld[2:]] self.win.viewport = viewportNew # assert that the change has been made correctly after setting assert numpy.allclose(self.win.viewport, viewportNew), \ "Failed to change viewport, expected `{}` got `{}`.".format( viewportNew, list(self.win.viewport)) # show as list # reset the viewport and check if the value is reset to original self.win.resetViewport() assert numpy.allclose(self.win.viewport, viewportOld), \ "Failed to reset viewport, expected `{}` got `{}`.".format( viewportOld, list(self.win.viewport)) class _baseVisualTest(): #this class allows others to be created that inherit all the tests for #a different window config @classmethod def setup_class(self):#run once for each test class (window) self.win=None self.contextName raise NotImplementedError @classmethod def teardown_class(self):#run once for each test class (window) self.win.close()#shutil.rmtree(self.temp_dir) def setup_method(self):#this is run for each test individually #make sure we start with a clean window self.win.flip() def test_imageAndGauss(self): win = self.win fileName = os.path.join(utils.TESTS_DATA_PATH, 'testimage.jpg') #use image stim size = numpy.array([2.0,2.0])*self.scaleFactor image = visual.ImageStim(win, image=fileName, mask='gauss', size=size, flipHoriz=True, flipVert=True) image.draw() utils.compareScreenshot('imageAndGauss_%s.png' %(self.contextName), win) win.flip() def test_gratingImageAndGauss(self): win = self.win size = numpy.array([2.0,2.0])*self.scaleFactor #generate identical image as test_imageAndGauss but using GratingStim fileName = os.path.join(utils.TESTS_DATA_PATH, 'testimage.jpg') if win.units in ['norm','height']: sf = -1.0 else: sf = -1.0 / size # this will do the flipping and get exactly one cycle image = visual.GratingStim(win, tex=fileName, size=size, sf=sf, mask='gauss') image.draw() utils.compareScreenshot('imageAndGauss_%s.png' %(self.contextName), win) win.flip() def test_numpyFilterMask(self): """if the mask is passed in as a numpy array it goes through a different set of rules when turned into a texture. But the outcome should be as above """ win = self.win from psychopy.visual import filters gaussMask = filters.makeMask(128, 'gauss') size = numpy.array([2.0,2.0])*self.scaleFactor fileName = os.path.join(utils.TESTS_DATA_PATH, 'testimage.jpg') image = visual.ImageStim(win, image=fileName, mask=gaussMask, size=size, flipHoriz=True, flipVert=True) image.draw() utils.compareScreenshot('imageAndGauss_%s.png' %(self.contextName), win) win.flip() def test_greyscaleImage(self): win = self.win fileName = os.path.join(utils.TESTS_DATA_PATH, 'greyscale.jpg') imageStim = visual.ImageStim(win, fileName) imageStim.draw() utils.compareScreenshot('greyscale_%s.png' %(self.contextName), win) "{}".format(imageStim) #check that str(xxx) is working win.flip() imageStim.color = [0.1,0.1,0.1] imageStim.draw() utils.compareScreenshot('greyscaleLowContr_%s.png' %(self.contextName), win) win.flip() imageStim.color = 1 imageStim.contrast = 0.1#should have identical effect to color=0.1 imageStim.draw() utils.compareScreenshot('greyscaleLowContr_%s.png' %(self.contextName), win) win.flip() imageStim.contrast = 1.0 fileName = os.path.join(utils.TESTS_DATA_PATH, 'greyscale2.png') imageStim.image = fileName imageStim.size *= 3 imageStim.draw() utils.compareScreenshot('greyscale2_%s.png' %(self.contextName), win) win.flip() def test_numpyTexture(self): win = self.win grating = filters.makeGrating(res=64, ori=20.0, cycles=3.0, phase=0.5, gratType='sqr', contr=1.0) imageStim = visual.ImageStim(win, image=grating, size = 3*self.scaleFactor, interpolate=True) imageStim.draw() utils.compareScreenshot('numpyImage_%s.png' %(self.contextName), win) "{}".format(imageStim) #check that str(xxx) is working win.flip() #set lowcontrast using color imageStim.color = [0.1,0.1,0.1] imageStim.draw() utils.compareScreenshot('numpyLowContr_%s.png' %(self.contextName), win) win.flip() #now try low contrast using contr imageStim.color = 1 imageStim.contrast = 0.1#should have identical effect to color=0.1 imageStim.draw() utils.compareScreenshot('numpyLowContr_%s.png' %(self.contextName), win) win.flip() def test_hexColors(self): win = self.win circle = visual.Circle(win, fillColor='#0000FF', lineColor=None, size=2* self.scaleFactor) circle.draw() grat = visual.GratingStim(win, ori=20, color='#00AAFF', pos=[0.6 * self.scaleFactor, -0.6 * self.scaleFactor], sf=3.0 / self.scaleFactor, size=2 * self.scaleFactor, interpolate=True) grat.draw() utils.compareScreenshot('circleHex_%s.png' %(self.contextName), win) win.flip() #def testMaskMatrix(self): # #aims to draw the exact same stimulus as in testGabor, but using filters # win=self.win # contextName=self.contextName # #create gabor using filters # size=2*self.scaleFactor#to match Gabor1 above # if win.units in ['norm','height']: # sf=1.0/size # else: # sf=2.0/self.scaleFactor#to match Gabor1 above # cycles=size*sf # grating = filters.makeGrating(256, ori=135, cycles=cycles) # gabor = filters.maskMatrix(grating, shape='gauss') # stim = visual.PatchStim(win, tex=gabor, # pos=[0.6*self.scaleFactor, -0.6*self.scaleFactor], # sf=1.0/size, size=size, # interpolate=True) # stim.draw() # utils.compareScreenshot('gabor1_%s.png' %(contextName), win) def test_text(self): win = self.win #set font fontFile = str(Path(prefs.paths['resources']) / "fonts" / 'DejaVuSerif.ttf') #using init stim = visual.TextStim(win,text=u'\u03A8a', color=[0.5, 1.0, 1.0], ori=15, height=0.8*self.scaleFactor, pos=[0,0], font='DejaVu Serif', fontFiles=[fontFile]) stim.draw() if self.win.winType != 'pygame': #compare with a LIBERAL criterion (fonts do differ) utils.compareScreenshot('text1_%s.png' %(self.contextName), win, crit=20) win.flip() # AFTER compare screenshot #using set stim.text = 'y' if sys.platform=='win32': stim.font = 'Courier New' else: stim.font = 'Courier' stim.ori = -30.5 stim.height = 1.0 * self.scaleFactor stim.setColor([0.1, -1, 0.8], colorSpace='rgb') stim.pos += [-0.5, 0.5] stim.contrast = 0.8 stim.opacity = 0.8 stim.draw() "{}".format(stim) #check that str(xxx) is working if self.win.winType != 'pygame': #compare with a LIBERAL criterion (fonts do differ) utils.compareScreenshot('text2_%s.png' %self.contextName, win, crit=20) def test_text_with_add(self): # pyglet text will reset the blendMode to 'avg' so check that we are # getting back to 'add' if we want it win = self.win text = visual.TextStim(win, pos=[0, 0.9]) grat1 = visual.GratingStim(win, size=2*self.scaleFactor, opacity=0.5, pos=[0.3,0.0], ori=45, sf=2*self.scaleFactor) grat2 = visual.GratingStim(win, size=2 * self.scaleFactor, opacity=0.5, pos=[-0.3, 0.0], ori=-45, sf=2*self.scaleFactor) text.draw() grat1.draw() grat2.draw() if systemtools.isVM_CI(): pytest.skip("Blendmode='add' doesn't work under a virtual machine for some reason") if self.win.winType != 'pygame': utils.compareScreenshot('blend_add_%s.png' %self.contextName, win, crit=20) def test_rect(self): win = self.win rect = visual.Rect(win) rect.draw() rect.lineColor = 'blue' rect.pos = [1, 1] rect.ori = 30 rect.fillColor = 'pink' rect.draw() "{}".format(rect) #check that str(xxx) is working rect.width = 1 rect.height = 1 def test_circle(self): win = self.win circle = visual.Circle(win) circle.fillColor = 'red' circle.draw() circle.lineColor = 'blue' circle.fillColor = None circle.pos = [0.5, -0.5] circle.ori = 30 circle.draw() "{}".format(circle) #check that str(xxx) is working def test_line(self): win = self.win line = visual.Line(win) line.start = (0, 0) line.end = (0.1, 0.1) line.draw() win.flip() "{}".format(line) # check that str(xxx) is working def test_Polygon(self): win = self.win cols = ['red','green','purple','orange','blue'] for n, col in enumerate(cols): poly = visual.Polygon(win, edges=n + 5, lineColor=col) poly.draw() win.flip() "{}".format(poly) #check that str(xxx) is working poly.edges = 3 poly.radius = 1 def test_shape(self): win = self.win arrow = [(-0.4,0.05), (-0.4,-0.05), (-.2,-0.05), (-.2,-0.1), (0,0), (-.2,0.1), (-.2,0.05)] shape = visual.ShapeStim(win, lineColor='white', lineWidth=1.0, fillColor='red', vertices=arrow, pos=[0, 0], ori=0.0, opacity=1.0, depth=0, interpolate=True) shape.draw() #NB shape rendering can differ a little, depending on aliasing utils.compareScreenshot('shape2_1_%s.png' %(self.contextName), win, crit=12.5) win.flip() # Using .set() shape.contrast = 0.8 shape.opacity = 0.8 shape.ori = 90 shape.draw() assert 'Shape' in "{}".format(shape) # check that str(xxx) is working utils.compareScreenshot('shape2_2_%s.png' %(self.contextName), win, crit=12.5) def test_simpleimage(self): win = self.win if win.useRetina: pytest.skip("Rendering pixel-for-pixel is not identical on retina") fileName = os.path.join(utils.TESTS_DATA_PATH, 'testimage.jpg') if not os.path.isfile(fileName): raise IOError('Could not find image file: %s' % os.path.abspath(fileName)) image = visual.SimpleImageStim(win, image=fileName, flipHoriz=True, flipVert=True) "{}".format(image) #check that str(xxx) is working image.draw() utils.compareScreenshot('simpleimage1_%s.png' %(self.contextName), win, crit=5.0) # Should be exact replication def test_dotsUnits(self): #to test this create a small dense circle of dots and check the circle #has correct dimensions fieldSize = numpy.array([1.0,1.0]) pos = numpy.array([0.5,0])*fieldSize dots = visual.DotStim(self.win, color=[-1.0,0.0,0.5], dotSize=5, nDots=1000, fieldShape='circle', fieldPos=pos) dots.draw() utils.compareScreenshot('dots_%s.png' %(self.contextName), self.win, crit=20) self.win.flip() def test_dots(self): #NB we can't use screenshots here - just check that no errors are raised win = self.win #using init dots =visual.DotStim(win, color=(1.0,1.0,1.0), dir=270, nDots=500, fieldShape='circle', fieldPos=(0.0,0.0),fieldSize=1*self.scaleFactor, dotLife=5, #number of frames for each dot to be drawn signalDots='same', #are the signal and noise dots 'different' or 'same' popns (see Scase et al) noiseDots='direction', #do the noise dots follow random- 'walk', 'direction', or 'position' speed=0.01*self.scaleFactor, coherence=0.9) dots.draw() win.flip() "{}".format(dots) #check that str(xxx) is working #using .set() and check the underlying variable changed prevDirs = copy.copy(dots._dotsDir) prevSignals = copy.copy(dots._signalDots) prevVerticesPix = copy.copy(dots.verticesPix) dots.dir = 20 dots.coherence = 0.5 dots.fieldPos = [-0.5, 0.5] dots.speed = 0.1 * self.scaleFactor dots.opacity = 0.8 dots.contrast = 0.8 dots.draw() #check that things changed assert (prevDirs-dots._dotsDir).sum()!=0, \ "dots._dotsDir failed to change after dots.setDir()" assert prevSignals.sum()!=dots._signalDots.sum(), \ "dots._signalDots failed to change after dots.setCoherence()" assert not numpy.alltrue(prevVerticesPix==dots.verticesPix), \ "dots.verticesPix failed to change after dots.setPos()" def test_element_array(self): win = self.win if not win._haveShaders: pytest.skip("ElementArray requires shaders, which aren't available") #using init thetas = numpy.arange(0,360,10) N=len(thetas) radii = numpy.linspace(0,1.0,N)*self.scaleFactor x, y = pol2cart(theta=thetas, radius=radii) xys = numpy.array([x,y]).transpose() spiral = visual.ElementArrayStim( win, opacities = 0, nElements=N, sizes=0.5*self.scaleFactor, sfs=1.0, xys=xys, oris=-thetas) spiral.draw() #check that the update function is working by changing vals after first draw() call spiral.opacities = 1.0 spiral.sfs = 3.0 spiral.draw() "{}".format(spiral) #check that str(xxx) is working win.flip() spiral.draw() utils.compareScreenshot('elarray1_%s.png' %(self.contextName), win) win.flip() def test_aperture(self): win = self.win if not win.allowStencil: pytest.skip("Don't run aperture test when no stencil is available") grating = visual.GratingStim( win, mask='gauss',sf=8.0, size=2,color='FireBrick', units='norm') aperture = visual.Aperture(win, size=1*self.scaleFactor, pos=[0.8*self.scaleFactor,0]) aperture.enabled = False grating.draw() aperture.enabled = True "{}".format(aperture) #check that str(xxx) is working grating.ori = 90 grating.color = 'black' grating.draw() utils.compareScreenshot('aperture1_%s.png' %(self.contextName), win) #aperture should automatically disable on exit for shape, nVert, pos in [(None, 4, (0,0)), ('circle', 72, (.2, -.7)), ('square', 4, (-.5,-.5)), ('triangle', 3, (1,1))]: aperture = visual.Aperture(win, pos=pos, shape=shape, nVert=nVert) assert len(aperture.vertices) == nVert # true for BaseShapeStim; expect (nVert-2)*3 if tesselated assert aperture.contains(pos) def test_aperture_image(self): win = self.win fileName = os.path.join(utils.TESTS_DATA_PATH, 'testwedges.png') if not win.allowStencil: pytest.skip("Don't run aperture test when no stencil is available") grating = visual.GratingStim(win, mask='gauss',sf=8.0, size=2, color='FireBrick', units='norm') aperture = visual.Aperture(win, size=1*self.scaleFactor, pos=[0.8*self.scaleFactor,0], shape=fileName) aperture.enabled = False grating.draw() aperture.enabled = True "{}".format(aperture) #check that str(xxx) is working grating.ori = 90 grating.color = 'black' grating.draw() utils.compareScreenshot('aperture2_%s.png' %(self.contextName), win, crit=30) #aperture should automatically disable on exit @skip_under_vm def test_refresh_rate(self): if self.win.winType=='pygame': pytest.skip("getMsPerFrame seems to crash the testing of pygame") #make sure that we're successfully syncing to the frame rate msPFavg, msPFstd, msPFmed = visual.getMsPerFrame(self.win, nFrames=60, showVisual=True) assert (1000/150.0) < msPFavg < (1000/40.0), \ "Your frame period is %.1fms which suggests you aren't syncing to the frame" %msPFavg #create different subclasses for each context/backend class TestPygletNorm(_baseVisualTest): @classmethod def setup_class(self): self.win = visual.Window([128,128], winType='pyglet', pos=[50,50], allowStencil=True, autoLog=False) self.contextName='norm' self.scaleFactor=1#applied to size/pos values class TestPygletHexColor(_baseVisualTest): @classmethod def setup_class(self): self.win = visual.Window([128,128], winType='pyglet', pos=[50,50], color="#FF0099", allowStencil=True, autoLog=False) self.contextName='normHexbackground' self.scaleFactor=1#applied to size/pos values if not systemtools.isVM_CI(): class TestPygletBlendAdd(_baseVisualTest): @classmethod def setup_class(self): self.win = visual.Window([128,128], winType='pyglet', pos=[50,50], blendMode='add', useFBO=True) self.contextName='normAddBlend' self.scaleFactor=1#applied to size/pos values class TestPygletNormFBO(_baseVisualTest): @classmethod def setup_class(self): self.win = visual.Window([128,128], units="norm", winType='pyglet', pos=[50,50], allowStencil=True, autoLog=False, useFBO=True) self.contextName='norm' self.scaleFactor=1#applied to size/pos values class TestPygletHeight(_baseVisualTest): @classmethod def setup_class(self): self.win = visual.Window([128,64], units="height", winType='pyglet', pos=[50,50], allowStencil=False, autoLog=False) self.contextName='height' self.scaleFactor=1#applied to size/pos values class TestPygletNormStencil(_baseVisualTest): @classmethod def setup_class(self): self.win = visual.Window([128,128], units="norm", monitor='testMonitor', winType='pyglet', pos=[50,50], allowStencil=True, autoLog=False) self.contextName='stencil' self.scaleFactor=1#applied to size/pos values class TestPygletPix(_baseVisualTest): @classmethod def setup_class(self): mon = monitors.Monitor('testMonitor') mon.setDistance(57) mon.setWidth(40.0) mon.setSizePix([1024,768]) self.win = visual.Window([128,128], units="pix", monitor=mon, winType='pyglet', pos=[50, 50], allowStencil=True, autoLog=False) self.contextName='pix' self.scaleFactor=60#applied to size/pos values class TestPygletCm(_baseVisualTest): @classmethod def setup_class(self): mon = monitors.Monitor('testMonitor') mon.setDistance(57.0) mon.setWidth(40.0) mon.setSizePix([1024,768]) self.win = visual.Window([128,128], units="cm", monitor=mon, winType='pyglet', pos=[50,50], allowStencil=False, autoLog=False) self.contextName='cm' self.scaleFactor=2#applied to size/pos values class TestPygletDeg(_baseVisualTest): @classmethod def setup_class(self): mon = monitors.Monitor('testMonitor') mon.setDistance(57.0) mon.setWidth(40.0) mon.setSizePix([1024,768]) self.win = visual.Window([128,128], units="deg", monitor=mon, winType='pyglet', pos=[50,50], allowStencil=True, autoLog=False) self.contextName='deg' self.scaleFactor=2#applied to size/pos values class TestPygletDegFlat(_baseVisualTest): @classmethod def setup_class(self): mon = monitors.Monitor('testMonitor') mon.setDistance(10.0) #exaggerate the effect of flatness by setting the monitor close mon.setWidth(40.0) mon.setSizePix([1024,768]) self.win = visual.Window([128,128], units="degFlat", monitor=mon, winType='pyglet', pos=[50,50], allowStencil=True, autoLog=False) self.contextName='degFlat' self.scaleFactor=4#applied to size/pos values class TestPygletDegFlatPos(_baseVisualTest): @classmethod def setup_class(self): mon = monitors.Monitor('testMonitor') mon.setDistance(10.0) #exaggerate the effect of flatness by setting the monitor close mon.setWidth(40.0) mon.setSizePix([1024,768]) self.win = visual.Window([128,128], units='degFlatPos', monitor=mon, winType='pyglet', pos=[50,50], allowStencil=True, autoLog=False) self.contextName='degFlatPos' self.scaleFactor=4#applied to size/pos values # @pytest.mark.needs_pygame # class TestPygameNorm(_baseVisualTest): # @classmethod # def setup_class(self): # self.win = visual.Window([128,128], winType='pygame', allowStencil=True, autoLog=False) # self.contextName='norm' # self.scaleFactor=1#applied to size/pos values #class TestPygamePix(_baseVisualTest): # @classmethod # def setup_class(self): # mon = monitors.Monitor('testMonitor') # mon.setDistance(57.0) # mon.setWidth(40.0) # mon.setSizePix([1024,768]) # self.win = visual.Window([128,128], monitor=mon, winType='pygame', allowStencil=True, # units='pix', autoLog=False) # self.contextName='pix' # self.scaleFactor=60#applied to size/pos values #class TestPygameCm(_baseVisualTest): # @classmethod # def setup_class(self): # mon = monitors.Monitor('testMonitor') # mon.setDistance(57.0) # mon.setWidth(40.0) # mon.setSizePix([1024,768]) # self.win = visual.Window([128,128], monitor=mon, winType='pygame', allowStencil=False, # units='cm') # self.contextName='cm' # self.scaleFactor=2#applied to size/pos values #class TestPygameDeg(_baseVisualTest): # @classmethod # def setup_class(self): # mon = monitors.Monitor('testMonitor') # mon.setDistance(57.0) # mon.setWidth(40.0) # mon.setSizePix([1024,768]) # self.win = visual.Window([128,128], monitor=mon, winType='pygame', allowStencil=True, # units='deg') # self.contextName='deg' # self.scaleFactor=2#applied to size/pos values # if __name__ == '__main__': cls = TestPygletDegFlatPos() cls.setup_class() cls.test_radial() cls.teardown_class()
26,499
Python
.py
583
35.732419
119
0.607259
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,549
test_glfw_backend.py
psychopy_psychopy/psychopy/tests/test_visual/test_glfw_backend.py
# Provisional (super simple) test file which doesn't really test anything else # besides simply opening a `pyGLFW` window. Add more complete `glfw` backend # tests to other scripts ASAP, then remove this file. from psychopy.tests import skip_under_vm import pytest @skip_under_vm(reason="GLFW doesn't work on (macOS) virtual machine") def test_open_glfw_window(): from psychopy.visual.window import Window win = Window(winType='glfw', autoLog=False) assert win.winType == 'glfw' win.flip() win.close()
524
Python
.py
12
40.833333
78
0.754902
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,550
test_panorama.py
psychopy_psychopy/psychopy/tests/test_visual/test_panorama.py
from psychopy import visual from .. import utils from pathlib import Path class TestPanorama: def setup_class(cls): cls.path = Path(utils.TESTS_DATA_PATH) / "test_panorama" cls.win = visual.Window(monitor="testMonitor") cls.obj = visual.PanoramicImageStim(cls.win, image=cls.path / "panoramaTestImage.png") def test_movement(self): cases = [] # Try different azimuths & elevations intervals = 3 for az in range(intervals): for al in range(intervals - 1): cases.append({ 'azimuth': (az * 2) / intervals - 1, 'elevation': ((al + 1) * 2) / intervals - 1, }) # Add tests for extreme elevation cases += [ {'azimuth': 0, 'elevation': -1}, # Min elevation, should be dark colours {'azimuth': 0, 'elevation': 1}, # Max elevation, should be light colours ] self.win.flip() for case in cases: # Set azimuth and elevation self.obj.azimuth = case['azimuth'] self.obj.elevation = case['elevation'] # Draw self.obj.draw() # Construct file path to check against exemplar = self.path / "testPanorama_mvmt_{azimuth:.1f}_{elevation:.1f}.png".format(**case) # Compare #self.win.getMovieFrame(buffer='back').save(exemplar) utils.compareScreenshot(str(exemplar), self.win, crit=7) # Flip self.win.flip()
1,545
Python
.py
37
31.027027
103
0.565824
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,551
test_dots.py
psychopy_psychopy/psychopy/tests/test_visual/test_dots.py
import numpy as np from psychopy import visual, colors class TestDots: @classmethod def setup_method(self): self.win = visual.Window([128, 128], monitor="testMonitor", pos=[50,50], allowGUI=False, autoLog=False) def test_fieldSize(self): """ Check that dot stim field size is interpreted correctly. Creates a dot stim at various sizes, and poygons at the same size to act as a reference. """ def _findColors(win): """ The window background is set to red, the max guides are white, the min guides are blue, and the dots are black at 50% opacity. If fieldSize is correct, dots should only be visible against guides, not background - so there should be grey and dark blue pixels, with no dark red pixels. """ # Define acceptable margin of error (out of 255) err = 5 # Get screenshot img = np.array(win._getFrame(buffer="back")) # Flatten screenshot img = img.flatten() # Unflatten screenshot to pixel level img = img.reshape((-1, 3)) # Get unique colors cols = np.unique(img, axis=0) # Define colors to seek/avoid darkblue = colors.Color( (np.array([-1, -1, 1]) + np.array([-1, -1, -1])) / 2, "rgb") grey = colors.Color( (np.array([1, 1, 1]) + np.array([-1, -1, -1])) / 2, "rgb") darkred = colors.Color( (np.array([1, -1, -1]) + np.array([-1, -1, -1])) / 2, "rgb") # We want dark blue - it means the middle is drawn inrange = np.logical_and((darkblue.rgb255 - err) < cols, cols < (darkblue.rgb255 + err)) inrange = np.all(inrange, axis=1) assert np.any(inrange), ( f"No pixel of color {darkblue.rgb255} found in dotstim, meaning the middle of the field is not drawn.\n" f"\n" f"Colors found:\n" f"{cols}" ) # We want grey - it means the edges are drawn inrange = np.logical_and((grey.rgb255 - err) < cols, cols < (grey.rgb255 + err)) inrange = np.all(inrange, axis=1) assert np.any(inrange), ( f"No pixel of color {grey.rgb255} found in dotstim, meaning the field of dots is too small.\n" f"\n" f"Colors found:\n" f"{cols}" ) # We don't want dark red - it means there are dots outside the field inrange = np.logical_and((darkred.rgb255 - err) < cols, cols < (darkred.rgb255 + err)) inrange = np.all(inrange, axis=1) assert not np.any(inrange), ( f"Pixel of color {darkred.rgb255} found in dotstim, meaning the field of dots is too big.\n" f"\n" f"Colors found:\n" f"{cols}" ) # Define cases to try cases = [ {'size': np.array([.5, .5]), 'units': 'height'}, {'size': np.array([1, 1]), 'units': 'deg'} ] # Define an acceptable margin of error (in proportion of size) err = 0.1 # Create dots params = { "win": self.win, "nDots": 50, "fieldPos": (0, 0), "dotSize": (5, 5), "dotLife": 0, "noiseDots": 'direction', "dir": 0, "speed": 0.25, "coherence": 1, "color": "black", "opacity": 0.5 } objCircle = visual.DotStim( fieldShape='circle', **params ) objRect = visual.DotStim( fieldShape='sqr', **params ) # Create reference objects for maximum size maxCircle = visual.Circle(self.win, fillColor="white") maxRect = visual.Rect(self.win, fillColor="white") # Create reference objects for minimum size minCircle = visual.Circle(self.win, fillColor="blue") minRect = visual.Rect(self.win, fillColor="blue") # Set window background and store original ogColor = self.win.color self.win.color = "red" # Draw a frame of each case for case in cases: self.win.flip() # Set params of dots objCircle.units = objRect.units = case['units'] objCircle.fieldSize = objRect.fieldSize = case['size'] # Set params of guides maxCircle.units = maxRect.units = minCircle.units = minRect.units = case['units'] maxCircle.size = maxRect.size = case['size'] * (1 + err) minCircle.size = minRect.size = case['size'] * (1 - err) # Test circle dots maxCircle.draw() minCircle.draw() objCircle.draw() _findColors(self.win) self.win.flip() # Test square dots maxRect.draw() minRect.draw() objRect.draw() _findColors(self.win) self.win.flip() # Restore window color self.win.color = ogColor def test_movement(self): # Window needs to be black so that adding 2 screens doesn't make a white screen self.win.color = "black" self.win.flip() # Create dots obj = visual.DotStim( self.win, nDots=1, fieldPos=(0, 0), fieldSize=(1, 1), units="height", dotSize=(32, 32), dotLife=0, noiseDots='direction', dir=0, speed=0.25, coherence=1 ) # Draw dots obj.draw() # Get screenshot 1 screen1 = np.array(self.win._getFrame(buffer="back")) self.win.flip() # Draw again, triggering position update obj.draw() # Get screenshot 2 screen2 = np.array(self.win._getFrame(buffer="back")) self.win.flip() # Create compound screenshot with a dot in BOTH positions compound = np.clip(screen1 + screen2, 0, 255) # If dots have moved, then there should be more white on the compound screen than on either original assert compound.mean() > screen1.mean() and compound.mean() > screen2.mean(), ( "Dot stimulus does not appear to have moved across two frames." )
6,360
Python
.py
147
31.591837
120
0.542862
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,552
test_roi.py
psychopy_psychopy/psychopy/tests/test_visual/test_roi.py
import numpy as np from .test_basevisual import _TestUnitsMixin, _TestSerializationMixin from psychopy.tests.test_experiment.test_component_compile_python import _TestBoilerplateMixin from psychopy import visual, core class TestROI(_TestUnitsMixin, _TestBoilerplateMixin, _TestSerializationMixin): def setup_method(self): self.win = visual.Window([128,128], pos=[50,50], units="pix", allowGUI=False, autoLog=False) self.obj = visual.ROI( self.win, name="testROI", device=None, debug=True, shape="rectangle", units='pix', pos=(0, 0), size=(64, 64), anchor="center", ori=0.0, autoLog=False ) # Replace tracker with a rect, as it still has setPos, getPos, etc. but doesn't require any device input self.obj.device = visual.Rect( self.win, name="fakeTracker", pos=(-128, -128), size=(1, 1), units="pix", autoLog=False ) @property def _eyeNoise(self): """ Apply random noise within 16 pixels """ radius = min(self.obj._size.pix) / 10 randBase = np.random.random() return randBase * radius * 2 - radius def _lookAt(self): """ Simulate a look at the ROI """ # Look at middle of ROI, with some noise self.obj.device.pos = ( self.obj.pos[0] + self._eyeNoise, self.obj.pos[1] + self._eyeNoise ) # Make sure we are not looking at ROI assert self.obj.isLookedIn, f"ROI not returning True for isLookedIn when looked at." def _lookAway(self): """ Simulate a look away from the ROI """ # Look away from ROI self.obj.device.pos = ( self.obj.pos[0] + self.obj.size[0] + self.obj.size[0] / 5 + self._eyeNoise, self.obj.pos[1] + self.obj.size[1] + self.obj.size[1] / 5 + self._eyeNoise, ) # Make sure we are not looking at ROI assert not self.obj.isLookedIn, f"ROI returning True for isLookedIn when not looked at." def test_look_at_away(self): # Define some look times to simulate looks = np.array([ [0.1, 0.2], [0.3, 0.4], [0.6, 0.65], [0.9, 1] ]) # Start a timer t = 0 clock = core.Clock() # Start off looking away self._lookAway() # Simulate a frame loop while t < looks.max() + 0.1: # Look at and away at specific times inLook = np.logical_and(looks[:, 0] < t, looks[:, 1] > t) if any(inLook): self._lookAt() else: self._lookAway() # Update timesOn if looked at if self.obj.isLookedIn and not self.obj.wasLookedIn: self.obj.timesOn.append(t) self.obj.wasLookedIn = True # Update times off if looked away if self.obj.wasLookedIn and not self.obj.isLookedIn: self.obj.timesOff.append(t) self.obj.wasLookedIn = False # Update t t = clock.getTime() # Check that times saved correctly assert all( np.isclose(self.obj.timesOn, looks[:, 0], 0.05) ) assert all( np.isclose(self.obj.timesOff, looks[:, 1], 0.05) ) # Check that convenience functios return correct values assert self.obj.numLooks == looks.shape[0]
3,516
Python
.py
90
28.9
112
0.565116
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,553
test_custommouse.py
psychopy_psychopy/psychopy/tests/test_visual/test_custommouse.py
from psychopy.visual import Window, CustomMouse, TextStim import pytest import pyglet # currently just a placeholder for better coverage # checks for syntax errors not proper function: flip, opacity, pos, etc class Test_Custommouse(): @classmethod def setup_class(self): self.win = Window([128,256]) self.winpix = Window([128,256], units='pix', autoLog=False) @classmethod def teardown_class(self): for win in [self.win, self.winpix]: win.close() def test_init(self): #for win in [self.win, self.winpix]: m = CustomMouse(self.win, showLimitBox=True, autoLog=False) assert (m.leftLimit, m.topLimit, m.rightLimit, m.bottomLimit) == (-1, 1, 0.99, -0.98) assert m.visible == True assert m.showLimitBox == True assert m.clickOnUp==False m.getPos() m.draw() m.clickOnUp = m.wasDown = True m.isDownNow = False m.draw() m.getClicks() m.resetClicks() m.getVisible() m.setVisible(False) with pytest.raises(AttributeError): m.setPointer('a') m.setPointer(TextStim(self.win, text='x')) m = CustomMouse(self.winpix, autoLog=False) assert (m.leftLimit, m.topLimit, m.rightLimit, m.bottomLimit) == (-64.0, 128.0, 59.0, -118.0) assert m.visible == True assert m.showLimitBox == m.clickOnUp == False m.getPos() def test_limits(self): # to-do: test setLimit pass
1,515
Python
.py
41
29.365854
101
0.623978
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,554
test_projections.py
psychopy_psychopy/psychopy/tests/test_visual/test_projections.py
import sys from pyglet.window import key from psychopy.visual import Window, TextStim, GratingStim, Circle from psychopy.visual.windowwarp import Warper from psychopy import event import pytest, copy """define WindowWarp configurations, test the logic test: cd psychopy/psychopy/ py.test -k projections --cov-report term-missing --cov visual/windowwarp.py """ foregroundColor = [-1, -1, -1] backgroundColor = [1, 1, 1] class ProjectionsLinesAndCircles: """ Test jig for projection warping. Switch between warpings by pressing a key 'S'pherical, 'C'ylindrical, 'N'one, warp'F'ile. Click the mouse to set the eyepoint X, Y. Up / Down arrow or mousewheel to move eyepoint in and out. """ def __init__(self, win, warper): self.win = win self.warper = warper self.stimT = TextStim(self.win, text='Null warper', units = 'pix', pos=(0, -140), height=20) self.bl = -win.size / 2.0 self.tl = (self.bl[0], -self.bl[1]) self.tr = win.size / 2.0 self.stims = [] self.degrees = 120 nLines = 12 for x in range(-nLines, nLines+1): t = GratingStim(win, tex=None, units='deg', size=[2, win.size[1]], texRes=128, color=foregroundColor, pos=[float(x) / nLines * self.degrees, 0]) self.stims.append (t) for y in range (-nLines, nLines+1): t = GratingStim(win, tex=None, units='deg', size=[win.size[0], 2], texRes=128, color=foregroundColor, pos=[0, float(y)/nLines * self.degrees]) self.stims.append(t) for c in range (1, nLines+1): t = Circle (win, radius=c * 10, edges=128, units='deg', lineWidth=4) self.stims.append(t) self.updateInfo() self.keys = key.KeyStateHandler() win.winHandle.push_handlers(self.keys) self.mouse = event.Mouse(win=self.win) def updateFrame(self): """ Updates frame with any item that is to be modulated per frame. """ for s in self.stims: s.draw() self.stimT.draw() def update_sweep(self): """ Update function for sweeps. Input is in domain units. """ self.updateFrame() self.check_keys() self._handleMouse() self.win.flip() def updateInfo(self): try: self.stimT.setText( "%s \n eyePoint: %.3f, %.3f \n eyeDistance: %.2f\n\n" "Projection: [s]pherical, [c]ylindrical, [n]one, warp[f]ile\n" "Flip: [h]orizontal, [v]ertical\n" "Mouse: wheel = eye distance, click to set eyepoint\n" "[q]uit" % ( self.warper.warp, self.warper.eyepoint[0], self.warper.eyepoint[1], self.warper.dist_cm)) except Exception: pass def check_keys(self): """Checks key input""" for keys in event.getKeys(timeStamped=True): k = keys[0] if k in ['escape', 'q']: self.win.close() sys.exit() elif k in ['space']: for c in range (1,2): t = Circle(self.win, radius=c) self.stims.append (t) #for c in range (1,2): # t = RadialStim(self.win) # self.stims.append(t) # handle projections elif k in ['s']: self.warper.changeProjection ('spherical', None, (0.5,0.5)) elif k in ['c']: self.warper.changeProjection ('cylindrical', None, (0.5,0.5)) elif k in ['n']: self.warper.changeProjection (None, None, (0.5,0.5)) elif k in ['f']: self.warper.changeProjection ('warpfile', r'..\data\sample.meshwarp.data', (0.5,0.5)) # flip horizontal and vertical elif k in ['h']: self.warper.changeProjection(self.warper.warp, self.warper.warpfile, flipHorizontal = not self.warper.flipHorizontal) elif k in ['v']: self.warper.changeProjection(self.warper.warp, self.warper.warpfile, flipVertical = not self.warper.flipVertical) # move eyepoint elif k in ['down']: if (self.warper.dist_cm > 1): self.warper.dist_cm -= 1 self.warper.changeProjection (self.warper.warp, None, self.warper.eyepoint) elif k in ['up']: if (self.warper.dist_cm < 200): self.warper.dist_cm += 1 self.warper.changeProjection (self.warper.warp, None, self.warper.eyepoint) elif k in ['right']: if (self.warper.eyepoint[0] < 0.9): self.warper.eyepoint = (self.warper.eyepoint[0] + 0.1, self.warper.eyepoint[1]) self.warper.changeProjection (self.warper.warp, None, self.warper.eyepoint) elif k in ['left']: if (self.warper.eyepoint[0] > 0.1): self.warper.eyepoint = (self.warper.eyepoint[0] - 0.1, self.warper.eyepoint[1]) self.warper.changeProjection (self.warper.warp, None, self.warper.eyepoint) self.updateInfo() def _handleMouse(self): x,y = self.mouse.getWheelRel() if y != 0: self.warper.dist_cm += y self.warper.dist_cm = max (1, min (200, self.warper.dist_cm)) self.warper.changeProjection (self.warper.warp, self.warper.warpfile, self.warper.eyepoint) self.updateInfo() pos = (self.mouse.getPos() + 1) / 2 leftDown = self.mouse.getPressed()[0] if leftDown: self.warper.changeProjection (self.warper.warp, self.warper.warpfile, pos) self.updateInfo() class Test_class_WindowWarp(): def setup_class(self): self.win = Window(monitor='testMonitor', screen=0, fullscr=True, color='gray', useFBO = True, autoLog=False) self.warper = Warper(self.win, warp='spherical', warpfile="", warpGridsize=128, eyepoint=[0.5, 0.5], flipHorizontal=False, flipVertical=False) self.warper.dist_cm = 15 self.g = ProjectionsLinesAndCircles(self.win, self.warper) def teardown_class(self): self.win.close() def draw_projection (self, frames=120): self.g.updateInfo() for i in range(frames): self.g.update_sweep() def test_spherical(self): self.warper.changeProjection('spherical') self.draw_projection() def test_cylindrical(self): self.warper.changeProjection('cylindrical') self.draw_projection() def test_warpfile(self): self.warper.changeProjection('warpfile', warpfile="") #jayb todo self.draw_projection() def test_distance(self): self.test_spherical() for i in range (1, 50, 2): self.warper.dist_cm = i self.warper.changeProjection(self.warper.warp) self.g.updateInfo() self.g.update_sweep() self.test_cylindrical() for i in range (1, 50, 2): self.warper.dist_cm = i self.warper.changeProjection(self.warper.warp) self.g.updateInfo() self.g.update_sweep() def test_flipHorizontal(self): self.warper.changeProjection(self.warper.warp, self.warper.warpfile, flipHorizontal = not self.warper.flipHorizontal) self.draw_projection() def test_flipVertical(self): self.warper.changeProjection(self.warper.warp, self.warper.warpfile, flipVertical = not self.warper.flipVertical) self.draw_projection() if __name__ == '__main__': # running interactive cls = Test_class_WindowWarp() cls.setup_class() for i in range(2 * 60 * 60): cls.g.update_sweep() cls.win.close()
8,092
Python
.py
180
33.383333
133
0.57141
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,555
test_framepacking.py
psychopy_psychopy/psychopy/tests/test_visual/test_framepacking.py
import pytest from psychopy.visual import Window from psychopy.visual.windowframepack import ProjectorFramePacker """define ProjectorFramePack configurations, test the logic test: cd psychopy/psychopy/ py.test -k projectorframepack --cov-report term-missing --cov visual/windowframepack.py """ class Test_class_ProjectorFramePacker(): """ """ def setup_class(self): self.win = Window(monitor='LightCrafter4500', screen=2, fullscr=True, color='gray', useFBO = True) self.win.setRecordFrameIntervals() self.packer = ProjectorFramePacker (self.win) def teardown_class(self): self.win.close() def flip (self, frames=120): for i in range(frames): self.win.flip() if __name__ == '__main__': cls = Test_class_ProjectorFramePacker() cls.setup_class() originalFPS = cls.win.fps() print('originalFPS = ' + str(originalFPS)) cls.flip(3) assert (cls.win.frames == 3) assert (cls.packer.flipCounter == 3) cls.flip(33) assert (cls.win.frames == 36) assert (cls.packer.flipCounter == 36) finalFPS = cls.win.fps() print('finalFPS = ' + str(finalFPS)) cls.teardown_class()
1,199
Python
.py
34
30.058824
106
0.680484
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,556
test_contains_overlaps.py
psychopy_psychopy/psychopy/tests/test_visual/test_contains_overlaps.py
"""Test polygon .contains and .overlaps methods py.test -k polygon --cov-report term-missing --cov visual/helpers.py """ from pathlib import Path from psychopy import visual, monitors, layout from psychopy.tests import utils from psychopy.visual import helpers from numpy import sqrt import matplotlib mon = monitors.Monitor('testMonitor') mon.setDistance(57) mon.setWidth(40.0) mon.setSizePix([1024,768]) win = visual.Window([512,512], monitor=mon, winType='pyglet', autoLog=False) unitDist = 0.2 sqrt2 = sqrt(2) points = [ layout.Position((0, 0), 'height', win), layout.Position((0, unitDist), 'height', win), layout.Position((0, unitDist * 2), 'height', win), layout.Position(((unitDist / sqrt2), (unitDist / sqrt2)), 'height', win), layout.Position((unitDist * sqrt2, 0), 'height', win), layout.Position((unitDist * sqrt2, unitDist * sqrt2), 'height', win)] postures = [ {'ori': 0, 'size': layout.Size((1.0, 1.0), 'height', win), 'pos': layout.Position((0, 0), 'height', win)}, {'ori': 0, 'size': layout.Size((1.0, 2.0), 'height', win), 'pos': layout.Position((0, 0), 'height', win)}, {'ori': 45, 'size': layout.Size((1.0, 1.0), 'height', win), 'pos': layout.Position((0, 0), 'height', win)}, {'ori': 45, 'size': layout.Size((2.0, 2.0), 'height', win), 'pos': layout.Position((0, 0), 'height', win)}, {'ori': 0, 'size': layout.Size((1.0, 1.0), 'height', win), 'pos': layout.Position((unitDist*sqrt2, 0), 'height', win)}, {'ori': 0, 'size': layout.Size((1.0, 2.0), 'height', win), 'pos': layout.Position((unitDist*sqrt2, 0), 'height', win)}, {'ori': -45, 'size': layout.Size((1.0, 1.0), 'height', win), 'pos': layout.Position((unitDist*sqrt2, 0), 'height', win)}, {'ori': -90, 'size': layout.Size((1.0, 2.0), 'height', win), 'pos': layout.Position((unitDist*sqrt2, 0), 'height', win)} ] correctResults = [ (True, True, False, False, False, False), (True, True, True, False, False, False), (True, False, False, True, False, False), (True, False, False, True, False, True), (False, False, False, False, True, False), (False, False, False, False, True, True), (False, False, False, True, True, False), (True, False, False, False, True, False)] mon = monitors.Monitor('testMonitor') mon.setDistance(57) mon.setWidth(40.0) mon.setSizePix([1024,768]) dbgStr = ('"%s" returns wrong value: unit=%s, ori=%.1f, size=%s, pos=%s, ' 'testpoint=%s, expected=%s') def contains_overlaps(testType): for units in ['pix', 'height', 'norm', 'cm', 'deg']: win.units = units # Create shape to test with vertices = [(0.05, 0.24), (0.05, -0.24), (-0.05, -0.24), (-0.05, 0.24)] shape = visual.ShapeStim(win, vertices=vertices, autoLog=False) # Create circles to show where each point is on screen testPoints = [] for p in points: testPoints.append( visual.Circle(win, size=layout.Size((10, 10), 'pix', win), pos=p, units=units, autoLog=False) ) # Try each point / posture combo for i in range(len(postures)): # Set shape attrs shape.setOri(postures[i]['ori'], log=False) shape.setSize(getattr(postures[i]['size'], units), log=False) shape.setPos(getattr(postures[i]['pos'], units), log=False) shape.draw() # Test each point for j in range(len(testPoints)): pointMarker = testPoints[j] p = points[j] # Check contains / overlap if testType == 'contains': res = shape.contains(getattr(p, units)) # test for two parameters x = getattr(p, units)[0] y = getattr(p, units)[1] assert (shape.contains(x, y) == res) elif testType == 'overlaps': res = shape.overlaps(testPoints[j]) else: raise ValueError('Invalid value for parameter `testType`.') # Is the point within the shape? Green == yes, red == no. pointMarker.setFillColor('green' if res else 'red', log=False) pointMarker.draw() # Assert if res != correctResults[i][j]: # Output debug image pointMarker.setBorderColor( 'green' if correctResults[i][j] else 'red', log=False) for marker in testPoints: marker.draw() shape.draw() win.flip() win.screenshot.save( Path(utils.TESTS_DATA_PATH) / f"{testType}_error_local_{i}_{j}.png") # Raise error print(res, points[j], i, j) raise AssertionError(dbgStr % ( testType, units, postures[i]['ori'], shape._size, shape._pos, points[j], correctResults[i][j] )) # Un-highlight marker pointMarker.draw() win.flip() mpl_version = matplotlib.__version__ try: from matplotlib import nxutils have_nxutils = True except Exception: have_nxutils = False # if matplotlib.__version__ > '1.2': try to use matplotlib Path objects # else: try to use nxutils # else: fall through to pure python def test_point(): poly1 = [(1,1), (1,-1), (-1,-1), (-1,1)] poly2 = [(2,2), (1,-1), (-1,-1), (-1,1)] assert helpers.pointInPolygon(0, 0, poly1) assert (helpers.pointInPolygon(12, 12, poly1) is False) assert (helpers.pointInPolygon(0, 0, [(0,0), (1,1)]) is False) if have_nxutils: helpers.nxutils = nxutils matplotlib.__version__ = '1.1' # matplotlib.nxutils assert helpers.polygonsOverlap(poly1, poly2) del helpers.nxutils matplotlib.__version__ = '0.0' # pure python assert helpers.polygonsOverlap(poly1, poly2) matplotlib.__version__ = mpl_version def test_contains(): contains_overlaps('contains') # matplotlib.path.Path if have_nxutils: helpers.nxutils = nxutils matplotlib.__version__ = '1.1' # matplotlib.nxutils contains_overlaps('contains') del helpers.nxutils matplotlib.__version__ = '0.0' # pure python contains_overlaps('contains') matplotlib.__version__ = mpl_version def test_overlaps(): contains_overlaps('overlaps') # matplotlib.path.Path if have_nxutils: helpers.nxutils = nxutils matplotlib.__version__ = '1.1' # matplotlib.nxutils contains_overlaps('overlaps') del helpers.nxutils matplotlib.__version__ = '0.0' # pure python contains_overlaps('overlaps') matplotlib.__version__ = mpl_version def test_border_contains(): # tests that the .border of ShapeStim is detected and used by .contains() win.units = 'height' # `thing` has a fake hole and discontinuity (as the border will reveal): thingVert = [(0,0),(0,.4),(.4,.4),(.4,0),(.1,0),(.1,.1),(.3,.1),(.3,.3), (.1,.3),(.1,0),(0,0),(.1,-.1),(.3,-.1),(.3,-.3),(.1,-.3), (.1,-.1)] inside_pts = [(.05,.05), (.15,-.15)] outside_pts = [(-.2,0)] hole_pts = [(.2,.2)] s = visual.ShapeStim(win, vertices=thingVert, fillColor='blue', lineWidth=1, lineColor='white') s.draw() win.flip() for p in inside_pts: assert s.contains(p) for p in outside_pts + hole_pts: assert (not s.contains(p)) # lacking a .border attribute, contains() will improperly succeed in some cases del s.border for p in hole_pts: assert s.contains(p), "no .border property (falls through to relying on tesselated .vertices)" for p in outside_pts: assert (not s.contains(p)) # ... and should work properly again when restore the .border s.border = thingVert for p in hole_pts: assert (not s.contains(p)) def test_line_overlaps(): win.units = 'height' circle_1 = visual.Circle(win, radius=0.25, pos=(0, 0)) circle_2 = visual.Circle(win, radius=0.25, pos=(0, -0.5)) line = visual.Line(win, start=(-1, -1), end=(1, 1)) assert line.overlaps(circle_1) assert circle_1.overlaps(circle_1) assert not line.overlaps(circle_2) assert not circle_2.overlaps(line) def test_line_contains(): win.units = 'height' point_1 = (0, 0) point_2 = (0, -0.5) line = visual.Line(win, start=(-1, -1), end=(1, 1)) assert (line.contains(point_1) is False) assert (line.contains(point_2) is False) if __name__ == '__main__': test_overlaps() test_contains() test_border_contains() test_line_overlaps() test_line_contains()
8,987
Python
.py
203
35.37931
126
0.575071
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,557
test_winScalePos.py
psychopy_psychopy/psychopy/tests/test_visual/test_winScalePos.py
from psychopy import visual from psychopy.tests import utils import os import pytest v = [(1, 1), (1, -1), (-1, -1), (-1, 1)] # vertices to use = square n = 15 # size of the base square pimg = (n, n) # position for the image pgrn = (-n, -n) # position for green square img_name = os.path.join(utils.TESTS_DATA_PATH, 'filltext.png') class Test_Win_Scale_Pos_Ori: def setup_class(self): self.win = visual.Window(size=(200, 200), units='pix', allowGUI=False, autoLog=False) def teardown_class(self): self.win.close() @pytest.mark.scalepos def test_winScalePosOri(self): """test window.viewScale and .viewPos simultaneous negative-going scale should mirror-reverse, and position should account for that visually, the green square/rect should move clockwise around the text Non-zero viewOri would not currently pass with a nonzero viewPos """ with pytest.raises(ValueError): # units must be define for viewPos! _, = visual.Window(size=(200, 200), viewPos=(1, 1), viewOri=1) with pytest.raises(NotImplementedError): # simultaneous viewPos and viewOri prohibited at present _, = visual.Window(size=(200, 200), units='pix', viewPos=(1, 1), viewOri=1) for ori in [0, 45]: self.win.viewOri = ori for offset in [(0, 0), (-0.4, 0)]: if ori and (offset[0] or offset[1]): continue # this combination is NotImplemented else: # NB assumes test win is in pixels! # convert from normalised offset to pixels offset_pix = (round(offs * siz / 2.) for offs, siz in zip(offset, self.win.size)) self.win.viewPos = offset_pix for scale in [[1, 1], # normal: green at lower left [1, -1], # mirror vert only: green appears to # move up, text mirrored [-1, -1], # mirror horiz & vert: green appears # to move right, text normal but # upside down [-1, 1], # mirror horiz only: green appears to # move down, text mirrored [2, 2], # same, but both larger [2, -2], [-2, -2], [-2, 2]]: self.win.viewScale = scale self.win.flip() grn = visual.ShapeStim(self.win, vertices=v, pos=pgrn, size=n, fillColor='darkgreen') img = visual.ImageStim(self.win, image=img_name, size=2*n, pos=pimg) grn.draw() img.draw() oristr = str(ori) scalestr = str(scale[0]) + '_' + str(scale[1]) posstr = str(offset[0]) + '_' + str(offset[1]) filename = 'winScalePos_ori%s_scale%s_pos%s.png' % \ (oristr, scalestr, posstr) utils.compareScreenshot(filename, self.win, crit=15)
3,444
Python
.py
66
34.287879
78
0.485298
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,558
test_button.py
psychopy_psychopy/psychopy/tests/test_visual/test_button.py
from psychopy import visual from psychopy.tests.test_visual.test_basevisual import _TestColorMixin, _TestSerializationMixin from psychopy.tests.test_experiment.test_component_compile_python import _TestBoilerplateMixin class TestButton(_TestColorMixin, _TestBoilerplateMixin, _TestSerializationMixin): @classmethod def setup_class(self): self.win = visual.Window([128,128], pos=[50,50], allowGUI=False, autoLog=False) self.obj = visual.ButtonStim(self.win, text="", units="pix", pos=(0, 0), size=(128, 128)) # Pixel which is the fill color self.fillPoint = (3, 3) self.fillUsed = True
637
Python
.py
11
52.181818
97
0.736334
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,559
test_shape.py
psychopy_psychopy/psychopy/tests/test_visual/test_shape.py
import pytest from psychopy import visual from .test_basevisual import _TestColorMixin, _TestUnitsMixin, _TestSerializationMixin from psychopy.tests.test_experiment.test_component_compile_python import _TestBoilerplateMixin class TestShape(_TestColorMixin, _TestUnitsMixin, _TestBoilerplateMixin, _TestSerializationMixin): @classmethod def setup_class(self): self.win = visual.Window([128,128], pos=[50,50], allowGUI=False, autoLog=False) self.obj = visual.Rect(self.win, units="pix", pos=(0, 0), size=(128, 128), lineWidth=10) # Pixel which is the border color self.borderPoint = (0, 0) self.borderUsed = True # Pixel which is the fill color self.fillPoint = (50, 50) self.fillUsed = True # Shape has no foreground color self.foreUsed = False
838
Python
.py
17
42.764706
98
0.711656
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,560
test_event.py
psychopy_psychopy/psychopy/tests/test_misc/test_event.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from psychopy.visual import Window, ShapeStim from psychopy import event, core, monitors from psychopy.constants import NOT_STARTED import pyglet from pyglet.window.mouse import LEFT, MIDDLE, RIGHT try: import pygame havePygame = True except Exception: havePygame = False import pytest import copy import threading import numpy as np from psychopy.tests import skip_under_vm """test with both pyglet and pygame: cd psychopy/psychopy/ py.test -k event --cov-report term-missing --cov event.py """ class DelayedFakeKeys(threading.Thread): def __init__(self, keys, modifiers=0, delay=.01): threading.Thread.__init__(self, None, 'fake key', None) if isinstance(keys, str): self.keys = [keys] else: self.keys = keys self.modifiers = modifiers self.delay = delay def run(self): core.wait(self.delay) [event._onPygletKey(key, modifiers=self.modifiers, emulated=True) for key in self.keys] class DelayedAddFakeKeysToBuffer(threading.Thread): def __init__(self, keys, modifiers=0, delay=.01): threading.Thread.__init__(self, None, 'fake key', None) if isinstance(keys, str): self.keys = [keys] else: self.keys = keys self.modifiers = modifiers self.delay = delay def run(self): core.wait(self.delay) fake_events = [(key, self.modifiers, -1) for key in self.keys] event._keyBuffer.extend(fake_events) class _baseTest(): #this class allows others to be created that inherit all the tests for #a different window config @classmethod def setup_class(self):#run once for each test class (window) self.win=None self.contextName raise NotImplementedError @classmethod def teardown_class(self):#run once for each test class (window) try: self.win.close() except AttributeError: pass def test_mouse_pos(self): if self.win.winType == 'pygame': pytest.skip() # pygame.setVisible errors for w in (self.win,): #, None): for p in (None, (0,0)): m = event.Mouse(newPos=p, win=w) assert m.units == 'norm' m.setPos((0,0)) m.getPos() def test_emulated_mouse(self): mouse = event.Mouse() # real mouse event.mouseButtons = [0,0,0] [c.reset() for c in event.mouseClick] # mouse click RT clocks assert not any(event.mouseButtons) assert not any(event.mouseTimes) # fake clicks on all buttons: event._onPygletMousePress(0, 0, LEFT | MIDDLE | RIGHT, None, emulated=True) assert all(mouse.getPressed()) assert all([RT < 0.01 for RT in event.mouseTimes]) # should be < .0001 # fake release all buttons: event._onPygletMouseRelease(0, 0, LEFT | MIDDLE | RIGHT, None, emulated=True) assert not any(event.mouseButtons) @skip_under_vm def test_mouse_clock(self): x, y = 0, 0 scroll_x, scroll_y = 1, 1 dx, dy = 1, 1 zeros = [0, 0, 0] for b in [pyglet.window.mouse.LEFT, pyglet.window.mouse.MIDDLE, pyglet.window.mouse.RIGHT]: event.mouseButtons = copy.copy(zeros) event.mouseTimes = copy.copy(zeros) event._onPygletMousePress(x,y, b, None) assert event.mouseButtons != zeros assert event.mouseTimes != zeros event._onPygletMouseRelease(x,y, b, None) assert event.mouseButtons == zeros event._onPygletMouseWheel(x,y,scroll_x, scroll_y) event._onPygletMouseMotion(x, y, dx, dy) event.startMoveClock() event.stopMoveClock() event.resetMoveClock() m = event.Mouse() assert m.mouseMoveTime() >= 0 t = 0.05 core.wait(t) assert t - 0.01 < m.mouseMoveTime() < t + 0.01 def test_clearEvents(self): for t in ['mouse', 'joystick', 'keyboard', None]: event.clearEvents(t) def test_clearEvents_keyboard(self): event._onPygletKey(symbol='x', modifiers=0, emulated=True) event.clearEvents('keyboard') assert not event._keyBuffer def test_clearEvents_mouse(self): """Keyboard buffer should not be affected. """ event._onPygletKey(symbol='x', modifiers=0, emulated=True) event.clearEvents('mouse') assert event._keyBuffer def test_clearEvents_joystick(self): """Keyboard buffer should not be affected. """ event._onPygletKey(symbol='x', modifiers=0, emulated=True) event.clearEvents('joystick') assert event._keyBuffer @skip_under_vm def test_keys(self): if self.win.winType == 'pygame': pytest.skip() event.clearEvents() assert event.getKeys() == [] for k in ['s', 'return']: event.clearEvents() event._onPygletKey(symbol=k, modifiers=0, emulated=True) assert k in event.getKeys() event._onPygletKey(symbol=17, modifiers=0, emulated=False) assert '17' in event.getKeys() # test that key-based RT is about right event.clearEvents() c = core.Clock() t = 0.05 core.wait(t) event._onPygletKey(symbol=k, modifiers=0, emulated=True) resp = event.getKeys(timeStamped=c) assert k in resp[0][0] assert t - 0.01 < resp[0][1] < t + 0.01 event._onPygletKey(symbol=k, modifiers=0, emulated=True) assert k in event.getKeys(timeStamped=True)[0] event._onPygletKey(symbol=k, modifiers=0, emulated=True) event._onPygletKey(symbol='x', modifiers=0, emulated=True) # nontarget assert k in event.getKeys(keyList=[k, 'd']) # waitKeys implicitly clears events, so use a thread to add a delayed key press assert event.waitKeys(maxWait=-1) is None keyThread = DelayedFakeKeys(k) keyThread.start() assert event.waitKeys(maxWait=.1) == [k] keyThread = DelayedFakeKeys(k) keyThread.start() assert event.waitKeys(maxWait=.1, keyList=[k]) == [k] # test time-stamped waitKeys c = core.Clock() delay=0.01 keyThread = DelayedFakeKeys(k, delay=delay) keyThread.start() result = event.waitKeys(maxWait=.1, keyList=[k], timeStamped=c) assert result[0][0] == k assert result[0][1] - delay < .01 # should be ~0 except for execution time @skip_under_vm def test_waitKeys_clearEvents_True(self): key = 'x' DelayedAddFakeKeysToBuffer(key).start() key_events = event.waitKeys(clearEvents=True) assert key_events == [key] @skip_under_vm def test_waitKeys_clearEvents_False(self): keys = ['x', 'y', 'z'] [event._onPygletKey(symbol=key, modifiers=0, emulated=True) for key in keys] key_events = event.waitKeys(keyList=keys[1:], clearEvents=False) assert 'x' not in key_events assert 'y' in key_events assert 'z' in key_events @skip_under_vm def test_waitKeys_keyList_clearEvents_True(self): keys = ['x', 'y', 'z'] DelayedAddFakeKeysToBuffer(keys).start() key_events = event.waitKeys(keyList=keys[:-1], clearEvents=True) assert 'x' in key_events assert 'y' in key_events assert 'z' not in key_events assert 'z' in event.getKeys() def test_xydist(self): assert event.xydist([0,0], [1,1]) == np.sqrt(2) @skip_under_vm def test_mouseMoved(self): m = event.Mouse() m.prevPos = [0, 0] m.lastPos = [0, 1] assert m.mouseMoved() # call to mouseMoved resets prev and last m.prevPos = [0, 0] m.lastPos = [0, 1] assert m.mouseMoved(distance=0.5) for reset in [True, 'here', (1,2)]: assert not m.mouseMoved(reset=reset) def test_set_visible(self): if self.win.winType == 'pygame': pytest.skip() m = event.Mouse() for v in (0, 1): m.setVisible(v) w = self.win m.win = None m.setVisible(v) m.win = w def test_misc(self): m = event.Mouse() m.getRel() m.getWheelRel() m.getVisible() m.clickReset() # to-do: proper test of mouseClick and mouseTimes being changed # not much to assert here: m.getPressed() m.getPressed(getTime=True) def test_isPressedIn(self): m = event.Mouse(self.win, newPos=(0,0)) s = ShapeStim(self.win, vertices=[[10,10],[10,-10],[-10,-10],[-10,10]], autoLog=False) if not s.contains(m.getPos()): pytest.skip() # or can't test event.mouseButtons = [1, 1, 1] assert m.isPressedIn(s) # obsolete? # m._pix2windowUnits() # m._windowUnits2pix() def test_builder_key_resp(self): # just inits bk = event.BuilderKeyResponse() assert bk.status == NOT_STARTED assert bk.keys == [] #the key(s) pressed assert bk.corr == 0 #was the resp correct this trial? (0=no, 1=yes) assert bk.rt == [] #response time(s) assert bk.clock.getTime() < .001 @pytest.mark.event class TestPygletNorm(_baseTest): @classmethod def setup_class(self): mon = monitors.Monitor('testMonitor') mon.setDistance(10.0) #exaggerate the effect of flatness by setting the monitor close mon.setWidth(40.0) mon.setSizePix([1024,768]) self.win = Window([128,128], monitor=mon, winType='pyglet', pos=[50,50], autoLog=False) if havePygame: assert pygame.display.get_init() == 0 class xxxTestPygameNorm(_baseTest): @classmethod def setup_class(self): self.win = Window([128,128], winType='pygame', pos=[50,50], autoLog=False) assert pygame.display.get_init() == 1 assert event.havePygame if __name__ == '__main__': import pytest pytest.main()
10,304
Python
.py
263
30.365019
99
0.603641
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,561
test_web.py
psychopy_psychopy/psychopy/tests/test_misc/test_web.py
from psychopy import web import pytest # py.test -k web --cov-report term-missing --cov web.py @pytest.mark.web class TestWeb(): @classmethod def setup_class(self): try: web.requireInternetAccess() except web.NoInternetAccessError: pytest.skip() def teardown_method(self): pass def test_setupProxy(self): web.getPacFiles() web.getWpadFiles() web.proxyFromPacFiles(web.getPacFiles(), log=False) web.setupProxy()
511
Python
.py
18
21.833333
59
0.656442
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,562
test_GammaFun.py
psychopy_psychopy/psychopy/tests/test_misc/test_GammaFun.py
from psychopy.monitors import calibTools import numpy yy=[0,0.2,0.4,0.8,1.0] minLum=2.0 maxLum=100.0 gamma=2.2 xxTest=numpy.array([ 0., 0.48115651, 0.65935329, 0.90354543, 1. ]) def test_GammaInverse_Eq1(): xx= calibTools.gammaInvFun(yy, minLum, maxLum, gamma, b=0, eq=1) assert numpy.allclose(xx,xxTest,0.0001) def test_GammaInverse_Eq4(): xx= calibTools.gammaInvFun(yy, minLum, maxLum, gamma, b=0, eq=4) assert numpy.allclose(xx,xxTest,0.0001)
483
Python
.py
13
34.769231
85
0.705128
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,563
test_color.py
psychopy_psychopy/psychopy/tests/test_misc/test_color.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """All tests in this file involve rapidly changing colours, do not run these tests in a setting where you can view the output if you have photosensitive epilepsy. """ from psychopy.alerts import addAlertHandler from psychopy.alerts._errorHandler import _BaseErrorHandler from psychopy.tests import utils from psychopy import visual, colors import numpy as np # Define expected values for different spaces exemplars = [ {'rgb': ( 1.00, 1.00, 1.00), 'rgb255': (255, 255, 255), 'hsv': ( 0, 0.00, 1.00), 'hex': '#ffffff', 'named': 'white'}, # Pure white {'rgb': ( 0.00, 0.00, 0.00), 'rgb255': (128, 128, 128), 'hsv': ( 0, 0.00, 0.50), 'hex': '#808080', 'named': 'gray'}, # Mid grey {'rgb': (-1.00, -1.00, -1.00), 'rgb255': ( 0, 0, 0), 'hsv': ( 0, 0.00, 0.00), 'hex': '#000000', 'named': 'black'}, # Pure black {'rgb': ( 1.00, -1.00, -1.00), 'rgb255': (255, 0, 0), 'hsv': ( 0, 1.00, 1.00), 'hex': '#ff0000', 'named': 'red'}, # Pure red {'rgb': (-1.00, 1.00, -1.00), 'rgb255': ( 0, 255, 0), 'hsv': (120, 1.00, 1.00), 'hex': '#00ff00', 'named': 'lime'}, # Pure green {'rgb': (-1.00, -1.00, 1.00), 'rgb255': ( 0, 0, 255), 'hsv': (240, 1.00, 1.00), 'hex': '#0000ff', 'named': 'blue'}, # Pure blue # Psychopy colours {'rgb': (-0.20, -0.20, -0.14), 'rgb255': (102, 102, 110), 'hsv': (240, 0.07, 0.43), 'hex': '#66666e'}, # grey {'rgb': ( 0.35, 0.35, 0.38), 'rgb255': (172, 172, 176), 'hsv': (240, 0.02, 0.69), 'hex': '#acacb0'}, # light grey {'rgb': ( 0.90, 0.90, 0.90), 'rgb255': (242, 242, 242), 'hsv': ( 0, 0.00, 0.95), 'hex': '#f2f2f2'}, # offwhite {'rgb': ( 0.90, -0.34, -0.29), 'rgb255': (242, 84, 91), 'hsv': (357, 0.65, 0.95), 'hex': '#f2545b'}, # red {'rgb': (-0.98, 0.33, 0.84), 'rgb255': ( 2, 169, 234), 'hsv': (197, 0.99, 0.92), 'hex': '#02a9ea'}, # blue {'rgb': (-0.15, 0.60, -0.09), 'rgb255': (108, 204, 116), 'hsv': (125, 0.47, 0.80), 'hex': '#6ccc74'}, # green {'rgb': ( 0.85, 0.18, -0.98), 'rgb255': (236, 151, 3), 'hsv': ( 38, 0.99, 0.93), 'hex': '#ec9703'}, # orange {'rgb': ( 0.89, 0.65, -0.98), 'rgb255': (241, 211, 2), 'hsv': ( 52, 0.99, 0.95), 'hex': '#f1d302'}, # yellow {'rgb': ( 0.53, 0.49, 0.94), 'rgb255': (195, 190, 247), 'hsv': (245, 0.23, 0.97), 'hex': '#c3bef7'}, # violet ] # A few values which are likely to mess things up tykes = [ {'rgba': ( 1.00, 1.00, 1.00, 0.50), 'rgba255': (255, 255, 255, 0.50), 'hsva': ( 0, 0.00, 1.00, 0.50)}, # Make sure opacities work in every space {'rgba': "white", 'rgba255': "white", "hsva": "white", "hex": "white", "rgb255": "#ffffff"}, # Overriding colorSpace with hex or named values {'rgba': None, 'named': None, 'hex': None, 'hsva': None}, # None as a value ] class Test_Window: """Some tests just for the window - we don't really care about what's drawn inside it """ @classmethod def setup_class(self): self.win = visual.Window([128,128], pos=[50,50], allowGUI=False, autoLog=False) self.error = _BaseErrorHandler() addAlertHandler(self.error) @classmethod def teardown_class(self): self.win.close() # Begin test def test_colors(self): for colorSet in exemplars + tykes: # Construct matrix of space pairs spaceMatrix = [] for space1 in colorSet: spaceMatrix.extend([[space1, space2] for space2 in colorSet if space2 != space1]) # Compare each space pair for consistency for space1, space2 in spaceMatrix: col1 = colors.Color(colorSet[space1], space1) col2 = colors.Color(colorSet[space2], space2) closeEnough = all(abs(col1.rgba[i]-col2.rgba[i])<0.02 for i in range(4)) # Check that valid color has been created assert (bool(col1) and bool(col2)) # Check setters assert (col1 == col2 or closeEnough) def test_window_colors(self): # Iterate through color sets for colorSet in exemplars + tykes: for space in colorSet: # Set window color self.win.colorSpace = space self.win.color = colorSet[space] self.win.flip() utils.comparePixelColor(self.win, colors.Color(colorSet[space], space)) def test_shape_colors(self): # Create rectangle with chunky border obj = visual.Rect(self.win, units="pix", pos=(0,0), size=(128, 128), lineWidth=10) # Iterate through color sets for colorSet in exemplars + tykes: for space in colorSet: # Check border color obj.colorSpace = space obj.borderColor = colorSet[space] obj.fillColor = 'white' obj.opacity = 1 # Fix opacity at full as this is not what we're testing self.win.flip() obj.draw() if colorSet[space]: # skip this comparison if color is None utils.comparePixelColor(self.win, colors.Color(colorSet[space], space), coord=(1, 1)) utils.comparePixelColor(self.win, colors.Color('white'), coord=(50, 50)) # Check fill color obj.colorSpace = space obj.fillColor = colorSet[space] obj.borderColor = 'white' obj.opacity = 1 # Fix opacity at full as this is not what we're testing self.win.flip() obj.draw() if colorSet[space]: # skip this comparison if color is None utils.comparePixelColor(self.win, colors.Color(colorSet[space], space), coord=(50, 50)) utils.comparePixelColor(self.win, colors.Color('white'), coord=(1,1)) # Testing foreColor is already done in test_textbox def test_element_array_colors(self): # Create element array with two elements covering the whole window in two block colours obj = visual.ElementArrayStim(self.win, units="pix", fieldPos=(0, 0), fieldSize=(128, 128), fieldShape='square', nElements=2, sizes=[[64, 128], [64, 128]], xys=[[-32, 0], [32, 0]], elementMask=None, elementTex=None) # Iterate through color sets for colorSet in exemplars + tykes: for space in colorSet: if space not in colors.strSpaces and not isinstance(colorSet[space], (str, type(None))): # Check that setting color arrays renders correctly obj.colorSpace = space col1 = np.array(colorSet[space]).reshape((1, -1)) col2 = getattr(colors.Color('black'), space).reshape((1, -1)) obj.colors = np.append(col1, col2, 0) # Set first color to current color set, second to black in same color space obj.opacity = 1 # Fix opacity at full as this is not what we're testing self.win.flip() obj.draw() utils.comparePixelColor(self.win, colors.Color(colorSet[space], space), coord=(10, 10)) utils.comparePixelColor(self.win, colors.Color('black'), coord=(10, 100)) def test_visual_helper(self): # Create rectangle with chunky border obj = visual.Rect(self.win, units="pix", pos=(0, 0), size=(128, 128), lineWidth=10) # Iterate through color sets for colorSet in exemplars + tykes: for space in colorSet: # Check border color visual.helpers.setColor(obj, color=colorSet[space], colorSpace=space, colorAttrib="borderColor") obj.fillColor = 'white' obj.opacity = 1 # Fix opacity at full as this is not what we're testing self.win.flip() obj.draw() if colorSet[space]: # skip this comparison if color is None utils.comparePixelColor(self.win, colors.Color(colorSet[space], space), coord=(1, 1)) utils.comparePixelColor(self.win, colors.Color('white'), coord=(50, 50)) # Check fill color visual.helpers.setColor(obj, color=colorSet[space], colorSpace=space, colorAttrib="fillColor") obj.borderColor = 'white' obj.opacity = 1 # Fix opacity at full as this is not what we're testing self.win.flip() obj.draw() if colorSet[space]: # skip this comparison if color is None utils.comparePixelColor(self.win, colors.Color(colorSet[space], space), coord=(50, 50)) utils.comparePixelColor(self.win, colors.Color('white'), coord=(1, 1)) # Check color addition obj.fillColor = 'white' visual.helpers.setColor(obj, color='black', colorAttrib='fillColor', operation='+') self.win.flip() obj.draw() utils.comparePixelColor(self.win, colors.Color('white') + colors.Color('black'), coord=(50, 50)) # Check color subtraction obj.fillColor = 'grey' visual.helpers.setColor(obj, color='black', colorAttrib='fillColor', operation='-') self.win.flip() obj.draw() utils.comparePixelColor(self.win, colors.Color('grey') - colors.Color('black'), coord=(50, 50)) # Check alerts visual.helpers.setColor(obj, color="white", colorSpaceAttrib="fillColorSpace", rgbAttrib="fillRGB") assert any(err.code == 8105 for err in self.error.alerts), "Alert 8105 not triggered" assert any(err.code == 8110 for err in self.error.alerts), "Alert 8110 not triggered" def test_contrast(self): # Create rectangle with chunky border obj = visual.Rect(self.win, units="pix", pos=(0, 0), size=(128, 128), lineWidth=10) # Set its colors to be rgb extremes obj.fillColor = 'red' obj.borderColor = 'blue' obj.opacity = 1 # Fix opacity at full as this is not what we're testing # Halve contrast obj.contrast = 0.5 # Refresh self.win.flip() obj.draw() # Check rendered color utils.comparePixelColor(self.win, colors.Color(( 0.5, -0.5, -0.5), "rgb"), coord=(50, 50)) utils.comparePixelColor(self.win, colors.Color((-0.5, -0.5, 0.5), "rgb"), coord=(1, 1)) def test_color_operators(): """Test for operators used to compare colors.""" red255 = colors.Color((255, 0, 0), space='rgb255') redRGB = colors.Color((1, -1, -1), space='rgb') redRGB1 = colors.Color((1, 0, 0), space='rgb1') assert (red255 == redRGB == redRGB1)
11,123
Python
.py
189
46.444444
152
0.556421
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,564
test_layout.py
psychopy_psychopy/psychopy/tests/test_misc/test_layout.py
import numpy from psychopy import layout, visual class TestVector: def setup_method(self): self.win = visual.Window(size=(128, 64), monitor="testMonitor") def teardown_method(self): self.win.close() del self.win def test_values(self): """ Check that Vector objects with various values return as intended in a variety of unit spaces. """ # List of objects with their intended values in various spaces cases = [ # (1, 1) height (layout.Vector((1, 1), 'height', self.win), {'pix': (64, 64), 'height': (1, 1), 'norm': (1, 2), 'cm': (1.875, 1.875)}), # (1, 1) norm (layout.Vector((1, 1), 'norm', self.win), {'pix': (64, 32), 'height': (1, 0.5), 'norm': (1, 1), 'cm': (1.875, 0.9375)}), # (1, 1) pix (layout.Vector((1, 1), 'pix', self.win), {'pix': (1, 1), 'height': (1/64, 1/64), 'norm': (1/64, 1/32), 'cm': (1.875/64, 1.875/64)}), # (1, 1) cm (layout.Vector((1, 1), 'cm', self.win), {'pix': (64/1.875, 64/1.875), 'height': (1/1.875, 1/1.875), 'norm': (1/1.875, 1/0.9375), 'cm': (1, 1)}), # Check ratio of pt to cm (layout.Vector(1, 'pt', self.win), {'pt': 1, 'cm': 0.03527778}), # Negative values (layout.Vector((-1, -1), 'height', self.win), {'pix': (-64, -64), 'height': (-1, -1), 'norm': (-1, -2), 'cm': (-1.875, -1.875)}), ] # Check that each object returns the correct value in each space specified for obj, ans in cases: for space in ans: # Convert both value and answer to numpy arrays and round to 5dp val = numpy.array(getattr(obj, space)).round(5) thisAns = numpy.array(ans[space]).round(5) # Check that they match assert (val == thisAns).all(), ( f"Vector of {obj._requested} in {obj._requestedUnits} should return {ans[space]} in {space} units, " f"but instead returned {val}" )
2,162
Python
.py
44
37.340909
120
0.498344
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,565
test_core.py
psychopy_psychopy/psychopy/tests/test_misc/test_core.py
# -*- coding: utf-8 -*- """ Created on Tue Apr 23 11:18:47 2013 Tests the psychopy.core.getTime Function: On Windows: 1) Checks that the currently used core.getTime() implementation gives duration results consistent with directly using the Python high resolution timer. 2) Checks that the time between core.getTime calls is never negative. 3) Tests the overhead in the core.getTime function call 4) Tries to assess the resolution of the underlying core.getTime() time base and the Python high resolution timer. 5) Tests MonotonicClock, Clock, CountdownTimer, wait @author: Sol ----- Jan 2014, Jeremy Gray: - Coverage of .quit, .shellCall, and increased coverage of StaticPeriod() """ import time import sys import numpy as np import gc import pytest import psychopy import psychopy.logging as logging from psychopy.tests.utils import RUNNING_IN_VM from psychopy.visual import Window from psychopy.core import (getTime, MonotonicClock, Clock, CountdownTimer, wait, StaticPeriod, shellCall) from psychopy.clock import monotonicClock from psychopy.tools import systemtools def test_EmptyFunction(): pass PRINT_TEST_RESULTS = False def printf(*args): if PRINT_TEST_RESULTS: for a in args: sys.stdout(a) print('') py_time = None py_timer_name = None py_time=time.time py_timer_name = 'time.time' def printExceptionDetails(): import traceback,pprint exc_type, exc_value, exc_traceback = sys.exc_info() pprint.pprint(exc_type, indent=1, width=80, depth=None) pprint.pprint(exc_value, indent=1, width=80, depth=None) pprint.pprint(traceback.format_tb(exc_traceback), indent=1, width=80, depth=None) @pytest.mark.slow def test_DelayDurationAccuracy(sample_size=100): # test with sample_size randomly selected durations between 0.05 and 1.0 msec durations=np.zeros((3,sample_size)) durations[0,:] = (np.random.randint(50, 1001, sample_size) * 0.001) for t in range(sample_size): cdur=durations[0][t] start_times=py_time(),getTime() stime=start_times[0] while py_time()-stime<cdur-0.02: end_times=py_time(),getTime() while py_time()-stime<cdur: end_times=py_time(),getTime() durations[1][t]=end_times[0]-start_times[0] durations[2][t]=end_times[1]-start_times[1] clockDurVsExpected=durations[1]-durations[0] clockDurVsQpc=durations[1]-durations[2] printf("## %s vs. psychopy getTime() Duration Difference Test:\n"%(py_timer_name)) printf(">> Actual Vs. Expected %s Duration Diffs (msec.usec):"%(py_timer_name)) printf("\tmin:\t\t%.3f"%(clockDurVsExpected.min()*1000.0)) printf("\tmax:\t\t%.3f"%(clockDurVsExpected.max()*1000.0)) printf("\tmean:\t\t%.3f"%(clockDurVsExpected.mean()*1000.0)) printf("\tstd:\t\t%.3f"%(clockDurVsExpected.std()*1000.0)) printf(">> %s vs getTime Duration Diffs (msec.usec):"%(py_timer_name)) printf("\tmin:\t\t%.3f"%(clockDurVsQpc.min()*1000.0)) printf("\tmax:\t\t%.3f"%(clockDurVsQpc.max()*1000.0)) printf("\tmean:\t\t%.3f"%(clockDurVsQpc.mean()*1000.0)) printf("\tstd:\t\t%.3f"%(clockDurVsQpc.std()*1000.0)) # check that the differences between time.clock and psychopy.getTime # (which is using Win QPC) are within these limits: # # fabs(min) or max diff: < 50 usec # mean diff: < 10 usec # std of diff: < 5 usec try: assert np.fabs(clockDurVsQpc.min())<0.00005 assert clockDurVsQpc.max()<0.00005 assert np.fabs(clockDurVsQpc.mean())<0.00001 assert clockDurVsQpc.std()<0.000005 printf("\nDuration Difference Test: PASSED") except Exception: printf("\nDuration Difference Test: FAILED") printf("-------------------------------------\n") @pytest.mark.slow def test_TimebaseQuality(sample_size=1000): gc.disable() callTimes=np.zeros((5,sample_size)) timer_clock_jumpbacks=0 core_getTime_jumpbacks=0 for t in range(sample_size): s=py_time() e=py_time() callTimes[0][t]=e-s if e<s: timer_clock_jumpbacks+=1 s=getTime() e=getTime() callTimes[1][t]=e-s if e<s: core_getTime_jumpbacks+=1 s=py_time() x=test_EmptyFunction() e=py_time() callTimes[2][t]=e-s s=py_time() x=py_time() e=py_time() callTimes[3][t]=e-s s=py_time() x=getTime() e=py_time() callTimes[4][t]=e-s gc.enable() printf("## Timebase 'Quality' Tests :\n") test_headers=(">> %s Resolution (msec.usec):"%(py_timer_name), ">> core.getTime() Resolution (msec.usec):", ">> Empty function (msec.usec):", ">> %s (msec.usec):"%(py_timer_name), ">> core.getTime() (msec.usec):") for i,header in enumerate(test_headers): printf(header) printf("\tmin:\t\t%.9f"%(callTimes[i].min()*1000.0)) printf("\tmax:\t\t%.6f"%(callTimes[i].max()*1000.0)) printf("\tmean:\t\t%.6f"%(callTimes[i].mean()*1000.0)) printf("\tstd:\t\t%.6f"%(callTimes[i].std()*1000.0)) printf(">> %s jumpbacks: "%(py_timer_name),timer_clock_jumpbacks) printf(">> core.getTime() jumpbacks: ",core_getTime_jumpbacks) # Test that these conditions are true: # - Effective Resolution (mean inter timer call duration) of timer is < 10 usec # - Maximum inter timer call duration is < 100 usec # - no negative durations in timer call durations try: assert (callTimes[0].mean()*1000.0)<0.01 assert (callTimes[0].max()*1000.0)<0.1 assert timer_clock_jumpbacks==0 printf("\n%s Call Time / Resolution Test: PASSED"%(py_timer_name)) except Exception: printf("\n%s Call Time / Resolution Test: FAILED"%(py_timer_name)) try: assert (callTimes[1].mean()*1000.0)<0.01 assert (callTimes[1].max()*1000.0)<0.1 assert core_getTime_jumpbacks==0 printf("\ncore.getTime() Call Time / Resolution Test: PASSED") except Exception: printf("\ncore.getTime() Call Time / Resolution Test: FAILED") printf("-------------------------------------\n") def test_MonotonicClock(): try: mc = MonotonicClock() t1=mc.getTime() time.sleep(1.0) t2=mc.getTime() startTime=mc.getLastResetTime() assert t2>t1 assert t2-t1 > 0.95 assert t2-t1 < 1.05 assert startTime > 0 # Test things that 'should fail': try: x=mc.timeAtLastReset assert 1=="MonotonicClock should not have an attribute called 'timeAtLastReset'." except Exception: pass try: x=mc.reset() assert 1=="MonotonicClock should not have a method 'reset()'." except Exception: pass try: x=mc.add() assert 1=="MonotonicClock should not have a method 'add()'." except Exception: pass printf(">> MonotonicClock Test: PASSED") except Exception: printf(">> MonotonicClock Test: FAILED") printExceptionDetails() printf("-------------------------------------\n") def test_Clock(): try: c = Clock() t1=c.getTime() time.sleep(1.0) t2=c.getTime() startTime=c.getLastResetTime() assert t2>t1 assert t2-t1 > 0.95 assert t2-t1 < 1.05 assert startTime > 0 c.reset() t=c.getTime() assert t < 0.01 c.reset(10) t=c.getTime() assert t > -10.0 assert t < -9.9 t1=c.getTime() c.add(50) t2=c.getTime() assert t2-t1 > -50.0 assert t2-t1 < -49.9 printf(">> Clock Test: PASSED") except Exception: printf(">> Clock Test: FAILED") printExceptionDetails() printf("-------------------------------------\n") def test_CountdownTimer(): try: cdt = CountdownTimer(5.0) assert cdt.getTime() <= 5.0 assert cdt.getTime() >= 4.75 time.sleep(cdt.getTime()) assert np.fabs(cdt.getTime()) < 0.1 printf(">> CountdownTimer Test: PASSED") except Exception: printf(">> CountdownTimer Test: FAILED") printExceptionDetails() printf("-------------------------------------\n") def test_Wait(duration=1.55): try: t1=getTime() wait(duration) t2=getTime() # Check that the actual duration of the wait was close to the requested delay. # # Note that I have had to set this to a relatively high value of # 50 msec because on my Win7, i7, 16GB machine I would get delta's of up to # 35 msec when I was testing this. # # This is 'way high', and I think is because the current wait() # implementation polls pyglet for events during the CPUhog period. # IMO, during the hog period, which should only need to be only 1 - 2 msec # , not the 200 msec default now, nothing should be done but tight looping # waiting for the wait() to expire. This is what I do in ioHub and on this same # PC I get actual vs. requested duration delta's of < 100 usec consistently. # # I have not changed the wait in psychopy until feedback is given, as I # may be missing a reason why the current wait() implementation is required. # assert np.fabs((t2-t1)-duration) < 0.05 printf(">> core.wait(%.2f) Test: PASSED"%(duration)) except Exception: printf(">> core.wait(%.2f) Test: FAILED. Actual Duration was %.3f"%(duration,(t2-t1))) printExceptionDetails() printf("-------------------------------------\n") def test_LoggingDefaultClock(): try: t1 = logging.defaultClock.getTime() t2 = getTime() t3 = monotonicClock.getTime() assert np.fabs(t1-t2) < 0.02 assert np.fabs(t1-t3) < 0.02 assert np.fabs(t3-t2) < 0.02 assert logging.defaultClock.getLastResetTime() == monotonicClock.getLastResetTime() printf(">> logging.defaultClock Test: PASSED") except Exception: printf(">> logging.defaultClock Test: FAILED. ") printExceptionDetails() printf("-------------------------------------\n") @pytest.mark.staticperiod def test_StaticPeriod(): # this test is speed sensitive, so skip under VM if RUNNING_IN_VM: pytest.skip() static = StaticPeriod() static.start(0.1) wait(0.05) assert static.complete()==1 static.start(0.1) wait(0.11) assert static.complete()==0 win = Window(autoLog=False) static = StaticPeriod(screenHz=60, win=win) static.start(.002) assert win.recordFrameIntervals is False static.complete() assert static._winWasRecordingIntervals == win.recordFrameIntervals win.close() # Test if screenHz parameter is respected, i.e., if after completion of the # StaticPeriod, 1/screenHz seconds are still remaining, so the period will # complete after the next flip. refresh_rate = 100.0 period_duration = 0.1 timer = CountdownTimer() win = Window(autoLog=False) static = StaticPeriod(screenHz=refresh_rate, win=win) static.start(period_duration) timer.reset(period_duration ) static.complete() if systemtools.isVM_CI(): tolerance = 0.01 # without a proper screen timing might not eb sub-ms else: tolerance = 0.001 assert np.allclose(timer.getTime(), 1.0/refresh_rate, atol=tolerance) win.close() @pytest.mark.quit def test_quit(): # to-do: make some active threads with pytest.raises(SystemExit): psychopy.core.quit() @pytest.mark.shellCall class Test_shellCall(): def setup_class(self): if sys.platform == 'win32': self.cmd = 'findstr' else: self.cmd = 'grep' self.msg = 'echo' def test_invalid_argument(self): with pytest.raises(TypeError): shellCall(12345) def test_stdin(self): echo = shellCall([self.cmd, self.msg], stdin=self.msg) assert echo == self.msg echo = shellCall(self.cmd + ' ' + self.msg, stdin=self.msg) assert echo == self.msg def test_stderr(self): _, se = shellCall([self.cmd, self.msg], stderr=True) assert se == '' _, se = shellCall(self.cmd + ' ' + self.msg, stderr=True) assert se == '' def test_stdin_and_stderr(self): echo, se = shellCall([self.cmd, self.msg], stdin='echo', stderr=True) assert echo == self.msg assert se == '' echo, se = shellCall(self.cmd + ' ' + self.msg, stdin='echo', stderr=True) assert echo == self.msg assert se == '' def test_encoding(self): shellCall([self.cmd, self.msg], stdin=self.msg, encoding='utf-8') if __name__ == '__main__': test_MonotonicClock() test_Clock() test_CountdownTimer() test_Wait() test_LoggingDefaultClock() test_TimebaseQuality() test_StaticPeriod() printf("\n** Next Test will Take ~ 1 minute...**\n") test_DelayDurationAccuracy()
13,416
Python
.py
350
31.028571
118
0.612958
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,566
test_clock.py
psychopy_psychopy/psychopy/tests/test_misc/test_clock.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from psychopy.clock import wait, StaticPeriod, CountdownTimer from psychopy.visual import Window from psychopy.tools import systemtools from psychopy.tests import skip_under_vm def test_StaticPeriod_finish_on_time(): """Test successful completion (finishing "on time") """ static = StaticPeriod() static.start(0.1) wait(0.01) assert static.complete() == 1 def test_StaticPeriod_overrun(): """Test unsuccessful completion (period "overran") """ static = StaticPeriod() static.start(0.1) wait(0.11) assert static.complete() == 0 def test_StaticPeriod_recordFrameIntervals(): win = Window(autoLog=False) static = StaticPeriod(screenHz=60, win=win) static.start(.002) assert win.recordFrameIntervals is False static.complete() assert static._winWasRecordingIntervals == win.recordFrameIntervals win.close() @skip_under_vm def test_StaticPeriod_screenHz(): """Test if screenHz parameter is respected, i.e., if after completion of the StaticPeriod, 1/screenHz seconds are still remaining, so the period will complete after the next flip. """ refresh_rate = 100.0 period_duration = 0.1 timer = CountdownTimer() win = Window(autoLog=False) static = StaticPeriod(screenHz=refresh_rate, win=win) static.start(period_duration) timer.reset(period_duration ) static.complete() if systemtools.isVM_CI(): tolerance = 0.01 # without a proper screen timing might not be sub-ms else: tolerance = 0.001 assert np.allclose(timer.getTime(), 1.0/refresh_rate, atol=tolerance) win.close()
1,746
Python
.py
51
29.039216
80
0.699346
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,567
test_locale.py
psychopy_psychopy/psychopy/tests/test_misc/test_locale.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest import locale from psychopy import localization from psychopy.localization import _translate welcome = u'Welcome to PsychoPy3!' trans = {'en': welcome, 'ja': u'PsychoPy3へようこそ!' } ### needs rewriting since localization.init() no longer sets the locale @pytest.mark.localization class XXXTestLocalization(): def setup_class(self): self.orig = localization.languageID def teardown_class(self): pass #localization.getID(self.orig) def test_set(self): lang = localization.getID('En_US') assert lang == 'en' for lang in ['En_US', 'Ja_JP', 'ja_JP']: setlang = localization.getID(lang) out = _translate(welcome) assert setlang == lang.lower()[:2] assert out == trans[setlang] #lo = 'en' #localization.init(lo) #for lang in ['', None, [], 'junk']: # setlang = localization.init(lang) # assert setlang == lo
1,042
Python
.py
30
27.8
71
0.621976
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,568
memory_usage.py
psychopy_psychopy/psychopy/tests/test_misc/memory_usage.py
from psychopy import visual, event, info import pytest import numpy as np import shutil, os from tempfile import mkdtemp from psychopy.tests import utils # Testing for memory leaks in PsychoPy classes (experiment run-time, not Builder, Coder, etc) # The tests are too unstable to include in travis-ci at this point. # command-line usage: # py.testw tests/test_misc/memory_usage.py # Define the "acceptable" leakage severity; some gc vagaries are possible. THRESHOLD = 0.5 win = visual.Window(size=(200,200), allowStencil=True) def leakage(Cls, *args, **kwargs): """make up to 100 instances of Cls(*args, **kwargs), return the difference in memory used by this python process (in M) as a severity measure, approx = 100 * mem leak per instance in M """ mem = [] for i in range(100): Cls(*args, **kwargs) # anonymous instance, gets gc'd each iteration mem.append(info.getMemoryUsage()) # don't keep going if we're leaking: if mem[i] - mem[0] > THRESHOLD: break proportion = i / 99. return round((mem[i] - mem[0]) / proportion, 1) @pytest.mark.needs_sound @pytest.mark.memory class TestMemorySound(): @classmethod def setup_class(self): global sound, pyo from psychopy import sound import pyo self.tmp = mkdtemp(prefix='psychopy-tests-memory-usage') @classmethod def teardown_class(self): if hasattr(self, 'tmp'): shutil.rmtree(self.tmp, ignore_errors=True) def test_soundpyo_array(self): """anything using a numpy.array uses pyo.DataTable """ if pyo.getVersion() < (0, 7, 7): pytest.xfail() # pyo leak fixed Oct 2015 for stim in [440, np.zeros(88200)]: # np.zeros(8820000) passes, slow assert leakage(sound.SoundPyo, stim, secs=2) < THRESHOLD, 'stim = ' + str(stim) def test_soundpyo_file(self): """files are handled by pyo.SndFile """ if pyo.getVersion() < (0, 7, 7): pytest.xfail() from scipy.io import wavfile tmp = os.path.join(self.tmp, 'zeros.wav') wavfile.write(tmp, 44100, np.zeros(88200)) assert leakage(sound.SoundPyo, tmp) < THRESHOLD @pytest.mark.needs_sound @pytest.mark.memory class TestMemoryMovie(): @classmethod def setup_class(self): self.mov = os.path.join(utils.TESTS_DATA_PATH, 'testMovie.mp4') @classmethod def teardown_class(self): if hasattr(self, 'tmp'): shutil.rmtree(self.tmp, ignore_errors=True) def test_movie3_leakage(self): assert leakage(visual.MovieStim3, win, self.mov) < THRESHOLD @pytest.mark.skipif('True') def test_movie_leakage(self): assert leakage(visual.MovieStim, win, self.mov) < THRESHOLD @pytest.mark.skipif('True') def test_movie2_leakage(self): assert leakage(visual.MovieStim2, win, self.mov) < THRESHOLD @pytest.mark.memory class TestMemory(): @classmethod def setup_class(self): self.imgs = [os.path.join(utils.TESTS_DATA_PATH, 'testimage.jpg'), # smaller os.path.join(utils.TESTS_DATA_PATH, 'greyscale.jpg')] # larger @classmethod def teardown_class(self): if hasattr(self, 'tmp'): shutil.rmtree(self.tmp, ignore_errors=True) def test_Mouse(self): assert leakage(event.Mouse, win=win) < THRESHOLD def test_VisualStim(self): """Visual stim that typically do not leak can all be tested together """ cleanStim = ['ShapeStim', 'Rect', 'Circle', 'Polygon', 'Line', 'CustomMouse', 'Aperture'] for StimName in cleanStim: Stim = eval('visual.' + StimName) assert leakage(Stim, win) < THRESHOLD, StimName def test_ShapeStim(self): v = [(-.2,-.05), (-.2,.05), (.2,.05), (.2,.15), (.35,0), (.2,-.15), (.2,-.05)] assert leakage(visual.ShapeStim, win, vertices=v) < THRESHOLD assert leakage(visual.ShapeStim, win, vertices=v * 100) < THRESHOLD @pytest.mark.xfail def test_Window(self): msg = 'leakage probably not a problem for typical users with 1 Window() instance' assert leakage(visual.Window, size=(100, 100)) < THRESHOLD, msg assert leakage(visual.Window, size=(2000, 2000)) < THRESHOLD, msg def test_TextStim(self): msg = "Note: some TextStim leakage is pyglet's fault" for txt in ['a', 'a'*1000]: assert leakage(visual.TextStim, win, txt) < THRESHOLD, msg def test_RatingScale(self): msg = "RatingScale will probably leak if TextStim does" # 'hover' has few visual items (no text, line, marker, accept box) for kwargs in [{'marker': 'hover', 'choices': [1,2]}, {}]: assert leakage(visual.RatingScale, win, **kwargs) < THRESHOLD, msg def test_BufferImageStim(self): msg = "Note: the size of the window and the rect to capture affects leak severity" for rect in [(-.1,.1,.1,-.1), (-1,1,1,-1)]: assert leakage(visual.BufferImageStim, win, rect=rect) < THRESHOLD, msg def test_ImageStim(self): msg = "Note: the image size affects leak severity" for img in self.imgs: assert leakage(visual.ImageStim, win, img) < THRESHOLD, msg def test_SimpleImageStim(self): for img in self.imgs: assert leakage(visual.SimpleImageStim, win, img) < THRESHOLD def test_GratingStim(self): assert leakage(visual.GratingStim, win) < THRESHOLD def test_DotStim(self): assert leakage(visual.DotStim, win, nDots=2000) < THRESHOLD def test_RadialStim(self): for r in [4, 16]: assert leakage(visual.RadialStim, win, radialCycles=r, angularCycles=r) < THRESHOLD def test_ElementArrayStim(self): for n in [100, 1000]: assert leakage(visual.ElementArrayStim, win, nElements=n) < THRESHOLD
5,930
Python
.py
132
37.674242
97
0.650711
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,569
test_info.py
psychopy_psychopy/psychopy/tests/test_misc/test_info.py
# -*- coding: utf-8 -*- from psychopy import info, visual import pytest # py.test -k info --cov-report term-missing --cov info.py @pytest.mark.info class TestInfo(): @classmethod def setup_class(self): self.win = visual.Window(size=(100,100), autoLog=False) def teardown_method(self): self.win.close() def test_info(self): info.RunTimeInfo(win=self.win, userProcsDetailed=True, verbose=True)
437
Python
.py
13
29.153846
76
0.694511
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,570
test_alerttools.py
psychopy_psychopy/psychopy/tests/test_alerts/test_alerttools.py
import sys from psychopy.alerts import addAlertHandler, alerttools from psychopy.alerts._errorHandler import _BaseErrorHandler from psychopy.experiment import getAllComponents, Experiment class TestAlertTools(): """A class for testing the alerttools module""" def setup_method(self): # Set ErrorHandler self.error = _BaseErrorHandler() addAlertHandler(self.error) # Create experiment, trial, flow and test components self.exp = Experiment() trial = self.exp.addRoutine('trial') self.exp.flow.addRoutine(trial, 0) allComp = getAllComponents(fetchIcons=False) # Polygon self.polygonComp = allComp["PolygonComponent"](parentName='trial', exp=self.exp) trial.addComponent(self.polygonComp) self.polygonComp.params['units'].val = 'height' self.polygonComp.params['startType'].val = "time (s)" self.polygonComp.params['stopType'].val = "time (s)" # Code component self.codeComp = allComp["CodeComponent"](parentName='trial', exp=self.exp) self.codeComp.params['Begin Experiment'].val = "(\n" self.codeComp.params['Begin JS Experiment'].val = "{\n" def test_2115_X_too_large(self): self.polygonComp.params['size'].val = [4, .5] self.exp.integrityCheck() assert ('Your stimulus size exceeds the X dimension of your window.' in self.error.alerts[0].msg) def test_2115_Y_too_large(self): self.polygonComp.params['size'].val = [.5, 4] self.exp.integrityCheck() assert ('Your stimulus size exceeds the Y dimension of your window.' in self.error.alerts[0].msg) def test_size_too_small_x(self): self.polygonComp.params['size'].val = [.0000001, .05] self.exp.integrityCheck() assert ('Your stimulus size is smaller than 1 pixel (X dimension)' in self.error.alerts[0].msg) def test_size_too_small_y(self): self.polygonComp.params['size'].val = [.05, .0000001] self.exp.integrityCheck() assert ('Your stimulus size is smaller than 1 pixel (Y dimension)' in self.error.alerts[0].msg) def test_position_x_dimension(self): self.polygonComp.params['pos'].val = [4, .5] self.exp.integrityCheck() assert ('Your stimulus position exceeds the X dimension' in self.error.alerts[0].msg) def test_position_y_dimension(self): self.polygonComp.params['pos'].val = [.5, 4] self.exp.integrityCheck() assert ('Your stimulus position exceeds the Y dimension' in self.error.alerts[0].msg) def test_variable_fail(self): self.polygonComp.params['pos'].val = '$pos' self.polygonComp.params['size'].val = '$size' self.exp.integrityCheck() assert (len(self.error.alerts) == 0) def test_timing(self): self.polygonComp.params['startVal'].val = 12 self.polygonComp.params['stopVal'].val = 10 self.exp.integrityCheck() assert ('Your stimulus start time exceeds the stop time' in self.error.alerts[0].msg) def test_disabled(self): self.polygonComp.params['disabled'].val = True alerttools.testDisabled(self.polygonComp) assert (f"The component {self.polygonComp.params['name']} is currently disabled" in self.error.alerts[0].msg) def test_achievable_visual_stim_onset(self): self.polygonComp.params['startVal'].val = .001 self.exp.integrityCheck() assert ('Your stimulus start time of 0.001 is less than a screen refresh for a 60Hz monitor' in self.error.alerts[0].msg) def test_achievable_visual_stim_offset(self): self.polygonComp.params['stopVal'].val = .001 self.polygonComp.params['stopType'].val = "duration (s)" self.exp.integrityCheck() assert ('Your stimulus stop time of 0.001 is less than a screen refresh for a 60Hz monitor' in self.error.alerts[0].msg) def test_valid_visual_timing(self): self.polygonComp.params['startVal'].val = 1.01 self.polygonComp.params['stopVal'].val = 2.01 self.exp.integrityCheck() assert ('start time of 1.01 seconds cannot be accurately presented' in self.error.alerts[0].msg) def test_4115_frames_as_int(self): self.polygonComp.params['startVal'].val = .5 self.polygonComp.params['startType'].val = "duration (frames)" self.exp.integrityCheck() assert ("Your stimulus start type \'duration (frames)\' must be expressed as a whole number" in self.error.alerts[0].msg) def test_python_syntax(self): alerttools.checkPythonSyntax(self.codeComp, 'Begin Experiment') assert ("Python Syntax Error in 'Begin Experiment'" in self.error.alerts[0].msg) def test_javascript_syntax(self): alerttools.checkJavaScriptSyntax(self.codeComp, 'Begin JS Experiment') assert ("JavaScript Syntax Error in 'Begin JS Experiment'" in self.error.alerts[0].msg) def test_validDuration(): testVals = [ {'t': 0.5, 'hz' : 60, 'ans': True}, {'t': 0.1, 'hz': 60, 'ans': True}, {'t': 0.01667, 'hz': 60, 'ans': True}, # 1 frame-ish {'t': 0.016, 'hz': 60, 'ans': False}, # too sloppy {'t': 0.01, 'hz': 60, 'ans': False}, {'t': 0.01, 'hz': 100, 'ans': True}, {'t': 0.009, 'hz': 100, 'ans': False}, # 0.9 frames {'t': 0.012, 'hz': 100, 'ans': False}, # 1.2 frames ] for this in testVals: assert alerttools.validDuration(this['t'], this['hz']) == this['ans'] if __name__ == "__main__": tester = TestAlertTools() tester.setup_method() tester.test_sizing_x_dimension()
5,751
Python
.py
107
45.074766
129
0.646022
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,571
test_alerts.py
psychopy_psychopy/psychopy/tests/test_alerts/test_alerts.py
import sys from psychopy.alerts import _alerts, validateCatalogue def test_catalogue(): valid, missing = validateCatalogue(dev=False) assert valid, f"Missing alerts: {missing}" class TestAlertsModule(): """A class for testing the alerts module""" def teardown_method(self): sys.stderr = sys.__stderr__ def test_alert_catalog(self): """Test the alerts catalog has been created and loaded correctly""" assert (isinstance(_alerts.catalog, _alerts.AlertCatalog)) assert (9999 in _alerts.catalog.alert.keys()) def test_alertentry(self): """Test creation of AlertEntry object""" newAlert = _alerts.AlertEntry(9999, self) assert (isinstance(newAlert, _alerts.AlertEntry)) assert (newAlert.msg == "TEST_MSG {testString}") def test_alertentry_stringformatting(self): """Test AlertEntry string formatting""" testString = {"testString": "TEST ALERT"} newAlert = _alerts.AlertEntry(9999, self, strFields=testString) assert (newAlert.msg == "TEST_MSG TEST ALERT") def test_alert_written_to_console(self, capsys): """Test alerts are written to console when no errorhandler exists""" _alerts.alert(9999, self, strFields={"testString": "TEST ALERT"}) out, err = capsys.readouterr() # Capture stdout stream and test assert ("TEST_MSG TEST ALERT" in err)
1,407
Python
.py
28
43.214286
76
0.684672
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,572
exports.py
psychopy_psychopy/psychopy/experiment/exports.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). """Experiment classes: Experiment, Flow, Routine, Param, Loop*, *Handlers, and NameSpace The code that writes out a *_lastrun.py experiment file is (in order): experiment.Experiment.writeScript() - starts things off, calls other parts settings.SettingsComponent.writeStartCode() experiment.Flow.writeBody() which will call the .writeBody() methods from each component settings.SettingsComponent.writeEndCode() """ import io import keyword import re import psychopy from psychopy import constants from psychopy.localization import _translate from .components.settings import _numpyImports, _numpyRandomImports from .utils import nonalphanumeric_re, valid_var_re # predefine some regex's; deepcopy complains if do in NameSpace.__init__() class IndentingBuffer(io.StringIO): def __init__(self, target='PsychoPy', initial_value='', newline='\n'): io.StringIO.__init__(self, initial_value, newline) self.oneIndent = " " self.indentLevel = 0 self._writtenOnce = [] self.target = target # useful to keep track of what language is written here def writeIndented(self, text): """Write to the StringIO buffer, but add the current indent. Use write() if you don't want the indent. To test if the prev character was a newline use:: self.getvalue()[-1]=='\n' """ for line in text.splitlines(keepends=True): self.write(self.oneIndent * self.indentLevel + line) def writeIndentedLines(self, text): """As writeIndented(text) except that each line in text gets the indent level rather than the first line only. """ if not text.endswith("\n"): text += "\n" self.writeIndented(text) def writeOnceIndentedLines(self, text): """Add code to the experiment that is only run exactly once, (typically this is used to write the writeOnceInit sections after all `import`s were done but before Window creation). Parameters ---------- text : str The code to run. May include newline characters to write several lines of code at once. Notes ----- For running an `import`, use meth:~`Experiment.requireImport` or :meth:~`Experiment.requirePsychopyLibs` instead. See also -------- :meth:~`Experiment.requireImport`, :meth:~`Experiment.requirePsychopyLibs` """ if text not in self._writtenOnce: self.writeIndentedLines(text) self._writtenOnce.append(text) def setIndentLevel(self, newLevel, relative=False): """Change the indent level for the buffer to a new value. Set relative to True to increment or decrement the current value. """ if relative: self.indentLevel += newLevel else: self.indentLevel = newLevel def write(self, text): io.StringIO.write(self, "{}".format(text)) # noinspection PyUnresolvedReferences class NameSpace: """class for managing variable names in builder-constructed experiments. The aim is to help detect and avoid name-space collisions from user-entered variable names. Track four groups of variables: numpy = part of numpy or numpy.random psychopy = part of psychopy, such as event or data; include os here builder = used internally by the builder when constructing an expt user = used 'externally' by a user when programming an experiment Some vars, like core, are part of both psychopy and numpy, so the order of operations can matter Notes for development: are these all of the ways to get into the namespace? - import statements at top of file: numpy, psychopy, os, etc - a handful of things that always spring up automatically, like t and win - routines: user-entered var name = routine['name'].val, plus sundry helper vars, like theseKeys - flow elements: user-entered = flowElement['name'].val - routine & flow from either GUI or .psyexp file - each routine and flow element potentially has a ._clockName, loops have thisName, albeit thisNam (missing end character) - column headers in condition files - abbreviating parameter names (e.g. rgb=thisTrial.rgb) :Author: 2011 Jeremy Gray """ def __init__(self, exp): """Set-up an experiment's namespace: reserved words and user space """ super(NameSpace, self).__init__() self.exp = exp # deepcopy fails if you pre-compile regular expressions and stash here self.numpy = _numpyImports + _numpyRandomImports + ['np'] # noinspection PyUnresolvedReferences self.keywords = keyword.kwlist + dir(__builtins__) + ['self'] # these are based on a partial test, known to be incomplete: self.psychopy = psychopy.__all__ + ['psychopy', 'os'] self.constants = dir(constants) self.builder = ['KeyResponse', 'keyboard', 'buttons', 'continueRoutine', 'expInfo', 'expName', 'thisExp', 'filename', 'logFile', 'paramName', 't', 'frameN', 'currentLoop', 'dlg', '_thisDir', 'endExpNow', 'globalClock', 'routineTimer', 'frameDur', 'theseKeys', 'win', 'x', 'y', 'level', 'component', 'thisComponent'] # user-entered, from Builder dialog or conditions file: self.user = [] self.nonUserBuilder = self.numpy + self.keywords + self.psychopy def __str__(self, numpy_count_only=True): varibs = self.user + self.builder + self.psychopy if numpy_count_only: return "%s + [%d numpy]" % (str(varibs), len(self.numpy)) return str(varibs + self.numpy) @property def all(self): return ( self.builder + self.constants + self.keywords + self.nonUserBuilder + self.numpy + self.psychopy + self.user ) def getCategories(self, name): """ Get list of categories in which a given name is found. Parameters ---------- name : str Name to look for """ # Define possible categories categories = ( "builder", "constants", "keywords", "nonUserBuilder", "numpy", "psychopy", "user" ) # Check for name in each category found = [] for cat in categories: if name in getattr(self, cat): found.append(cat) return found def getDerived(self, basename): """ buggy idea: return variations on name, based on its type, to flag name that will come to exist at run-time; more specific than is_possibly-derivable() if basename is a routine, return continueBasename and basenameClock, if basename is a loop, return makeLoopIndex(name) """ derived_names = [] for flowElement in self.exp.flow: if flowElement.getType() in ('LoopInitiator', 'LoopTerminator'): flowElement = flowElement.loop # we want the loop itself # basename can be <type 'instance'> derived_names += [self.makeLoopIndex(basename)] if (basename == str(flowElement.params['name']) and basename + 'Clock' not in derived_names): derived_names += [basename + 'Clock', 'continue' + basename.capitalize()] # other derived_names? # return derived_names def getCollisions(self): """return None, or a list of names in .user that are also in one of the other spaces """ standard = set(self.builder + self.psychopy + self.numpy) duplicates = list(set(self.user).intersection(standard)) su = sorted(self.user) duplicates += [var for i, var in enumerate(su) if i < len(su) - 1 and su[i + 1] == var] return duplicates or None def isValid(self, name): """var-name compatible? return True if string name is alphanumeric + underscore only, with non-digit first """ return bool(valid_var_re.match(name)) def isPossiblyDerivable(self, name): """catch all possible derived-names, regardless of whether currently """ derivable = (name.startswith('this') or name.startswith('these') or name.startswith('continue') or name.endswith('Clock') or name.lower().find('component') > -1) if derivable: return (" Avoid `this`, `these`, `continue`, `Clock`," " or `component` in name") return None def exists(self, name): """returns None, or a message indicating where the name is in use. cannot guarantee that a name will be conflict-free. does not check whether the string is a valid variable name. >>> exists('t') Builder variable """ try: name = str(name) # convert from unicode if possible except Exception: pass # check getDerived: # check in this order: return unlocalized value if name in self.user: return "one of your Components, Routines, or condition parameters" if name in self.builder: return "Builder variable" if name in self.psychopy: return "Psychopy module" if name in self.numpy: return "numpy function" if name in self.keywords: return "python keyword" return # None, meaning does not exist already def add(self, name, sublist='default'): """add name to namespace by appending a name or list of names to a sublist, eg, self.user """ if name is None: return if sublist == 'default': sublist = self.user if not isinstance(name, list): sublist.append(name) else: sublist += name def remove(self, name, sublist='default'): """remove name from the specified sublist (and hence from the name-space), eg, self.user """ if name is None: return if sublist == 'default': sublist = self.user if not isinstance(name, list): name = [name] for n in list(name): if n in sublist: del sublist[sublist.index(n)] def rename(self, name, newName, sublist='default'): if name is None: return if sublist == 'default': sublist = self.user if not isinstance(name, list): name = [name] for n in list(name): if n in sublist: sublist[sublist.index(n)] = newName def makeValid(self, name, prefix='var'): """given a string, return a valid and unique variable name. replace bad characters with underscore, add an integer suffix until its unique >>> makeValid('Z Z Z') 'Z_Z_Z' >>> makeValid('a') 'a' >>> makeValid('a') 'a_2' >>> makeValid('123') 'var_123' """ # make it legal: try: # convert from unicode, flag as uni if can't convert name = str(name) except Exception: prefix = 'uni' if not name: name = prefix + '_1' if name[0].isdigit(): name = prefix + '_' + name # replace all bad chars with _ name = nonalphanumeric_re.sub('_', name) # try to make it unique; success depends on accuracy of self.exists(): i = 2 # skip _1: user can rename the first one to be _1 if desired # maybe it already has _\d+? if so, increment from there if self.exists(name) and '_' in name: basename, count = name.rsplit('_', 1) try: i = int(count) + 1 name = basename except Exception: pass nameStem = name + '_' while self.exists(name): # brute-force a unique name name = nameStem + str(i) i += 1 return name def makeLoopIndex(self, name): """return a valid, readable loop-index name: 'this' + (plural->singular).capitalize() [+ (_\\d+)] """ try: newName = str(name) except Exception: newName = name prefix = 'this' irregular = {'stimuli': 'stimulus', 'mice': 'mouse', 'people': 'person'} for plural, singular in list(irregular.items()): nn = re.compile(plural, re.IGNORECASE) newName = nn.sub(singular, newName) if newName.endswith('s') and newName.lower() not in list(irregular.values()): newName = newName[:-1] # trim last 's' else: # might end in s_2, so delete that s; leave S match = re.match(r"^(.*)s(_\d+)$", newName) if match: newName = match.group(1) + match.group(2) # retain CamelCase: newName = prefix + newName[0].capitalize() + newName[1:] newName = self.makeValid(newName) return newName
13,876
Python
.py
337
31.175074
85
0.588449
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,573
plugins.py
psychopy_psychopy/psychopy/experiment/plugins.py
class PluginDevicesMixin: """ Mixin for Components and Routines which adds behaviour to get parameters and values from plugins and use them to create different devices for different plugin backends. """ def __init_subclass__(cls): # list of backends for this component - each should be a subclass of DeviceBackend cls.backends = [] def loadBackends(self): # add params from backends for backend in self.backends: # get params using backend's method params, order = backend.getParams(self) # get reference to package plugin = None if hasattr(backend, "__module__") and backend.__module__: pkg = backend.__module__.split(".")[0] if pkg != "psychopy": plugin = pkg # add order self.order.extend(order) # add any params for key, param in params.items(): if key in self.params: # if this param already exists (i.e. from saved data), get the saved val param.val = self.params[key].val param.updates = self.params[key].updates # add param self.params[key] = param # store plugin reference self.params[key].plugin = plugin # add dependencies so that backend params are only shown for this backend for name in params: self.depends.append( { "dependsOn": "deviceBackend", # if... "condition": f"== '{backend.key}'", # meets... "param": name, # then... "true": "show", # should... "false": "hide", # otherwise... } ) # add requirements backend.addRequirements(self) def getBackendKeys(self): keys = [] for backend in self.backends: keys.append(backend.key) return keys def getBackendLabels(self): labels = [] for backend in self.backends: labels.append(backend.label) return labels def writeDeviceCode(self, buff): # write init code from backend for backend in self.backends: if backend.key == self.params['deviceBackend']: backend.writeDeviceCode(self, buff) class DeviceBackend: # which component is this backend for? component = PluginDevicesMixin # what value should Builder use for this backend? key = "" # what label should be displayed by Builder for this backend? label = "" # values to append to the component's deviceClasses array deviceClasses = [] def __init_subclass__(cls): # add class to list of backends for ButtonBoxComponent cls.component.backends = cls.component.backends.copy() cls.component.backends.append(cls) # add device classes to component if cls is not PluginDevicesMixin and hasattr(cls.component, "deviceClasses"): for deviceClass in cls.deviceClasses: if deviceClass not in cls.component.deviceClasses: cls.component.deviceClasses = cls.component.deviceClasses.copy() cls.component.deviceClasses.append(deviceClass) def getParams(self): """ Get parameters from this backend to add to each new instance of ButtonBoxComponent Returns ------- dict[str:Param] Dict of Param objects, which will be added to any Button Box Component's params, along with a dependency to only show them when this backend is selected list[str] List of param names, defining the order in which params should appear """ raise NotImplementedError() def addRequirements(self): """ Add any required module/package imports for this backend """ raise NotImplementedError() def writeDeviceCode(self, buff): """ Write the code to create a device for this backend """ raise NotImplementedError()
4,245
Python
.py
100
30.86
98
0.585956
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,574
_experiment.py
psychopy_psychopy/psychopy/experiment/_experiment.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). """Experiment classes: Experiment, Flow, Routine, Param, Loop*, *Handlers, and NameSpace The code that writes out a *_lastrun.py experiment file is (in order): experiment.Experiment.writeScript() - starts things off, calls other parts settings.SettingsComponent.writeStartCode() experiment.Flow.writeBody() which will call the .writeBody() methods from each component settings.SettingsComponent.writeEndCode() """ import collections import os import codecs import xml.etree.ElementTree as xml from xml.dom import minidom from copy import deepcopy, copy from pathlib import Path from packaging.version import Version import psychopy from psychopy import data, __version__, logging from psychopy.tools import filetools as ft from .components.resourceManager import ResourceManagerComponent from .components.static import StaticComponent from .exports import IndentingBuffer, NameSpace from .flow import Flow from .loops import TrialHandler, LoopInitiator, \ LoopTerminator, StairHandler, MultiStairHandler from .params import _findParam, Param, legacyParams from psychopy.experiment.routines._base import Routine, BaseStandaloneRoutine from psychopy.experiment.routines import getAllStandaloneRoutines from . import utils, py2js from .components import getComponents, getAllComponents, getInitVals from psychopy.localization import _translate import locale from collections import namedtuple, OrderedDict from ..alerts import alert RequiredImport = namedtuple('RequiredImport', field_names=('importName', 'importFrom', 'importAs')) # some params have previously had types which cause errors compiling in new versions, so we need to keep track of # them and force them to the new type if needed forceType = { 'pos': 'list', 'size': 'list', ('KeyboardComponent', 'allowedKeys'): 'list', ('cedrusButtonBoxComponent', 'allowedKeys'): 'list', ('DotsComponent', 'fieldPos'): 'list', ('JoyButtonsComponent', 'allowedKeys'): 'list', ('JoyButtonsComponent', 'correctAns'): 'list', ('JoystickComponent', 'clickable'): 'list', ('JoystickComponent', 'saveParamsClickable'): 'list', ('JoystickComponent', 'allowedButtons'): 'list', ('MicrophoneComponent', 'transcribeWords'): 'list', ('MouseComponent', 'clickable'): 'list', ('MouseComponent', 'saveParamsClickable'): 'list', ('NoiseStimComponent', 'noiseElementSize'): 'list', ('PatchComponent', 'sf'): 'list', ('RatingScaleComponent', 'categoryChoices'): 'list', ('RatingScaleComponent', 'labels'): 'list', ('RegionOfInterestComponent', 'vertices'): 'list', ('SettingsComponent', 'Window size (pixels)'): 'list', ('SettingsComponent', 'Resources'): 'list', ('SettingsComponent', 'mgBlink'): 'list', ('SliderComponent', 'ticks'): 'list', ('SliderComponent', 'labels'): 'list', ('SliderComponent', 'styleTweaks'): 'list' } # some components in plugins used to be in the main lib, keep track of which plugins they're in pluginComponents = { 'QmixPumpComponent': "psychopy-qmix", 'PeristalticPumpComponent': "psychopy-labeotech", 'ioLabsButtonBoxComponent': "psychopy-iolabs", 'cedrusButtonBoxComponent': "psychopy-cedrus", 'EmotivRecordingComponent': "psychopy-emotiv", 'EmotivMarkingComponent': "psychopy-emotiv", 'EnvGratingComponent': "psychopy-visionscience", 'NoiseStimComponent': "psychopy-visionscience", } # # Code to generate force list # comps = experiment.components.getAllComponents() # exp = experiment._experiment.Experiment() # rt = experiment.routines.Routine("routine", exp) # exp.addRoutine("routine", rt) # # forceType = { # 'pos': 'list', # 'size': 'list', # 'vertices': 'list', # } # for Comp in comps.values(): # comp = Comp(exp=exp, parentName="routine") # for key, param in comp.params.items(): # if param.valType == 'list' and key not in forceType: # forceType[(Comp.__name__, key)] = 'list' class Experiment: """ An experiment contains a single Flow and at least one Routine. The Flow controls how Routines are organised e.g. the nature of repeats and branching of an experiment. """ def __init__(self, prefs=None): super(Experiment, self).__init__() self.filename = '' # update during load/save xml self.flow = Flow(exp=self) # every exp has exactly one flow self.routines = collections.OrderedDict() # get prefs (from app if poss or from cfg files) if prefs is None: prefs = psychopy.prefs # deepCopy doesn't like the full prefs object to be stored, so store # each subset self.prefsAppDataCfg = prefs.appDataCfg self.prefsGeneral = prefs.general self.prefsApp = prefs.app self.prefsCoder = prefs.coder self.prefsBuilder = prefs.builder self.prefsPaths = prefs.paths # this can be checked by the builder that this is an experiment and a # compatible version self.psychopyVersion = __version__ # What libs are needed (make sound come first) self.requiredImports = [] libs = ('sound', 'gui', 'visual', 'core', 'data', 'event', 'logging', 'clock', 'colors', 'layout') self.requirePsychopyLibs(libs=libs) self.requireImport(importName='keyboard', importFrom='psychopy.hardware') _settingsComp = getComponents(fetchIcons=False)['SettingsComponent'] self.settings = _settingsComp(parentName='', exp=self) # this will be the xml.dom.minidom.doc object for saving self._doc = xml.ElementTree() self.namespace = NameSpace(self) # manage variable names # _expHandler is a hack to allow saving data from components not # inside a loop. data-saving machinery relies on loops, not worth # rewriting. `thisExp` will be an ExperimentHandler when used in # the generated script, but its easier to use treat it as a # TrialHandler during script generation to avoid effectively # duplicating code just to work around any differences # in writeRoutineEndCode self._expHandler = TrialHandler(exp=self, name='thisExp') self._expHandler.type = 'ExperimentHandler' # true at run-time def __eq__(self, other): if isinstance(other, Experiment): # if another experiment, compare filenames return other.filename == self.filename elif isinstance(other, (str, Path)): # if a string or path, compare against filename return other == self.filename else: # if neither, it's not the same return False def requirePsychopyLibs(self, libs=()): """Add a list of top-level psychopy libs that the experiment will need. e.g. [visual, event] Notes ----- This is a convenience method for `requireImport()`. """ for lib in libs: self.requireImport(importName=lib, importFrom='psychopy') @property def name(self): return self.settings.params['expName'].val @name.setter def name(self, value): self.settings.params['expName'].val = value @property def eyetracking(self): """What kind of eyetracker this experiment is set up for""" return self.settings.params['eyetracker'] @property def legacyFilename(self): """ Variant of this experiment's filename with "_legacy" on the end """ return ft.constructLegacyFilename(self.filename) @property def runMode(self): return int(self.settings.params['runMode'].val) @runMode.setter def runMode(self, value): self.settings.params['runMode'].val = value def requireImport(self, importName, importFrom='', importAs=''): """Add a top-level import to the experiment. Parameters ---------- importName : str Name of the package or module to import. importFrom : str Where to import ``from``. importAs : str Import ``as`` this name. """ import_ = RequiredImport(importName=importName, importFrom=importFrom, importAs=importAs) if import_ not in self.requiredImports: self.requiredImports.append(import_) def addRoutine(self, routineName, routine=None): """Add a Routine to the current list of them. Can take a Routine object directly or will create an empty one if none is given. """ if routine is None: # create a default routine with this name self.routines[routineName] = Routine(routineName, exp=self) else: self.routines[routineName] = routine return self.routines[routineName] def addStandaloneRoutine(self, routineName, routine): """Add a standalone Routine to the current list of them. Can take a Routine object directly or will create an empty one if none is given. """ self.routines[routineName] = routine return self.routines[routineName] def integrityCheck(self): """Check the integrity of the Experiment""" # add some checks for things outside the Flow? # then check the contents 1-by-1 from the Flow self.flow.integrityCheck() def writeScript(self, expPath=None, target="PsychoPy", modular=True): """Write a PsychoPy script for the experiment """ # self.integrityCheck() self.psychopyVersion = psychopy.__version__ # make sure is current # set this so that params write for approp target utils.scriptTarget = target self.expPath = expPath script = IndentingBuffer(target=target) # a string buffer object # get date info, in format preferred by current locale as set by app: if hasattr(locale, 'nl_langinfo'): fmt = locale.nl_langinfo(locale.D_T_FMT) localDateTime = data.getDateStr(format=fmt) else: localDateTime = data.getDateStr(format="%B %d, %Y, at %H:%M") # Remove disabled components, but leave original experiment unchanged. self_copy = deepcopy(self) for key, routine in list(self_copy.routines.items()): # PY2/3 compat # Remove disabled / unimplemented routines if routine.disabled or target not in routine.targets: for node in self_copy.flow: if node == routine: self_copy.flow.removeComponent(node) if target not in routine.targets: # If this routine isn't implemented in target library, print alert and mute it alertCode = 4335 if target == "PsychoPy" else 4340 alert(alertCode, strFields={'comp': type(routine).__name__}) # Remove disabled / unimplemented components within routine if isinstance(routine, Routine): for component in [comp for comp in routine]: if component.disabled or target not in component.targets: routine.removeComponent(component) if component.targets and target not in component.targets: # If this component isn't implemented in target library, print alert and mute it alertCode = 4335 if target == "PsychoPy" else 4340 alert(alertCode, strFields={'comp': type(component).__name__}) if target == "PsychoPy": # Imports self_copy.settings.writeInitCode(script, self_copy.psychopyVersion, localDateTime) # Write "run once" code sections for entry in self_copy.flow: # NB each entry is a routine or LoopInitiator/Terminator self_copy._currentRoutine = entry if hasattr(entry, 'writePreCode'): entry.writePreCode(script) # global variables self_copy.settings.writeGlobals(script, version=self_copy.psychopyVersion) # present info self_copy.settings.writeExpInfoDlgCode(script) # setup data and saving self_copy.settings.writeDataCode(script) # make logfile self_copy.settings.writeLoggingCode(script) # setup window self_copy.settings.writeWindowCode(script) # create our visual.Window() # setup devices self_copy.settings.writeDevicesCode(script) # pause experiment self_copy.settings.writePauseCode(script) # write the bulk of the experiment code self_copy.flow.writeBody(script) # save data self_copy.settings.writeSaveDataCode(script) # end experiment self_copy.settings.writeEndCode(script) # to do if running as main code = ( "\n" "# if running this experiment as a script...\n" "if __name__ == '__main__':\n" " # call all functions in order\n" ) if self_copy.settings.params['Show info dlg'].val: # Only show exp info dlg if indicated to by settings code += ( " expInfo = showExpInfoDlg(expInfo=expInfo)\n" ) code += ( " thisExp = setupData(expInfo=expInfo)\n" " logFile = setupLogging(filename=thisExp.dataFileName)\n" " win = setupWindow(expInfo=expInfo)\n" " setupDevices(expInfo=expInfo, thisExp=thisExp, win=win)\n" " run(\n" " expInfo=expInfo, \n" " thisExp=thisExp, \n" " win=win,\n" " globalClock=%(clockFormat)s\n" " )\n" " saveData(thisExp=thisExp)\n" " quit(thisExp=thisExp, win=win)\n" ) script.writeIndentedLines(code % self.settings.params) script = script.getvalue() elif target == "PsychoJS": script.oneIndent = " " # use 2 spaces rather than python 4 self_copy.settings.writeInitCodeJS(script, self_copy.psychopyVersion, localDateTime, modular) script.writeIndentedLines("// Start code blocks for 'Before Experiment'") toWrite = list(self_copy.routines) toWrite.extend(list(self_copy.flow)) for entry in self_copy.flow: # NB each entry is a routine or LoopInitiator/Terminator self_copy._currentRoutine = entry if hasattr(entry, 'writePreCodeJS') and entry.name in toWrite: entry.writePreCodeJS(script) toWrite.remove(entry.name) # this one's done # Write window code self_copy.settings.writeWindowCodeJS(script) self_copy.flow.writeFlowSchedulerJS(script) self_copy.settings.writeExpSetupCodeJS(script, self_copy.psychopyVersion) # initialise the components for all Routines in a single function script.writeIndentedLines("\nasync function experimentInit() {") script.setIndentLevel(1, relative=True) # routine init sections toWrite = list(self_copy.routines) toWrite.extend(list(self_copy.flow)) for entry in self_copy.flow: # NB each entry is a routine or LoopInitiator/Terminator self_copy._currentRoutine = entry if hasattr(entry, 'writeInitCodeJS') and entry.name in toWrite: entry.writeInitCodeJS(script) toWrite.remove(entry.name) # this one's done # create globalClock etc code = ("// Create some handy timers\n" "globalClock = new util.Clock();" " // to track the time since experiment started\n" "routineTimer = new util.CountdownTimer();" " // to track time remaining of each (non-slip) routine\n" "\nreturn Scheduler.Event.NEXT;") script.writeIndentedLines(code) script.setIndentLevel(-1, relative=True) script.writeIndentedLines("}\n") # This differs to the Python script. We can loop through all # Routines once (whether or not they get used) because we're using # functions that may or may not get called later. # Do the Routines of the experiment first toWrite = list(self_copy.routines) for thisItem in self_copy.flow: if thisItem.getType() in ['LoopInitiator', 'LoopTerminator']: self_copy.flow.writeLoopHandlerJS(script, modular) elif thisItem.name in toWrite: self_copy._currentRoutine = self_copy.routines[thisItem.name] self_copy._currentRoutine.writeRoutineBeginCodeJS(script, modular) self_copy._currentRoutine.writeEachFrameCodeJS(script, modular) self_copy._currentRoutine.writeRoutineEndCodeJS(script, modular) toWrite.remove(thisItem.name) self_copy.settings.writeEndCodeJS(script) # Add JS variable declarations e.g., var msg; script = py2js.addVariableDeclarations(script.getvalue(), fileName=self.expPath) # Reset loop controller ready for next call to writeScript self_copy.flow._resetLoopController() return script @property def _xml(self): # Create experiment root element experimentNode = xml.Element("PsychoPy2experiment") experimentNode.set('encoding', 'utf-8') experimentNode.set('version', __version__) # Add settings node settingsNode = self.settings._xml experimentNode.append(settingsNode) # Add routines node routineNode = xml.Element("Routines") for key, routine in self.routines.items(): routineNode.append(routine._xml) experimentNode.append(routineNode) # Add flow node flowNode = self.flow._xml experimentNode.append(flowNode) return experimentNode def sanitizeForVersion(self, targetVersion): """ Create a copy of this experiment with components/routines added after the given version removed. Parameters ---------- version : packaging.Version, str Version of PsychoPy to sanitize for. Returns ------- Experiment Sanitized copy of this experiment """ # copy self exp = deepcopy(self) # parse version targetVersion = Version(targetVersion) # change experiment version exp.psychopyVersion = targetVersion # iterate through Routines for rtName, rt in copy(exp.routines).items(): # if Routine was added after the target version, remove it if hasattr(type(rt), "version") and Version(rt.version) > targetVersion: exp.routines.pop(rtName) # if Routine is a standalone, we're done if isinstance(rt, BaseStandaloneRoutine): continue # iterate through Components for comp in copy(rt): # if Component was added after target version, remove it if hasattr(type(comp), "version") and Version(comp.version) > targetVersion: i = rt.index(comp) rt.pop(i) return exp def saveToXML(self, filename, makeLegacy=True): """ Save this experiment to a `.psyexp` file (under the hood, this is XML) Parameters ---------- filename : str, Path Filename to save to. makeLegacy : bool If True, and useVersion is lower than the current version, a legacy-safe version of this experiment is also saved. Returns ------- filename : str The filename which was eventually saved to """ # get current version self.psychopyVersion = psychopy.__version__ # make path object filename = Path(filename) # create the dom object self.xmlRoot = self._xml # update our document to use the new root self._doc._setroot(self.xmlRoot) simpleString = xml.tostring(self.xmlRoot, 'utf-8') # convert to a pretty string pretty = minidom.parseString(simpleString).toprettyxml(indent=" ") # make sure we have the correct extension if filename.suffix != ".psyexp": filename = filename.parent / (filename.stem + ".psyexp") # write to file with codecs.open(str(filename), 'wb', encoding='utf-8-sig') as f: f.write(pretty) # if useVersion is less than current version, create a sanitized legacy variant if self.settings.params['Use version'].val and makeLegacy: # create sanitized legacy experiment object legacy = self.sanitizeForVersion(self.settings.params['Use version'].val) # construct a legacy variant of the filename legacyFilename = ft.constructLegacyFilename(filename) # call save method from that experiment legacy.saveToXML(filename=str(legacyFilename), makeLegacy=False) # update internal reference to filename self.filename = str(filename) return str(filename) # this may have been updated to include an extension def _getShortName(self, longName): return longName.replace('(', '').replace(')', '').replace(' ', '') def _getXMLparam(self, params, paramNode, componentNode=None): """params is the dict of params of the builder component (e.g. stimulus) into which the parameters will be inserted (so the object to store the params should be created first) paramNode is the parameter node fetched from the xml file Returns ------- bool True if the param is recognised by this version of PsychoPy, False otherwise """ recognised = True name = paramNode.get('name') valType = paramNode.get('valType') val = paramNode.get('val') # many components need web char newline replacement if not name == 'advancedParams': val = val.replace("&#10;", "\n") # custom settings (to be used when if valType == 'fixedList': # convert the string to a list try: params[name].val = eval('list({})'.format(val)) except NameError: # if val is a single string it will look like variable params[name].val = [val] elif name == 'storeResponseTime': return recognised # deprecated in v1.70.00 because it was redundant elif name == 'nVertices': # up to 1.85 there was no shape param # if no shape param then use "n vertices" only if _findParam('shape', componentNode) is None: if val == '2': params['shape'].val = "line" elif val == '3': params['shape'].val = "triangle" elif val == '4': params['shape'].val = "rectangle" else: params['shape'].val = "regular polygon..." params['nVertices'].val = val elif name == 'startTime': # deprecated in v1.70.00 params['startType'].val = "{}".format('time (s)') params['startVal'].val = "{}".format(val) return recognised # times doesn't need to update its type or 'updates' rule elif name == 'forceEndTrial': # deprecated in v1.70.00 params['forceEndRoutine'].val = bool(val) return recognised # forceEndTrial doesn't need to update type or 'updates' elif name == 'forceEndTrialOnPress': # deprecated in v1.70.00 params['forceEndRoutineOnPress'].val = bool(val) return recognised # forceEndTrial doesn't need to update type or 'updates' elif name == 'forceEndRoutineOnPress': if val == 'True': val = "any click" elif val == 'False': val = "never" params['forceEndRoutineOnPress'].val = val return recognised elif name == 'trialList': # deprecated in v1.70.00 params['conditions'].val = eval(val) return recognised # forceEndTrial doesn't need to update type or 'updates' elif name == 'trialListFile': # deprecated in v1.70.00 params['conditionsFile'].val = "{}".format(val) return recognised # forceEndTrial doesn't need to update type or 'updates' elif name == 'duration': # deprecated in v1.70.00 params['stopType'].val = u'duration (s)' params['stopVal'].val = "{}".format(val) return recognised # times doesn't need to update its type or 'updates' rule elif name == 'allowedKeys' and valType == 'str': # changed v1.70.00 # ynq used to be allowed, now should be 'y','n','q' or # ['y','n','q'] if len(val) == 0: newVal = val elif val[0] == '$': newVal = val[1:] # they were using code (which we can reuse) elif val.startswith('[') and val.endswith(']'): # they were using code (slightly incorrectly!) newVal = val[1:-1] elif val in ['return', 'space', 'left', 'right', 'escape']: newVal = val # they were using code else: # convert string to list of keys then represent again as a # string! newVal = repr(list(val)) params['allowedKeys'].val = newVal params['allowedKeys'].valType = 'code' elif name == 'correctIf': # deprecated in v1.60.00 corrIf = val corrAns = corrIf.replace( 'resp.keys==unicode(', '').replace(')', '') params['correctAns'].val = corrAns name = 'correctAns' # then we can fetch other aspects below elif 'olour' in name: # colour parameter was Americanised v1.61.00 name = name.replace('olour', 'olor') params[name].val = val elif name == 'times': # deprecated in v1.60.00 times = eval('%s' % val) params['startType'].val = "{}".format('time (s)') params['startVal'].val = "{}".format(times[0]) params['stopType'].val = "{}".format('time (s)') params['stopVal'].val = "{}".format(times[1]) return recognised # times doesn't need to update its type or 'updates' rule elif name in ('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'): # up to version 1.78.00 and briefly in 2021.1.0-1.1 these were 'code' params[name].val = val params[name].valType = 'extendedCode' return recognised # so that we don't update valType again below elif name == 'Saved data folder': # deprecated in 1.80 for more complete data filename control params[name] = Param( val, valType='code', allowedTypes=[], hint=_translate("Name of the folder in which to save data" " and log files (blank defaults to the " "builder pref)"), categ='Data') elif name == 'channel': # was incorrectly set to be valType='str' until 3.1.2 params[name].val = val params[name].valType = 'code' # override elif 'val' in list(paramNode.keys()): if val == 'window units': # changed this value in 1.70.00 params[name].val = 'from exp settings' # in v1.80.00, some RatingScale API and Param fields were changed # Try to avoid a KeyError in these cases so can load the expt elif name in ('choiceLabelsAboveLine', 'lowAnchorText', 'highAnchorText'): # not handled, just ignored; want labels=[lowAnchor, # highAnchor] return recognised elif name == 'customize_everything': # Try to auto-update the code: v = val # python code, not XML v = v.replace('markerStyle', 'marker').replace( 'customMarker', 'marker') v = v.replace('stretchHoriz', 'stretch').replace( 'displaySizeFactor', 'size') v = v.replace('textSizeFactor', 'textSize') v = v.replace('ticksAboveLine=False', 'tickHeight=-1') v = v.replace('showScale=False', 'scale=None').replace( 'allowSkip=False', 'skipKeys=None') v = v.replace('showAnchors=False', 'labels=None') # lowAnchorText highAnchorText will trigger obsolete error # when run the script params[name].val = v elif name == 'storeResponseTime': return recognised # deprecated in v1.70.00 because it was redundant elif name == 'Resources': # if the xml import hasn't automatically converted from string? if type(val) == str: resources = data.utils.listFromString(val) if self.psychopyVersion == '2020.2.5': # in 2020.2.5 only, problems were: # a) resources list was saved as a string and # b) with wrong root folder resList = [] for resourcePath in resources: # doing this the blunt way but should we check for existence? resourcePath = resourcePath.replace("../", "") # it was created using wrong root resourcePath = resourcePath.replace("\\", "/") # created using windows \\ resList.append(resourcePath) resources = resList # push our new list back to resources params[name].val = resources else: if name in params: params[name].val = val else: # we found an unknown parameter (probably from the future) params[name] = Param( val, valType=paramNode.get('valType'), inputType="inv", categ="Unknown", allowedTypes=[], label=_translate(name), hint=_translate( "This parameter is not known by this version " "of PsychoPy. It might be worth upgrading, otherwise " "press the X button to remove this parameter.")) params[name].allowedTypes = paramNode.get('allowedTypes') if params[name].allowedTypes is None: params[name].allowedTypes = [] if name in legacyParams + ['JS libs', 'OSF Project ID']: # don't warn people if we know it's OK (e.g. for params # that have been removed pass elif componentNode is not None and componentNode.get("plugin") not in ("None", None): # don't warn people if comp/routine is from a plugin pass elif paramNode.get('plugin', False): # load plugin name if param is from a plugin params[name].plugin = paramNode.get('plugin') else: # if param not recognised, mark as such recognised = False # get the value type and update rate if 'valType' in list(paramNode.keys()): params[name].valType = paramNode.get('valType') # compatibility checks: if name in ['allowedKeys'] and paramNode.get('valType') == 'str': # these components were changed in v1.70.00 params[name].valType = 'code' elif name == 'Selected rows': # changed in 1.81.00 from 'code' to 'str': allow string or var params[name].valType = 'str' # conversions based on valType if params[name].valType == 'bool': params[name].val = eval("%s" % params[name].val) if 'updates' in list(paramNode.keys()): params[name].updates = paramNode.get('updates') return recognised @staticmethod def fromFile(filename): """ Creates a new Experiment object and loads a Builder Experiment from file. Parameters ---------- filename : pathlike `.psyexp` file to load. Returns ------- Experiment Loaded Experiment object """ # make new Experiment exp = Experiment() # load file exp.loadFromXML(filename) return exp def loadFromXML(self, filename): """Loads an xml file and parses the builder Experiment from it """ self._doc.parse(filename) root = self._doc.getroot() # some error checking on the version (and report that this isn't valid # .psyexp)? filenameBase = os.path.basename(filename) unknownParams = [] if root.tag != "PsychoPy2experiment": logging.error('%s is not a valid .psyexp file, "%s"' % (filenameBase, root.tag)) # the current exp is already vaporized at this point, oops return self.psychopyVersion = root.get('version') # If running an experiment from a future version, send alert to change "Use Version" if Version(psychopy.__version__) < Version(self.psychopyVersion): alert(code=4051, strFields={'version': self.psychopyVersion}) # If versions are either side of 2021, send alert if Version(psychopy.__version__) >= Version("2021.1.0") > Version(self.psychopyVersion): alert(code=4052, strFields={'version': self.psychopyVersion}) # Parse document nodes # first make sure we're empty self.flow = Flow(exp=self) # every exp has exactly one flow self.routines = {} self.namespace = NameSpace(self) # start fresh modifiedNames = [] duplicateNames = [] # fetch exp settings settingsNode = root.find('Settings') for child in settingsNode: recognised = self._getXMLparam( params=self.settings.params, paramNode=child, componentNode=settingsNode ) # append unknown params to warning array if not recognised: unknownParams.append(child.get("name")) # name should be saved as a settings parameter (only from 1.74.00) if self.settings.params['expName'].val in ['', None, 'None']: shortName = os.path.splitext(filenameBase)[0] self.setExpName(shortName) # fetch routines routinesNode = root.find('Routines') allCompons = getAllComponents( self.prefsBuilder['componentsFolders'], fetchIcons=False) allRoutines = getAllStandaloneRoutines(fetchIcons=False) # get each routine node from the list of routines for routineNode in routinesNode: if routineNode.tag == "Routine": routineGoodName = self.namespace.makeValid( routineNode.get('name')) if routineGoodName != routineNode.get('name'): modifiedNames.append(routineNode.get('name')) self.namespace.user.append(routineGoodName) routine = Routine(name=routineGoodName, exp=self) # self._getXMLparam(params=routine.params, paramNode=routineNode) self.routines[routineNode.get('name')] = routine for componentNode in routineNode: componentType = componentNode.tag # get plugin, if any plugin = componentNode.get('plugin') if plugin in ("None", None) and componentNode.tag in pluginComponents: plugin = pluginComponents[componentNode.tag] if componentType == "RoutineSettingsComponent": # if settings, use existing component component = routine.settings elif componentType in allCompons: # create an actual component of that type component = allCompons[componentType]( name=componentNode.get('name'), parentName=routineNode.get('name'), exp=self) elif plugin: # create UnknownPluginComponent instead component = allCompons['UnknownPluginComponent']( name=componentNode.get('name'), compType=componentType, parentName=routineNode.get('name'), exp=self) alert(7105, strFields={'name': componentNode.get('name'), 'plugin': plugin}) else: # create UnknownComponent instead component = allCompons['UnknownComponent']( name=componentNode.get('name'), compType=componentType, parentName=routineNode.get('name'), exp=self) component.plugin = plugin # check for components that were absent in older versions of # the builder and change the default behavior # (currently only the new behavior of choices for RatingScale, # HS, November 2012) # HS's modification superseded Jan 2014, removing several # RatingScale options if componentType == 'RatingScaleComponent': if (componentNode.get('choiceLabelsAboveLine') or componentNode.get('lowAnchorText') or componentNode.get('highAnchorText')): pass # if not componentNode.get('choiceLabelsAboveLine'): # # this rating scale was created using older version # component.params['choiceLabelsAboveLine'].val=True # populate the component with its various params for paramNode in componentNode: recognised = self._getXMLparam( params=component.params, paramNode=paramNode, componentNode=componentNode ) # append unknown params to warning array if not recognised: unknownParams.append(paramNode.get("name")) # sanitize name (unless this comp is settings) compName = componentNode.get('name') if compName != routineNode.get('name'): compGoodName = self.namespace.makeValid(compName) if compGoodName != compName: modifiedNames.append(compName) self.namespace.add(compGoodName) component.params['name'].val = compGoodName # Add to routine if component not in routine: routine.append(component) else: if routineNode.tag in allRoutines: # If not a routine, may be a standalone routine routine = allRoutines[routineNode.tag](exp=self, name=routineNode.get('name')) else: # Otherwise treat as unknown routine = allRoutines['UnknownRoutine'](exp=self, name=routineNode.get('name')) # Apply all params for paramNode in routineNode: if paramNode.tag == "Param": for key, val in paramNode.items(): name = paramNode.get("name") if name in routine.params: setattr(routine.params[name], key, val) # Add routine to experiment self.addStandaloneRoutine(routine.name, routine) # for each component that uses a Static for updates, we need to set # that for thisRoutine in list(self.routines.values()): for thisComp in thisRoutine: for thisParamName in thisComp.params: thisParam = thisComp.params[thisParamName] if thisParamName == 'advancedParams': continue # advanced isn't a normal param elif thisParam.updates and "during:" in thisParam.updates: # remove the part that says 'during' updates = thisParam.updates.split(': ')[1] routine, static = updates.split('.') if routine not in self.routines: msg = ("%s was set to update during %s Static " "Component, but that component no longer " "exists") logging.warning(msg % (thisParamName, static)) else: thisRoutine = \ self.routines[routine].getComponentFromName( static) if thisRoutine is None: continue self.routines[routine].getComponentFromName( static).addComponentUpdate( thisRoutine.params['name'], thisComp.params['name'], thisParamName) # fetch flow settings flowNode = root.find('Flow') loops = {} for elementNode in flowNode: if elementNode.tag == "LoopInitiator": loopType = elementNode.get('loopType') loopName = self.namespace.makeValid(elementNode.get('name')) if loopName != elementNode.get('name'): modifiedNames.append(elementNode.get('name')) self.namespace.add(loopName) loop = eval('%s(exp=self,name="%s")' % (loopType, loopName)) loops[loopName] = loop for paramNode in elementNode: recognised = self._getXMLparam(paramNode=paramNode, params=loop.params) # for conditions convert string rep to list of dicts if paramNode.get('name') == 'conditions': param = loop.params['conditions'] # e.g. param.val=[{'ori':0},{'ori':3}] try: param.val = eval('%s' % (param.val)) except (NameError, SyntaxError): """ Catches ------- SyntaxError This can occur if Python2.7 conditions string contained long ints (e.g. 8L) and these can't be parsed by Py3. But allow the file to carry on loading and the conditions will still be loaded from the xlsx file NameError Happens when a cell in the conditions file contains a reserved JSON keyword which isn't a reserved Python keyword (e.g. nan), as it's read in as literal but can't be evaluated. """ pass # append unknown params to warning array if not recognised: unknownParams.append(paramNode.get("name")) # get condition names from within conditionsFile, if any: try: # psychophysicsstaircase demo has no such param conditionsFile = loop.params['conditionsFile'].val except Exception: conditionsFile = None if conditionsFile in ['None', '']: conditionsFile = None if conditionsFile: try: trialList, fieldNames = data.importConditions( conditionsFile, returnFieldNames=True) for fname in fieldNames: if fname != self.namespace.makeValid(fname): duplicateNames.append(fname) else: self.namespace.add(fname) except Exception: pass # couldn't load the conditions file for now self.flow.append(LoopInitiator(loop=loops[loopName])) elif elementNode.tag == "LoopTerminator": self.flow.append(LoopTerminator( loop=loops[elementNode.get('name')])) else: if elementNode.get('name') in self.routines: self.flow.append(self.routines[elementNode.get('name')]) else: logging.error("A Routine called '{}' was on the Flow but " "could not be found (failed rename?). You " "may need to re-insert it".format( elementNode.get('name'))) logging.flush() if modifiedNames: msg = 'duplicate variable name(s) changed in loadFromXML: %s\n' logging.warning(msg % ', '.join(list(set(modifiedNames)))) if duplicateNames: msg = 'duplicate variable names: %s' logging.warning(msg % ', '.join(list(set(duplicateNames)))) # Modernise params for rt in self.routines.values(): if not isinstance(rt, list): # Treat standalone routines as a routine with one component rt = [rt] for comp in rt: # For each param, if it's pointed to in the forceType array, set it to the new valType for paramName, param in comp.params.items(): # Param pointed to by name if paramName in forceType: param.valType = forceType[paramName] if (type(comp).__name__, paramName) in forceType: param.valType = forceType[(type(comp).__name__, paramName)] # if we succeeded then save current filename to self self.filename = filename # warn about any unknown params if len(unknownParams): # construct message msg = _translate( "Parameters not known to this version of PsychoPy have come from your experiment " "file: %s. This experiment may not run correctly in the current version." ) # log message logging.warn(msg % ", ".join(unknownParams)) logging.flush() @staticmethod def getRunModeFromFile(file): """ Get the run mode stored in an experiment file without fully loading the experiment. Parameters ---------- file : Path or str Path of the file to read Returns ------- int 0 for piloting mode, 1 for running mode """ file = str(file) # make and populate xml root element tree = xml.ElementTree() tree.parse(file) # get root root = tree.getroot() # find settings node settings = root.find("Settings") # find param for runMode for child in settings: if child.attrib['name'] == "runMode": # get value return int(child.attrib['val']) return 1 def setExpName(self, name): self.settings.params['expName'].val = name def getExpName(self): return self.settings.params['expName'].val @property def htmlFolder(self): return self.settings.params['HTML path'].val def getComponentFromName(self, name): """Searches all the Routines in the Experiment for a matching Comp name :param name: str name of a component :return: a component class or None """ for routine in self.routines.values(): comp = routine.getComponentFromName(name) if comp: return comp return None def getComponentFromType(self, thisType): """Searches all the Routines in the Experiment for a matching component type :param name: str type of a component e.g., 'KeyBoard' :return: True if component exists in experiment """ for routine in self.routines.values(): exists = routine.getComponentFromType(type) exists = routine.getComponentFromType(thisType) if exists: return True return False def getResourceFiles(self): """Returns a list of known files needed for the experiment Interrogates each loop looking for conditions files and each """ join = os.path.join abspath = os.path.abspath srcRoot = os.path.split(self.filename)[0] def getPaths(filePath): """Helper to return absolute and relative paths (or None) :param filePath: str to a potential file path (rel or abs) :return: dict of 'asb' and 'rel' paths or None """ # Only construct paths if filePath is a string if type(filePath) != str: return None thisFile = {} # NB: Pathlib might be neater here but need to be careful # e.g. on mac: # Path('C:/test/test.xlsx').is_absolute() returns False # Path('/folder/file.xlsx').relative_to('/Applications') gives error # but os.path.relpath('/folder/file.xlsx', '/Applications') correctly uses ../ if filePath in list(ft.defaultStim): # Default/asset stim are a special case as the file doesn't exist in the usual path thisFile['rel'] = thisFile['abs'] = "https://pavlovia.org/assets/default/" + ft.defaultStim[filePath] thisFile['name'] = filePath return thisFile if len(filePath) > 2 and (filePath[0] == "/" or filePath[1] == ":")\ and os.path.isfile(filePath): thisFile['abs'] = filePath thisFile['rel'] = os.path.relpath(filePath, srcRoot) thisFile['name'] = Path(filePath).name return thisFile else: thisFile['rel'] = filePath thisFile['abs'] = os.path.normpath(join(srcRoot, filePath)) if "/" in filePath: thisFile['name'] = filePath.split("/")[-1] else: thisFile['name'] = filePath if len(thisFile['abs']) <= 256 and os.path.isfile(thisFile['abs']): return thisFile def findPathsInFile(filePath): """Recursively search a conditions file (xlsx or csv) extracting valid file paths in any param/cond :param filePath: str to a potential file path (rel or abs) :return: list of dicts{'rel','abs'} of valid file paths """ # Clean up filePath that cannot be eval'd if filePath.startswith('$'): try: filePath = filePath.strip('$') filePath = eval(filePath) except NameError: # List files in directory and get condition files if 'xlsx' in filePath or 'xls' in filePath or 'csv' in filePath: # Get all xlsx and csv files expFolder = Path(self.filename).parent spreadsheets = [] for pattern in ['*.xlsx', '*.xls', '*.csv', '*.tsv']: # NB potentially make this search recursive with # '**/*.xlsx' but then need to exclude 'data/*.xlsx' spreadsheets.extend(expFolder.glob(pattern)) files = [] for condFile in spreadsheets: # call the function recursively for each excel file files.extend(findPathsInFile(str(condFile))) return files paths = [] # is it a file? thisFile = getPaths(filePath) # get the abs/rel paths # does it exist? if not thisFile: return paths # OK, this file itself is valid so add to resources if thisFile not in paths: paths.append(thisFile) # does it look at all like an excel file? if (not isinstance(filePath, str) or not os.path.splitext(filePath)[1] in ['.csv', '.xlsx', '.xls']): return paths conds = data.importConditions(thisFile['abs']) # load the abs path for thisCond in conds: # thisCond is a dict for param, val in list(thisCond.items()): if isinstance(val, str) and len(val): # only add unique entries (can't use set() on a dict) for thisFile in findPathsInFile(val): if thisFile not in paths: paths.append(thisFile) return paths # Get resources for components compResources = [] handled = False for thisEntry in self.flow.getUniqueEntries(): if thisEntry.getType() == 'Routine': # find all params of all compons and check if valid filename for thisComp in thisEntry: # if current component is a Resource Manager, we don't need to pre-load ANY resources if isinstance(thisComp, (ResourceManagerComponent, StaticComponent)): handled = True for paramName in thisComp.params: thisParam = thisComp.params[paramName] thisFile = '' if isinstance(thisParam, str): thisFile = getPaths(thisParam) elif isinstance(thisParam.val, str): thisFile = getPaths(thisParam.val) if paramName == "surveyId" and thisComp.params.get('surveyType', "") == "id": # Survey IDs are a special case, they need adding verbatim, no path sanitizing thisFile = {'surveyId': thisParam.val} # then check if it's a valid path and not yet included if thisFile and thisFile not in compResources: compResources.append(thisFile) # if param updates on frame/repeat, check its init val too if hasattr(thisParam, "updates") and thisParam.updates != "constant": inits = getInitVals({paramName: thisParam}) thisFile = getPaths(inits[paramName].val) # then check if it's a valid path and not yet included if thisFile and thisFile not in compResources: compResources.append(thisFile) elif isinstance(thisEntry, BaseStandaloneRoutine): for paramName in thisEntry.params: thisParam = thisEntry.params[paramName] thisFile = '' if isinstance(thisParam, str): thisFile = getPaths(thisParam) elif isinstance(thisParam.val, str): thisFile = getPaths(thisParam.val) if paramName == "surveyId" and thisEntry.params.get('surveyType', "") == "id": # Survey IDs are a special case, they need adding verbatim, no path sanitizing thisFile = {'surveyId': thisParam.val} # then check if it's a valid path and not yet included if thisFile and thisFile not in compResources: compResources.append(thisFile) # if param updates on frame/repeat, check its init val too if hasattr(thisParam, "updates") and thisParam.updates != "constant": inits = getInitVals({paramName: thisParam}) thisFile = getPaths(inits[paramName].val) # then check if it's a valid path and not yet included if thisFile and thisFile not in compResources: compResources.append(thisFile) elif thisEntry.getType() == 'LoopInitiator' and "Stair" in thisEntry.loop.type: url = 'https://lib.pavlovia.org/vendors/jsQUEST.min.js' compResources.append({ 'rel': url, 'abs': url, }) if handled: # if resources are handled, clear all component resources handledResources = compResources compResources = [] # exceptions to the rule... for thisFile in handledResources: # still add default stim if thisFile.get('name', False) in list(ft.defaultStim): compResources.append(thisFile) # still add survey ID if 'surveyId' in thisFile: compResources.append(thisFile) # Get resources for loops loopResources = [] for thisEntry in self.flow: if thisEntry.getType() == 'LoopInitiator': # find all loops and check for conditions filename params = thisEntry.loop.params if 'conditionsFile' in params: condsPaths = findPathsInFile(params['conditionsFile'].val) # If handled, remove non-conditions file resources if handled: condsPathsRef = copy(condsPaths) # copy of condsPaths for reference in loop for thisPath in condsPathsRef: isCondFile = any([ str(thisPath['rel']).endswith('.xlsx'), str(thisPath['rel']).endswith('.xls'), str(thisPath['rel']).endswith('.csv'), str(thisPath['rel']).endswith('.tsv'), ]) if not isCondFile: condsPaths.remove(thisPath) loopResources.extend(condsPaths) # Add files from additional resources box chosenResources = [] val = self.settings.params['Resources'].val for thisEntry in val: thisFile = getPaths(thisEntry) if thisFile: chosenResources.append(thisFile) # Check for any resources not in experiment path resources = loopResources + compResources + chosenResources resources = [res for res in resources if res is not None] for res in resources: if res in list(ft.defaultStim): # Skip default stim here continue if isinstance(res, dict) and 'abs' in res and 'rel' in res: if srcRoot not in res['abs'] and 'https://' not in res['abs']: psychopy.logging.warning("{} is not in the experiment path and " "so will not be copied to Pavlovia" .format(res['rel'])) return resources class ExpFile(list): """An ExpFile is similar to a Routine except that it generates its code from the Flow of a separate, complete psyexp file. """ def __init__(self, name, exp, filename=''): super(ExpFile, self).__init__() self.params = {'name': name} self.name = name self.exp = exp # the exp we belong to # the experiment we represent on disk (see self.loadExp) self.expObject = None self.filename = filename self._clockName = None # used in script "t = trialClock.GetTime()" self.type = 'ExpFile' def __repr__(self): _rep = "psychopy.experiment.ExpFile(name='%s',exp=%s,filename='%s')" return _rep % (self.name, self.exp, self.filename) def writeStartCode(self, buff): # tell each object on our flow to write its start code for entry in self.flow: # NB each entry is a routine or LoopInitiator/Terminator self._currentRoutine = entry if hasattr(entry, 'writeStartCode'): entry.writeStartCode(buff) def loadExp(self): # fetch the file self.expObject = Experiment() self.expObject.loadFromXML(self.filename) # extract the flow, which is the key part for us: self.flow = self.expObject.flow def writeInitCode(self, buff): # tell each object on our flow to write its init code for entry in self.flow: # NB each entry is a routine or LoopInitiator/Terminator self._currentRoutine = entry entry.writeInitCode(buff) def writeMainCode(self, buff): """This defines the code for the frames of a single routine """ # tell each object on our flow to write its run code for entry in self.flow: self._currentRoutine = entry entry.writeMainCode(buff) def writeExperimentEndCode(self, buff): """This defines the code for the frames of a single routine """ for entry in self.flow: self._currentRoutine = entry entry.writeExperimentEndCode(buff) def getType(self): return 'ExpFile' def getMaxTime(self): """What the last (predetermined) stimulus time to be presented. If there are no components or they have code-based times then will default to 10secs """ pass # todo?: currently only Routines perform this action
64,566
Python
.py
1,272
36.227201
120
0.563586
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,575
params.py
psychopy_psychopy/psychopy/experiment/params.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). """Experiment classes: Experiment, Flow, Routine, Param, Loop*, *Handlers, and NameSpace The code that writes out a *_lastrun.py experiment file is (in order): experiment.Experiment.writeScript() - starts things off, calls other parts settings.SettingsComponent.writeStartCode() experiment.Flow.writeBody() which will call the .writeBody() methods from each component settings.SettingsComponent.writeEndCode() """ import functools from xml.etree.ElementTree import Element import re from pathlib import Path from psychopy import logging from . import utils from . import py2js from ..colors import Color from numpy import ndarray from ..alerts import alert def _findParam(name, node): """Searches an XML node in search of a particular param name :param name: str indicating the name of the attribute :param node: xml element/node to be searched :return: None, or a parameter child node """ for attr in node: if attr.get('name') == name: return attr inputDefaults = { 'str': 'single', 'code': 'single', 'num': 'single', 'bool': 'bool', 'list': 'single', 'file': 'file', 'color': 'color', } # These are parameters which once existed but are no longer needed, so inclusion in this list will silence any "future # version" warnings legacyParams = [ 'lineColorSpace', 'borderColorSpace', 'fillColorSpace', 'foreColorSpace', # 2021.1, we standardised colorSpace to be object-wide rather than param-specific ] class Param(): r"""Defines parameters for Experiment Components A string representation of the parameter will depend on the valType: >>> print(Param(val=[3,4], valType='num')) asarray([3, 4]) >>> print(Param(val=3, valType='num')) # num converts int to float 3.0 >>> print(Param(val=3, valType='str') # str keeps as int, converts to code 3 >>> print(Param(val='3', valType='str')) # ... and keeps str as str '3' >>> print(Param(val=[3,4], valType='str')) # val is <type 'list'> -> code [3, 4] >>> print(Param(val='[3,4]', valType='str')) '[3,4]' >>> print(Param(val=[3,4], valType='code')) [3, 4] >>> print(Param(val='"yes", "no"', valType='list')) ["yes", "no"] >>> #### auto str -> code: at least one non-escaped '$' triggers >>> print(Param('[x,y]','str')) # str normally returns string '[x,y]' >>> print(Param('$[x,y]','str')) # code, as triggered by $ [x,y] >>> print(Param('[$x,$y]','str')) # code, redundant $ ok, cleaned up [x,y] >>> print(Param('[$x,y]','str')) # code, a $ anywhere means code [x,y] >>> print(Param('[x,y]$','str')) # ... even at the end [x,y] >>> print(Param('[x,\$y]','str')) # string, because the only $ is escaped '[x,$y]' >>> print(Param('[x,\ $y]','str')) # improper escape -> code [x,\ y] >>> print(Param('/$[x,y]','str')) # improper escape -> code /[x,y] >>> print(Param('[\$x,$y]','str')) # code, python syntax error [$x,y] >>> print(Param('["\$x",$y]','str') # ... python syntax ok ["$x",y] >>> print(Param("'$a'",'str')) # code, with the code being a string 'a' >>> print(Param("'\$a'",'str')) # str, with the str containing a str "'$a'" >>> print(Param('$$$$$myPathologicalVa$$$$$rName','str')) myPathologicalVarName >>> print(Param('\$$$$$myPathologicalVa$$$$$rName','str')) $myPathologicalVarName >>> print(Param('$$$$\$myPathologicalVa$$$$$rName','str')) $myPathologicalVarName >>> print(Param('$$$$\$$$myPathologicalVa$$$\$$$rName','str')) $myPathologicalVa$rName """ def __init__(self, val, valType, inputType=None, allowedVals=None, allowedTypes=None, hint="", label="", updates=None, allowedUpdates=None, allowedLabels=None, direct=True, canBePath=True, ctrlParams=None, categ="Basic"): """ Parameters ---------- val : any The value for this parameter valType : str The type of this parameter, one of: - str: A string, will be compiled with " around it - extendedStr: A long string, will be compiled with " around it and linebreaks will be preserved - code: Some code, will be compiled verbatim or translated to JS (no ") - extendedCode: A block of code, will be compiled verbatim or translated to JS and linebreaks will be preserved - file: A file path, will be compiled like str but will replace unescaped \ with / - list: A list of values, will be compiled like code but if there's no [] or () then these are added Note that, if value begins with a $, it will always be treated as code regardless of valType inputType : str The type of control to make for this parameter in Builder, one of: - single: A single-line text control - multi: A multi-line text control - color: A single-line text control with a button to open the color picker - survey: A single-line text control with a button to open Pavlovia surveys list - file: A single-line text control with a button to open a file browser - fileList: Several file controls with buttons to add/remove - table: A file control with an additional button to open in Excel - choice: A single-choice control (dropdown) - multiChoice: A multi-choice control (tickboxes) - richChoice: A single-choice control (dropdown) with rich text for each option - bool: A single checkbox control - dict: Several key:value pair controls with buttons to add/remove fields allowedVals : list[str] Possible vals for this param (e.g. units param can only be 'norm','pix',...), these are used in the compiled code allowedLabels : list[str] or None Labels corresponding to each value in allowedVals, these are displayed in Builder but not used in the compiled code. Leave as None to simply copy allowedVals. hint : str Tooltip to display when param is hovered over label : str Label to display next to param updates : str How often does this parameter update, usually one of: - constant: Value is set just the once - set every repeat: Value is set at the start of each Routine - set every frame: Value is set each frame allowedUpdates : list[str] List of values to show in the choice control for updates. direct : bool Are we expecting the value of this param to directly appear in the compiled code? Mostly used by the test suite to check that params which should be used are used. canBePath : bool Is it possible for this parameter to be a path? Setting to False will disable filepath sanitization (e.g. for textbox you may not want to replace \ with /) ctrlParams : dict Extra information to pass to the control, such as the Excel template file to use in a `table` control. categ : str Category (tab) under which this param appears in Builder. Deprecated params ----------------- allowedTypes """ super(Param, self).__init__() self.label = label self.val = val self.valType = valType self.allowedTypes = allowedTypes or [] self.hint = hint self.updates = updates self.allowedUpdates = allowedUpdates self.allowedVals = allowedVals or [] self.allowedLabels = allowedLabels or [] self.staticUpdater = None self.categ = categ self.readOnly = False self.codeWanted = False self.canBePath = canBePath self.direct = direct self.ctrlParams = ctrlParams or {} self.plugin = None if inputType: self.inputType = inputType elif valType in inputDefaults: self.inputType = inputDefaults[valType] else: self.inputType = "String" def __str__(self): if self.valType == 'num': if self.val in [None, ""]: return "None" try: # will work if it can be represented as a float return "{}".format(float(self.val)) except Exception: # might be an array return "%s" % self.val elif self.valType == 'int': try: return "%i" % self.val # int and float -> str(int) except TypeError: return "%s" % self.val # try array of float instead? elif self.valType in ['extendedStr','str', 'file', 'table']: # at least 1 non-escaped '$' anywhere --> code wanted # return str if code wanted # return repr if str wanted; this neatly handles "it's" and 'He # says "hello"' val = self.val if isinstance(self.val, str): valid, val = self.dollarSyntax() if self.codeWanted and valid: # If code is wanted, return code (translated to JS if needed) if utils.scriptTarget == 'PsychoJS': valJS = py2js.expression2js(val) if self.val != valJS: logging.debug("Rewriting with py2js: {} -> {}".format(self.val, valJS)) return valJS else: return val else: # If str is wanted, return literal if utils.scriptTarget != 'PsychoPy': if val.startswith("u'") or val.startswith('u"'): # if target is python2.x then unicode will be u'something' # but for other targets that will raise an annoying error val = val[1:] # If param is a path or pathlike use Path to make sure it's valid (with / not \) isPathLike = bool(re.findall(r"[\\/](?!\W)", val)) if self.valType in ['file', 'table'] or (isPathLike and self.canBePath): val = val.replace("\\\\", "/") val = val.replace("\\", "/") # Hide escape char on escaped $ (other escaped chars are handled by wx but $ is unique to us) val = re.sub(r"\\\$", "$", val) # Replace line breaks with escaped line break character val = re.sub("\n", "\\n", val) return repr(val) return repr(self.val) elif self.valType in ['code', 'extendedCode']: isStr = isinstance(self.val, str) if isStr and self.val.startswith("$"): # a $ in a code parameter is unnecessary so remove it val = "%s" % self.val[1:] elif isStr and self.val.startswith(r"\$"): # the user actually wanted just the $ val = "%s" % self.val[1:] elif isStr: val = "%s" % self.val else: # if val was a tuple it needs converting to a string first val = "%s" % repr(self.val) if utils.scriptTarget == "PsychoJS": if self.valType == 'code': valJS = py2js.expression2js(val) elif self.valType == 'extendedCode': valJS = py2js.snippet2js(val) if val != valJS: logging.debug("Rewriting with py2js: {} -> {}".format(val, valJS)) return valJS else: return val elif self.valType == 'color': _, val = self.dollarSyntax() if self.codeWanted: # Handle code return val elif "," in val: # Handle lists (e.g. RGB, HSV, etc.) val = toList(val) return "{}".format(val) else: # Otherwise, treat as string return repr(val) elif self.valType == 'list': valid, val = self.dollarSyntax() val = toList(val) return "{}".format(val) elif self.valType == 'fixedList': return "{}".format(self.val) elif self.valType == 'fileList': return "{}".format(self.val) elif self.valType == 'bool': if utils.scriptTarget == "PsychoJS": return ("%s" % self.val).lower() # make True -> "true" else: return "%s" % self.val elif self.valType == "table": return "%s" % self.val elif self.valType == "color": if re.match(r"\$", self.val): return self.val.strip('$') else: return f"\"{self.val}\"" elif self.valType == "dict": return str(self.val) else: raise TypeError("Can't represent a Param of type %s" % self.valType) def __repr__(self): return f"<Param: val={self.val}, valType={self.valType}>" def __eq__(self, other): """Test for equivalence is needed for Params because what really typically want to test is whether the val is the same """ return self.val == other def __ne__(self, other): """Test for (non)equivalence is needed for Params because what really typically want to test is whether the val is the same/different """ return self.val != other def __bool__(self): """Return a bool, so we can do `if thisParam` rather than `if thisParam.val`""" if self.val in ['True', 'true', 'TRUE', True, 1, 1.0]: # return True for aliases of True return True if self.val in ['False', 'false', 'FALSE', False, 0, 0.0]: # return False for aliases of False return False if self.val in ['None', 'none', None, ""]: # return False for aliases of None return False # if not a clear alias, use bool method of value return bool(self.val) def copy(self): """ Create a copy of this Param object """ return Param( val=self.val, valType=self.valType, inputType=self.inputType, allowedVals=self.allowedVals, allowedTypes=self.allowedTypes, hint=self.hint, label=self.label, updates=self.updates, allowedUpdates=self.allowedUpdates, allowedLabels=self.allowedLabels, direct=self.direct, canBePath=self.canBePath, categ=self.categ ) def __deepcopy__(self, memo): return self.copy() @property def _xml(self): # Make root element element = Element('Param') # Assign values if hasattr(self, 'val'): element.set('val', u"{}".format(self.val).replace("\n", "&#10;")) if hasattr(self, 'valType'): element.set('valType', self.valType) if hasattr(self, 'updates'): element.set('updates', "{}".format(self.updates)) if hasattr(self, 'plugin') and self.plugin is not None: element.set('plugin', "{}".format(self.plugin)) return element def dollarSyntax(self): """ Interpret string according to dollar syntax, return: 1: Whether syntax is valid (True/False) 2: Whether code is wanted (True/False) 3: The value, stripped of any unnecessary $ """ val = self.val if self.valType in ['extendedStr','str', 'file', 'table', 'color', 'list']: # How to handle dollar signs in a string param self.codeWanted = str(val).startswith("$") if not re.search(r"\$", str(val)): # Return if there are no $ return True, val if self.codeWanted: # If value begins with an unescaped $, remove the first char and treat the rest as code val = val[1:] inComment = "".join(re.findall(r"\#.*", val)) inQuotes = "".join(re.findall("[\'\"][^\"|^\']*[\'\"]", val)) if not re.findall(r"\$", val): # Return if there are no further dollar signs return True, val if len(re.findall(r"\$", val)) == len(re.findall(r"\$", inComment)): # Return if all $ are commented out return True, val if len(re.findall(r"\$", val)) - len(re.findall(r"\$", inComment)) == len(re.findall(r"\$", inQuotes)): # Return if all non-commended $ are in strings return True, val else: # If value does not begin with an unescaped $, treat it as a string if not re.findall(r"(?<!\\)\$", val): # Return if all $ are escaped (\$) return True, val else: # If valType does not interact with $, return True return True, val # Return false if method has not returned yet return False, val __nonzero__ = __bool__ # for python2 compatibility class Partial(functools.partial): """ Value to supply to `allowedVals` or `allowedLabels` which contains a reference to a method and arguments to use when populating the control. Parameters ---------- method : method Method to call, should return the values to be used in the relevant control. args : tuple, list Array of positional arguments. To use the value of another parameter, supply a handle to its Param object. kwargs : dict Dict of keyword arguments. To use the value of another parameter, supply a handle to its Param object. """ def __init__(self, method, args=(), kwargs=dict()): self.method = method self.args = args self.kwargs = kwargs def getCodeFromParamStr(val, target=None): """Convert a Param.val string to its intended python code (as triggered by special char $) """ # Substitute target if target is None: target = utils.scriptTarget # remove leading $, if any tmp = re.sub(r"^(\$)+", '', val) # remove all nonescaped $, squash $$$$$ tmp2 = re.sub(r"([^\\])(\$)+", r"\1", tmp) out = re.sub(r"[\\]\$", '$', tmp2) # remove \ from all \$ if target == 'PsychoJS': out = py2js.expression2js(out) return out if out else '' def toList(val): """ Parameters ---------- val Returns ------- A list of entries in the string value """ if isinstance(val, (list, tuple, ndarray)): return val # already a list. Nothing to do if isinstance(val, (int, float)): return [val] # single value, just needs putting in a cell # we really just need to check if they need parentheses stripped = val.strip() if utils.scriptTarget == "PsychoJS": return py2js.expression2js(stripped) elif (stripped.startswith('(') and stripped.endswith(')')) or (stripped.startswith('[') and stripped.endswith(']')): return stripped elif utils.valid_var_re.fullmatch(stripped): return "{}".format(stripped) else: return "[{}]".format(stripped)
19,992
Python
.py
458
33.218341
160
0.564745
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,576
flow.py
psychopy_psychopy/psychopy/experiment/flow.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). """Describes the Flow of an experiment """ from xml.etree.ElementTree import Element from psychopy.experiment import getAllStandaloneRoutines from psychopy.experiment.routines._base import Routine, BaseStandaloneRoutine from psychopy.experiment.loops import LoopTerminator, LoopInitiator from psychopy.tools import filetools as ft from psychopy.preferences import prefs class Flow(list): """The flow of the experiment is a list of L{Routine}s, L{LoopInitiator}s and L{LoopTerminator}s, that will define the order in which events occur """ def __init__(self, exp): list.__init__(self) self.exp = exp self._currentRoutine = None self._loopList = [] # will be used while we write the code self._loopController = {'LoopInitiator': [], 'LoopTerminator': []} # Controls whether loop is written @property def loopDict(self): """Creates a tree of the Flow: {entry:object, children:list, parent:object} :return: """ loopDict = {} currentList = [] loopStack = [currentList] for thisEntry in self: if thisEntry.getType() == 'LoopInitiator': currentList.append(thisEntry.loop) # this loop is child of current loopDict[thisEntry.loop] = [] # and is (current) empty list awaiting children currentList = loopDict[thisEntry.loop] loopStack.append(loopDict[thisEntry.loop]) # update the list of loops (for depth) elif thisEntry.getType() == 'LoopTerminator': loopStack.pop() currentList = loopStack[-1] else: # routines should be added to current currentList.append(thisEntry) return loopDict def __repr__(self): return "psychopy.experiment.Flow(%s)" % (str(list(self))) @property def _xml(self): # Make root element element = Element("Flow") # Add an element for every Routine, Loop Initiator, Loop Terminator for item in self: sub = item._xml if isinstance(item, Routine) or isinstance(item, BaseStandaloneRoutine): # Remove all sub elements (we only need its name) comps = [comp for comp in sub] for comp in comps: sub.remove(comp) element.append(sub) return element def getUniqueEntries(self): """ Get all entries on the flow, without duplicate entries. """ # array to store entries in entries = [] # iterate through all entries for entry in self: # append if not present if entry not in entries: entries.append(entry) return entries def addLoop(self, loop, startPos, endPos): """Adds initiator and terminator objects for the loop into the Flow list""" self.insert(int(endPos), LoopTerminator(loop)) self.insert(int(startPos), LoopInitiator(loop)) self.exp.requirePsychopyLibs(['data']) # needed for TrialHandlers etc def addRoutine(self, newRoutine, pos): """Adds the routine to the Flow list""" self.insert(int(pos), newRoutine) def removeComponent(self, component, id=None): """Removes a Loop, LoopTerminator or Routine from the flow For a Loop (or initiator or terminator) to be deleted we can simply remove the object using normal list syntax. For a Routine there may be more than one instance in the Flow, so either choose which one by specifying the id, or all instances will be removed (suitable if the Routine has been deleted). """ if component.getType() in ['LoopInitiator', 'LoopTerminator']: component = component.loop # and then continue to do the next handlers = ('StairHandler', 'TrialHandler', 'MultiStairHandler') if component.getType() in handlers: # we need to remove the loop's termination points toBeRemoved = [] for comp in self: # bad to change the contents of self when looping through self if comp.getType() in ['LoopInitiator', 'LoopTerminator']: if comp.loop == component: # self.remove(comp) --> skips over loop terminator if # its an empty loop toBeRemoved.append(comp) for comp in toBeRemoved: self.remove(comp) elif component.getType() in ['Routine'] + list(getAllStandaloneRoutines()): if id is None: # a Routine may come up multiple times - remove them all # self.remove(component) # can't do this - two empty routines # (with diff names) look the same to list comparison toBeRemoved = [] for id, compInFlow in enumerate(self): if (hasattr(compInFlow, 'name') and component.name == compInFlow.name): toBeRemoved.append(id) # need to delete from the end backwards or the order changes toBeRemoved.reverse() for id in toBeRemoved: del self[id] else: # just delete the single entry we were given (e.g. from # right-click in GUI) del self[id] def integrityCheck(self): """Check that the flow makes sense together and check each component""" # force monitor to reload for checks (ie. in case monitor has changed) self.exp.settings._monitor = None # No checks currently made on flow itself trailingWhitespace = [] constWarnings = [] for entry in self: if hasattr(entry, "integrityCheck"): entry.integrityCheck() # Now check each routine/loop # NB each entry is a routine or LoopInitiator/Terminator if not isinstance(entry, Routine): continue # TODO: the following tests of dubiousConstantUpdates should be # moved into the alerts mechanism under the comp.integrityCheck() for component in entry: # detect and strip trailing whitespace (can cause problems): for key in component.params: field = component.params[key] if not hasattr(field, 'label'): continue # no problem, no warning if (field.label.lower() in ['text', 'customize'] or field.valType not in ('str', 'code')): continue if (isinstance(field.val, str) and field.val != field.val.strip()): trailingWhitespace.append( (field.val, key, component, entry)) field.val = field.val.strip() # detect 'constant update' fields that seem intended to be # dynamic: for field, key in component._dubiousConstantUpdates(): if field: constWarnings.append( (field.val, key, component, entry)) if trailingWhitespace: warnings = [] msg = '"%s", in Routine %s (%s: %s)' for field, key, component, routine in trailingWhitespace: vals = (field, routine.params['name'], component.params['name'], key.capitalize()) warnings.append(msg % vals) print('Note: Trailing white-space removed:\n ', end='') # non-redundant, order unknown print('\n '.join(list(set(warnings)))) if constWarnings: warnings = [] msg = '"%s", in Routine %s (%s: %s)' for field, key, component, routine in constWarnings: vals = (field, routine.params['name'], component.params['name'], key.capitalize()) warnings.append(msg % vals) print('Note: Dynamic code seems intended but updating ' 'is "constant":\n ', end='') # non-redundant, order unknown print('\n '.join(list(set(warnings)))) def writePreCode(self, script): """Write the code that comes before the Window is created """ script.writeIndentedLines("\n# Start Code - component code to be " "run before the window creation\n") for entry in self: # NB each entry is a routine or LoopInitiator/Terminator self._currentRoutine = entry # very few components need writeStartCode: if hasattr(entry, 'writePreCode'): entry.writePreCode(script) def writeStartCode(self, script): """Write the code that comes after the Window is created """ script.writeIndentedLines("\n# Start Code - component code to be " "run after the window creation\n") for entry in self: # NB each entry is a routine or LoopInitiator/Terminator self._currentRoutine = entry # very few components need writeStartCode: if hasattr(entry, 'writeStartCode'): entry.writeStartCode(script) def writeBody(self, script): """Write the rest of the code """ # Open function def code = ( '\n' 'def run(expInfo, thisExp, win, globalClock=None, thisSession=None):\n' ' """\n' ' Run the experiment flow.\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' ' psychopy.visual.Window\n' ' Window in which to run this experiment.\n' ' globalClock : psychopy.core.clock.Clock or None\n' ' Clock to get global time from - supply None to make a new one.\n' ' thisSession : psychopy.session.Session or None\n' ' Handle of the Session object this experiment is being run from, if any.\n' ' """\n' ) script.writeIndentedLines(code) script.setIndentLevel(+1, relative=True) # start rush mode if self.exp.settings.params['rush']: code = ( "# enter 'rush' mode (raise CPU priority)\n" ) # put inside an if statement if rush can be overwritten by piloting if prefs.piloting['forceNonRush']: code += ( "if not PILOTING:\n" " " ) code += ( "core.rush(enable=True)\n" ) script.writeIndentedLines(code) # initialisation code = ( "# mark experiment as started\n" "thisExp.status = STARTED\n" "# make sure window is set to foreground to prevent losing focus\n" "win.winHandle.activate()\n" "# make sure variables created by exec are available globally\n" "exec = environmenttools.setExecEnvironment(globals())\n" "# get device handles from dict of input devices\n" "ioServer = deviceManager.ioServer\n" "# get/create a default keyboard (e.g. to check for escape)\n" "defaultKeyboard = deviceManager.getDevice('defaultKeyboard')\n" "if defaultKeyboard is None:\n" " deviceManager.addDevice(\n" " deviceClass='keyboard', deviceName='defaultKeyboard', backend=%(keyboardBackend)s\n" " )\n" "eyetracker = deviceManager.getDevice('eyetracker')\n" "# make sure we're running in the directory for this experiment\n" "os.chdir(_thisDir)\n" "# get filename from ExperimentHandler for convenience\n" "filename = thisExp.dataFileName\n" "frameTolerance = 0.001 # how close to onset before 'same' frame\n" "endExpNow = False # flag for 'escape' or other condition => quit the exp\n" ) script.writeIndentedLines(code % self.exp.settings.params) # get frame dur from frame rate code = ( "# get frame duration from frame rate in expInfo\n" "if 'frameRate' in expInfo and expInfo['frameRate'] is not None:\n" " frameDur = 1.0 / round(expInfo['frameRate'])\n" "else:\n" " frameDur = 1.0 / 60.0 # could not measure, so guess\n" ) script.writeIndentedLines(code) # writes any components with a writeStartCode() self.writeStartCode(script) # writeStartCode and writeInitCode: for entry in self: # NB each entry is a routine or LoopInitiator/Terminator self._currentRoutine = entry if hasattr(entry, 'writeRunOnceInitCode'): entry.writeRunOnceInitCode(script) entry.writeInitCode(script) # create clocks (after initialising stimuli) code = ("\n" "# create some handy timers\n" "\n" "# global clock to track the time since experiment started\n" "if globalClock is None:\n" " # create a clock if not given one\n" " globalClock = core.Clock()\n" "if isinstance(globalClock, str):\n" " # if given a string, make a clock accoridng to it\n" " if globalClock == 'float':\n" " # get timestamps as a simple value\n" " globalClock = core.Clock(format='float')\n" " elif globalClock == 'iso':\n" " # get timestamps in ISO format\n" " globalClock = core.Clock(format='%Y-%m-%d_%H:%M:%S.%f%z')\n" " else:\n" " # get timestamps in a custom format\n" " globalClock = core.Clock(format=globalClock)\n" "if ioServer is not None:\n" " ioServer.syncClock(globalClock)\n" "logging.setDefaultClock(globalClock)\n" "# routine timer to track time remaining of each (possibly non-slip) routine\n" "routineTimer = core.Clock()\n" "win.flip() # flip window to reset last flip timer\n" "# store the exact time the global clock started\n" "expInfo['expStart'] = data.getDateStr(\n" " format='%Y-%m-%d %Hh%M.%S.%f %z', fractionalSecondDigits=6\n" ")\n" ) script.writeIndentedLines(code) # run-time code for entry in self: self._currentRoutine = entry entry.writeMainCode(script) if hasattr(entry, "writeRoutineEndCode"): entry.writeRoutineEndCode(script) # tear-down code (very few components need this) for entry in self: self._currentRoutine = entry entry.writeExperimentEndCode(script) # Mark as finished code = ( "\n" "# mark experiment as finished\n" "endExperiment(thisExp, win=win)\n" ) script.writeIndentedLines(code) # end rush mode if self.exp.settings.params['rush']: code = ( "# end 'rush' mode\n" "core.rush(enable=False)\n" ) script.writeIndentedLines(code) # Exit function def script.setIndentLevel(-1, relative=True) script.writeIndentedLines("\n") def writeFlowSchedulerJS(self, script): """Initialise each component and then write the per-frame code too """ # handle email for error messages if 'email' in self.exp.settings.params and self.exp.settings.params['email'].val: code = ("// If there is an error, we should inform the participant and email the experimenter\n" "// note: we use window.onerror rather than a try/catch as the latter\n" "// do not handle so well exceptions thrown asynchronously\n" "/*window.onerror = function(message, source, lineno, colno, error) {\n" " console.error(error);\n" " psychoJS.gui.dialog({'error' : error});\n" " //psychoJS.core.sendErrorToExperimenter(exception);\n" " // show error stack on console:\n" " var json = JSON.parse(error);\n" " console.error(json.stack);\n" " return true;\n" "}*/\n") script.writeIndentedLines(code) code = ("// schedule the experiment:\n" "psychoJS.schedule(psychoJS.gui.DlgFromDict({\n" " dictionary: expInfo,\n" " title: expName\n}));\n" "\n" "const flowScheduler = new Scheduler(psychoJS);\n" "const dialogCancelScheduler = new Scheduler(psychoJS);\n" "psychoJS.scheduleCondition(function() { return (psychoJS.gui.dialogComponent.button === 'OK'); }," "flowScheduler, dialogCancelScheduler);\n" "\n") script.writeIndentedLines(code) code = ("// flowScheduler gets run if the participants presses OK\n" "flowScheduler.add(updateInfo); // add timeStamp\n" "flowScheduler.add(experimentInit);\n") script.writeIndentedLines(code) loopStack = [] for thisEntry in self: if not loopStack: # if not currently in a loop if thisEntry.getType() == 'LoopInitiator': code = ("const {name}LoopScheduler = new Scheduler(psychoJS);\n" "flowScheduler.add({name}LoopBegin({name}LoopScheduler));\n" "flowScheduler.add({name}LoopScheduler);\n" "flowScheduler.add({name}LoopEnd);\n" .format(name=thisEntry.loop.params['name'].val)) loopStack.append(thisEntry.loop) elif isinstance(thisEntry, (Routine, BaseStandaloneRoutine)): code = ("flowScheduler.add({params[name]}RoutineBegin());\n" "flowScheduler.add({params[name]}RoutineEachFrame());\n" "flowScheduler.add({params[name]}RoutineEnd());\n" .format(params=thisEntry.params)) else: # we are already in a loop so don't code here just count code = "" if thisEntry.getType() == 'LoopInitiator': loopStack.append(thisEntry.loop) elif thisEntry.getType() == 'LoopTerminator': loopStack.remove(thisEntry.loop) script.writeIndentedLines(code) # quit when all routines are finished code = ( "flowScheduler.add(quitPsychoJS, %(End Message)s, true);\n" ) script.writeIndentedLines(code % self.exp.settings.params) # handled all the flow entries code = ( "\n" "// quit if user presses Cancel in dialog box:\n" "dialogCancelScheduler.add(quitPsychoJS, %(End Message)s, false);\n" "\n" ) script.writeIndentedLines(code % self.exp.settings.params) # Write resource list resourceFiles = [] for resource in self.exp.getResourceFiles(): if isinstance(resource, dict): # Get name if "https://" in resource: name = resource.split('/')[-1] elif 'surveyId' in resource: name = 'surveyId' elif 'name' in resource and resource['name'] in list(ft.defaultStim): name = resource['name'] elif 'rel' in resource: name = resource['rel'] else: name = "" # Get resource resourceFile = None if 'rel' in resource: # If resource is a file path, add its relative path resourceFile = resource['rel'].replace("\\", "/") elif 'surveyId' in resource: # If resource is a survey ID, add it and mark as a survey id resourceFile = "sid:" + resource['surveyId'] # If we have a resource, add it if resourceFile is not None: resourceFiles.append((name, resourceFile)) if self.exp.htmlFolder: resourceFolderStr = "resources/" else: resourceFolderStr = "" # start PsychoJS script.writeIndented("psychoJS.start({\n") script.setIndentLevel(1, relative=True) script.writeIndentedLines("expName: expName,\n" "expInfo: expInfo,\n") # if we have an html folder then we moved files there so just use that # if not, then we'll need to list all known resource files if not self.exp.htmlFolder: script.writeIndentedLines("resources: [\n") script.setIndentLevel(1, relative=True) # do we need to load surveys? needsSurveys = False for rt in self: if hasattr(rt, "type") and rt.type == "PavloviaSurvey": needsSurveys = True if needsSurveys: script.writeIndentedLines( "// libraries:\n" "{'surveyLibrary': true},\n" ) code = "// resources:\n" for name, resource in resourceFiles: if "sid:" in resource: # Strip sid prefix from survey id resource = resource.replace("sid:", "") # Add this line code += f"{{'surveyId': '{resource}'}},\n" else: if "https://" in resource: # URL paths are already fine pass else: # Anything else make it relative to resources folder resource = resourceFolderStr + resource # Add this line code += f"{{'name': '{name}', 'path': '{resource}'}},\n" script.writeIndentedLines(code) script.setIndentLevel(-1, relative=True) script.writeIndented("]\n") script.setIndentLevel(-1, relative=True) script.writeIndented("});\n\n") def writeLoopHandlerJS(self, script, modular): """ Function for setting up handler to look after randomisation of conditions etc """ # Then on the flow we need only the Loop Init/terminate for entry in self: loopType = entry.getType() # Get type i.e., routine or loop if loopType in self._loopController: loopName = entry.loop.params['name'].val # Get loop name if loopName not in self._loopController[loopType]: # Write if not already written entry.writeMainCodeJS(script, modular) # will either be function trialsBegin() or trialsEnd() self._loopController[loopType].append(loopName) def _resetLoopController(self): """Resets _loopController so loops are written on each call to write script""" self._loopController = {'LoopInitiator': [], 'LoopTerminator': []} # Controls whether loop is written
24,641
Python
.py
501
35.219561
115
0.553214
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,577
py2js.py
psychopy_psychopy/psychopy/experiment/py2js.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). """Converting code parameters and components from python (PsychoPy) to JS (ES6/PsychoJS) """ import ast from pathlib import Path import astunparse import esprima from os import path from psychopy import logging from io import StringIO from psychopy.experiment.py2js_transpiler import translatePythonToJavaScript class TupleTransformer(ast.NodeTransformer): """ An ast subclass that walks the abstract syntax tree and allows modification of nodes. This class transforms a tuple to a list. :returns node """ def visit_Tuple(self, node): return ast.List(node.elts, node.ctx) class Unparser(astunparse.Unparser): """astunparser had buried the future_imports option underneath its init() so we need to override that method and change it.""" def __init__(self, tree, file): """Unparser(tree, file=sys.stdout) -> None. Print the source for tree to file.""" self.f = file self.future_imports = ['unicode_literals'] self._indent = 0 self.dispatch(tree) self.f.flush() def unparse(tree): v = StringIO() Unparser(tree, file=v) return v.getvalue() def expression2js(expr): """Convert a short expression (e.g. a Component Parameter) Python to JS""" # if the code contains a tuple (anywhere), convert parenths to be list. # This now works for compounds like `(2*(4, 5))` where the inner # parenths becomes a list and the outer parens indicate priority. # This works by running an ast transformer class to swap the contents of the tuple # into a list for the number of tuples in the expression. try: syntaxTree = ast.parse(expr) except Exception: try: syntaxTree = ast.parse(str(expr)) except Exception as err: logging.error(err) return str(expr) for node in ast.walk(syntaxTree): TupleTransformer().visit(node) # Transform tuples to list # for py2 using 'unicode_literals' we don't want if isinstance(node, ast.Str) and type(node.s)==bytes: node.s = str(node.s, 'utf-8') elif isinstance(node, ast.Str) and node.s.startswith("u'"): node.s = node.s[1:] if isinstance(node, ast.Name): if node.id == 'undefined': continue jsStr = unparse(syntaxTree).strip() if not any(ch in jsStr for ch in ("=",";","\n")): try: jsStr = translatePythonToJavaScript(jsStr) if jsStr.endswith(';\n'): jsStr = jsStr[:-2] except: # If translation fails, just use old translation pass return jsStr def snippet2js(expr): """Convert several lines (e.g. a Code Component) Python to JS""" # for now this is just adding ';' onto each line ending so will fail on # most code (e.g. if... for... will certainly fail) # do nothing for now return expr def findUndeclaredVariables(ast, allUndeclaredVariables): """Detect undeclared variables """ undeclaredVariables = [] for expression in ast: if expression.type == 'ExpressionStatement': expression = expression.expression if expression.type == 'AssignmentExpression' and expression.operator == '=' and expression.left.type == 'Identifier': variableName = expression.left.name if variableName not in allUndeclaredVariables: undeclaredVariables.append(variableName) allUndeclaredVariables.append(variableName) elif expression.type == 'IfStatement': if expression.consequent.body is None: consequentVariables = findUndeclaredVariables( [expression.consequent], allUndeclaredVariables) else: consequentVariables = findUndeclaredVariables( expression.consequent.body, allUndeclaredVariables) undeclaredVariables.extend(consequentVariables) elif expression.type == "ReturnStatement": if expression.argument.type == "FunctionExpression": consequentVariables = findUndeclaredVariables( expression.argument.body.body, allUndeclaredVariables) undeclaredVariables.extend(consequentVariables) return undeclaredVariables def addVariableDeclarations(inputProgram, fileName): """Transform the input program by adding just before each function a declaration for its undeclared variables """ # parse Javascript code into abstract syntax tree: # NB: esprima: https://media.readthedocs.org/pdf/esprima/4.0/esprima.pdf fileName = Path(str(fileName)) try: ast = esprima.parseScript(inputProgram, {'range': True, 'tolerant': True}) except esprima.error_handler.Error as err: if fileName: logging.error(f"Error parsing JS in {fileName.name}:\n{err}") else: logging.error(f"Error parsing JS: {err}") logging.flush() return inputProgram # So JS can be written to file # find undeclared vars in functions and declare them before the function outputProgram = inputProgram offset = 0 allUndeclaredVariables = [] for expression in ast.body: if expression.type == 'FunctionDeclaration': # find all undeclared variables: undeclaredVariables = findUndeclaredVariables(expression.body.body, allUndeclaredVariables) # add declarations (var) just before the function: funSpacing = ['', '\n'][len(undeclaredVariables) > 0] # for consistent function spacing declaration = funSpacing + '\n'.join(['var ' + variable + ';' for variable in undeclaredVariables]) + '\n' startIndex = expression.range[0] + offset outputProgram = outputProgram[ :startIndex] + declaration + outputProgram[ startIndex:] offset += len(declaration) return outputProgram if __name__ == '__main__': for expr in ['sin(t)', 't*5', '(3, 4)', '(5*-2)', # tuple and not tuple '(1,(2,3), (1,2,3), (-4,-5,-6))', '2*(2, 3)', # combinations '[1, (2*2)]', # List with nested operations returns list + nested tuple '(.7, .7)', # A tuple returns list '(-.7, .7)', # A tuple with unary operators returns nested lists '[-.7, -.7]', # A list with unary operators returns list with nested tuple '[-.7, (-.7 * 7)]']: # List with unary operators and nested tuple with operations returns list + tuple print("{} -> {}".format(repr(expr), repr(expression2js(expr))))
7,115
Python
.py
151
37.536424
129
0.631852
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,578
py2js_transpiler.py
psychopy_psychopy/psychopy/experiment/py2js_transpiler.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). import ast import sys import re try: from metapensiero.pj.api import translates except ImportError: pass # metapensiero not installed import astunparse namesJS = { 'sin': 'Math.sin', 'cos': 'Math.cos', 'tan': 'Math.tan', 'pi': 'Math.PI', 'rand': 'Math.random', 'random': 'Math.random', 'sqrt': 'Math.sqrt', 'abs': 'Math.abs', 'floor': 'Math.floor', 'ceil': 'Math.ceil', 'randint': 'util.randint', 'range': 'util.range', 'randchoice': 'util.randchoice', 'round': 'util.round', # better than Math.round, supports n DPs arg 'sum': 'util.sum', } class psychoJSTransformer(ast.NodeTransformer): """PsychoJS-specific AST transformer """ def visit_Name(self, node): if node.id in namesJS: node.id = namesJS[node.id] # status = STOPPED --> status = PsychoJS.Status.STOPPED if node.id in ['STARTED', 'FINISHED', 'STOPPED'] and isinstance(node.ctx, ast.Load): return ast.copy_location( ast.Attribute( value=ast.Attribute( value=ast.Name(id='PsychoJS', ctx=ast.Load()), attr='Status', ctx=ast.Load() ), attr=node.id, ctx=ast.Load() ), node) # thisExp --> psychoJS.experiment elif node.id == 'thisExp' and isinstance(node.ctx, ast.Load): return ast.Attribute( value=ast.Name(id='psychoJS', ctx=ast.Load()), attr='experiment', ctx=ast.Load() ) # win --> psychoJS.window elif node.id == 'win' and isinstance(node.ctx, ast.Load): return ast.Attribute( value=ast.Name(id='psychoJS', ctx=ast.Load()), attr='window', ctx=ast.Load() ) # event --> psychoJS.eventManager elif node.id == 'event' and isinstance(node.ctx, ast.Load): return ast.Attribute( value=ast.Name(id='psychoJS', ctx=ast.Load()), attr='eventManager', ctx=ast.Load() ) # _thisDir --> '.' elif node.id == '_thisDir' and isinstance(node.ctx, ast.Load): return ast.Constant( value='.', kind=None ) # return the node by default: return node def visit_Attribute(self, node): node.value = psychoJSTransformer().visit(node.value) if isinstance(node.value, ast.Name): # os.sep --> '/' if node.value.id == 'os' and node.attr == 'sep': return ast.Constant( value='/', kind=None ) # return the node by default: return node class pythonTransformer(ast.NodeTransformer): """Python-specific AST transformer """ # operations from the math python module or builtin operations that exist in JavaScript Math: directMathOperations = ['abs', 'min', 'max', 'round', 'ceil', 'fabs', 'floor', 'trunc', 'exp', 'log', 'log2', 'pow', 'sqrt', 'acos', 'asin', 'atan2', 'cos', 'sin', 'tan', 'acosh', 'asinh', 'atanh', 'cosh', 'sinh', 'tanh', 'random'] # operation from the math python module or builtin operations that are available # in util/Util.js: utilOperations = ['sum', 'average', 'randint', 'range', 'sort', 'shuffle', 'randchoice', 'pad', 'Clock'] def visit_BinOp(self, node): # transform the left and right arguments of the binary operation: node.left = pythonTransformer().visit(node.left) node.right = pythonTransformer().visit(node.right) # formatted strings with % # note: we have extended the pythong syntax slightly, to accommodate both tuples and lists # so both '%_%' % (1,2) and '%_%' % [1,2] are successfully transpiled if isinstance(node.op, ast.Mod) and isinstance(node.left, ast.Str): # transform the node into an f-string node: stringFormat = node.left.value stringTuple = node.right.elts if ( isinstance(node.right, ast.Tuple) or isinstance(node.right, ast.List))\ else [node.right] values = [] tupleIndex = 0 while True: # TODO deal with more complicated formats, such as %.3f match = re.search(r'%.', stringFormat) if match is None: break values.append(ast.Constant(value=stringFormat[0:match.span(0)[0]], kind=None)) values.append( self.visit_FormattedValue( ast.FormattedValue( value=stringTuple[tupleIndex], conversion=-1, format_spec=None ) ) ) stringFormat = stringFormat[match.span(0)[1]:] tupleIndex += 1 return ast.JoinedStr(values) return node def visit_FormattedValue(self, node): # unformatted f-strings: if not node.format_spec: return node # formatted f-strings: if isinstance(node.format_spec, ast.JoinedStr) and len(node.format_spec.values) > 0 and isinstance( node.format_spec.values[0], ast.Str): # split the format: format = node.format_spec.values[0].s match = re.search(r"([0-9]*).([0-9]+)(f|i)", format) if not match: raise Exception(format + ' format is not currently supported') matchGroups = match.groups() width = matchGroups[0] width = int(width) if width != '' else 1 precision = matchGroups[1] precision = int(precision) if precision != '' else 1 conversion = matchGroups[2] value = node.value # prepare the conversion: conversionFunc = ast.Call( func=ast.Attribute( value=ast.Name(id='Number', ctx=ast.Load()), attr='parseFloat' if conversion == 'f' else 'parseInt', ctx=ast.Load() ), args=[value], keywords=[] ) # deal with precision: precisionCall = ast.Call( func=ast.Attribute( value=conversionFunc, attr='toFixed', ctx=ast.Load() ), args=[ast.Constant(value=precision, kind=None)], keywords=[] ) # deal with width: widthCall = ast.Call( func=ast.Name(id='pad', ctx=ast.Load()), args=[precisionCall, ast.Constant(value=width, kind=None)], keywords=[] ) # return the node: node.value = self.visit_Call(widthCall) node.conversion = -1 node.format_spec = None return node raise Exception('formatted f-string are not all supported at the moment') def visit_Call(self, node): # transform the node arguments: nbArgs = len(node.args) for i in range(0, nbArgs): node.args[i] = pythonTransformer().visit(node.args[i]) # transform the node func: node.func = pythonTransformer().visit(node.func) # substitutable transformation, e.g. Vector.append(5) --> Vector.push(5): if isinstance(node.func, ast.Attribute): # and isinstance(node.func.value, ast.Name): substitutedNode = self.substitutionTransform(node.func, node.args, node.keywords) if substitutedNode: return substitutedNode # operations with module prefix, e.g. a = math.fabs(-1.2) if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name): prefix = node.func.value.id attribute = node.func.attr if prefix == 'math': mathNode = self.mathTransform(attribute, node.args) if mathNode: return mathNode elif prefix == 'core': utilNode = self.utilTransform(attribute, node.args) if utilNode: return utilNode # operations without prefix: if isinstance(node.func, ast.Name): attribute = node.func.id # check whether this is a math operation: mathNode = self.mathTransform(attribute, node.args) if mathNode: return mathNode # check whether we have code for it in util/Util: utilNode = self.utilTransform(attribute, node.args) if utilNode: return utilNode # string.format(args): if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Str) and node.func.attr == 'format': raise Exception('format() is not supported at the moment, please use f-strings instead') # return the node by default: return node def substitutionTransform(self, func, args, keywords): # Substitutions where only the function name changes (see below) functionSubsJS = { 'lower': 'toLowerCase', 'append': 'push', 'upper': 'toUpperCase', 'extend': 'concat', } # Substitions that become util functions utilSubsJS = [ 'index', 'count' ] # Substitutions where only the function name changes # Examples: # a = 'HELLO' # a.lower() --> a.toLowerCase() # # a = [1,2,3] # a.append(4) --> a.push(4) # # a = 'hello # a.upper() --> a.toUpperCase() # # a = [1,2,3] # a.extend([4, 5, 6]) --> a.concat([4, 5, 6]) if func.attr in functionSubsJS: func.attr = functionSubsJS[func.attr] return ast.Call( func=func, args=args, keywords=[] ) # Substitutions where the function is changed to a util.function and the original value becomes an argument # a = [1,2,3] # a.index(2) --> util.index(a,2) # value=Call(func=Attribute(value=Name(id='a', ctx=Load()), attr='index', ctx=Load()), args=[Num(n=2)], keywords=[]) # value=Call(func=Attribute(value=Name(id='util', ctx=Load()), attr='index', ctx=Load()), args=[Name(id='a', ctx=Load()), Num(n=2)], keywords=[]) # # a = [1,2,3] # a.count(2) --> util.count(a,2) # value=Call(func=Attribute(value=Name(id='a', ctx=Load()), attr='count', ctx=Load()), args=[Num(n=2)], keywords=[]) # value=Call(func=Attribute(value=Name(id='util', ctx=Load()), attr='count', ctx=Load()), args=[Name(id='a', ctx=Load()), Num(n=2)], keywords=[]) elif func.attr in utilSubsJS: value = func.value func.value = ast.Name(id='util', ctx=ast.Load()) args = [value, args] return ast.Call( func=func, args=args, keywords=[] ) # Substitutions where more than one of the function, value, and arguments change # a = [1,2,3] # a.pop(2) -> a.splice(2, 1); # a.pop() -> a.splice(-1, 1); # The second argument of splice is the number of elements to delete; pass 1 for functionality equivalent to pop. # The default first argument for pop is -1 (remove the last item). elif func.attr == 'pop': func.attr = 'splice' # if no args, construct an index that's `<name>.length-1` if not args: args = ast.BinOp( ast.Attribute(value=func.value, attr="length"), ast.Sub(), ast.Constant(1, kind="int") ) # add 1 as a second argument so the last item is deleted args = [args, [ast.Constant(value=1, kind=None)]] return ast.Call( func=func, args=args, keywords=[] ) # a = [1, 2, 3, 4] # a.insert(0, 5) -> a.splice(0, 0, 5); # Note that .insert only inserts a single element, so there should always be exactly two input args). elif func.attr == 'insert': func.attr = 'splice' args = [args[0], [ast.Constant(value=0, kind=None)], args[1]] return ast.Call( func=func, args=args, keywords=[] ) # a = ['This', 'is', 'a', 'test'] # ' '.join(a) -> a.join(" "); # In this case func.value and args need to be switched. elif func.attr == 'join': new_args = [ast.Constant(value=func.value.value, kind=None)] func.value = args[0] return ast.Call( func=func, args=new_args, keywords=[] ) # a = "This is a test" # a.split() -> a.split(" ") # Note that this function translates correctly if there's an input arg; only the default requires modification. elif func.attr == 'split' and not args: args = [ast.Constant(value=" ", kind=None)] return ast.Call( func=func, args=args, keywords=[] ) # a = [3, 7, 9, 0, 1, 5] # a.sort(reverse=True) -> a.reverse() # This one only needs adjustment if the reverse=True keyword argument is included. elif func.attr == 'sort' and keywords and keywords[0].arg == 'reverse' and keywords[0].value.value: func.attr = 'reverse' return ast.Call( func=func, args=[], keywords=[] ) # Substitutions where the value on which the function is performed (not the function itself) changes elif isinstance(func.value, ast.Name): # webbrowser.open('https://pavlovia.org') --> window.open('https://pavlovia.org') if func.value.id == 'webbrowser': func.value.id = 'window' return ast.Call( func=func, args=args, keywords=[] ) return None def utilTransform(self, attribute, args): # operations from the math python module or builtin operations that are available # in util/Util.js: if attribute in self.utilOperations: func = ast.Attribute( value=ast.Name(id='util', ctx=ast.Load()), attr=attribute, ctx=ast.Load() ) return ast.Call( func=func, args=args, keywords=[] ) def mathTransform(self, attribute, args): # operations from the math python module or builtin operations that exist in JavaScript Math: if attribute in self.directMathOperations: func = ast.Attribute( value=ast.Name(id='Math', ctx=ast.Load()), attr=attribute, ctx=ast.Load() ) return ast.Call( func=func, args=args, keywords=[] ) class pythonAddonVisitor(ast.NodeVisitor): # operations that require an addon: addonOperations = ['list'] def __init__(self): self.addons = [] def visit_Call(self, node): if isinstance(node.func, ast.Name) and node.func.id in self.addonOperations: self.addons.append(node.func.id) def transformNode(astNode): """Transform the input AST Args: astNode (ast.Node): the input AST Returns: ast.Node: transformed AST """ # deal with PsychoJS specific changes: psychoJSTransformedNode = psychoJSTransformer().visit(astNode) # deal with python specific changes: pythonBuiltinTransformedNode = pythonTransformer().visit(psychoJSTransformedNode) # look for operations requiring an addon: visitor = pythonAddonVisitor() visitor.visit(psychoJSTransformedNode) return pythonBuiltinTransformedNode, visitor.addons def transformPsychoJsCode(psychoJsCode, addons, namespace=[]): """Transform the input PsychoJS code. Args: psychoJsCode (str): the input PsychoJS JavaScript code namespace (list): list of varnames which are already defined Returns: (str) the transformed code """ transformedPsychoJSCode = '' # add addons on a need-for basis: if 'list' in addons: transformedPsychoJSCode += """ // add-on: list(s: string): string[] function list(s) { // if s is a string, we return a list of its characters if (typeof s === 'string') return s.split(''); else // otherwise we return s: return s; } """ for index, thisLine in enumerate(psychoJsCode.splitlines()): include = True # remove the initial variable declarations, unless it is for _pj: if index == 0 and thisLine.find('var _pj;') == 0: transformedPsychoJSCode = 'var _pj;\n' continue # Remove var defs if variable is defined earlier in experiment if thisLine.startswith("var "): # Get var names varNames = thisLine[4:-1].split(", ") validVarNames = [] for varName in varNames: if namespace is not None and varName not in namespace: # If var name not is already in namespace, keep it in validVarNames.append(varName) # If there are no var names left, remove statement altogether if not len(validVarNames): include = False # Recombine line thisLine = f"var {', '.join(validVarNames)};" # Append line if include: transformedPsychoJSCode += thisLine transformedPsychoJSCode += '\n' return transformedPsychoJSCode def translatePythonToJavaScript(psychoPyCode, namespace=[]): """Translate PsychoPy python code into PsychoJS JavaScript code. Args: psychoPyCode (str): the input PsychoPy python code namespace (list, None): list of varnames which are already defined Returns: str: the PsychoJS JavaScript code Raises: (Exception): whenever a step of the translation process failed """ # get the Abstract Syntax Tree (AST) # this checks that the code is valid python try: astNode = ast.parse(psychoPyCode) # print('>>> AST node: ' + ast.dump(astNode)) except Exception as error: raise Exception('unable to parse the PsychoPy code into an abstract syntax tree: ' + str(error)) # transform the AST by making PsychoJS-specific substitutions and dealing with python built-ins: try: transformedAstNode, addons = transformNode(astNode) # print('>>> transformed AST node: ' + ast.dump(transformedAstNode)) # print('>>> addons: ' + str(addons)) except Exception as error: raise Exception('unable to transform the abstract syntax tree: ' + str(error)) # turn the transformed AST into code: try: transformedPsychoPyCode = astunparse.unparse(transformedAstNode) # print('>>> transformed PsychoPy code:\n' + transformedPsychoPyCode) except Exception as error: raise Exception('unable to turn the transformed abstract syntax tree back into code: ' + str(error)) # translate the python code into JavaScript code: try: psychoJsCode, psychoJsSourceMap = translates(transformedPsychoPyCode, enable_es6=True) # print('>>> PsychoJS code:\n' + psychoJsCode) except Exception as error: raise Exception( 'unable to translate the transformed PsychoPy code into PsychoJS JavaScript code: ' + str(error)) # transform the JavaScript code: try: transformedPsychoJsCode = transformPsychoJsCode(psychoJsCode, addons, namespace=namespace) except Exception as error: raise Exception('unable to transform the PsychoJS JavaScript code: ' + str(error)) return transformedPsychoJsCode def main(argv=None): """Read PsychoPy code from the command line and translate it into PsychoJS code. """ # other read PsychoPy code from the command line: print('Enter PsychoPY code (finish with Ctrl+Z):') psychoPyCode = sys.stdin.read() # translate it to PsychoJS: psychoJSCode = translatePythonToJavaScript(psychoPyCode) print('>>> translated PsychoJS code:\n' + psychoJSCode) if __name__ == "__main__": main()
21,501
Python
.py
504
31.035714
153
0.560213
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,579
utils.py
psychopy_psychopy/psychopy/experiment/utils.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). """Utility functions to support Experiment classes """ import re # this needs to be accessed from __str__ method of Param scriptTarget = "PsychoPy" # predefine some regex's; deepcopy complains if do in NameSpace.__init__() unescapedDollarSign_re = re.compile(r"^\$|[^\\]\$") # detect "code wanted" valid_var_re = re.compile(r"^[a-zA-Z_][\w]*$") # filter for legal var names nonalphanumeric_re = re.compile(r'\W') # will match all bad var name chars list_like_re = re.compile(r"(?<!\\),") # will match for strings which could be a list class CodeGenerationException(Exception): """ Exception thrown by a component when it is unable to generate its code. """ def __init__(self, source, message=""): super(CodeGenerationException, self).__init__() self.source = source self.message = message def __str__(self): return "{}: ".format(self.source, self.message) def canBeNumeric(inStr): """Determines whether the input can be converted to a float (using a try: float(instr)) """ try: float(inStr) return True except Exception: return False
1,372
Python
.py
34
36.235294
86
0.679217
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,580
__init__.py
psychopy_psychopy/psychopy/experiment/__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). """Experiment classes: Experiment, Flow, Routine, Param, Loop*, *Handlers, and NameSpace The code that writes out a *_lastrun.py experiment file is (in order): experiment.Experiment.writeScript() - starts things off, calls other parts settings.SettingsComponent.writeStartCode() experiment.Flow.writeBody() which will call the .writeBody() methods from each component settings.SettingsComponent.writeEndCode() """ from .params import getCodeFromParamStr, Param from .components import getInitVals, getComponents, getAllComponents from .routines import getAllStandaloneRoutines from ._experiment import Experiment from .utils import unescapedDollarSign_re, valid_var_re, nonalphanumeric_re from psychopy.experiment.utils import CodeGenerationException def getAllElements(fetchIcons=True): """ Get all components and all standalone routines """ comps = getAllComponents(fetchIcons=fetchIcons) rts = getAllStandaloneRoutines(fetchIcons=fetchIcons) comps.update(rts) return comps def getAllCategories(): """ Get all categories which components and standalone routines can be sorted into """ categories = [] # For each component/standalone routine... for name, thisComp in getAllElements().items(): for thisCat in thisComp.categories: # If category is not already present, append it if thisCat not in categories: categories.append(thisCat) return categories
1,727
Python
.py
41
37.560976
79
0.75358
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,581
localization.py
psychopy_psychopy/psychopy/experiment/localization.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). """These are probably going to get used a lot so translate them once and reuse """ from psychopy.localization import _translate
359
Python
.py
8
43.5
79
0.758621
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,582
loops.py
psychopy_psychopy/psychopy/experiment/loops.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). """Experiment classes: Experiment, Flow, Routine, Param, Loop*, *Handlers, and NameSpace The code that writes out a *_lastrun.py experiment file is (in order): experiment.Experiment.writeScript() - starts things off, calls other parts settings.SettingsComponent.writeStartCode() experiment.Flow.writeBody() which will call the .writeBody() methods from each component settings.SettingsComponent.writeEndCode() """ from copy import deepcopy from pathlib import Path from xml.etree.ElementTree import Element from psychopy.experiment import getInitVals from psychopy.localization import _translate from psychopy.experiment.params import Param from .components import getInitVals, getAllComponents class _BaseLoopHandler: def writeInitCode(self, buff): # no longer needed - initialise the trial handler just before it runs pass def writeInitCodeJS(self, buff): pass def writeLoopEndIterationCodeJS(self, buff): """Ends this iteration of a loop (calling nextEntry if needed)""" endLoopInteration = (f"\nfunction {self.name}LoopEndIteration(scheduler, snapshot) {{\n" " // ------Prepare for next entry------\n" " return async function () {\n") # check if the loop has ended prematurely and stop() if needed endLoopInteration += ( " if (typeof snapshot !== 'undefined') {\n" " // ------Check if user ended loop early------\n" " if (snapshot.finished) {\n" " // Check for and save orphaned data\n" " if (psychoJS.experiment.isEntryEmpty()) {\n" " psychoJS.experiment.nextEntry(snapshot);\n" " }\n" " scheduler.stop();\n") # if isTrials then always perform experiment.nextEntry if self.params['isTrials']: endLoopInteration += ( " } else {\n" " psychoJS.experiment.nextEntry(snapshot);\n") # then always close the loop and return NEXT to scheduler endLoopInteration += ( " }\n" " return Scheduler.Event.NEXT;\n" " }\n" " };\n" "}\n") buff.writeIndentedLines(endLoopInteration) class TrialHandler(_BaseLoopHandler): """A looping experimental control object (e.g. generating a psychopy TrialHandler or StairHandler). """ def __init__(self, exp, name, loopType='random', nReps=5, conditions=(), conditionsFile='', endPoints=(0, 1), randomSeed='', selectedRows='', isTrials=True): """ @param name: name of the loop e.g. trials @type name: string @param loopType: @type loopType: string ('rand', 'seq') @param nReps: number of reps (for all conditions) @type nReps:int @param conditions: list of different trial conditions to be used @type conditions: list (of dicts?) @param conditionsFile: filename of the .csv file that contains conditions info @type conditions: string (filename) """ super(TrialHandler, self).__init__() self.type = 'TrialHandler' self.exp = exp self.order = ['name'] # make name come first (others don't matter) self.params = {} self.params['name'] = Param( name, valType='code', inputType="single", updates=None, allowedUpdates=None, label=_translate('Name'), hint=_translate("Name of this loop")) self.params['nReps'] = Param( nReps, valType='num', inputType="spin", updates=None, allowedUpdates=None, label=_translate('Num. repeats'), hint=_translate("Number of repeats (for each condition)")) self.params['conditions'] = Param( list(conditions), valType='str', inputType="single", updates=None, allowedUpdates=None, label=_translate('Conditions'), hint=_translate("A list of dictionaries describing the " "parameters in each condition")) self.params['conditionsFile'] = Param( conditionsFile, valType='file', inputType="table", updates=None, allowedUpdates=None, label=_translate('Conditions'), hint=_translate("Name of a file specifying the parameters for " "each condition (.csv, .xlsx, or .pkl). Browse " "to select a file. Right-click to preview file " "contents, or create a new file."), ctrlParams={ 'template': Path(__file__).parent / "loopTemplate.xltx" } ) self.params['endPoints'] = Param( list(endPoints), valType='num', inputType="single", updates=None, allowedUpdates=None, label=_translate('End points'), hint=_translate("The start and end of the loop (see flow " "timeline)")) self.params['Selected rows'] = Param( selectedRows, valType='str', inputType="single", updates=None, allowedUpdates=None, label=_translate('Selected rows'), hint=_translate("Select just a subset of rows from your condition" " file (the first is 0 not 1!). Examples: 0, " "0:5, 5:-1")) # NB staircase is added for the sake of the loop properties dialog: self.params['loopType'] = Param( loopType, valType='str', inputType="choice", allowedVals=['random', 'sequential', 'fullRandom', 'staircase', 'interleaved staircases'], label=_translate('Loop type'), hint=_translate("How should the next condition value(s) be " "chosen?")) self.params['random seed'] = Param( randomSeed, valType='code', inputType="single", updates=None, allowedUpdates=None, label=_translate('Random seed'), hint=_translate("To have a fixed random sequence provide an " "integer of your choosing here. Leave blank to " "have a new random sequence on each run of the " "experiment.")) self.params['isTrials'] = Param( isTrials, valType='bool', inputType="bool", updates=None, allowedUpdates=None, label=_translate("Is trials"), hint=_translate("Indicates that this loop generates TRIALS, " "rather than BLOCKS of trials or stimuli within " "a trial. It alters how data files are output")) def writeLoopStartCode(self, buff): """Write the code to create and run a sequence of trials """ # first create the handler init values inits = getInitVals(self.params) # import conditions from file? if self.params['conditionsFile'].val in ['None', None, 'none', '']: inits['trialList'] = ( "[None]" ) elif self.params['Selected rows'].val in ['None', None, 'none', '']: # just a conditions file with no sub-selection inits['trialList'] = ( "data.importConditions(%(conditionsFile)s)" ) % inits else: # a subset of a conditions file inits['trialList'] = ( "data.importConditions(\n" " %(conditionsFile)s, \n" " selection=%(Selected rows)s\n" ")\n" ) % inits # also a 'thisName' for use in "for thisTrial in trials:" makeLoopIndex = self.exp.namespace.makeLoopIndex self.thisName = inits['loopIndex'] = makeLoopIndex(self.params['name'].val) # write the code code = ( "\n" "# set up handler to look after randomisation of conditions etc\n" "%(name)s = data.TrialHandler2(\n" " name='%(name)s',\n" " nReps=%(nReps)s, \n" " method=%(loopType)s, \n" " extraInfo=expInfo, \n" " originPath=-1, \n" " trialList=%(trialList)s, \n" " seed=%(random seed)s, \n" ")\n" ) buff.writeIndentedLines(code % inits) code = ( "thisExp.addLoop(%(name)s) # add the loop to the experiment\n" "%(loopIndex)s = %(name)s.trialList[0] # so we can initialise stimuli with some values\n" ) buff.writeIndentedLines(code % inits) # unclutter the namespace if not self.exp.prefsBuilder['unclutteredNamespace']: code = ("# abbreviate parameter names if possible (e.g. rgb = %(name)s.rgb)\n" "if %(name)s != None:\n" " for paramName in %(name)s:\n" " globals()[paramName] = %(name)s[paramName]\n") buff.writeIndentedLines(code % {'name': self.thisName}) # send data to Liaison before loop starts if self.params['isTrials'].val: buff.writeIndentedLines( "if thisSession is not None:\n" " # if running in a Session with a Liaison client, send data up to now\n" " thisSession.sendExperimentData()\n" ) # then run the trials loop code = "\nfor %s in %s:\n" buff.writeIndentedLines(code % (self.thisName, self.params['name'])) buff.setIndentLevel(1, relative=True) # mark current trial as started code = ( "%(name)s.status = STARTED\n" "if hasattr(%(loopIndex)s, 'status'):\n" " %(loopIndex)s.status = STARTED\n" ) buff.writeIndentedLines(code % inits) # fetch parameter info from conditions code = ( "currentLoop = %(name)s\n" "thisExp.timestampOnFlip(win, 'thisRow.t', format=globalClock.format)\n" ) buff.writeIndentedLines(code % self.params) # send data to Liaison at start of each iteration if self.params['isTrials'].val: buff.writeIndentedLines( "if thisSession is not None:\n" " # if running in a Session with a Liaison client, send data up to now\n" " thisSession.sendExperimentData()\n" ) # unclutter the namespace if not self.exp.prefsBuilder['unclutteredNamespace']: code = ("# abbreviate parameter names if possible (e.g. rgb = %(name)s.rgb)\n" "if %(name)s != None:\n" " for paramName in %(name)s:\n" " globals()[paramName] = %(name)s[paramName]\n") buff.writeIndentedLines(code % {'name': self.thisName}) def writeLoopStartCodeJS(self, buff, modular): """Write the code to create and run a sequence of trials """ # some useful variables # create the variable "thisTrial" from "trials" makeLoopIndex = self.exp.namespace.makeLoopIndex self.thisName = makeLoopIndex(self.params['name'].val) # Convert filepath separator conditionsFile = self.params['conditionsFile'].val self.params['conditionsFile'].val = conditionsFile.replace('\\\\', '/').replace('\\', '/') # seed might be undefined seed = self.params['random seed'].val or 'undefined' if self.params['conditionsFile'].val in ['None', None, 'none', '']: trialList='undefined' elif self.params['Selected rows'].val in ['None', None, 'none', '']: trialList = self.params['conditionsFile'] else: trialList = ("TrialHandler.importConditions" "(psychoJS.serverManager, {}, {})" ).format(self.params['conditionsFile'], self.params['Selected rows']) nReps = self.params['nReps'].val if nReps in ['None', None, 'none', '']: nReps = 'undefined' elif isinstance(nReps, str): nReps = nReps.strip("$") code = ("\nfunction {loopName}LoopBegin({loopName}LoopScheduler, snapshot) {{\n" " return async function() {{\n" .format(loopName=self.params['name'], loopType=(self.params['loopType'].val).upper(), nReps=nReps, trialList=trialList, seed=seed)) buff.writeIndentedLines(code) buff.setIndentLevel(2, relative=True) code = ("TrialHandler.fromSnapshot(snapshot); // update internal variables (.thisN etc) of the loop\n\n" "// set up handler to look after randomisation of conditions etc\n" "{loopName} = new TrialHandler({{\n" " psychoJS: psychoJS,\n" " nReps: {nReps}, method: TrialHandler.Method.{loopType},\n" " extraInfo: expInfo, originPath: undefined,\n" " trialList: {trialList},\n" " seed: {seed}, name: '{loopName}'\n" "}});\n" "psychoJS.experiment.addLoop({loopName}); // add the loop to the experiment\n" "currentLoop = {loopName}; // we're now the current loop\n" .format(loopName=self.params['name'], loopType=(self.params['loopType'].val).upper(), nReps=nReps, trialList=trialList, seed=seed)) buff.writeIndentedLines(code) # for the scheduler if modular: code = ("\n// Schedule all the trials in the trialList:\n" "for (const {thisName} of {loopName}) {{\n" " snapshot = {loopName}.getSnapshot();\n" " {loopName}LoopScheduler.add(importConditions(snapshot));\n") else: code = ("\n// Schedule all the trials in the trialList:\n" "{loopName}.forEach(function() {{\n" " snapshot = {loopName}.getSnapshot();\n\n" " {loopName}LoopScheduler.add(importConditions(snapshot));\n") buff.writeIndentedLines(code.format(loopName=self.params['name'], thisName=self.thisName)) # then we need to include begin, eachFrame and end code for each entry within that loop loopDict = self.exp.flow.loopDict thisLoop = loopDict[self] # dict containing lists of children code = "" for thisChild in thisLoop: if isinstance(thisChild, (LoopInitiator, _BaseLoopHandler)): # for a LoopInitiator code += ( " const {childName}LoopScheduler = new Scheduler(psychoJS);\n" " {loopName}LoopScheduler.add({childName}LoopBegin({childName}LoopScheduler, snapshot));\n" " {loopName}LoopScheduler.add({childName}LoopScheduler);\n" " {loopName}LoopScheduler.add({childName}LoopEnd);\n" .format(childName=thisChild.params['name'], loopName=self.params['name']) ) else: code += ( " {loopName}LoopScheduler.add({childName}RoutineBegin(snapshot));\n" " {loopName}LoopScheduler.add({childName}RoutineEachFrame());\n" " {loopName}LoopScheduler.add({childName}RoutineEnd(snapshot));\n" .format(childName=thisChild.params['name'], loopName=self.params['name']) ) code += " {loopName}LoopScheduler.add({loopName}LoopEndIteration({loopName}LoopScheduler, snapshot));\n" code += "}}%s\n" % ([');', ''][modular]) code += ("\n" "return Scheduler.Event.NEXT;\n") buff.writeIndentedLines(code.format(loopName=self.params['name'])) buff.setIndentLevel(-2, relative=True) buff.writeIndentedLines( " }\n" "}\n" ) def writeLoopEndCode(self, buff): # copy params so we can safely add to it params = self.params.copy() # add param for current trial name params['thisName'] = self.thisName # mark current trial as finished at end of each iteration code = ( "# mark %(thisName)s as finished\n" "if hasattr(%(thisName)s, 'status'):\n" " %(thisName)s.status = FINISHED\n" "# if awaiting a pause, pause now\n" "if %(name)s.status == PAUSED:\n" " thisExp.status = PAUSED\n" " pauseExperiment(\n" " thisExp=thisExp, \n" " win=win, \n" " timers=[globalClock], \n" " )\n" " # once done pausing, restore running status\n" " %(name)s.status = STARTED" ) buff.writeIndentedLines(code % params) # just within the loop advance data line if loop is whole trials if self.params['isTrials'].val == True: buff.writeIndentedLines( "thisExp.nextEntry()\n" "\n" ) # end of the loop. dedent buff.setIndentLevel(-1, relative=True) # mark finished code = ( "# completed %(nReps)s repeats of '%(name)s'\n" "%(name)s.status = FINISHED\n" "\n" ) buff.writeIndentedLines(code % params) # save data if self.params['isTrials'].val: # send final data to Liaison buff.writeIndentedLines( "if thisSession is not None:\n" " # if running in a Session with a Liaison client, send data up to now\n" " thisSession.sendExperimentData()\n" ) # a string to show all the available variables (if the conditions # isn't just None or [None]) saveExcel = self.exp.settings.params['Save excel file'].val saveCSV = self.exp.settings.params['Save csv file'].val # get parameter names if saveExcel or saveCSV: code = ("# get names of stimulus parameters\n" "if %(name)s.trialList in ([], [None], None):\n" " params = []\n" "else:\n" " params = %(name)s.trialList[0].keys()\n") buff.writeIndentedLines(code % self.params) # write out each type of file if saveExcel or saveCSV: buff.writeIndented("# save data for this loop\n") if saveExcel: code = ("%(name)s.saveAsExcel(filename + '.xlsx', sheetName='%(name)s',\n" " stimOut=params,\n" " dataOut=['n','all_mean','all_std', 'all_raw'])\n") buff.writeIndentedLines(code % self.params) if saveCSV: code = ("%(name)s.saveAsText(filename + '%(name)s.csv', " "delim=',',\n" " stimOut=params,\n" " dataOut=['n','all_mean','all_std', 'all_raw'])\n") buff.writeIndentedLines(code % self.params) def writeLoopEndCodeJS(self, buff): code = ( "\n" "async function %(name)sLoopEnd() {\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(1, relative=True) code = ( "// terminate loop\n" "psychoJS.experiment.removeLoop(%(name)s);\n" "// update the current loop from the ExperimentHandler\n" "if (psychoJS.experiment._unfinishedLoops.length>0)\n" " currentLoop = psychoJS.experiment._unfinishedLoops.at(-1);\n" "else\n" " currentLoop = psychoJS.experiment; // so we use addData from the experiment\n" "return Scheduler.Event.NEXT;\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ( "}" ) buff.writeIndentedLines(code % self.params) def getType(self): return 'TrialHandler' @property def name(self): return self.params['name'].val class StairHandler(_BaseLoopHandler): """A staircase experimental control object. """ def __init__(self, exp, name, nReps='50', startVal='', nReversals='', nUp=1, nDown=3, minVal=0, maxVal=1, stepSizes='[4,4,2,2,1]', stepType='db', endPoints=(0, 1), isTrials=True): """ @param name: name of the loop e.g. trials @type name: string @param nReps: number of reps (for all conditions) @type nReps:int """ super(StairHandler, self).__init__() self.type = 'StairHandler' self.exp = exp self.order = ['name'] # make name come first (others don't matter) self.children = [] self.params = {} self.params['name'] = Param( name, valType='code', hint=_translate("Name of this loop"), label=_translate('Name')) self.params['nReps'] = Param( nReps, valType='num', inputType='spin', label=_translate('nReps'), hint=_translate("(Minimum) number of trials in the staircase")) self.params['start value'] = Param( startVal, valType='num', inputType='single', label=_translate('Start value'), hint=_translate("The initial value of the parameter")) self.params['max value'] = Param( maxVal, valType='num', inputType='single', label=_translate('Max value'), hint=_translate("The maximum value the parameter can take")) self.params['min value'] = Param( minVal, valType='num', inputType='single', label=_translate('Min value'), hint=_translate("The minimum value the parameter can take")) self.params['step sizes'] = Param( stepSizes, valType='list', inputType='single', label=_translate('Step sizes'), hint=_translate("The size of the jump at each step (can change" " on each 'reversal')")) self.params['step type'] = Param( stepType, valType='str', inputType='choice', allowedVals=['lin', 'log', 'db'], label=_translate('Step type'), hint=_translate("The units of the step size (e.g. 'linear' will" " add/subtract that value each step, whereas " "'log' will ad that many log units)")) self.params['N up'] = Param( nUp, valType='num', inputType='spin', label=_translate('N up'), hint=_translate("The number of 'incorrect' answers before the " "value goes up")) self.params['N down'] = Param( nDown, valType='num', inputType='spin', label=_translate('N down'), hint=_translate("The number of 'correct' answers before the " "value goes down")) self.params['N reversals'] = Param( nReversals, valType='num', inputType='spin', label=_translate('N reversals'), hint=_translate("Minimum number of times the staircase must " "change direction before ending")) # these two are really just for making the dialog easier (they won't # be used to generate code) self.params['loopType'] = Param( 'staircase', valType='str', inputType='choice', allowedVals=['random', 'sequential', 'fullRandom', 'staircase', 'interleaved staircases'], label=_translate('Loop type'), hint=_translate("How should the next trial value(s) be chosen?")) # NB this is added for the sake of the loop properties dialog self.params['endPoints'] = Param( list(endPoints), valType='num', inputType='spin', label=_translate('End points'), hint=_translate('Where to loop from and to (see values currently' ' shown in the flow view)')) self.params['isTrials'] = Param( isTrials, valType='bool', inputType='bool', updates=None, allowedUpdates=None, label=_translate("Is trials"), hint=_translate("Indicates that this loop generates TRIALS, " "rather than BLOCKS of trials or stimuli within" " a trial. It alters how data files are output")) @property def name(self): return self.params['name'].val def writeInitCode(self, buff): # not needed - initialise the staircase only when needed pass def writeLoopStartCode(self, buff): # create the staircase # also a 'thisName' for use in "for thisTrial in trials:" makeLoopIndex = self.exp.namespace.makeLoopIndex self.thisName = makeLoopIndex(self.params['name'].val) if self.params['N reversals'].val in ("", None, 'None'): self.params['N reversals'].val = '0' # write the code code = ('\n# --------Prepare to start Staircase "%(name)s" --------\n' "# set up handler to look after next chosen value etc\n" "%(name)s = data.StairHandler(startVal=%(start value)s, extraInfo=expInfo,\n" " stepSizes=%(step sizes)s, stepType=%(step type)s,\n" " nReversals=%(N reversals)s, nTrials=%(nReps)s, \n" " nUp=%(N up)s, nDown=%(N down)s,\n" " minVal=%(min value)s, maxVal=%(max value)s,\n" " originPath=-1, name='%(name)s')\n" "thisExp.addLoop(%(name)s) # add the loop to the experiment") buff.writeIndentedLines(code % self.params) code = "level = %s = %s # initialise some vals\n" buff.writeIndented(code % (self.thisName, self.params['start value'])) # then run the trials # work out a name for e.g. thisTrial in trials: code = "\nfor %s in %s:\n" buff.writeIndentedLines(code % (self.thisName, self.params['name'])) buff.setIndentLevel(1, relative=True) code = ( "currentLoop = %(name)s\n" "thisExp.timestampOnFlip(win, 'thisRow.t', format=globalClock.format)\n" ) buff.writeIndentedLines(code % self.params) buff.writeIndented("level = %s\n" % self.thisName) def writeLoopEndCode(self, buff): # Just within the loop advance data line if loop is whole trials if self.params['isTrials'].val: buff.writeIndentedLines( "thisExp.nextEntry()\n" "\n" "if thisSession is not None:\n" " # if running in a Session with a Liaison client, send data up to now\n" " thisSession.sendExperimentData()\n" ) # end of the loop. dedent buff.setIndentLevel(-1, relative=True) buff.writeIndented("# staircase completed\n") buff.writeIndented("\n") # save data if self.params['isTrials'].val: if self.exp.settings.params['Save excel file'].val: code = ("%(name)s.saveAsExcel(filename + '.xlsx'," " sheetName='%(name)s')\n") buff.writeIndented(code % self.params) if self.exp.settings.params['Save csv file'].val: code = ("%(name)s.saveAsText(filename + " "'%(name)s.csv', delim=',')\n") buff.writeIndented(code % self.params) def getType(self): return 'StairHandler' class MultiStairHandler(_BaseLoopHandler): """To handle multiple interleaved staircases """ def __init__(self, exp, name, nReps='50', stairType='simple', switchStairs='random', conditions=(), conditionsFile='', endPoints=(0, 1), isTrials=True): """ @param name: name of the loop e.g. trials @type name: string @param nReps: number of reps (for all conditions) @type nReps:int """ super(MultiStairHandler, self).__init__() self.type = 'MultiStairHandler' self.exp = exp self.order = ['name'] # make name come first self.params = {} self.params['name'] = Param( name, valType='code', inputType='single', label=_translate('Name'), hint=_translate("Name of this loop")) self.params['nReps'] = Param( nReps, valType='num', inputType='spin', label=_translate('nReps'), hint=_translate("(Minimum) number of trials in *each* staircase")) self.params['stairType'] = Param( stairType, valType='str', inputType='choice', allowedVals=['simple', 'QUEST', 'questplus'], label=_translate('Stair type'), hint=_translate("How to select the next staircase to run")) self.params['switchMethod'] = Param( switchStairs, valType='str', inputType='choice', allowedVals=['random', 'sequential', 'fullRandom'], label=_translate('Switch method'), hint=_translate("How to select the next staircase to run")) # these two are really just for making the dialog easier (they won't # be used to generate code) self.params['loopType'] = Param( 'staircase', valType='str', inputType='choice', allowedVals=['random', 'sequential', 'fullRandom', 'staircase', 'interleaved staircases'], label=_translate('Loop type'), hint=_translate("How should the next trial value(s) be chosen?")) self.params['endPoints'] = Param( list(endPoints), valType='num', inputType='spin', label=_translate('End points'), hint=_translate('Where to loop from and to (see values currently' ' shown in the flow view)')) self.params['conditions'] = Param( list(conditions), valType='list', inputType='single', updates=None, allowedUpdates=None, label=_translate('Conditions'), hint=_translate("A list of dictionaries describing the " "differences between each staircase")) def getTemplate(): """ Method to get the template for this loop's chosen stair type. This is specified as a method rather than a simple value as the control needs to update its target according to the current value of stairType. Returns ------- pathlib.Path Path to the appropriate template file """ # root folder root = Path(__file__).parent # get file path according to stairType param if self.params['stairType'] == "QUEST": return root / "questTemplate.xltx" elif self.params['stairType'] == "questplus": return root / "questPlusTemplate.xltx" else: return root / "staircaseTemplate.xltx" self.params['conditionsFile'] = Param( conditionsFile, valType='file', inputType='table', updates=None, allowedUpdates=None, label=_translate('Conditions'), hint=_translate("An xlsx or csv file specifying the parameters " "for each condition"), ctrlParams={ 'template': getTemplate } ) self.params['isTrials'] = Param( isTrials, valType='bool', inputType='bool', updates=None, allowedUpdates=None, label=_translate("Is trials"), hint=_translate("Indicates that this loop generates TRIALS, " "rather than BLOCKS of trials or stimuli within " "a trial. It alters how data files are output")) pass # don't initialise at start of exp, create when needed @property def name(self): return self.params['name'].val def writeLoopStartCode(self, buff): # create a 'thisName' for use in "for thisTrial in trials:" makeLoopIndex = self.exp.namespace.makeLoopIndex self.thisName = makeLoopIndex(self.params['name'].val) # create the MultistairHander code = ("\n# set up handler to look after randomisation of trials etc\n" "conditions = data.importConditions(%(conditionsFile)s)\n" "%(name)s = data.MultiStairHandler(stairType=%(stairType)s, " "name='%(name)s',\n" " nTrials=%(nReps)s,\n" " conditions=conditions,\n" " method=%(switchMethod)s,\n" " originPath=-1)\n" "thisExp.addLoop(%(name)s) # add the loop to the experiment\n" "# initialise values for first condition\n" "level = %(name)s._nextIntensity # initialise some vals\n" "condition = %(name)s.currentStaircase.condition\n" # start the loop: "\nfor level, condition in %(name)s:\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(1, relative=True) code = ( "currentLoop = %(name)s\n" "thisExp.timestampOnFlip(win, 'thisRow.t', format=globalClock.format)\n" ) buff.writeIndentedLines(code % self.params) # uncluttered namespace if not self.exp.prefsBuilder['unclutteredNamespace']: code = ("# abbreviate parameter names if possible (e.g. " "rgb=condition.rgb)\n" "for paramName in condition:\n" " globals()[paramName] = condition[paramName]\n") buff.writeIndentedLines(code) def writeLoopStartCodeJS(self, buff, modular): inits = deepcopy(self.params) # For JS, stairType needs to be code inits['stairType'].valType = "code" # Method needs to be code and upper inits['switchMethod'].valType = "code" inits['switchMethod'].val = inits['switchMethod'].val.upper() code = ( "\nfunction %(name)sLoopBegin(%(name)sLoopScheduler, snapshot) {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "return async function() {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "// setup a MultiStairTrialHandler\n" "%(name)sConditions = TrialHandler.importConditions(psychoJS.serverManager, %(conditionsFile)s);\n" "%(name)s = new data.MultiStairHandler({stairType:MultiStairHandler.StaircaseType.%(stairType)s, \n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "psychoJS: psychoJS,\n" "name: '%(name)s',\n" "varName: 'intensity',\n" "nTrials: %(nReps)s,\n" "conditions: %(name)sConditions,\n" "method: TrialHandler.Method.%(switchMethod)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "});\n" "psychoJS.experiment.addLoop(%(name)s); // add the loop to the experiment\n" "currentLoop = %(name)s; // we're now the current loop\n" "// Schedule all the trials in the trialList:\n" "for (const thisQuestLoop of %(name)s) {\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) thisLoop = self.exp.flow.loopDict[self] buff.writeIndentedLines( "%(name)sLoopScheduler.add(%(name)sLoopBeginIteration(snapshot));\n" % inits) for thisChild in thisLoop: if thisChild.getType() == 'Routine': code = ( "snapshot = %(name)s.getSnapshot();\n" "{loopName}LoopScheduler.add(importConditions(snapshot));\n" "{loopName}LoopScheduler.add({childName}RoutineBegin(snapshot));\n" "{loopName}LoopScheduler.add({childName}RoutineEachFrame());\n" "{loopName}LoopScheduler.add({childName}RoutineEnd());\n" .format(childName=thisChild.params['name'], loopName=self.params['name']) ) else: # for a LoopInitiator code = ( "snapshot = %(name)s.getSnapshot();\n" "const {childName}LoopScheduler = new Scheduler(psychoJS);\n" "{loopName}LoopScheduler.add(importConditions(snapshot));\n" "{loopName}LoopScheduler.add({childName}LoopBegin({childName}LoopScheduler, snapshot));\n" "{loopName}LoopScheduler.add({childName}LoopScheduler);\n" "{loopName}LoopScheduler.add({childName}LoopEnd);\n" .format(childName=thisChild.params['name'], loopName=self.params['name']) ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ("// then iterate over this loop (%(name)s)\n" "%(name)sLoopScheduler.add(%(name)sLoopEndIteration(%(name)sLoopScheduler, snapshot));\n" "}" "\n\n" "return Scheduler.Event.NEXT;\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) def writeLoopEndCode(self, buff): # Just within the loop advance data line if loop is whole trials if self.params['isTrials'].val: buff.writeIndentedLines( "thisExp.nextEntry()\n" "\n" "if thisSession is not None:\n" " # if running in a Session with a Liaison client, send data up to now\n" " thisSession.sendExperimentData()\n" ) # end of the loop. dedent buff.setIndentLevel(-1, relative=True) buff.writeIndented("# all staircases completed\n") buff.writeIndented("\n") # save data if self.params['isTrials'].val: if self.exp.settings.params['Save excel file'].val: code = "%(name)s.saveAsExcel(filename + '.xlsx')\n" buff.writeIndented(code % self.params) if self.exp.settings.params['Save csv file'].val: code = ("%(name)s.saveAsText(filename + '%(name)s.csv', " "delim=',')\n") buff.writeIndented(code % self.params) def writeLoopBeginIterationCodeJS(self, buff): startLoopInteration = (f"\nfunction {self.name}LoopBeginIteration(snapshot) {{\n" f" return async function() {{\n" f" // ------Prepare for next entry------\n" f" level = {self.name}.intensity;\n\n" f" return Scheduler.Event.NEXT;\n" f" }}\n" f"}}\n") buff.writeIndentedLines(startLoopInteration % self.params) def writeLoopEndCodeJS(self, buff): code = ( "\n" "async function %(name)sLoopEnd() {\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(1, relative=True) code = ( "// terminate loop\n" "psychoJS.experiment.removeLoop(%(name)s);\n" "// update the current loop from the ExperimentHandler\n" "if (psychoJS.experiment._unfinishedLoops.length>0)\n" " currentLoop = psychoJS.experiment._unfinishedLoops.at(-1);\n" "else\n" " currentLoop = psychoJS.experiment; // so we use addData from the experiment\n"\ "return Scheduler.Event.NEXT;\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-1, relative=True) code = ( "}" ) buff.writeIndentedLines(code % self.params) def getType(self): return 'MultiStairHandler' def writeInitCode(self, buff): # not needed - initialise the staircase only when needed pass class LoopInitiator: """A simple class for inserting into the flow. This is created automatically when the loop is created""" def __init__(self, loop): super(LoopInitiator, self).__init__() self.loop = loop self.exp = loop.exp loop.initiator = self def __eq__(self, obj): if isinstance(obj, str): return self.loop.name == obj elif isinstance(obj, LoopInitiator): return self.loop.name == obj.loop.name def __ne__(self, obj): return not (self == obj) @property def _xml(self): # Make root element element = Element("LoopInitiator") element.set("loopType", self.loop.__class__.__name__) element.set("name", self.loop.params['name'].val) # Add an element for each parameter for key, param in sorted(self.loop.params.items()): # Create node paramNode = Element("Param") paramNode.set("name", key) # Assign values if hasattr(param, 'updates'): paramNode.set('updates', "{}".format(param.updates)) if hasattr(param, 'val'): paramNode.set('val', u"{}".format(param.val).replace("\n", "&#10;")) if hasattr(param, 'valType'): paramNode.set('valType', param.valType) element.append(paramNode) return element @property def name(self): return self.loop.name def getType(self): return 'LoopInitiator' def writePreCodeJS(self, buff): if hasattr(self.loop, 'writePreCodeJS'): self.loop.writePreCodeJS(buff) def writeInitCode(self, buff): self.loop.writeInitCode(buff) def writeInitCodeJS(self, buff): if hasattr(self.loop, "writeInitCodeJS"): # the loop may not have/need this option self.loop.writeInitCodeJS(buff) def writeMainCode(self, buff): self.loop.writeLoopStartCode(buff) # we are now the inner-most loop self.exp.flow._loopList.append(self.loop) def writeMainCodeJS(self, buff, modular): self.loop.writeLoopStartCodeJS(buff, modular) # some loops do extra things in their beginIteration if hasattr(self.loop, 'writeLoopBeginIterationCodeJS'): self.loop.writeLoopBeginIterationCodeJS(buff) # we are now the inner-most loop self.exp.flow._loopList.append(self.loop) def writeExperimentEndCode(self, buff): # not needed pass class LoopTerminator: """A simple class for inserting into the flow. This is created automatically when the loop is created""" def __init__(self, loop): super(LoopTerminator, self).__init__() self.loop = loop self.exp = loop.exp loop.terminator = self @property def _xml(self): # Make root element element = Element("LoopTerminator") element.set("name", self.loop.params['name'].val) return element @property def name(self): return self.loop.name def getType(self): return 'LoopTerminator' def writeInitCode(self, buff): pass def writeMainCode(self, buff): self.loop.writeLoopEndCode(buff) # _loopList[-1] will now be the inner-most loop self.exp.flow._loopList.remove(self.loop) def writeMainCodeJS(self, buff, modular): self.loop.writeLoopEndCodeJS(buff) self.loop.writeLoopEndIterationCodeJS(buff) # _loopList[-1] will now be the inner-most loop self.exp.flow._loopList.remove(self.loop) def writeExperimentEndCode(self, buff): # not needed pass
45,898
Python
.py
941
35.553666
120
0.553636
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,583
__init__.py
psychopy_psychopy/psychopy/experiment/routines/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Classes and functions for routines in Builder. """ # 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 importlib import import_module from ._base import BaseStandaloneRoutine, BaseValidatorRoutine, Routine from .unknown import UnknownRoutine from pathlib import Path from psychopy import logging # Standalone components loaded from plugins are stored in this dictionary. These # are added by calling `addStandaloneRoutine`. Plugins will always override # builtin components with the same name. pluginRoutines = {} def addStandaloneRoutine(routineClass): """Add a standalone routine to Builder. This function will override any routine already loaded with the same class name. Usually, this function is called by the plugin system. The user typically does not need to call this directly. Parameters ---------- routineClass : object Standalone routine class. Should be a subclass of `BaseStandaloneRoutine`. """ global pluginRoutines # components loaded at runtime routineName = routineClass.__name__ logging.debug("Registering Builder routine class `{}`.".format(routineName)) # check type and attributes of the class if not issubclass(routineClass, BaseStandaloneRoutine): logging.warning( "Component `{}` does not appear to be a subclass of " "`psychopy.experiment.routines._base.BaseStandaloneRoutine`. This " " may not work correcty.".format(routineName)) elif not hasattr(routineClass, 'categories'): logging.warning( "Routine `{}` does not define a `.categories` attribute.".format( routineName)) pluginRoutines[routineName] = routineClass def getAllStandaloneRoutines(fetchIcons=True): """Get a mapping of all standalone routines. This function will return a dictionary of all standalone routines available in Builder. The dictionary is indexed by the class name of the routine. The values are the routine classes themselves. Parameters ---------- fetchIcons : bool If `True`, the routine classes will be asked to fetch their icons. Returns ------- dict Dictionary of all standalone routines available in Builder, including those added by plugins. """ # Safe import all modules within this folder (apart from protected ones with a _) for loc in Path(__file__).parent.glob("*"): if loc.is_dir() and not loc.name.startswith("_"): import_module("." + loc.name, package="psychopy.experiment.routines") # Get list of subclasses of BaseStandalone def getSubclasses(cls, classList=None): # create list if needed if classList is None: classList = [] # add to class list classList.append(cls) # recur for subclasses for subcls in cls.__subclasses__(): getSubclasses(subcls, classList) return classList classList = getSubclasses(BaseStandaloneRoutine) # Remove unknown #if UnknownRoutine in classList: # classList.remove(UnknownRoutine) # Get list indexed by class name with Routine removed classDict = {c.__name__: c for c in classList} # merge with plugin components global pluginRoutines if pluginRoutines: logging.debug("Merging plugin routines with builtin Builder routines.") classDict.update(pluginRoutines) return classDict if __name__ == "__main__": pass
3,672
Python
.py
85
37.2
85
0.707351
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,584
_base.py
psychopy_psychopy/psychopy/experiment/routines/_base.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). """Describes the Flow of an experiment """ import copy import textwrap from psychopy.constants import FOREVER from xml.etree.ElementTree import Element from pathlib import Path from psychopy.experiment.components.static import StaticComponent from psychopy.experiment.components.routineSettings import RoutineSettingsComponent from psychopy.localization import _translate from psychopy.experiment import Param class BaseStandaloneRoutine: categories = ['Custom'] targets = [] iconFile = Path(__file__).parent / "unknown" / "unknown.png" tooltip = "" limit = float('inf') # what version was this Routine added in? version = "0.0.0" # is it still in beta? beta = False def __init__(self, exp, name='', stopType='duration (s)', stopVal='', disabled=False): self.params = {} self.name = name self.exp = exp self.url = "" self.type = 'StandaloneRoutine' self.depends = [] # allows params to turn each other off/on self.order = ['stopVal', 'stopType', 'name'] msg = _translate( "Name of this Routine (alphanumeric or _, no spaces)") self.params['name'] = Param(name, valType='code', inputType="single", categ='Basic', hint=msg, label=_translate('Name')) self.params['stopVal'] = Param(stopVal, valType='num', inputType="single", categ='Basic', updates='constant', allowedUpdates=[], allowedTypes=[], hint=_translate("When does the Routine end? (blank is endless)"), label=_translate('Stop')) msg = _translate("How do you want to define your end point?") self.params['stopType'] = Param(stopType, valType='str', inputType="choice", categ='Basic', allowedVals=['duration (s)', 'duration (frames)', 'condition'], hint=msg, direct=False, label=_translate('Stop type...')) # Testing msg = _translate("Disable this Routine") self.params['disabled'] = Param(disabled, valType='bool', inputType="bool", categ="Testing", hint=msg, allowedTypes=[], direct=False, label=_translate('Disable Routine')) def __repr__(self): _rep = "psychopy.experiment.routines.%s(name='%s', exp=%s)" return _rep % (self.__class__.__name__, self.name, self.exp) def __iter__(self): """Overloaded iteration behaviour - if iterated through, a standaloneRoutine returns itself once, so it can be treated like a regular routine""" self.__iterstop = False return self def __next__(self): """Overloaded iteration behaviour - if iterated through, a standaloneRoutine returns itself once, so it can be treated like a regular routine""" if self.__iterstop: # Stop after one iteration self.__iterstop = False raise StopIteration else: self.__iterstop = True return self @property def _xml(self): # Make root element element = Element(self.__class__.__name__) element.set("name", self.params['name'].val) # Add an element for each parameter for key, param in sorted(self.params.items()): # Create node paramNode = Element("Param") paramNode.set("name", key) # Assign values if hasattr(param, 'updates'): paramNode.set('updates', "{}".format(param.updates)) if hasattr(param, 'val'): paramNode.set('val', u"{}".format(param.val).replace("\n", "&#10;")) if hasattr(param, 'valType'): paramNode.set('valType', param.valType) element.append(paramNode) return element def copy(self): # Create a deep copy of self dupe = copy.deepcopy(self) # ...but retain original exp reference dupe.exp = self.exp return dupe def writeDeviceCode(self, buff): return def writePreCode(self, buff): return def writePreCodeJS(self, buff): return def writeStartCode(self, buff): return def writeStartCodeJS(self, buff): return def writeRunOnceInitCode(self, buff): return def writeInitCode(self, buff): return def writeInitCodeJS(self, buff): return def writeMainCode(self, buff): return def writeRoutineBeginCodeJS(self, buff, modular): code = ( "function %(name)sRoutineBegin(snapshot) {\n" " return async function () {\n" " return Scheduler.Event.NEXT;\n" " }\n" "}\n" ) buff.writeIndentedLines(code % self.params) def writeEachFrameCodeJS(self, buff, modular): code = ( "function %(name)sRoutineEachFrame(snapshot) {\n" " return async function () {\n" " return Scheduler.Event.NEXT;\n" " }\n" "}\n" ) buff.writeIndentedLines(code % self.params) def writeRoutineEndCode(self, buff): # what loop are we in (or thisExp)? if len(self.exp.flow._loopList): currLoop = self.exp.flow._loopList[-1] # last (outer-most) loop else: currLoop = self.exp._expHandler if currLoop.params['name'].val == self.exp._expHandler.name: buff.writeIndented("%s.nextEntry()\n" % self.exp._expHandler.name) # reset routineTimer at the *very end* of all non-nonSlip routines code = ('# the Routine "%s" was not non-slip safe, so reset ' 'the non-slip timer\n' 'routineTimer.reset()\n') buff.writeIndentedLines(code % self.name) def writeRoutineEndCodeJS(self, buff, modular): code = ( "function %(name)sRoutineEnd(snapshot) {\n" " return async function () {\n" " return Scheduler.Event.NEXT;\n" " }\n" "}\n" ) buff.writeIndentedLines(code % self.params) def writeExperimentEndCode(self, buff): return def writeExperimentEndCodeJS(self, buff): return def getType(self): return self.__class__.__name__ def getComponentFromName(self, name): return None def getComponentFromType(self, thisType): return None def hasOnlyStaticComp(self): return False def getMaxTime(self): """If routine has a set duration, will return this along with True (as this routine is nonSlipSafe, i.e. has a fixed duration). Otherwise, will treat max time as 0 and will mark routine as nonSlipSafe (i.e. has a variable duration).. """ # Assume max time of 0 and not nonSlipSafe maxTime = 0 nonSlipSafe = False # If has a set duration, store set duration and mark as nonSlipSafe if 'stopVal' in self.params and 'stopType' in self.params: if self.params['stopType'] in ['duration (s)', 'duration (frames)']: maxTime = float(self.params['stopVal'].val or 0) nonSlipSafe = True return maxTime, nonSlipSafe def getStatics(self): return [] def getFullDocumentation(self, fmt="rst"): """ Automatically generate documentation for this Component. We recommend using this as a starting point, but checking the documentation yourself afterwards and adding any more detail you'd like to include (e.g. usage examples) Parameters ---------- fmt : str Format to write documentation in. One of: - "rst": Restructured text (numpy style) -"md": Markdown (mkdocs style) """ # make sure format is correct assert fmt in ("md", "rst"), ( f"Unrecognised format {fmt}, allowed formats are 'md' and 'rst'." ) # define templates for md and rst h1 = { 'md': "# %s", 'rst': ( "-------------------------------\n" "%s\n" "-------------------------------" ) }[fmt] h2 = { 'md': "## %s", 'rst': ( "%s\n" "-------------------------------" ) }[fmt] h3 = { 'md': "### %s", 'rst': ( "%s\n" "===============================" ) }[fmt] h4 = { 'md': "#### `%s`", 'rst': "%s" }[fmt] # start off with nothing content = "" # header and class docstring content += ( f"{h1 % type(self).__name__}\n" f"{textwrap.dedent(self.__doc__ or '')}\n" f"\n" ) # attributes content += ( f"{h4 % 'Categories:'}\n" f" {', '.join(self.categories)}\n" f"{h4 % 'Works in:'}\n" f" {', '.join(self.targets)}\n" f"\n" ) # beta warning if self.beta: content += ( f"**Note: Since this is still in beta, keep an eye out for bug fixes.**\n" f"\n" ) # params heading content += ( f"{h2 % 'Parameters'}\n" f"\n" ) # sort params by category byCateg = {} for param in self.params.values(): if param.categ not in byCateg: byCateg[param.categ] = [] byCateg[param.categ].append(param) # iterate through categs for categ, params in byCateg.items(): # write a heading for each categ content += ( f"{h3 % categ}\n" f"\n" ) # add each param... for param in params: # write basics (heading and description) content += ( f"{h4 % param.label}\n" f" {param.hint}\n" ) # if there are options, display them if bool(param.allowedVals) or bool(param.allowedLabels): # if no allowed labels, use allowed vals options = param.allowedLabels or param.allowedVals # handle callable methods if callable(options): content += ( f"\n" f" Options are generated live, so will vary according to your setup.\n" ) else: # write heading content += ( f" \n" f" Options:\n" ) # add list item for each option for opt in options: content += ( f" - {opt}\n" ) # add newline at the end content += "\n" return content @property def name(self): if hasattr(self, 'params'): if 'name' in self.params: if hasattr(self.params['name'], "val"): return self.params['name'].val else: return self.params['name'] return self.type @name.setter def name(self, value): if hasattr(self, 'params'): if 'name' in self.params: self.params['name'].val = value @property def disabled(self): return bool(self.params['disabled']) @disabled.setter def disabled(self, value): self.params['disabled'].val = value class BaseValidatorRoutine(BaseStandaloneRoutine): """ Subcategory of Standalone Routine, which sets up a "validator" - an object which is linked to in the Testing tab of another Component and validates that the component behaved as expected. Any validator Routines should subclass this rather than BaseStandaloneRoutine. """ # list of class strings (readable by DeviceManager) which this component's device could be deviceClasses = [] def writeRoutineStartValidationCode(self, buff, stim): """ Write the routine start code to validate a given stimulus using this validator. Parameters ---------- buff : StringIO String buffer to write code to. stim : BaseComponent Stimulus to validate Returns ------- int Change in indentation level after writing """ # this method should be overloaded when subclassing! return 0 def writeEachFrameValidationCode(self, buff, stim): """ Write the each frame code to validate a given stimulus using this validator. Parameters ---------- buff : StringIO String buffer to write code to. stim : BaseComponent Stimulus to validate Returns ------- int Change in indentation level after writing """ # this method should be overloaded when subclassing! return 0 class Routine(list): """ A Routine determines a single sequence of events, such as the presentation of trial. Multiple Routines might be used to comprise an Experiment (e.g. one for presenting instructions, one for trials, one for debriefing subjects). In practice a Routine is simply a python list of Components, each of which knows when it starts and stops. """ targets = ["PsychoPy", "PsychoJS"] version = "0.0.0" def __init__(self, name, exp, components=(), disabled=False): self.settings = RoutineSettingsComponent(exp, name, disabled=disabled) super(Routine, self).__init__() self.exp = exp self._clockName = None # for scripts e.g. "t = trialClock.GetTime()" self.type = 'Routine' list.__init__(self, list(components)) self.addComponent(self.settings) def __repr__(self): _rep = "psychopy.experiment.Routine(name='%s', exp=%s, components=%s)" return _rep % (self.name, self.exp, str(list(self))) def copy(self): # Create a new routine with the same experiment and name as this one dupe = type(self)(self.name, self.exp, components=()) # Replace duplicate Routine's setting component dupe.settings.params = copy.deepcopy(self.settings.params) # Iterate through components for comp in self: # Skip settings component if isinstance(comp, RoutineSettingsComponent): continue # Create a deep copy of each component... newComp = copy.deepcopy(comp) # ...but retain original exp reference newComp.exp = self.exp # Append to new routine dupe.append(newComp) return dupe @property def _xml(self): # Make root element element = Element("Routine") element.set("name", self.name) # Add each component's element for comp in self: element.append(comp._xml) return element @property def name(self): return self.params['name'].val @name.setter def name(self, name): self.params['name'].val = name # Update references in components for comp in self: comp.parentName = name @property def params(self): return self.settings.params def integrityCheck(self): """Run tests on self and on all the Components inside""" for entry in self: if hasattr(entry, "integrityCheck"): entry.integrityCheck() def addComponent(self, component): """Add a component to the end of the routine""" self.append(component) def insertComponent(self, index, component): """Insert a component at some point of the routine. Parameters ---------- index : int Position in the routine to insert the component. component : object Component object to insert. """ try: self.insert(index, component) except IndexError: self.append(component) # just insert at the end on invalid index def removeComponent(self, component): """Remove a component from the end of the routine""" name = component.params['name'] self.remove(component) # if this is a static component, we need to remove references to it if isinstance(component, StaticComponent): for update in component.updatesList: # remove reference in component comp = self.exp.getComponentFromName(update['compName']) if comp: param = comp.params[update['fieldName']] param.updates = None # check if the component was using any Static Components for updates for thisParamName, thisParam in list(component.params.items()): if (hasattr(thisParam, 'updates') and thisParam.updates and 'during:' in thisParam.updates): # remove the part that says 'during' updates = thisParam.updates.split(': ')[1] routine, static = updates.split('.') comp = self.exp.routines[routine].getComponentFromName(static) comp.remComponentUpdate(routine, name, thisParamName) def getStatics(self): """Return a list of Static components """ statics = [] for comp in self: if comp.type == 'Static': statics.append(comp) return statics def writePreCode(self, buff): """This is start of the script (before window is created) """ for thisCompon in self: # check just in case; try to ensure backwards compatibility _base if hasattr(thisCompon, 'writePreCode'): thisCompon.writePreCode(buff) def writePreCodeJS(self, buff): """This is start of the script (before window is created) """ for thisCompon in self: # check just in case; try to ensure backwards compatibility _base if hasattr(thisCompon, 'writePreCodeJS'): thisCompon.writePreCodeJS(buff) def writeStartCode(self, buff): """This is start of the *experiment* (after window is created) """ for thisCompon in self: # check just in case; try to ensure backwards compatibility _base if hasattr(thisCompon, 'writeStartCode'): thisCompon.writeStartCode(buff) def writeStartCodeJS(self, buff): """This is start of the *experiment* """ # few components will have this for thisCompon in self: # check just in case; try to ensure backwards compatibility _base if hasattr(thisCompon, 'writeStartCodeJS'): thisCompon.writeStartCodeJS(buff) def writeRunOnceInitCode(self, buff): """ Run once init code goes at the beginning of the script (before Window creation) and the code will be run only once no matter how many similar components request it """ for thisCompon in self: # check just in case; try to ensure backwards compatibility _base if hasattr(thisCompon, 'writeRunOnceInitCode'): thisCompon.writeRunOnceInitCode(buff) def writeInitCode(self, buff): code = '\n# --- Initialize components for Routine "%s" ---\n' buff.writeIndentedLines(code % self.name) maxTime, useNonSlip = self.getMaxTime() self._clockName = 'routineTimer' for thisCompon in self: thisCompon.writeInitCode(buff) def writeInitCodeJS(self, buff): code = '// Initialize components for Routine "%s"\n' buff.writeIndentedLines(code % self.name) self._clockName = self.name + "Clock" buff.writeIndented('%s = new util.Clock();\n' % self._clockName) for thisCompon in self: if hasattr(thisCompon, 'writeInitCodeJS'): thisCompon.writeInitCodeJS(buff) def writeMainCode(self, buff): """This defines the code for the frames of a single routine """ # create the frame loop for this routine code = ('\n# --- Prepare to start Routine "%s" ---\n') buff.writeIndentedLines(code % (self.name)) # get list of components which have an in-experiment object comps = [ c.name for c in self if 'startType' in c.params and c.type != 'Variable' ] compStr = ", ".join(comps) # create object code = ( "# create an object to store info about Routine %(name)s\n" "%(name)s = data.Routine(\n" " name='%(name)s',\n" " components=[{}],\n" ")\n" "%(name)s.status = NOT_STARTED\n" ).format(compStr) buff.writeIndentedLines(code % self.params) code = ( 'continueRoutine = True\n' ) buff.writeIndentedLines(code) # can we use non-slip timing? maxTime, useNonSlip = self.getMaxTime() # this is the beginning of the routine, before the loop starts code = "# update component parameters for each repeat\n" buff.writeIndentedLines(code) for event in self: # don't write Routine Settings just yet... if event is self.settings: continue # write the other Components' event.writeRoutineStartCode(buff) event.writeRoutineStartValidationCode(buff) # write the Routine Settings code last self.settings.writeRoutineStartCode(buff) self.settings.writeRoutineStartValidationCode(buff) code = '# keep track of which components have finished\n' buff.writeIndentedLines(code) # legacy code to support old `...Components` variable code = ( "%(name)sComponents = %(name)s.components" ) buff.writeIndentedLines(code % self.params) code = ("for thisComponent in {name}.components:\n" " thisComponent.tStart = None\n" " thisComponent.tStop = None\n" " thisComponent.tStartRefresh = None\n" " thisComponent.tStopRefresh = None\n" " if hasattr(thisComponent, 'status'):\n" " thisComponent.status = NOT_STARTED\n" "# reset timers\n" 't = 0\n' '_timeToFirstFrame = win.getFutureFlipTime(clock="now")\n' # '{clockName}.reset(-_timeToFirstFrame) # t0 is time of first possible flip\n' 'frameN = -1\n' '\n# --- Run Routine "{name}" ---\n') buff.writeIndentedLines(code.format(name=self.name, clockName=self._clockName)) # initial value for forceRoutineEnded (needs to happen now as Code components will have executed # their Begin Routine code) code = ( '%(name)s.forceEnded = routineForceEnded = not continueRoutine\n' ) buff.writeIndentedLines(code % self.params) if useNonSlip: code = f'while continueRoutine and routineTimer.getTime() < {maxTime}:\n' else: code = 'while continueRoutine:\n' buff.writeIndented(code) buff.setIndentLevel(1, True) # check for the trials loop ending this Routine if len(self.exp.flow._loopList): loop = self.exp.flow._loopList[-1] code = ( "# if trial has changed, end Routine now\n" "if hasattr({thisName}, 'status') and {thisName}.status == STOPPING:\n" " continueRoutine = False\n" ).format(thisName=loop.thisName) buff.writeIndentedLines(code) # on each frame code = ('# get current time\n' 't = {clockName}.getTime()\n' 'tThisFlip = win.getFutureFlipTime(clock={clockName})\n' 'tThisFlipGlobal = win.getFutureFlipTime(clock=None)\n' 'frameN = frameN + 1 # number of completed frames ' '(so 0 is the first frame)\n') buff.writeIndentedLines(code.format(clockName=self._clockName)) # write the code for each component during frame buff.writeIndentedLines('# update/draw components on each frame\n') # just 'normal' components for event in self: if event.type == 'Static': continue # we'll do those later event.writeFrameCode(buff) event.writeEachFrameValidationCode(buff) # update static component code last for event in self.getStatics(): event.writeFrameCode(buff) # allow subject to quit via Esc key? if self.exp.settings.params['Enable Escape'].val: code = ( '\n' '# check for quit (typically the Esc key)\n' 'if defaultKeyboard.getKeys(keyList=["escape"]):\n' ' thisExp.status = FINISHED\n' ) buff.writeIndentedLines(code) code = ( "if thisExp.status == FINISHED or endExpNow:\n" " endExperiment(thisExp, win=win)\n" " return\n" ) buff.writeIndentedLines(code) # handle pausing playbackComponents = [ comp.name for comp in self if type(comp).__name__ in ("MovieComponent", "SoundComponent") ] playbackComponentsStr = ", ".join(playbackComponents) code = ( "# pause experiment here if requested\n" "if thisExp.status == PAUSED:\n" " pauseExperiment(\n" " thisExp=thisExp, \n" " win=win, \n" " timers=[routineTimer, globalClock], \n" " playbackComponents=[{playbackComponentsStr}]\n" " )\n" " # skip the frame we paused on\n" " continue" ) code = code.format(playbackComponentsStr=playbackComponentsStr) buff.writeIndentedLines(code) # are we done yet? code = ( '\n' '# check if all components have finished\n' 'if not continueRoutine: # a component has requested a ' 'forced-end of Routine\n' ' %(name)s.forceEnded = routineForceEnded = True\n' ' break\n' 'continueRoutine = False # will revert to True if at least ' 'one component still running\n' 'for thisComponent in %(name)s.components:\n' ' if hasattr(thisComponent, "status") and ' 'thisComponent.status != FINISHED:\n' ' continueRoutine = True\n' ' break # at least one component has not yet finished\n') buff.writeIndentedLines(code % self.params) # update screen code = ('\n# refresh the screen\n' "if continueRoutine: # don't flip if this routine is over " "or we'll get a blank screen\n" ' win.flip()\n') buff.writeIndentedLines(code) # that's done decrement indent to end loop buff.setIndentLevel(-1, True) # write the code for each component for the end of the routine code = ('\n# --- Ending Routine "%(name)s" ---\n' 'for thisComponent in %(name)s.components:\n' ' if hasattr(thisComponent, "setAutoDraw"):\n' ' thisComponent.setAutoDraw(False)\n') buff.writeIndentedLines(code % self.params) for event in self: event.writeRoutineEndCode(buff) if useNonSlip: code = ( "# using non-slip timing so subtract the expected duration of this Routine (unless ended on request)\n" "if %(name)s.maxDurationReached:\n" " routineTimer.addTime(-%(name)s.maxDuration)\n" "elif %(name)s.forceEnded:\n" " routineTimer.reset()\n" "else:\n" " routineTimer.addTime(-{:f})\n" ).format(maxTime) buff.writeIndentedLines(code % self.params) def writeRoutineBeginCodeJS(self, buff, modular): # create the frame loop for this routine code = ("\nfunction %(name)sRoutineBegin(snapshot) {\n" % self.params) buff.writeIndentedLines(code) buff.setIndentLevel(1, relative=True) buff.writeIndentedLines("return async function () {\n") buff.setIndentLevel(1, relative=True) code = ("TrialHandler.fromSnapshot(snapshot); // ensure that .thisN vals are up to date\n\n" "//--- Prepare to start Routine '%(name)s' ---\n" "t = 0;\n" "frameN = -1;\n" "continueRoutine = true; // until we're told otherwise\n" % self.params) buff.writeIndentedLines(code) # can we use non-slip timing? maxTime, useNonSlip = self.getMaxTime() if useNonSlip: code = ( "%(name)sClock.reset(routineTimer.getTime());\n" "routineTimer.add({maxTime:f});\n" ).format(maxTime=maxTime) buff.writeIndentedLines(code % self.params) else: code = ( "%(name)sClock.reset();\n" "routineTimer.reset();\n" ) buff.writeIndentedLines(code % self.params) # keep track of whether max duration is reached code = ( "%(name)sMaxDurationReached = false;\n" ) buff.writeIndentedLines(code % self.params) code = "// update component parameters for each repeat\n" buff.writeIndentedLines(code) # This is the beginning of the routine, before the loop starts for thisCompon in self: if thisCompon is self.settings: continue if "PsychoJS" in thisCompon.targets: thisCompon.writeRoutineStartCodeJS(buff) self.settings.writeRoutineStartCodeJS(buff) code = ("// keep track of which components have finished\n" "%(name)sComponents = [];\n" % self.params) buff.writeIndentedLines(code) for thisCompon in self: if (('startType' in thisCompon.params) and ("PsychoJS" in thisCompon.targets)): code = ("%sComponents.push(%s);\n" % (self.name, thisCompon.params['name'])) buff.writeIndentedLines(code) if modular: code = ("\nfor (const thisComponent of %(name)sComponents)\n" " if ('status' in thisComponent)\n" " thisComponent.status = PsychoJS.Status.NOT_STARTED;\n" % self.params) else: code = ("\n%(name)sComponents.forEach( function(thisComponent) {\n" " if ('status' in thisComponent)\n" " thisComponent.status = PsychoJS.Status.NOT_STARTED;\n" " });\n" % self.params) buff.writeIndentedLines(code) # are we done yet? code = ("return Scheduler.Event.NEXT;\n") buff.writeIndentedLines(code) buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("}\n") buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("}\n") def writeEachFrameCodeJS(self, buff, modular): # can we use non-slip timing? maxTime, useNonSlip = self.getMaxTime() # write code for each frame code = ("\nfunction %(name)sRoutineEachFrame() {\n" % self.params) buff.writeIndentedLines(code) buff.setIndentLevel(1, relative=True) buff.writeIndentedLines("return async function () {\n") buff.setIndentLevel(1, relative=True) code = ("//--- Loop for each frame of Routine '%(name)s' ---\n" "// get current time\n" "t = %(name)sClock.getTime();\n" "frameN = frameN + 1;" "// number of completed frames (so 0 is the first frame)\n" % self.params) buff.writeIndentedLines(code) # write the code for each component during frame buff.writeIndentedLines('// update/draw components on each frame\n') # just 'normal' components for comp in self: if "PsychoJS" in comp.targets and comp.type != 'Static': comp.writeFrameCodeJS(buff) # update static component code last for comp in self.getStatics(): if "PsychoJS" in comp.targets: comp.writeFrameCodeJS(buff) if self.exp.settings.params['Enable Escape'].val: code = ("// check for quit (typically the Esc key)\n" "if (psychoJS.experiment.experimentEnded || psychoJS.eventManager.getKeys({keyList:['escape']}).length > 0) {\n" " return quitPsychoJS('The [Escape] key was pressed. Goodbye!', false);\n" "}\n\n") buff.writeIndentedLines(code) # are we done yet? code = ("// check if the Routine should terminate\n" "if (!continueRoutine) {" " // a component has requested a forced-end of Routine\n" " return Scheduler.Event.NEXT;\n" "}\n\n" "continueRoutine = false; " "// reverts to True if at least one component still running\n") buff.writeIndentedLines(code) if modular: code = ("for (const thisComponent of %(name)sComponents)\n" " if ('status' in thisComponent && thisComponent.status !== PsychoJS.Status.FINISHED) {\n" " continueRoutine = true;\n" " break;\n" " }\n") else: code = ("%(name)sComponents.forEach( function(thisComponent) {\n" " if ('status' in thisComponent && thisComponent.status !== PsychoJS.Status.FINISHED) {\n" " continueRoutine = true;\n" " }\n" "});\n") buff.writeIndentedLines(code % self.params) buff.writeIndentedLines("\n// refresh the screen if continuing\n") if useNonSlip: buff.writeIndentedLines("if (continueRoutine " "&& routineTimer.getTime() > 0) {") else: buff.writeIndentedLines("if (continueRoutine) {") code = (" return Scheduler.Event.FLIP_REPEAT;\n" "} else {\n" " return Scheduler.Event.NEXT;\n" "}\n") buff.writeIndentedLines(code) buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("};\n") buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("}\n") def writeRoutineEndCode(self, buff): # can we use non-slip timing? maxTime, useNonSlip = self.getMaxTime() # what loop are we in (or thisExp)? if len(self.exp.flow._loopList): currLoop = self.exp.flow._loopList[-1] # last (outer-most) loop else: currLoop = self.exp._expHandler if currLoop.params['name'].val == self.exp._expHandler.name: buff.writeIndented("%s.nextEntry()\n" % self.exp._expHandler.name) # reset routineTimer at the *very end* of all non-nonSlip routines if not useNonSlip: code = ('# the Routine "%s" was not non-slip safe, so reset ' 'the non-slip timer\n' 'routineTimer.reset()\n') buff.writeIndentedLines(code % self.name) def writeRoutineEndCodeJS(self, buff, modular): # can we use non-slip timing? maxTime, useNonSlip = self.getMaxTime() code = ("\nfunction %(name)sRoutineEnd(snapshot) {\n" % self.params) buff.writeIndentedLines(code) buff.setIndentLevel(1, relative=True) buff.writeIndentedLines("return async function () {\n") buff.setIndentLevel(1, relative=True) if modular: code = ("//--- Ending Routine '%(name)s' ---\n" "for (const thisComponent of %(name)sComponents) {\n" " if (typeof thisComponent.setAutoDraw === 'function') {\n" " thisComponent.setAutoDraw(false);\n" " }\n" "}\n") else: code = ("//--- Ending Routine '%(name)s' ---\n" "%(name)sComponents.forEach( function(thisComponent) {\n" " if (typeof thisComponent.setAutoDraw === 'function') {\n" " thisComponent.setAutoDraw(false);\n" " }\n" "});\n") buff.writeIndentedLines(code % self.params) # add the EndRoutine code for each component for compon in self: if "PsychoJS" in compon.targets: compon.writeRoutineEndCodeJS(buff) # reset routineTimer at the *very end* of all non-nonSlip routines if useNonSlip: code = ( "if (%(name)sMaxDurationReached) {{\n" " %(name)sClock.add(%(name)sMaxDuration);\n" "}} else {{\n" " %(name)sClock.add({:f});\n" "}}\n" ).format(maxTime) buff.writeIndented(code % self.params) else: code = ('// the Routine "%s" was not non-slip safe, so reset ' 'the non-slip timer\n' 'routineTimer.reset();\n\n') buff.writeIndentedLines(code % self.name) buff.writeIndentedLines( "// Routines running outside a loop should always advance the datafile row\n" "if (currentLoop === psychoJS.experiment) {\n" " psychoJS.experiment.nextEntry(snapshot);\n" "}\n") buff.writeIndented('return Scheduler.Event.NEXT;\n') buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("}\n") buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines("}\n") def writeExperimentEndCode(self, buff): """Some components have """ # This is the beginning of the routine, before the loop starts for component in self: component.writeExperimentEndCode(buff) def writeExperimentEndCodeJS(self, buff): """This defines the code for the frames of a single routine """ # This is the beginning of the routine, before the loop starts for component in self: if 'writeExperimentEndCodeJS' in dir(component): component.writeExperimentEndCodeJS(buff) def getType(self): return 'Routine' def getComponentFromName(self, name): for comp in self: if comp.params['name'].val == name: return comp return None def getComponentFromType(self, thisType): for comp in self: if comp.type == thisType: return comp return None def hasOnlyStaticComp(self): return all([comp.type == 'Static' for comp in self]) def getMaxTime(self): """What the last (predetermined) stimulus time to be presented. If there are no components or they have code-based times then will default to 10secs """ maxTime = 0 nonSlipSafe = True # if possible for component in self: if 'startType' in component.params: start, duration, nonSlip = component.getStartAndDuration() if not nonSlip: nonSlipSafe = False if duration == FOREVER: # only the *start* of an unlimited event should contribute # to maxTime, plus some minimal duration so it's visible duration = 0 if self.settings.params['forceNonSlip'] else 1 # now see if we have a end t value that beats the previous max try: # will fail if either value is not defined: thisT = start + duration except Exception: thisT = 0 maxTime = max(maxTime, thisT) # if max set by routine, override calculated max rtDur, numericStop = self.settings.getDuration() if rtDur != FOREVER: maxTime = rtDur # if nonslip is actively requested, force it if self.settings.params['forceNonSlip'] and maxTime not in (0, FOREVER): nonSlipSafe = True # if there are no components, default to 10s if maxTime in (0, None): maxTime = 10 nonSlipSafe = False return maxTime, nonSlipSafe @property def disabled(self): return bool(self.params['disabled']) @disabled.setter def disabled(self, value): self.params['disabled'].val = value
42,032
Python
.py
975
31.515897
241
0.562948
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,585
__init__.py
psychopy_psychopy/psychopy/experiment/routines/counterbalance/__init__.py
from .. import BaseStandaloneRoutine from ... import Param from pathlib import Path from psychopy.localization import _translate class CounterbalanceRoutine(BaseStandaloneRoutine): categories = ['Custom'] targets = ["PsychoPy", "PsychoJS"] iconFile = Path(__file__).parent / "counterbalance.png" label = _translate("Counter-balance") tooltip = _translate( "Counterbalance Routine: use the Shelf to choose a value taking into account previous runs of this experiment." ) def __init__( self, exp, name='counterbalance', specMode="uniform", conditionsFile="", conditionsVariable="", nGroups=2, nSlots=10, nReps=1, endExperimentOnDepletion="ignore", saveData=True, saveRemaining=True ): BaseStandaloneRoutine.__init__(self, exp, name=name) self.url = "https://psychopy.org/builder/components/counterbalanceComponent.html" # we don't need a stop time del self.params['stopVal'] del self.params['stopType'] self.type = "CounterBalance" # --- Basic --- self.order += [ 'specMode', 'conditionsFile', 'nGroups', 'nSlots', 'nReps', 'endExperimentOnDepletion' ] self.params['specMode'] = Param( specMode, valType="str", inputType="choice", categ="Basic", allowedVals=["uniform", "file"], allowedLabels=[_translate("Num. groups"), _translate("Conditions file (local only)")], label=_translate("Groups from..."), hint=_translate( "Specify groups using an Excel file (for fine tuned control), specify as a variable name, or specify a " "number of groups to create equally likely groups with a uniform cap." ) ) self.params['nReps'] = Param( nReps, valType="code", inputType="single", categ="Basic", label=_translate("Num. repeats"), hint=_translate( "How many times to run slots down to depletion?" ) ) self.depends += [{ "dependsOn": "specMode", # must be param name "condition": "=='file'", # val to check for "param": 'conditionsFile', # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }, { "dependsOn": "specMode", # must be param name "condition": "=='variable'", # val to check for "param": 'conditionsVariable', # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }, { "dependsOn": "specMode", # must be param name "condition": "=='uniform'", # val to check for "param": 'nGroups', # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }, { "dependsOn": "specMode", # must be param name "condition": "=='uniform'", # val to check for "param": 'nSlots', # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }] self.params['conditionsFile'] = Param( conditionsFile, valType='file', inputType="table", categ="Basic", label=_translate('Conditions'), hint=_translate( "Name of a file specifying the parameters for each group (.csv, .xlsx, or .pkl). Browse to select " "a file. Right-click to preview file contents, or create a new file." ), ctrlParams={ 'template': Path(__file__).parent / "counterbalanceItems.xltx" } ) self.params['conditionsVariable'] = Param( conditionsVariable, valType='code', inputType="single", categ="Basic", label=_translate('Conditions'), hint=_translate( "Name of a variable specifying the parameters for each group. Should be a list of dicts, like the " "output of data.conditionsFromFile" )) self.params['nGroups'] = Param( nGroups, valType="code", inputType="single", categ="Basic", label=_translate("Num. groups"), hint=_translate( "Number of groups to use." ) ) self.params['nSlots'] = Param( nSlots, valType="code", inputType="single", categ="Basic", label=_translate("Slots per group"), hint=_translate( "Max number of participants in each group for each repeat." ) ) self.params['endExperimentOnDepletion'] = Param( endExperimentOnDepletion, valType="code", inputType="bool", categ="Basic", label=_translate("End experiment on depletion"), hint=_translate( "When all slots and repetitions are depleted, should the experiment end or " "continue with .finished on this Routine as True?" ) ) # --- Data --- self.order += [ 'saveData', 'saveRemaining', ] self.params['saveData'] = Param( saveData, valType="bool", inputType="bool", categ="Data", label=_translate("Save data"), hint=_translate( "Save chosen group and associated params this repeat to the data file?" ) ) self.params['saveRemaining'] = Param( saveRemaining, valType="bool", inputType="bool", categ="Data", label=_translate("Save remaining cap"), hint=_translate( "Save the remaining cap for the chosen group this repeat to the data file?" ) ) def writeInitCode(self, buff): code = ( "expShelf = data.shelf.Shelf(scope='experiment', expPath=_thisDir)" ) buff.writeOnceIndentedLines(code % self.params) if self.params['specMode'] == "file": # if we're going from a file, read in file to get conditions code = ( "# load in conditions for %(name)s\n" "%(name)sConditions = data.utils.importConditions(%(conditionsFile)s);\n" ) elif self.params['specMode'] == "variable": code = ( "# get conditions for %(name)s\n" "%(name)sConditions = %(conditionsVariable)s\n" ) else: # otherwise, create conditions code = ( "# create uniform conditions for %(name)s\n" "%(name)sConditions = []\n" "for n in range(%(nGroups)s):\n" " %(name)sConditions.append({\n" " 'group': n,\n" " 'probability': 1/%(nGroups)s,\n" " 'cap': %(nSlots)s\n" " })\n" ) buff.writeIndentedLines(code % self.params) # make Counterbalancer object code = ( "\n" "# create counterbalance object for %(name)s \n" "%(name)s = data.Counterbalancer(\n" " shelf=expShelf,\n" " entry='%(name)s',\n" " conditions=%(name)sConditions,\n" " nReps=%(nReps)s\n" ")\n" ) buff.writeIndentedLines(code % self.params) def writeMainCode(self, buff): # get group code = ( "# get group from shelf\n" "%(name)s.allocateGroup()" "\n" ) buff.writeIndentedLines(code % self.params) # if ending experiment on depletion, write the code to do so if self.params['endExperimentOnDepletion']: msg = _translate( "Slots for Counterbalancer %(name)s have been fully depleted, ending experiment." ) code = ( f"# if slots and repeats are fully depleted, end the experiment now\n" f"if %(name)s.finished:\n" f" # first print and log a message to make it clear why the experiment ended\n" f" print('{msg}')\n" f" logging.exp('{msg}')\n" f" endExperiment(thisExp, win=win)\n" ) buff.writeIndentedLines(code % self.params) # save data if self.params['saveData']: code = ( "thisExp.addData('%(name)s.group', %(name)s.group)\n" "for _key, _val in %(name)s.params.items():\n" " thisExp.addData(f'%(name)s.{_key}', _val)\n" ) buff.writeIndentedLines(code % self.params) # save remaining cap if self.params['saveRemaining']: code = ( "thisExp.addData('%(name)s.remaining', %(name)s.remaining)" ) buff.writeIndentedLines(code % self.params) def writeRoutineBeginCodeJS(self, buff, modular=True): # enter function def code = ( "\n" "function %(name)sRoutineBegin(snapshot) {\n" " return async function () {\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(2, relative=True) if self.params['specMode'] == "file": # if we're going from a file, read in file to get conditions code = ( "// load in conditions for %(name)s\n" "let %(name)sConditions = data.conditionsFromFile(%(conditionsFile)s);\n" ) else: # otherwise, create conditions code = ( "// create uniform conditions for %(name)s\n" "let %(name)sConditions = [];\n" "for (let n = 0; n < %(nGroups)s; n++) {\n" " %(name)sConditions.push({\n" " 'group': n,\n" " 'probability': 1/%(nGroups)s,\n" " 'cap': %(nSlots)s\n" " });\n" "}\n" ) buff.writeIndentedLines(code % self.params) code = ( "\n" "// get counterbalancing group \n" "%(name)s = await psychoJS.shelf.counterbalanceSelect({\n" " key: ['%(name)s', '@designer', '@experiment'],\n" " groups: %(name)sConditions.map(row => row.group),\n" " groupSizes: %(name)sConditions.map(row => row.cap),\n" "});\n" ) buff.writeIndentedLines(code % self.params) # if ending experiment on depletion, write the code to do so if self.params['endExperimentOnDepletion']: code = ( "// if slots and repeats are fully depleted, end the experiment now\n" "if (%(name)s.finished) {\n" " quitPsychoJS('No more slots remaining for this study.', true)\n" "}\n" ) buff.writeIndentedLines(code % self.params) # save data if self.params['saveData']: code = ( "psychoJS.experiment.addData('%(name)s.group', %(name)s.group)\n" "for (let _key in %(name)s.params) {\n" " psychoJS.experiment.addData(`%(name)s.${_key}`, %(name)s.params[_key])\n" "}\n" ) buff.writeIndentedLines(code % self.params) # save remaining cap if self.params['saveRemaining']: code = ( "psychoJS.experiment.addData('%(name)s.remaining', %(name)s.remaining)\n" ) buff.writeIndentedLines(code % self.params) # exit function def code = ( " return Scheduler.Event.NEXT;\n" " }\n" "}\n" ) buff.setIndentLevel(-2, relative=True) buff.writeIndentedLines(code % self.params) def writeExperimentEndCodeJS(self, buff): code = ( "if (%(name)s && !%(name)s.finished) {\n" " await psychoJS.shelf.counterbalanceConfirm(\n" " ['%(name)s', '@designer', '@experiment'],\n" " %(name)s.participantToken,\n" " isCompleted\n" " );\n" "}\n" ) buff.writeIndentedLines(code % self.params)
12,744
Python
.py
295
30.989831
120
0.525913
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,586
__init__.py
psychopy_psychopy/psychopy/experiment/routines/pavlovia_survey/__init__.py
from psychopy.experiment.components import getInitVals from psychopy.experiment.routines import BaseStandaloneRoutine from psychopy.localization import _translate from psychopy.experiment import Param from pathlib import Path class PavloviaSurveyRoutine(BaseStandaloneRoutine): categories = ['Responses'] targets = ["PsychoJS"] version = "2023.1.0" iconFile = Path(__file__).parent / "survey.png" tooltip = _translate("Run a SurveyJS survey in Pavlovia") beta = False def __init__(self, exp, name='survey', surveyType="id", surveyId="", surveyJson="", disabled=False ): # Initialise base routine BaseStandaloneRoutine.__init__( self, exp=exp, name=name, disabled=disabled ) del self.params['stopVal'] del self.params['stopType'] self.url = "https://psychopy.org/builder/components/advanced_survey.html" self.type = "PavloviaSurvey" # Define relationships self.depends = [] self.order += [ 'surveyType', 'surveyId', 'surveyJson', ] self.params['surveyType'] = Param( surveyType, valType='code', inputType="richChoice", categ='Basic', allowedVals=["id", "json"], allowedLabels=[ {'label': _translate("Survey id"), 'body': _translate( "Linking to a survey ID from Pavlovia Surveys means that the content will automatically update " "if that survey changes (better for dynamic use)"), 'linkText': _translate("How do I get my survey ID?"), 'link': "https://psychopy.org/builder/components/advanced_survey.html#get-id", 'startShown': 'always'}, {'label': _translate("Survey Model File"), 'body': _translate( "Inserting a JSON file (exported from Pavlovia Surveys) means that the survey is embedded within " "this project and will not change unless you import it again (better for archiving)"), 'linkText': _translate("How do I get my survey model file?"), 'link': "https://psychopy.org/builder/components/advanced_survey.html#get-json", 'startShown': 'always'}, ], label=_translate("Survey type")) self.depends += [{ "dependsOn": "surveyType", # must be param name "condition": "=='id'", # val to check for "param": 'surveyId', # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }] self.params['surveyId'] = Param( surveyId, valType='str', inputType="survey", categ='Basic', hint=_translate( "The ID for your survey on Pavlovia. Tip: Right click to open the survey in your browser!" ), label=_translate("Survey id")) self.depends += [{ "dependsOn": "surveyType", # must be param name "condition": "=='json'", # val to check for "param": 'surveyJson', # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }] self.params['surveyJson'] = Param( surveyJson, valType='str', inputType="file", categ='Basic', hint=_translate( "File path of the JSON file used to construct the survey" ), label=_translate("Survey JSON")) def writeRoutineBeginCodeJS(self, buff, modular): code = ( "\n" "function %(name)sRoutineBegin(snapshot) {\n" " return async function () {\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(2, relative=True) # Usual routine setup stuff code = ( "TrialHandler.fromSnapshot(snapshot); // ensure that .thisN vals are up to date\n" "\n" "//--- Prepare to start Routine '%(name)s' ---\n" "t = 0;\n" "frameN = -1;\n" "continueRoutine = true; // until we're told otherwise\n" ) buff.writeIndentedLines(code % self.params) # Create Survey object code = ( "//--- Starting Routine '%(name)s' ---\n" "%(name)s = new visual.Survey({\n" " win: psychoJS.window,\n" " name: '%(name)s',\n" ) buff.writeIndentedLines(code % self.params) # Write either survey ID or model if self.params['surveyType'] == "id": code = ( " surveyId: %(surveyId)s,\n" ) else: code = ( " model: %(surveyJson)s,\n" ) buff.writeIndentedLines(code % self.params) code = ( "});\n" "%(name)sClock = new util.Clock();\n" "%(name)s.setAutoDraw(true);\n" "%(name)s.status = PsychoJS.Status.STARTED;\n" "%(name)s.isFinished = false;\n" "%(name)s.tStart = t; // (not accounting for frame time here)\n" "%(name)s.frameNStart = frameN; // exact frame index\n" "return Scheduler.Event.NEXT;\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-2, relative=True) code = ( " }\n" "}\n" ) buff.writeIndentedLines(code % self.params) def writeEachFrameCodeJS(self, buff, modular): code = ( "\n" "function %(name)sRoutineEachFrame() {\n" " return async function () {\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(2, relative=True) # Write each frame active code code = ( "t = %(name)sClock.getTime();\n" "frameN = frameN + 1; // number of completed frames (so 0 is the first frame)\n" "// if %(name)s is completed, move on\n" "if (%(name)s.isFinished) {\n" " %(name)s.setAutoDraw(false);\n" " %(name)s.status = PsychoJS.Status.FINISHED;\n" " // survey routines are not non-slip safe, so reset the non-slip timer\n" " routineTimer.reset();\n" " return Scheduler.Event.NEXT;\n" "}\n" ) buff.writeIndentedLines(code % self.params) # Check for escape if self.exp.settings.params['Enable Escape'].val: code = ("// check for quit (typically the Esc key)\n" "if (psychoJS.experiment.experimentEnded || psychoJS.eventManager.getKeys({keyList:['escape']}).length > 0) {\n" " return quitPsychoJS('The [Escape] key was pressed. Goodbye!', false);\n" "}\n") buff.writeIndentedLines(code) # Flip frame code = ( "return Scheduler.Event.FLIP_REPEAT;\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-2, relative=True) code = ( " }\n" "}\n" ) buff.writeIndentedLines(code % self.params) def writeRoutineEndCodeJS(self, buff, modular): code = ( "\n" "function %(name)sRoutineEnd(snapshot) {\n" " return async function () {\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(2, relative=True) code = ( "//--- Ending Routine '%(name)s' ---\n" "// get data from %(name)s\n" "const %(name)sResponse = %(name)s.getResponse();\n" "function addRecursively(resp, name) {\n" " if (resp.constructor === Object) {\n" " // if resp is an object, add each part as a column\n" " for (let subquestion in resp) {\n" " addRecursively(resp[subquestion], `${name}.${subquestion}`);\n" " }\n" " } else {\n" " psychoJS.experiment.addData(name, resp);\n" " }\n" "}\n" "// recursively add survey responses\n" "addRecursively(%(name)sResponse, '%(name)s');\n" ) if self.params['surveyType'] == "id": # Only call save if using an ID, otherwise saving is just to exp file code += ( "await %(name)s.save();\n" ) buff.writeIndentedLines(code % self.params) code = ( "// Routines running outside a loop should always advance the datafile row\n" "if (currentLoop === psychoJS.experiment) {\n" " psychoJS.experiment.nextEntry(snapshot);\n" "}\n" "return Scheduler.Event.NEXT;\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-2, relative=True) code = ( " }\n" "}\n" ) buff.writeIndentedLines(code % self.params)
9,324
Python
.py
215
31.567442
132
0.534441
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,587
__init__.py
psychopy_psychopy/psychopy/experiment/routines/eyetracker_validate/__init__.py
from copy import deepcopy from .. import BaseStandaloneRoutine from psychopy.localization import _translate from psychopy.experiment import Param from pathlib import Path from psychopy.alerts import alert positions = ['THREE_POINTS', 'FIVE_POINTS', 'NINE_POINTS', "THIRTEEN_POINTS", "SEVENTEEN_POINTS"] class EyetrackerValidationRoutine(BaseStandaloneRoutine): categories = ['Eyetracking'] targets = ["PsychoPy"] version = "2021.2.0" iconFile = Path(__file__).parent / "eyetracker_valid.png" tooltip = _translate("Validation routine for eyetrackers") beta = True def __init__(self, exp, name='validation', showCursor=True, cursorFillColor="green", innerFillColor='green', innerBorderColor='black', innerBorderWidth=2, innerRadius=0.0035, fillColor='', borderColor="black", borderWidth=2, outerRadius=0.01, colorSpace="rgb", units='from exp settings', textColor="auto", randomisePos=True, targetLayout="NINE_POINTS", targetPositions="NINE_POINTS", progressMode="time", targetDur=1.5, expandDur=1, expandScale=1.5, movementAnimation=True, movementDur=1.0, targetDelay=1.0, saveAsImg=False, showResults=True, disabled=False ): # Initialise base routine BaseStandaloneRoutine.__init__(self, exp, name=name, disabled=disabled) self.url = "https://psychopy.org/builder/components/eyetracker_validation.html" self.exp.requirePsychopyLibs(['iohub', 'hardware']) # Define relationships self.depends = [ # allows params to turn each other off/on # Only enable positions if targetLayout is custom {"dependsOn": "targetLayout", # must be param name "condition": "=='custom...'", # val to check for "param": "positions", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable }, ] # Basic params del self.params['stopVal'] del self.params['stopType'] self.order += [ "targetLayout", "targetPositions", "randomisePos", "showCursor", "cursorFillColor", "textColor" ] self.params['targetLayout'] = Param(targetLayout, valType='str', inputType="choice", categ='Basic', allowedVals=positions + ["CUSTOM..."], hint=_translate("Pre-defined target layouts"), label=_translate("Target layout")) self.depends.append( {"dependsOn": "targetLayout", # must be param name "condition": "not in {}".format(positions), # val to check for "param": "targetPositions", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) self.params['targetPositions'] = Param(targetPositions, valType='list', inputType="single", categ='Basic', hint=_translate( "List of positions (x, y) at which the target can appear"), label=_translate("Target positions")) self.params['randomisePos'] = Param(randomisePos, valType='bool', inputType="bool", categ='Basic', hint=_translate("Should the order of target positions be randomised?"), label=_translate("Randomise target positions")) self.params['cursorFillColor'] = Param(cursorFillColor, valType="color", inputType="color", categ="Basic", hint=_translate("Fill color of the gaze cursor"), label=_translate("Gaze cursor color")) self.params['textColor'] = Param(textColor, valType="color", inputType="color", categ="Basic", hint=_translate("Color of text used in validation procedure."), label=_translate("Text color")) # Target Params self.order += [ "targetStyle", "fillColor", "borderColor", "innerFillColor", "innerBorderColor", "colorSpace", "borderWidth", "innerBorderWidth", "outerRadius", "innerRadius", ] self.params['innerFillColor'] = Param(innerFillColor, valType='color', inputType="color", categ='Target', hint=_translate("Fill color of the inner part of the target"), label=_translate("Inner fill color")) self.params['innerBorderColor'] = Param(innerBorderColor, valType='color', inputType="color", categ='Target', hint=_translate("Border color of the inner part of the target"), label=_translate("Inner border color")) self.params['fillColor'] = Param(fillColor, valType='color', inputType="color", categ='Target', hint=_translate("Fill color of the outer part of the target"), label=_translate("Outer fill color")) self.params['borderColor'] = Param(borderColor, valType='color', inputType="color", categ='Target', hint=_translate("Border color of the outer part of the target"), label=_translate("Outer border color")) self.params['colorSpace'] = Param(colorSpace, valType='str', inputType="choice", categ='Target', allowedVals=['rgb', 'dkl', 'lms', 'hsv'], hint=_translate( "In what format (color space) have you specified the colors? (rgb, dkl, lms, hsv)"), label=_translate("Color space")) self.params['borderWidth'] = Param(borderWidth, valType='num', inputType="single", categ='Target', hint=_translate("Width of the line around the outer part of the target"), label=_translate("Outer border width")) self.params['innerBorderWidth'] = Param(innerBorderWidth, valType='num', inputType="single", categ='Target', hint=_translate( "Width of the line around the inner part of the target"), label=_translate("Inner border width")) self.params['outerRadius'] = Param(outerRadius, valType='num', inputType="single", categ='Target', hint=_translate("Size (radius) of the outer part of the target"), label=_translate("Outer radius")) self.params['innerRadius'] = Param(innerRadius, valType='num', inputType="single", categ='Target', hint=_translate("Size (radius) of the inner part of the target"), label=_translate("Inner radius")) self.params['units'] = Param(units, valType='str', inputType="choice", categ='Target', allowedVals=['from exp settings'], direct=False, hint=_translate("Units of dimensions for this stimulus"), label=_translate("Spatial units")) # Animation Params self.order += [ "progressMode", "targetDur", "expandDur", "expandScale", "movementAnimation", "movementDur", "targetDelay" ] self.params['progressMode'] = Param(progressMode, valType="str", inputType="choice", categ="Animation", allowedVals=["space key", "time"], hint=_translate("Should the target move to the next position after a " "keypress or after an amount of time?"), label=_translate("Progress mode")) self.depends.append( {"dependsOn": "progressMode", # must be param name "condition": "in ['time', 'either']", # val to check for "param": "targetDur", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) self.params['targetDur'] = Param(targetDur, valType='num', inputType="single", categ='Animation', hint=_translate( "Time limit (s) after which progress to next position"), label=_translate("Target duration")) self.depends.append( {"dependsOn": "progressMode", # must be param name "condition": "in ['space key', 'either']", # val to check for "param": "expandDur", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) self.params['expandDur'] = Param(expandDur, valType='num', inputType="single", categ='Animation', hint=_translate( "Duration of the target expand/contract animation"), label=_translate("Expand / contract duration")) self.params['expandScale'] = Param(expandScale, valType='num', inputType="single", categ='Animation', hint=_translate("How many times bigger than its size the target grows"), label=_translate("Expand scale")) self.params['movementAnimation'] = Param(movementAnimation, valType='bool', inputType="bool", categ='Animation', hint=_translate("Enable / disable animations as target stim changes position"), label=_translate("Animate position changes")) self.depends.append( {"dependsOn": "movementAnimation", # must be param name "condition": "== True", # val to check for "param": "movementDur", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) self.params['movementDur'] = Param(movementDur, valType='num', inputType="single", categ='Animation', hint=_translate( "Duration of the animation during position changes."), label=_translate("Movement duration")) self.depends.append( {"dependsOn": "movementAnimation", # must be param name "condition": "== False", # val to check for "param": "targetDelay", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) self.params['targetDelay'] = Param(targetDelay, valType='num', inputType="single", categ='Animation', hint=_translate( "Duration of the delay between positions."), label=_translate("Target delay")) # Data params self.order += [ "saveAsImg", "showResults", ] self.params['saveAsImg'] = Param(saveAsImg, valType='bool', inputType="bool", categ='Data', hint=_translate( "Save results as an image"), label=_translate("Save as image")) self.params['showResults'] = Param(showResults, valType='bool', inputType="bool", categ='Data', hint=_translate( "Show a screen with results after completion?"), label=_translate("Show results screen")) def writeMainCode(self, buff): # Alert user if eyetracking isn't setup if self.exp.eyetracking == "None": alert(code=4505) # Get inits inits = deepcopy(self.params) # Code-ify 'from exp settings' if inits['units'].val == 'from exp settings': inits['units'].val = None # Synonymise expand dur and target dur if inits['progressMode'].val == 'time': inits['expandDur'] = inits['targetDur'] if inits['progressMode'].val == 'space key': inits['targetDur'] = inits['expandDur'] # Synonymise movement dur and target delay if inits['movementAnimation'].val: inits['targetDelay'] = inits['movementDur'] else: inits['movementDur'] = inits['targetDelay'] # Convert progress mode to ioHub format if inits['progressMode'].val == 'space key': inits['progressKey'] = "'space'" else: inits['progressKey'] = "None" # If positions are preset, override param value if inits['targetLayout'].val in positions: inits['targetPositions'].val = inits['targetLayout'].val inits['targetPositions'].valType = 'str' BaseStandaloneRoutine.writeMainCode(self, buff) # Make target code = ( "# define target for %(name)s\n" "%(name)sTarget = visual.TargetStim(win, \n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "name='%(name)sTarget',\n" "radius=%(outerRadius)s, fillColor=%(fillColor)s, borderColor=%(borderColor)s, lineWidth=%(borderWidth)s,\n" "innerRadius=%(innerRadius)s, innerFillColor=%(innerFillColor)s, innerBorderColor=%(innerBorderColor)s, innerLineWidth=%(innerBorderWidth)s,\n" "colorSpace=%(colorSpace)s, units=%(units)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( ")" ) buff.writeIndentedLines(code % inits) # Make validation object code = ( "# define parameters for %(name)s\n" "%(name)s = iohub.ValidationProcedure(win,\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "target=%(name)sTarget,\n" "gaze_cursor=%(cursorFillColor)s, \n" "positions=%(targetPositions)s, randomize_positions=%(randomisePos)s,\n" "expand_scale=%(expandScale)s, target_duration=%(targetDur)s,\n" "enable_position_animation=%(movementAnimation)s, target_delay=%(targetDelay)s,\n" "progress_on_key=%(progressKey)s, text_color=%(textColor)s,\n" "show_results_screen=%(showResults)s, save_results_screen=%(saveAsImg)s,\n" "color_space=%(colorSpace)s, unit_type=%(units)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( ")\n" ) buff.writeIndentedLines(code % inits) # Run code = ( "# run %(name)s\n" "%(name)s.run()\n" "# clear any keypresses from during %(name)s so they don't interfere with the experiment\n" "defaultKeyboard.clearEvents()\n" ) buff.writeIndentedLines(code % inits)
17,578
Python
.py
307
37.267101
159
0.499477
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,588
__init__.py
psychopy_psychopy/psychopy/experiment/routines/eyetracker_calibrate/__init__.py
from .. import BaseStandaloneRoutine from psychopy.localization import _translate from psychopy.experiment import Param from pathlib import Path from psychopy.alerts import alert class EyetrackerCalibrationRoutine(BaseStandaloneRoutine): categories = ['Eyetracking'] targets = ["PsychoPy"] version = "2021.2.0" iconFile = Path(__file__).parent / "eyetracker_calib.png" tooltip = _translate("Calibration routine for eyetrackers") beta = True def __init__(self, exp, name='calibration', progressMode="time", targetDur=1.5, expandDur=1, expandScale=1.5, movementAnimation=True, movementDur=1.0, targetDelay=1.0, innerFillColor='green', innerBorderColor='black', innerBorderWidth=2, innerRadius=0.0035, fillColor='', borderColor="black", borderWidth=2, outerRadius=0.01, colorSpace="rgb", units='from exp settings', targetLayout="NINE_POINTS", randomisePos=True, textColor='white', disabled=False ): # Initialise base routine BaseStandaloneRoutine.__init__(self, exp, name=name, disabled=disabled) self.url = "https://psychopy.org/builder/components/eyetracker_calibration.html" self.exp.requirePsychopyLibs(['iohub', 'hardware']) # Basic params self.order += [ "targetLayout", "randomisePos", "textColor" ] del self.params['stopVal'] del self.params['stopType'] self.params['targetLayout'] = Param(targetLayout, valType='str', inputType="choice", categ='Basic', allowedVals=['THREE_POINTS', 'FIVE_POINTS', 'NINE_POINTS', "THIRTEEN_POINTS"], hint=_translate("Pre-defined target layouts"), label=_translate("Target layout")) self.params['randomisePos'] = Param(randomisePos, valType='bool', inputType="bool", categ='Basic', hint=_translate("Should the order of target positions be randomised?"), label=_translate("Randomise target positions")) self.params['textColor'] = Param(textColor, valType='color', inputType="color", categ='Basic', hint=_translate("Text foreground color"), label=_translate("Text color")) # Target Params self.order += [ "targetStyle", "fillColor", "borderColor", "innerFillColor", "innerBorderColor", "colorSpace", "borderWidth", "innerBorderWidth", "outerRadius", "innerRadius", ] self.params['innerFillColor'] = Param(innerFillColor, valType='color', inputType="color", categ='Target', hint=_translate("Fill color of the inner part of the target"), label=_translate("Inner fill color")) self.params['innerBorderColor'] = Param(innerBorderColor, valType='color', inputType="color", categ='Target', hint=_translate("Border color of the inner part of the target"), label=_translate("Inner border color")) self.params['fillColor'] = Param(fillColor, valType='color', inputType="color", categ='Target', hint=_translate("Fill color of the outer part of the target"), label=_translate("Outer fill color")) self.params['borderColor'] = Param(borderColor, valType='color', inputType="color", categ='Target', hint=_translate("Border color of the outer part of the target"), label=_translate("Outer border color")) self.params['colorSpace'] = Param(colorSpace, valType='str', inputType="choice", categ='Target', allowedVals=['rgb', 'dkl', 'lms', 'hsv'], hint=_translate( "In what format (color space) have you specified the colors? (rgb, dkl, lms, hsv)"), label=_translate("Color space")) self.params['borderWidth'] = Param(borderWidth, valType='num', inputType="single", categ='Target', hint=_translate("Width of the line around the outer part of the target"), label=_translate("Outer border width")) self.params['innerBorderWidth'] = Param(innerBorderWidth, valType='num', inputType="single", categ='Target', hint=_translate("Width of the line around the inner part of the target"), label=_translate("Inner border width")) self.params['outerRadius'] = Param(outerRadius, valType='num', inputType="single", categ='Target', hint=_translate("Size (radius) of the outer part of the target"), label=_translate("Outer radius")) self.params['innerRadius'] = Param(innerRadius, valType='num', inputType="single", categ='Target', hint=_translate("Size (radius) of the inner part of the target"), label=_translate("Inner radius")) self.params['units'] = Param(units, valType='str', inputType="choice", categ='Target', allowedVals=['from exp settings'], direct=False, hint=_translate("Units of dimensions for this stimulus"), label=_translate("Spatial units")) # Animation Params self.order += [ "progressMode", "targetDur", "expandDur", "expandScale", "movementAnimation", "movementDur", "targetDelay" ] self.params['progressMode'] = Param(progressMode, valType="str", inputType="choice", categ="Animation", allowedVals=["space key", "time"], hint=_translate("Should the target move to the next position after a " "keypress or after an amount of time?"), label=_translate("Progress mode")) self.depends.append( {"dependsOn": "progressMode", # must be param name "condition": "in ['time', 'either']", # val to check for "param": "targetDur", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) self.params['targetDur'] = Param(targetDur, valType='num', inputType="single", categ='Animation', hint=_translate( "Time limit (s) after which progress to next position"), label=_translate("Target duration")) self.depends.append( {"dependsOn": "progressMode", # must be param name "condition": "in ['space key', 'either']", # val to check for "param": "expandDur", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) self.params['expandDur'] = Param(expandDur, valType='num', inputType="single", categ='Animation', hint=_translate( "Duration of the target expand/contract animation"), label=_translate("Expand / contract duration")) self.params['expandScale'] = Param(expandScale, valType='num', inputType="single", categ='Animation', hint=_translate("How many times bigger than its size the target grows"), label=_translate("Expand scale")) self.params['movementAnimation'] = Param(movementAnimation, valType='bool', inputType="bool", categ='Animation', hint=_translate( "Enable / disable animations as target stim changes position"), label=_translate("Animate position changes")) self.depends.append( {"dependsOn": "movementAnimation", # must be param name "condition": "== True", # val to check for "param": "movementDur", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) self.params['movementDur'] = Param(movementDur, valType='num', inputType="single", categ='Animation', hint=_translate( "Duration of the animation during position changes."), label=_translate("Movement duration")) self.depends.append( {"dependsOn": "movementAnimation", # must be param name "condition": "== False", # val to check for "param": "targetDelay", # param property to alter "true": "show", # what to do with param if condition is True "false": "hide", # permitted: hide, show, enable, disable } ) self.params['targetDelay'] = Param(targetDelay, valType='num', inputType="single", categ='Animation', hint=_translate( "Duration of the delay between positions."), label=_translate("Target delay")) def writeMainCode(self, buff): # Alert user if eyetracking isn't setup if self.exp.eyetracking == "None": alert(code=4505) # Get inits inits = self.params # Code-ify 'from exp settings' if self.params['units'].val == 'from exp settings': inits['units'].val = None # Synonymise expand dur and target dur if inits['progressMode'].val == 'time': inits['expandDur'] = inits['targetDur'] if inits['progressMode'].val == 'space key': inits['targetDur'] = inits['expandDur'] # Synonymise movement dur and target delay if inits['movementAnimation'].val: inits['targetDelay'] = inits['movementDur'] else: inits['movementDur'] = inits['targetDelay'] BaseStandaloneRoutine.writeMainCode(self, buff) # Make target code = ( "# define target for %(name)s\n" "%(name)sTarget = visual.TargetStim(win, \n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "name='%(name)sTarget',\n" "radius=%(outerRadius)s, fillColor=%(fillColor)s, borderColor=%(borderColor)s, lineWidth=%(borderWidth)s,\n" "innerRadius=%(innerRadius)s, innerFillColor=%(innerFillColor)s, innerBorderColor=%(innerBorderColor)s, innerLineWidth=%(innerBorderWidth)s,\n" "colorSpace=%(colorSpace)s, units=%(units)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( ")" ) buff.writeIndentedLines(code % inits) # Make config object code = ( "# define parameters for %(name)s\n" "%(name)s = hardware.eyetracker.EyetrackerCalibration(win, \n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "eyetracker, %(name)sTarget,\n" "units=%(units)s, colorSpace=%(colorSpace)s,\n" "progressMode=%(progressMode)s, targetDur=%(targetDur)s, expandScale=%(expandScale)s,\n" "targetLayout=%(targetLayout)s, randomisePos=%(randomisePos)s, textColor=%(textColor)s,\n" "movementAnimation=%(movementAnimation)s, targetDelay=%(targetDelay)s\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( ")\n" "# run calibration\n" "%(name)s.run()\n" "# clear any keypresses from during %(name)s so they don't interfere with the experiment\n" "defaultKeyboard.clearEvents()\n" ) buff.writeIndentedLines(code % inits)
14,143
Python
.py
242
37.743802
159
0.497693
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,589
__init__.py
psychopy_psychopy/psychopy/experiment/routines/photodiodeValidator/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path from psychopy.experiment import Param from psychopy.experiment.plugins import PluginDevicesMixin, DeviceBackend from psychopy.experiment.components import getInitVals from psychopy.experiment.routines import Routine, BaseValidatorRoutine from psychopy.localization import _translate class PhotodiodeValidatorRoutine(BaseValidatorRoutine, PluginDevicesMixin): """ Use a photodiode to confirm that stimuli are presented when they should be. """ targets = ['PsychoPy'] categories = ['Validation'] iconFile = Path(__file__).parent / 'photodiode_validator.png' tooltip = _translate('Photodiode validator') deviceClasses = [] version = "2025.1.0" def __init__( self, # basic exp, name='photodiode', variability="1/60", report="log", findThreshold=True, threshold=127, # layout findDiode=True, diodePos="(1, 1)", diodeSize="(0.1, 0.1)", diodeUnits="norm", # device deviceLabel="", deviceBackend="screenbuffer", port="", channel="0", # data saveValid=True, ): self.exp = exp # so we can access the experiment if necess self.params = {} self.depends = [] super(PhotodiodeValidatorRoutine, self).__init__(exp, name=name) self.order += [] self.type = 'PhotodiodeValidator' exp.requireImport( importName="photodiode", importFrom="psychopy.hardware", importAs="phd" ) # --- Basic --- self.order += [ "variability", "report", "findThreshold", "threshold", "findDiode", "diodePos", "diodeSize", "diodeUnits", ] self.params['variability'] = Param( variability, valType="code", inputType="single", categ="Basic", label=_translate("Variability (s)"), hint=_translate( "How much variation from intended presentation times (in seconds) is acceptable?" ) ) self.params['report'] = Param( report, valType="str", inputType="choice", categ="Basic", allowedVals=["log", "err"], allowedLabels=[_translate("Log warning"), _translate("Raise error")], label=_translate("On fail..."), hint=_translate( "What to do when the validation fails. Just log, or stop the script and raise an error?" ) ) self.params['findThreshold'] = Param( findThreshold, valType="bool", inputType="bool", categ="Basic", label=_translate("Find best threshold?"), hint=_translate( "Run a brief Routine to find the best threshold for the photodiode at experiment start?" ) ) self.params['threshold'] = Param( threshold, valType="code", inputType="single", categ="Basic", label=_translate("Threshold"), hint=_translate( "Light threshold at which the photodiode should register a positive, units go from 0 (least light) to " "255 (most light)." ) ) self.depends.append({ "dependsOn": "findThreshold", # if... "condition": "==True", # is... "param": "threshold", # then... "true": "hide", # should... "false": "show", # otherwise... }) self.params['findDiode'] = Param( findDiode, valType="code", inputType="bool", categ="Basic", label=_translate("Find diode?"), hint=_translate( "Run a brief Routine to find the size and position of the photodiode at experiment start?" ) ) self.params['diodePos'] = Param( diodePos, valType="list", inputType="single", categ="Basic", updates="constant", allowedUpdates=['constant', 'set every repeat', 'set every frame'], label=_translate("Position [x,y]"), hint=_translate( "Position of the photodiode on the window." ) ) self.params['diodeSize'] = Param( diodeSize, valType="list", inputType="single", categ="Basic", updates="constant", allowedUpdates=['constant', 'set every repeat', 'set every frame'], label=_translate("Size [x,y]"), hint=_translate( "Size of the area covered by the photodiode on the window." ) ) self.params['diodeUnits'] = Param( diodeUnits, valType="str", inputType="choice", categ="Basic", allowedVals=['from exp settings', 'deg', 'cm', 'pix', 'norm', 'height', 'degFlatPos', 'degFlat'], label=_translate("Spatial units"), hint=_translate( "Spatial units in which the photodiode size and position are specified." ) ) for param in ("diodePos", "diodeSize", "diodeUnits"): self.depends.append({ "dependsOn": "findDiode", # if... "condition": "==True", # is... "param": param, # then... "true": "hide", # should... "false": "show", # otherwise... }) del self.params['stopType'] del self.params['stopVal'] # --- Device --- self.order += [ "deviceLabel", "deviceBackend", "channel", ] self.params['deviceLabel'] = Param( deviceLabel, valType="str", inputType="single", categ="Device", label=_translate("Device name"), hint=_translate( "A name to refer to this Component's associated hardware device by. If using the " "same device for multiple components, be sure to use the same name here." ) ) self.params['deviceBackend'] = Param( deviceBackend, valType="code", inputType="choice", categ="Device", allowedVals=self.getBackendKeys, allowedLabels=self.getBackendLabels, label=_translate("Photodiode type"), hint=_translate( "Type of photodiode to use." ), direct=False ) self.params['channel'] = Param( channel, valType="code", inputType="single", categ="Device", label=_translate("Photodiode channel"), hint=_translate( "If relevant, a channel number attached to the photodiode, to distinguish it " "from other photodiodes on the same port. Leave blank to use the first photodiode " "which can detect the Window." ) ) # --- Data --- self.params['saveValid'] = Param( saveValid, valType="code", inputType="bool", categ="Data", label=_translate('Save validation results'), hint=_translate( "Save validation results after validating on/offset times for stimuli" ) ) self.loadBackends() def writeDeviceCode(self, buff): """ Code to setup the CameraDevice for this component. Parameters ---------- buff : io.StringIO Text buffer to write code to. """ # do usual backend-specific device code writing PluginDevicesMixin.writeDeviceCode(self, buff) # get inits inits = getInitVals(self.params) # get device handle code = ( "%(deviceLabelCode)s = deviceManager.getDevice(%(deviceLabel)s)" ) buff.writeOnceIndentedLines(code % inits) # find threshold if indicated if self.params['findThreshold']: code = ( "# find threshold for photodiode\n" "if %(deviceLabelCode)s.getThreshold(channel=%(channel)s) is None:\n" " %(deviceLabelCode)s.findThreshold(win, channel=%(channel)s)\n" ) else: code = ( "%(deviceLabelCode)s.setThreshold(%(threshold)s, channel=%(channel)s)" ) buff.writeOnceIndentedLines(code % inits) # find pos if indicated if self.params['findDiode']: code = ( "# find position and size of photodiode\n" "if %(deviceLabelCode)s.pos is None and %(deviceLabelCode)s.size is None and %(deviceLabelCode)s.units is None:\n" " %(deviceLabelCode)s.findPhotodiode(win, channel=%(channel)s)\n" ) buff.writeOnceIndentedLines(code % inits) def writeMainCode(self, buff): inits = getInitVals(self.params) # get diode code = ( "# diode object for %(name)s\n" "%(name)sDiode = deviceManager.getDevice(%(deviceLabel)s)\n" ) buff.writeIndentedLines(code % inits) if self.params['threshold'] and not self.params['findThreshold']: code = ( "%(name)sDiode.setThreshold(%(threshold)s, channel=%(channel)s)\n" ) buff.writeIndentedLines(code % inits) # find/set diode position if not self.params['findDiode']: code = "" # set units (unless None) if self.params['diodeUnits']: code += ( "%(name)sDiode.units = %(diodeUnits)s\n" ) # set pos (unless None) if self.params['diodePos']: code += ( "%(name)sDiode.pos = %(diodePos)s\n" ) # set size (unless None) if self.params['diodeSize']: code += ( "%(name)sDiode.size = %(diodeSize)s\n" ) buff.writeIndentedLines(code % inits) # create validator object code = ( "# validator object for %(name)s\n" "%(name)s = phd.PhotodiodeValidator(\n" " win, %(name)sDiode, %(channel)s,\n" " variability=%(variability)s,\n" " report=%(report)s,\n" ")\n" ) buff.writeIndentedLines(code % inits) # connect stimuli for stim in self.findConnectedStimuli(): code = ( "# connect {stim} to %(name)s\n" "%(name)s.connectStimulus({stim})\n" ).format(stim=stim.params['name']) buff.writeIndentedLines(code % inits) def writeRoutineStartValidationCode(self, buff, stim): """ Write the routine start code to validate a given stimulus using this validator. Parameters ---------- buff : StringIO String buffer to write code to. stim : BaseComponent Stimulus to validate Returns ------- int Change in indentation level after writing """ # get starting indent level startIndent = buff.indentLevel # choose a clock to sync to according to component's params if "syncScreenRefresh" in stim.params and stim.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) # return change in indent level return buff.indentLevel - startIndent def writeEachFrameValidationCode(self, buff, stim): """ Write the each frame code to validate a given stimulus using this validator. Parameters ---------- buff : StringIO String buffer to write code to. stim : BaseComponent Stimulus to validate Returns ------- int Change in indentation level after writing """ # get starting indent level startIndent = buff.indentLevel # validate start time code = ( "# validate {name} start time\n" "if {name}.status == STARTED and %(name)s.status == STARTED:\n" " %(name)s.tStart, %(name)s.tStartValid = %(name)s.validate(state=True, t={name}.tStartRefresh)\n" " if %(name)s.tStart is not None:\n" " %(name)s.status = FINISHED\n" ) if stim.params['saveStartStop']: # save validated start time if stim requested code += ( " thisExp.addData('{name}.%(name)s.started', %(name)s.tStart)\n" ) if self.params['saveValid']: # save validation result if params requested code += ( " thisExp.addData('{name}.started.valid', %(name)s.tStartValid)\n" ) buff.writeIndentedLines(code.format(**stim.params) % self.params) # validate stop time code = ( "# validate {name} stop time\n" "if {name}.status == FINISHED and %(name)s.status == STARTED:\n" " %(name)s.tStop, %(name)s.tStopValid = %(name)s.validate(state=False, t={name}.tStopRefresh)\n" " if %(name)s.tStop is not None:\n" " %(name)s.status = FINISHED\n" ) if stim.params['saveStartStop']: # save validated start time if stim requested code += ( " thisExp.addData('{name}.%(name)s.stopped', %(name)s.tStop)\n" ) if self.params['saveValid']: # save validation result if params requested code += ( " thisExp.addData('{name}.stopped.valid', %(name)s.tStopValid)\n" ) buff.writeIndentedLines(code.format(**stim.params) % self.params) # return change in indent level return buff.indentLevel - startIndent def findConnectedStimuli(self): # list of linked components stims = [] # inspect each Routine for emt in self.exp.flow: # skip non-standard Routines if not isinstance(emt, Routine): continue # inspect each Component for comp in emt: # get validators for this component compValidator = comp.getValidator() # look for self if compValidator == self: # if found, add the comp to the list stims.append(comp) return stims class ScreenBufferPhotodiodeValidatorBackend(DeviceBackend): """ Adds a basic screen buffer emulation backend for PhotodiodeValidator, as well as acting as an example for implementing other photodiode device backends. """ key = "screenbuffer" label = _translate("Screen Buffer (Debug)") component = PhotodiodeValidatorRoutine deviceClasses = ["psychopy.hardware.photodiode.ScreenBufferSampler"] def getParams(self: PhotodiodeValidatorRoutine): # define order order = [ ] # define params params = {} return params, order def addRequirements(self): # no requirements needed - so just return return def writeDeviceCode(self: PhotodiodeValidatorRoutine, buff): # get inits inits = getInitVals(self.params) # make ButtonGroup object code = ( "deviceManager.addDevice(\n" " deviceClass='psychopy.hardware.photodiode.ScreenBufferSampler',\n" " deviceName=%(deviceLabel)s,\n" " win=win,\n" ")\n" ) buff.writeOnceIndentedLines(code % inits)
15,995
Python
.py
393
29.407125
130
0.555156
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,590
__init__.py
psychopy_psychopy/psychopy/experiment/routines/unknown/__init__.py
from .. import BaseStandaloneRoutine from pathlib import Path class UnknownRoutine(BaseStandaloneRoutine): categories = ['Other'] targets = [] iconFile = Path(__file__).parent / "unknown.png" tooltip = "Unknown routine" def __init__(self, exp, name=''): BaseStandaloneRoutine.__init__(self, exp, name=name) def writeMainCode(self, buff): code = ( "\n" "# Unknown standalone routine ignored: %(name)s\n" "\n" ) buff.writeIndentedLines(code % self.params) def writeRoutineBeginCodeJS(self, buff): code = ( "\n" "// Unknown standalone routine ignored: %(name)s\n" "\n" ) buff.writeIndentedLines(code % self.params)
773
Python
.py
23
25.608696
63
0.591946
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,591
__init__.py
psychopy_psychopy/psychopy/experiment/components/__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). """Extensible set of components for the PsychoPy Builder view. """ import sys import os import glob import copy import shutil from os.path import join, dirname, abspath, split from importlib import import_module # helps python 2.7 -> 3.x migration from ._base import BaseVisualComponent, BaseComponent, BaseDeviceComponent from ..params import Param from psychopy.localization import _translate from psychopy.experiment import py2js import psychopy.logging as logging excludeComponents = [ 'BaseComponent', 'BaseVisualComponent', 'BaseDeviceComponent', 'BaseStandaloneRoutine' # templates only ] # this one isn't ready yet # Plugin components are added dynamically at runtime, usually from plugin # packages. These are managed by a different system than 'legacy' # components. pluginComponents = {} # try to remove old pyc files in case they're detected as components pycFiles = glob.glob(join(split(__file__)[0], "*.pyc")) for filename in pycFiles: # check for matching py file if not os.path.isfile(filename[:-2]): try: os.remove(filename) except: pass # may not have sufficient privs def addComponent(compClass): """Add a component to Builder. This function will override any component already loaded with the same class name. Usually, this function is called by the plugin system. The user typically does not need to call this. Parameters ---------- compClass : object Component class. Should be a subclass of `BaseComponent`. """ global pluginComponents # components loaded at runtime compName = compClass.__name__ logging.debug("Registering Builder component class `{}`.".format(compName)) # check type and attributes of the class if not issubclass(compClass, (BaseComponent, BaseVisualComponent)): return elif not hasattr(compClass, 'categories'): logging.warning( "Component `{}` does not define a `.categories` attribute.".format( compName)) pluginComponents[compName] = compClass def getAllCategories(folderList=()): """Get all component categories. Parameters ---------- folderList : list or tuple List of directories to search for components. These are for 'legacy'-style components. Using plugins is now the prefered method of adding components to Builder. Returns ------- list of str Names of all categories which the working set of components specify. """ allComps = getAllComponents(folderList) # Hardcode some categories to always appear first/last firstCats = ['Favorites', 'Stimuli', 'Responses', 'Custom'] lastCats = ['I/O', 'Other'] # Start getting categories allCats = firstCats for name, thisComp in list(allComps.items()): for thisCat in thisComp.categories: if thisCat not in allCats + lastCats: allCats.append(thisCat) return allCats + lastCats def getAllComponents(folderList=(), fetchIcons=True): """Get all available components, from the builtins, plugins and folders. User-defined components will override built-ins with the same name. Parameters ---------- folderList : list or tuple List of directories to search for components. fetchIcons : bool Whether to also fetch icons. Default is `True`. """ if isinstance(folderList, str): raise TypeError('folderList should be iterable, not a string') components = getComponents(fetchIcons=fetchIcons) # get the built-ins for folder in folderList: userComps = getComponents(folder) for thisKey in userComps: components[thisKey] = userComps[thisKey] # add components registered by plugins that have been loaded components.update(pluginComponents) return components def getComponents(folder=None, fetchIcons=True): """Get a dictionary of available components for the Builder experiments. If folder is None then the built-in components will be imported and returned, otherwise the components found in the folder provided will be. Changed v1.84.00: The Builder preference "components folders" should be of the form: `/.../.../compts`. This is unchanged from previously, and allows for backwards compatibility. New as of v1.84: A slightly different directory structure is needed. An existing directory will be automatically upgraded if the previous one was not empty. However, files starting with '_' will be skipped, as will any directories. You will need to manually move those into the new directory (from the old .../compts/ into the new .../compts/compts/). As of v1.84, a components path needs directory structure `/.../.../compts/compts`. That is, the path should end with the name repeated. (It does not need to be 'compts' literally.) The .py and .png files for a component should all go in this directory. (Previously, files were in `/.../.../compts`.) In addition, the directory must contain a python init file, ` /.../.../compts/compts/__init__.py`, to allow it to be treated as a module in python so that the components can be imported. For this reason, the file name for a component cannot begin with a number; it must be a legal python name. The code within the component.py file itself must use absolute paths for importing from psychopy: `from psychopy.experiment.components import BaseComponent, Param` """ if folder is None: pth = folder = dirname(__file__) pkg = 'psychopy.experiment.components' else: # default shared location is often not actually a folder if not os.path.isdir(folder): return {} pth = folder = folder.rstrip(os.sep) pkg = os.path.basename(folder) if not folder.endswith(join(pkg, pkg)): folder = os.path.join(folder, pkg) # update the old style directory (v1.83.03) to the new style # try to retain backwards compatibility: copy files, not move them # ideally hard link them, but permissions fail on windows if not os.path.isdir(folder): files = [f for f in glob.glob(join(pth, '*')) if not os.path.isdir(f) and not f[0] in '_0123456789'] if files: os.mkdir(folder) with open(join(folder, '__init__.py'), 'a') as fileh: fileh.write('') for f in files: if f.startswith('_'): continue shutil.copy(f, folder) if pth not in sys.path: sys.path.insert(0, pth) components = {} # go through components in directory cfiles = glob.glob(os.path.join(folder, '*.py')) # old-style: just comp.py # new-style: directories w/ __init__.py dfiles = [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))] for cmpfile in cfiles + dfiles: cmpfile = os.path.split(cmpfile)[1] if cmpfile[0] in '_0123456789': # __init__.py, _base.py, leading digit continue # can't use imp - breaks py2app: # module = imp.load_source(file[:-3], fullPath) # v1.83.00 used exec(implicit-relative), no go for python3: # exec('import %s as module' % file[:-3]) # importlib.import_module eases 2.7 -> 3.x migration if cmpfile.endswith('.py'): explicit_rel_path = pkg + '.' + cmpfile[:-3] else: explicit_rel_path = pkg + '.' + cmpfile try: module = import_module(explicit_rel_path, package=pkg) except ImportError: logging.error( 'Failed to load component package `{}`. Does it have a ' '`__init__.py`?'.format(cmpfile)) continue # not a valid module (no __init__.py?) # check for orphaned pyc files (__file__ is not a .py file) if hasattr(module, '__file__'): if not module.__file__: # with Py3, orphans have a __pycharm__ folder but no file continue elif module.__file__.endswith('.pyc'): # with Py2, orphans have a xxxxx.pyc file if not os.path.isfile(module.__file__[:-1]): continue # looks like an orphaned pyc file # give a default category if not hasattr(module, 'categories'): module.categories = ['Custom'] # check if module contains a component for attrib in dir(module): name = None # fetch the attribs that end with 'Component' if attrib.endswith('omponent') and attrib not in excludeComponents: name = attrib components[attrib] = getattr(module, attrib) # skip if this class was imported, not defined here if module.__name__ != components[attrib].__module__: continue # class was defined in different module if hasattr(module, 'tooltip'): tooltips[name] = module.tooltip if hasattr(components[attrib], 'iconFile'): iconFiles[name] = components[attrib].iconFile # assign the module categories to the Component if not hasattr(components[attrib], 'categories'): components[attrib].categories = ['Custom'] return components def getInitVals(params, target="PsychoPy"): """Works out a suitable initial value for a parameter (e.g. to go into the __init__ of a stimulus object, avoiding using a variable name if possible """ inits = copy.deepcopy(params) # Alias units = from exp settings with None if 'units' in inits and str(inits['units'].val).lower() in ( "from experiment settings", "from exp settings", "none" ): if target == "PsychoJS": inits['units'].val = "psychoJS.window.units" else: inits['units'].val = "win.units" inits['units'].valType = 'code' for name in params: if target == "PsychoJS": # convert (0,0.5) to [0,0.5] but don't convert "rand()" to "rand[]" and don't convert text valStr = str(inits[name].val).strip() if valStr.startswith("(") and valStr.endswith(")") and name != 'text': inits[name].val = py2js.expression2js(inits[name].val) # filenames (e.g. for image) need to be loaded from resources if name in ["sound"]: val = str(inits[name].val) if val not in [None, 'None', 'none', '']: inits[name].val = ("psychoJS.resourceManager.getResource({})" .format(inits[name])) inits[name].valType = 'code' if name == "deviceLabel": if "name" in inits and not params[name]: # if deviceName exists but is blank, use component name inits[name].val = inits['name'].val # make a code version of device name inits['deviceLabelCode'] = copy.copy(inits[name]) inits['deviceLabelCode'].valType = "code" if not hasattr(inits[name], 'updates'): # might be settings parameter instead continue # value should be None (as code) elif inits[name].val in [None, 'None', 'none', '']: if name in ['text']: inits[name].val = None inits[name].valType = 'extendedStr' else: inits[name].val = 'None' inits[name].valType = 'code' # is constant so don't touch the parameter value elif inits[name].updates in ['constant', None, 'None']: continue # things that are constant don't need handling # is changing so work out a reasonable default elif name in ['pos', 'fieldPos']: inits[name].val = '[0,0]' inits[name].valType = 'code' elif name in ['color', 'foreColor', 'borderColor', 'lineColor', 'fillColor']: inits[name].val = 'white' inits[name].valType = 'str' elif name in ['ori', 'sf', 'size', 'height', 'letterHeight', 'lineWidth', 'phase', 'opacity', 'volume', # sounds 'coherence', 'nDots', 'fieldSize', 'dotSize', 'dotLife', 'dir', 'speed', 'contrast', 'moddepth', 'envori', 'envphase', 'envsf', 'noiseClip', 'noiseBWO', 'noiseFilterUpper', 'noiseFilterLower', 'noiseBaseSf', 'noiseBW', 'noiseElementSize', 'noiseFilterOrder', 'noiseFractalPower', 'zoom']: inits[name].val = "1.0" inits[name].valType = 'code' elif name in ['progress']: inits[name].val = "0.0" inits[name].valType = 'code' elif name in ['image']: inits[name].val = "default.png" inits[name].valType = 'str' elif name in ['mask', 'envelope', 'carrier']: inits[name].val = "sin" inits[name].valType = 'str' elif name == 'texture resolution': inits[name].val = "128" inits[name].valType = 'code' elif name == 'colorSpace': inits[name].val = "rgb" inits[name].valType = 'str' elif name == 'font': inits[name].val = "Arial" inits[name].valType = 'str' elif name == 'units': inits[name].val = "norm" inits[name].valType = 'str' elif name in ('text', 'placeholder'): inits[name].val = "" inits[name].valType = 'str' elif name == 'flip': inits[name].val = "" inits[name].valType = 'str' elif name == 'sound': inits[name].val = "A" inits[name].valType = 'str' elif name == 'blendmode': inits[name].val = "avg" inits[name].valType = 'str' elif name == 'beat': inits[name].val = "False" inits[name].valType = 'str' elif name == 'noiseImage': inits[name].val = "None" inits[name].valType = 'str' elif name == 'noiseType': inits[name].val = 'Binary' inits[name].valType = 'str' elif name == 'emotiv_marker_label': inits[name].val = 'Label' inits[name].valType = 'str' elif name == 'emotiv_marker_value': inits[name].val = 'Value' inits[name].valType = 'str' elif name == 'buttonRequired': inits[name].val = "True" inits[name].valType = 'code' elif name == 'vertices': inits[name].val = "[[-0.5,-0.5], [-0.5, 0.5], [0.5, 0.5], [0.5, -0.5]]" inits[name].valType = 'code' elif name == 'shape': inits[name].val = 'triangle' inits[name].valType = 'str' elif name in ('movie', 'latitude', 'longitude', 'elevation', 'azimuth', 'speechPoint'): inits[name].val = 'None' inits[name].valType = 'code' elif name == 'allowedKeys': inits[name].val = "[]" inits[name].valType = 'code' else: # if not explicitly handled, default to None inits[name].val = "None" inits[name].valType = "code" return inits tooltips = {} iconFiles = {} if __name__ == "__main__": pass
15,947
Python
.py
352
35.454545
102
0.59687
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,592
_base.py
psychopy_psychopy/psychopy/experiment/components/_base.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). """ import copy import textwrap from pathlib import Path from xml.etree.ElementTree import Element from psychopy import prefs from psychopy.constants import FOREVER from ..params import Param from psychopy.experiment.utils import canBeNumeric from psychopy.experiment.utils import CodeGenerationException from psychopy.experiment.utils import unescapedDollarSign_re from psychopy.experiment.params import getCodeFromParamStr from psychopy.alerts import alerttools from psychopy.colors import nonAlphaSpaces from psychopy.localization import _translate class BaseComponent: """A template for components, defining the methods to be overridden""" # override the categories property below # an attribute of the class, determines the section in the components panel categories = ['Custom'] targets = [] plugin = None iconFile = Path(__file__).parent / "unknown" / "unknown.png" tooltip = "" # what version was this Component added in? version = "0.0.0" # is it still in beta? beta = False def __init__(self, exp, parentName, name='', startType='time (s)', startVal='', stopType='duration (s)', stopVal='', startEstim='', durationEstim='', saveStartStop=True, syncScreenRefresh=False, disabled=False): self.type = type(self).__name__ 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 = [] # allows params to turn each other off/on """{ "dependsOn": "shape", "condition": "=='n vertices", "param": "n vertices", "true": "enable", # what to do with param if condition is True "false": "disable", # permitted: hide, show, enable, disable }""" self.order = ['name', 'startVal', 'startEstim', 'startType', 'stopVal', 'durationEstim', 'stopType'] # name first, then timing, then others msg = _translate( "Name of this Component (alphanumeric or _, no spaces)") self.params['name'] = Param(name, valType='code', inputType="single", categ='Basic', hint=msg, label=_translate("Name")) msg = _translate("How do you want to define your start point?") self.params['startType'] = Param(startType, valType='str', inputType="choice", categ='Basic', allowedVals=['time (s)', 'frame N', 'condition'], hint=msg, direct=False, label=_translate("Start type")) msg = _translate("How do you want to define your end point?") self.params['stopType'] = Param(stopType, valType='str', inputType="choice", categ='Basic', allowedVals=['duration (s)', 'duration (frames)', 'time (s)', 'frame N', 'condition'], hint=msg, direct=False, label=_translate("Stop type")) self.params['startVal'] = Param(startVal, valType='code', inputType="single", categ='Basic', hint=_translate("When does the Component start?"), allowedTypes=[], label=_translate("Start")) self.params['stopVal'] = Param(stopVal, valType='code', inputType="single", categ='Basic', updates='constant', allowedUpdates=[], allowedTypes=[], hint=_translate("When does the Component end? (blank is endless)"), label=_translate("Stop")) msg = _translate("(Optional) expected start (s), purely for " "representing in the timeline") self.params['startEstim'] = Param(startEstim, valType='code', inputType="single", categ='Basic', hint=msg, allowedTypes=[], direct=False, label=_translate("Expected start (s)")) msg = _translate("(Optional) expected duration (s), purely for " "representing in the timeline") self.params['durationEstim'] = Param(durationEstim, valType='code', inputType="single", categ='Basic', hint=msg, allowedTypes=[], direct=False, label=_translate("Expected duration (s)")) msg = _translate("Store the onset/offset times in the data file " "(as well as in the log file).") self.params['saveStartStop'] = Param(saveStartStop, valType='bool', inputType="bool", categ='Data', hint=msg, allowedTypes=[], label=_translate('Save onset/offset times')) msg = _translate("Synchronize times with screen refresh (good for " "visual stimuli and responses based on them)") self.params['syncScreenRefresh'] = Param(syncScreenRefresh, valType='bool', inputType="bool", categ="Data", hint=msg, allowedTypes=[], label=_translate('Sync timing with screen refresh')) msg = _translate("Disable this Component") self.params['disabled'] = Param(disabled, valType='bool', inputType="bool", categ="Testing", hint=msg, allowedTypes=[], direct=False, label=_translate('Disable Component')) @property def _xml(self): return self.makeXmlNode(self.__class__.__name__) def makeXmlNode(self, tag): # Make root element element = Element(tag) element.set("name", self.params['name'].val) element.set("plugin", str(self.plugin)) # Add an element for each parameter for key, param in sorted(self.params.items()): # Create node paramNode = param._xml paramNode.set("name", key) # Add node element.append(paramNode) return element def __repr__(self): _rep = "psychopy.experiment.components.%s(name='%s', exp=%s)" return _rep % (self.__class__.__name__, self.name, self.exp) def copy(self, exp=None, parentName=None, name=None): # Alias None with current attributes if exp is None: exp = self.exp if parentName is None: parentName = self.parentName if name is None: name = self.name # Create new component of same class with bare minimum inputs newCompon = type(self)(exp=exp, parentName=parentName, name=name) # Add params for name, param in self.params.items(): # Don't copy name if name == "name": continue # Copy other params newCompon.params[name] = copy.deepcopy(param) return newCompon def hideParam(self, name): """ Set a param to always be hidden. Parameters ========== name : str Name of the param to hide """ # Add to depends, but have it depend on itself and be hidden either way self.depends.append( { "dependsOn": name, # if... "condition": "", # meets... "param": name, # then... "true": "hide", # should... "false": "hide", # otherwise... } ) def integrityCheck(self): """ Run component integrity checks for non-visual components """ alerttools.testDisabled(self) alerttools.testStartEndTiming(self) def _dubiousConstantUpdates(self): """Return a list of fields in component that are set to be constant but seem intended to be dynamic. Some code fields are constant, and some denoted as code by $ are constant. """ warnings = [] # treat expInfo as likely to be constant; also treat its keys as # constant because its handy to make a short-cut in code: # exec(key+'=expInfo[key]') expInfo = self.exp.settings.getInfo() keywords = self.exp.namespace.nonUserBuilder[:] keywords.extend(['expInfo'] + list(expInfo.keys())) reserved = set(keywords).difference({'random', 'rand'}) for key in self.params: field = self.params[key] if (not hasattr(field, 'val') or not isinstance(field.val, str)): continue # continue == no problem, no warning if not (field.allowedUpdates and isinstance(field.allowedUpdates, list) and len(field.allowedUpdates) and field.updates == 'constant'): continue # now have only non-empty, possibly-code, and 'constant' updating if field.valType == 'str': if not bool(unescapedDollarSign_re.search(field.val)): continue code = getCodeFromParamStr(field.val) elif field.valType == 'code': code = field.val else: continue # get var names in the code; no names == constant try: names = compile(code, '', 'eval').co_names except SyntaxError: continue # ignore reserved words: if not set(names).difference(reserved): continue warnings.append((field, key)) return warnings or [(None, None)] def writeInitCode(self, buff): """Write any code that a component needs that should only ever be done at start of an experiment, BEFORE window creation. """ pass def writeStartCode(self, buff): """Write any code that a component needs that should only ever be done at start of an experiment, AFTER window creation. """ # e.g., create a data subdirectory unique to that component type. # Note: settings.writeStartCode() is done first, then # Routine.writeStartCode() will call this method for each component in # each routine pass def writePreCode(self, buff): """Write any code that a component needs that should be done before the session's `run` method is called. """ pass def writeFrameCode(self, buff): """Write the code that will be called every frame """ pass def writeRoutineStartCode(self, buff): """Write the code that will be called at the beginning of a routine (e.g. to update stimulus parameters) """ self.writeParamUpdates(buff, 'set every repeat') def writeRoutineStartCodeJS(self, buff): """Same as writeRoutineStartCode, but for JS """ self.writeParamUpdatesJS(buff, 'set every repeat') def writeRoutineEndCode(self, buff): """Write the code that will be called at the end of a routine (e.g. to save data) """ if 'saveStartStop' in self.params and self.params['saveStartStop'].val: # what loop are we in (or thisExp)? if len(self.exp.flow._loopList): currLoop = self.exp.flow._loopList[-1] # last (outer-most) loop else: currLoop = self.exp._expHandler if 'Stair' in currLoop.type and buff.target == 'PsychoPy': addDataFunc = 'addOtherData' elif 'Stair' in currLoop.type and buff.target == 'PsychoJS': addDataFunc = 'psychojs.experiment.addData' else: addDataFunc = 'addData' loop = currLoop.params['name'] name = self.params['name'] # NOTE: this function does not write any code right now! def writeRoutineEndCodeJS(self, buff): """Write the code that will be called at the end of a routine (e.g. to save data) """ pass 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) """ pass def writeStartTestCode(self, buff, extra=""): """ Test whether we need to start (if there is a start time at all) Returns True if start test was written, False if it was skipped. Recommended usage: ``` indented = self.writeStartTestCode(buff) if indented: code = ( "%(name)s.attribute = value\n" ) buff.writeIndentedLines(code % self.params) buff.setIndentLevel(-indented, relative=True) ``` Parameters ---------- buff : io.StringIO Text buffer to write code to. extra : str Additional conditions to check, including any boolean operators (and, or, etc.). Use `%(key)s` syntax to insert the values of any necessary params. Default is an empty string. """ # create copy of params dict so we can change stuff without harm params = self.params.copy() # Get starting indent level startIndent = buff.indentLevel if params['startVal'].val in ('', None, -1, 'None'): if extra: # if we have extra and no stop condition, extra is the only stop condition params['startType'] = params['startType'].copy() params['startVal'] = params['startVal'].copy() params['startType'].val = "condition" params['startVal'].val = "False" else: # if we just have no stop time, don't write stop code return buff.indentLevel - startIndent # Newline buff.writeIndentedLines("\n") if params['syncScreenRefresh']: tCompare = 'tThisFlip' else: tCompare = 't' t = tCompare # add handy comment code = ( "# if %(name)s is starting this frame...\n" ) buff.writeIndentedLines(code % params) # add starting if statement if params['startType'].val == 'time (s)': # if startVal is an empty string then set to be 0.0 if ( isinstance(params['startVal'].val, str) and not params['startVal'].val.strip() ): params['startVal'].val = '0.0' code = ( "if %(name)s.status == NOT_STARTED and {} >= %(startVal)s-frameTolerance" ).format(t) elif params['startType'].val == 'frame N': code = ( "if %(name)s.status == NOT_STARTED and frameN >= %(startVal)s" ) elif params['startType'].val == 'condition': code = ( "if %(name)s.status == NOT_STARTED and %(startVal)s" ) else: msg = f"Not a known startType (%(startVal)s) for %(name)s" raise CodeGenerationException(msg % params) # add any other conditions and finish the statement if extra and not extra.startswith(" "): extra = " " + extra code += f"{extra}:\n" # write if statement and indent buff.writeIndentedLines(code % params) buff.setIndentLevel(+1, relative=True) code = (f"# keep track of start time/frame for later\n" f"{params['name']}.frameNStart = frameN # exact frame index\n" f"{params['name']}.tStart = t # local t and not account for scr refresh\n" f"{params['name']}.tStartRefresh = tThisFlipGlobal # on global time\n" ) if self.type != "Sound": # for sounds, don't update to actual frame time because it will start # on the *expected* time of the flip code += (f"win.timeOnFlip({params['name']}, 'tStartRefresh')" f" # time at next scr refresh\n") if params['saveStartStop']: code += f"# add timestamp to datafile\n" if self.type=='Sound' and params['syncScreenRefresh']: # use the time we *expect* the flip code += f"thisExp.addData('{params['name']}.started', tThisFlipGlobal)\n" elif 'syncScreenRefresh' in params and params['syncScreenRefresh']: # use the time we *detect* the flip (in the future) code += f"thisExp.timestampOnFlip(win, '{params['name']}.started')\n" else: # use the time ignoring any flips code += f"thisExp.addData('{params['name']}.started', t)\n" buff.writeIndentedLines(code) # validate presentation time validator = self.getValidator() if validator: # queue validation code = ( "# tell attached validator (%(name)s) to start looking for a start flag\n" "%(name)s.status = STARTED\n" ) buff.writeIndentedLines(code % validator.params) # Set status code = ( "# update status\n" "%(name)s.status = STARTED\n" ) buff.writeIndentedLines(code % params) # Return True if start test was written return buff.indentLevel - startIndent def writeStartTestCodeJS(self, buff, extra=""): """Test whether we need to start Parameters ---------- buff : io.StringIO Text buffer to write code to. extra : str Additional conditions to check, including any boolean operators (and, or, etc.). Use `%(key)s` syntax to insert the values of any necessary params. Default is an empty string. """ # create copy of params dict so we can change stuff without harm params = self.params.copy() # Get starting indent level startIndent = buff.indentLevel if params['startVal'].val in ('', None, -1, 'None'): if extra: # if we have extra and no stop condition, extra is the only stop condition params['startType'] = params['startType'].copy() params['startVal'] = params['startVal'].copy() params['startType'].val = "condition" params['startVal'].val = "False" else: # if we just have no stop time, don't write stop code return buff.indentLevel - startIndent if params['startType'].val == 'time (s)': # if startVal is an empty string then set to be 0.0 if ( isinstance(params['startVal'].val, str) and not params['startVal'].val.strip() ): params['startVal'].val = '0.0' code = ( "if (t >= %(startVal)s && %(name)s.status === PsychoJS.Status.NOT_STARTED" ) elif params['startType'].val == 'frame N': code = ( "if (frameN >= %(startVal)s && %(name)s.status === PsychoJS.Status.NOT_STARTED" ) elif params['startType'].val == 'condition': code = ( "if ((%(startVal)s) && %(name)s.status === PsychoJS.Status.NOT_STARTED" ) else: msg = f"Not a known startType (%(startVal)s) for %(name)s" raise CodeGenerationException(msg) # add any other conditions and finish the statement if extra and not extra.startswith(" "): extra = " " + extra code += f"{extra}) {{\n" # write if statement and indent buff.writeIndentedLines(code % params) buff.setIndentLevel(+1, relative=True) code = (f"// keep track of start time/frame for later\n" f"{params['name']}.tStart = t; // (not accounting for frame time here)\n" f"{params['name']}.frameNStart = frameN; // exact frame index\n\n") buff.writeIndentedLines(code) # Return True if start test was written return buff.indentLevel - startIndent def writeStopTestCode(self, buff, extra=""): """ Test whether we need to stop (if there is a stop time at all) Returns True if stop test was written, False if it was skipped. Recommended usage: ``` indented = self.writeStopTestCode(buff) if indented: code = ( "%(name)s.attribute = value\n" ) buff.writeIndentedLines(code % params) buff.setIndentLevel(-indented, relative=True) ``` Parameters ---------- buff : io.StringIO Text buffer to write code to. extra : str Additional conditions to check, including any boolean operators (and, or, etc.). Use `%(key)s` syntax to insert the values of any necessary params. Default is an empty string. """ # create copy of params dict so we can change stuff without harm params = self.params.copy() # Get starting indent level startIndent = buff.indentLevel if params['stopVal'].val in ('', None, -1, 'None'): if extra: # if we have extra and no stop condition, extra is the only stop condition params['stopType'] = params['stopType'].copy() params['stopVal'] = params['stopVal'].copy() params['stopType'].val = "condition" params['stopVal'].val = "False" else: # if we just have no stop time, don't write stop code return buff.indentLevel - startIndent # Newline buff.writeIndentedLines("\n") # add handy comment code = ( "# if %(name)s is stopping this frame...\n" ) buff.writeIndentedLines(code % params) buff.writeIndentedLines(f"if {params['name']}.status == STARTED:\n") buff.setIndentLevel(+1, relative=True) # If start time is blank ad stop is a duration, raise alert if params['stopType'] in ('duration (s)', 'duration (frames)'): if ('startVal' not in params) or (params['startVal'] in ("", "None", None)): alerttools.alert(4120, strFields={'component': params['name']}) if params['stopType'].val == 'time (s)': code = ( "# is it time to stop? (based on local clock)\n" "if tThisFlip > %(stopVal)s-frameTolerance" ) # duration in time (s) elif (params['stopType'].val == 'duration (s)'): code = ( "# is it time to stop? (based on global clock, using actual start)\n" "if tThisFlipGlobal > %(name)s.tStartRefresh + %(stopVal)s-frameTolerance" ) elif params['stopType'].val == 'duration (frames)': code = ( "if frameN >= (%(name)s.frameNStart + %(stopVal)s)" ) elif params['stopType'].val == 'frame N': code = ( "if frameN >= %(stopVal)s" ) elif params['stopType'].val == 'condition': code = ( "if bool(%(stopVal)s)" ) else: msg = ( "Didn't write any stop line for startType=%(startType)s, stopType=%(stopType)s" ) raise CodeGenerationException(msg) # add any other conditions and finish the statement if extra and not extra.startswith(" "): extra = " " + extra code += f"{extra}:\n" # write if statement and indent buff.writeIndentedLines(code % params) buff.setIndentLevel(+1, relative=True) code = (f"# keep track of stop time/frame for later\n" f"{params['name']}.tStop = t # not accounting for scr refresh\n" f"{params['name']}.tStopRefresh = tThisFlipGlobal # on global time\n" f"{params['name']}.frameNStop = frameN # exact frame index\n" ) if params['saveStartStop']: code += f"# add timestamp to datafile\n" if 'syncScreenRefresh' in params and params['syncScreenRefresh']: # use the time we *detect* the flip (in the future) code += f"thisExp.timestampOnFlip(win, '{params['name']}.stopped')\n" else: # use the time ignoring any flips code += f"thisExp.addData('{params['name']}.stopped', t)\n" buff.writeIndentedLines(code) # validate presentation time validator = self.getValidator() if validator: # queue validation code = ( "# tell attached validator (%(name)s) to start looking for a start flag\n" "%(name)s.status = STARTED\n" ) buff.writeIndentedLines(code % validator.params) # Set status code = ( "# update status\n" "%(name)s.status = FINISHED\n" ) buff.writeIndentedLines(code % params) # Return True if stop test was written return buff.indentLevel - startIndent def writeStopTestCodeJS(self, buff, extra=""): """Test whether we need to stop Parameters ---------- buff : io.StringIO Text buffer to write code to. extra : str Additional conditions to check, including any boolean operators (and, or, etc.). Use `%(key)s` syntax to insert the values of any necessary params. Default is an empty string. """ # create copy of params dict so we can change stuff without harm params = self.params.copy() # Get starting indent level startIndent = buff.indentLevel if params['stopVal'].val in ('', None, -1, 'None'): if extra: # if we have extra and no stop time, extra is only stop condition params['stopType'] = params['stopType'].copy() params['stopVal'] = params['stopVal'].copy() params['stopType'].val = "condition" params['stopVal'].val = "false" else: # if we just have no stop time, don't write stop code return buff.indentLevel - startIndent if params['stopType'].val == 'time (s)': code = ( "frameRemains = %(stopVal)s - psychoJS.window.monitorFramePeriod * 0.75;" "// most of one frame period left\n" "if ((%(name)s.status === PsychoJS.Status.STARTED || %(name)s.status === " "PsychoJS.Status.FINISHED) && t >= frameRemains" ) # duration in time (s) elif ( params['stopType'].val == 'duration (s)' and params['startType'].val == 'time (s)' ): code = ( "frameRemains = %(startVal)s + %(stopVal)s - psychoJS.window.monitorFramePeriod " "* 0.75;" "// most of one frame period left\n" "if (%(name)s.status === PsychoJS.Status.STARTED && t >= frameRemains" ) # start at frame and end with duratio (need to use approximate) elif params['stopType'].val == 'duration (s)': code = ( "if (%(name)s.status === PsychoJS.Status.STARTED && t >= (%(name)s.tStart + " "%(stopVal)s)" ) elif params['stopType'].val == 'duration (frames)': code = ( "if (%(name)s.status === PsychoJS.Status.STARTED && frameN >= " "(%(name)s.frameNStart + %(stopVal)s)" ) elif params['stopType'].val == 'frame N': code = ( "if (%(name)s.status === PsychoJS.Status.STARTED && frameN >= %(stopVal)s" ) elif params['stopType'].val == 'condition': code = ( "if (%(name)s.status === PsychoJS.Status.STARTED && Boolean(%(stopVal)s)" ) else: msg = ( "Didn't write any stop line for startType=%(startType)s, stopType=%(stopType)s" ) raise CodeGenerationException(msg) # add any other conditions and finish the statement if extra and not extra.startswith(" "): extra = " " + extra code += f"{extra}) {{\n" # write if statement and indent buff.writeIndentedLines(code % params) buff.setIndentLevel(+1, relative=True) # store stop code = ( "// keep track of stop time/frame for later\n" "%(name)s.tStop = t; // not accounting for scr refresh\n" "%(name)s.frameNStop = frameN; // exact frame index\n" ) buff.writeIndentedLines(code % params) # set status code = ( "// update status\n" "%(name)s.status = PsychoJS.Status.FINISHED;\n" ) buff.writeIndentedLines(code % params) # Return True if stop test was written return buff.indentLevel - startIndent def writeActiveTestCode(self, buff, extra=""): """ Test whether component is started and has not finished. Recommended usage: ``` self.writeActiveTestCode(buff): code = ( "%(name)s.attribute = value\n" "\n" ) buff.writeIndentedLines(code % self.params) self.exitActiveTest(buff) ``` Parameters ---------- buff : io.StringIO Text buffer to write code to. extra : str Additional conditions to check, including any boolean operators (and, or, etc.). Use `%(key)s` syntax to insert the values of any necessary params. Default is an empty string. """ # create copy of params dict so we can change stuff without harm params = self.params.copy() # Newline buff.writeIndentedLines("\n") # Get starting indent level startIndent = buff.indentLevel # construct if statement code = ( "# if %(name)s is active this frame...\n" "if %(name)s.status == STARTED" ) # add any other conditions and finish the statement if extra and not extra.startswith(" "): extra = " " + extra code += f"{extra}:\n" buff.writeIndentedLines(code % params) # Indent buff.setIndentLevel(+1, relative=True) # Write param updates (if needed) code = ( "# update params\n" ) buff.writeIndentedLines(code % params) if self.checkNeedToUpdate('set every frame'): self.writeParamUpdates(buff, 'set every frame') else: code = ( "pass\n" ) buff.writeIndentedLines(code) return buff.indentLevel - startIndent def writeActiveTestCodeJS(self, buff, extra=""): """ Test whether component is started and has not finished. Recommended usage: ``` self.writeActiveTestCodeJS(self, buff): code = ( "%(name)s.attribute = value\n" "\n" ) self.exitActiveTestJS(buff) ``` Parameters ---------- buff : io.StringIO Text buffer to write code to. extra : str Additional conditions to check, including any boolean operators (and, or, etc.). Use `%(key)s` syntax to insert the values of any necessary params. Default is an empty string. """ # create copy of params dict so we can change stuff without harm params = self.params.copy() # Get starting indent level startIndent = buff.indentLevel # Newline buff.writeIndentedLines("\n") # construct if statement code = ( "// if %(name)s is active this frame...\n" "if (%(name)s.status == STARTED" ) # add any other conditions and finish the statement if extra and not extra.startswith(" "): extra = " " + extra code += f"{extra}) {{\n" # write if statement and indent buff.writeIndentedLines(code % params) buff.setIndentLevel(+1, relative=True) if self.checkNeedToUpdate('set every frame'): # Write param updates (if needed) code = ( "// update params\n" ) buff.writeIndentedLines(code % params) self.writeParamUpdates(buff, 'set every frame') return buff.indentLevel - startIndent def writeParamUpdates(self, buff, updateType, paramNames=None, target="PsychoPy"): """write updates to the buffer for each parameter that needs it updateType can be 'experiment', 'routine' or 'frame' """ if paramNames is None: paramNames = list(self.params.keys()) for thisParamName in paramNames: if thisParamName == 'advancedParams': continue # advancedParams is not really a parameter itself thisParam = self.params[thisParamName] if thisParam.updates == updateType: self.writeParamUpdate( buff, self.params['name'], thisParamName, thisParam, thisParam.updates, target=target) def writeParamUpdatesJS(self, buff, updateType, paramNames=None): """Pass this to the standard writeParamUpdates but with new 'target' """ self.writeParamUpdates(buff, updateType, paramNames, target="PsychoJS") def _getParamCaps(self, paramName): """ Get param name in title case, useful for working out the `.set____` function in boilerplate. """ if paramName == 'advancedParams': return # advancedParams is not really a parameter itself elif paramName == 'image' and self.getType() == 'PatchComponent': paramCaps = 'Tex' # setTex for PatchStim elif paramName == 'sf': paramCaps = 'SF' # setSF, not SetSf elif paramName == 'coherence': paramCaps = 'FieldCoherence' else: paramCaps = paramName[0].capitalize() + paramName[1:] return paramCaps def writeParamUpdate(self, buff, compName, paramName, val, updateType, params=None, target="PsychoPy"): """Writes an update string for a single parameter. This should not need overriding for different components - try to keep constant """ if params is None: params = self.params # first work out the name for the set____() function call paramCaps = self._getParamCaps(paramName) # code conversions for PsychoJS if target == 'PsychoJS': endStr = ';' try: valStr = str(val).strip() except TypeError: if isinstance(val, Param): val = val.val raise TypeError(f"Value of parameter {paramName} of component {compName} " f"could not be converted to JS. Value is {val}") # convert (0,0.5) to [0,0.5] but don't convert "rand()" to "rand[]" if valStr.startswith("(") and valStr.endswith(")"): valStr = valStr.replace("(", "[", 1) valStr = valStr[::-1].replace(")", "]", 1)[ ::-1] # replace from right # filenames (e.g. for image) need to be loaded from resources if paramName in ["sound"]: valStr = (f"psychoJS.resourceManager.getResource({valStr})") else: endStr = '' # then write the line if updateType == 'set every frame' and target == 'PsychoPy': loggingStr = ', log=False' elif updateType == 'set every frame' and target == 'PsychoJS': loggingStr = ', false' # don't give the keyword 'log' in JS else: loggingStr = '' if target == 'PsychoPy': if paramName == 'color': buff.writeIndented(f"{compName}.setColor({params['color']}, colorSpace={params['colorSpace']}") buff.write(f"{loggingStr}){endStr}\n") elif paramName == 'sound': stopVal = params['stopVal'].val if stopVal in ['', None, -1, 'None']: stopVal = '-1' buff.writeIndented(f"{compName}.setSound({params['sound']}, secs={stopVal}){endStr}\n") elif paramName == 'movie' and params['backend'].val in ('moviepy', 'avbin', 'vlc', 'opencv'): # we're going to do this for now ... if params['units'].val == 'from exp settings': unitsStr = "units=''" else: unitsStr = "units=%(units)s" % params if 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 params['backend'].val == 'avbin': code = ("%s = visual.MovieStim(\n" % params['name'] + " win=win, name='%s', %s,\n" % ( params['name'], unitsStr)) elif params['backend'].val == 'vlc': code = ("%s = visual.VlcMovieStim(\n" % params['name'] + " win=win, name='%s', %s,\n" % ( params['name'], unitsStr)) else: code = ("%s = visual.MovieStim(\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 params['size'].val != '': buff.writeIndented(" size=%(size)s,\n" % params) depth = -self.getPosInRoutine() code = (" depth=%.1f,\n" " )\n") buff.writeIndentedLines(code % depth) else: buff.writeIndented(f"{compName}.set{paramCaps}({val}{loggingStr}){endStr}\n") elif target == 'PsychoJS': # write the line if paramName == 'color': buff.writeIndented(f"{compName}.setColor(new util.Color({params['color']})") buff.write(f"{loggingStr}){endStr}\n") elif paramName == 'fillColor': buff.writeIndented(f"{compName}.setFillColor(new util.Color({params['fillColor']})") buff.write(f"{loggingStr}){endStr}\n") elif paramName == 'lineColor': buff.writeIndented(f"{compName}.setLineColor(new util.Color({params['lineColor']})") buff.write(f"{loggingStr}){endStr}\n") elif paramName == 'emotiv_marker_label' or paramName == "emotiv_marker_value" or paramName == "emotiv_stop_marker": # This allows the eeg_marker to be updated by a code component or a conditions file # There is no setMarker_label or setMarker_value function in the eeg_marker object # The marker label and value are set by the variables set in the dialogue pass else: buff.writeIndented(f"{compName}.set{paramCaps}({val}{loggingStr}){endStr}\n") def checkNeedToUpdate(self, updateType): """Determine whether this component has any parameters set to repeat at this level usage:: True/False = checkNeedToUpdate(self, updateType) """ for thisParamName in self.params: if thisParamName == 'advancedParams': continue thisParam = self.params[thisParamName] if thisParam.updates == updateType: return True return False def getStart(self): # deduce a start time (s) if possible startType = self.params['startType'].val numericStart = canBeNumeric(self.params['startVal'].val) if canBeNumeric(self.params['startEstim'].val): startTime = float(self.params['startEstim'].val) elif startType == 'time (s)' and numericStart: startTime = float(self.params['startVal'].val) else: startTime = None return startTime, numericStart def getDuration(self, startTime=0): # deduce stop time (s) if possible stopType = self.params['stopType'].val numericStop = canBeNumeric(self.params['stopVal'].val) if stopType == 'time (s)' and numericStop: duration = float(self.params['stopVal'].val) - (startTime or 0) elif stopType == 'duration (s)' and numericStop: duration = float(self.params['stopVal'].val) else: # deduce duration (s) if possible. Duration used because component # time icon needs width if canBeNumeric(self.params['durationEstim'].val): duration = float(self.params['durationEstim'].val) elif self.params['stopVal'].val in ['', '-1', 'None']: duration = FOREVER # infinite duration else: duration = None return duration, numericStop def getStartAndDuration(self, params=None): """Determine the start and duration of the stimulus When nonSlipSafe is False, the outputs of this function are used purely for Routine rendering purposes in the app (does not affect actual drawing during the experiment). When nonSlipSafe is True or when `forceNonSlip` is True, the outputs of this function are used to determine maxTime of routine, which is written into the generated script during writeMainCode() to as a part of the stopping criteria of the routine while loop. In these two cases, the outputs of this function does affect actual during during the experiment (not only for Routine rendering purposes in the app). start, duration, nonSlipSafe = component.getStartAndDuration() nonSlipSafe indicates that the component's duration is a known fixed value and can be used in non-slip global clock timing (e.g for fMRI) Parameters ---------- params : dict[Param] Dict of params to use. If None, will use the values in `self.params`. """ # if not given any params, use from self if params is None: params = self.params # If has a start, calculate it if 'startType' in params: startTime, numericStart = self.getStart() else: startTime, numericStart = None, False # If has a stop, calculate it if 'stopType' in params: duration, numericStop = self.getDuration(startTime=startTime) else: duration, numericStop = 0, False nonSlipSafe = numericStop and (numericStart or params['stopType'].val == 'time (s)') return startTime, duration, nonSlipSafe def getPosInRoutine(self): """Find the index (position) in the parent Routine (0 for top) """ # get Routine routine = self.exp.routines[self.parentName] # make list of non-settings components in Routine comps = [comp for comp in routine if not comp == routine.settings] # get index return comps.index(self) def getType(self): """Returns the name of the current object class""" return self.__class__.__name__ def getShortType(self): """Replaces word component with empty string""" return self.getType().replace('Component', '') def getAllValidatorRoutines(self, attr="vals"): """ Return a list of names for all validator Routines in the current experiment. Used to populate allowedVals in the `validator` param. Parameters ---------- attr : str Attribute to get - either values (for allowedVals) or labels (for allowedLabels) Returns ------- list[str] List of Routine names/labels """ from psychopy.experiment.routines import BaseValidatorRoutine # iterate through all Routines in this Experiment names = [""] labels = [_translate("Do not validate")] for rtName, rt in self.exp.routines.items(): # if Routine is a validator, include it if isinstance(rt, BaseValidatorRoutine): # add name names.append(rtName) # construct label rtType = type(rt).__name__ labels.append( f"{rtName} ({rtType})" ) if attr == "labels": return labels else: return names def getAllValidatorRoutineVals(self): """ Shorthand for calling getAllValidatorRoutines with `attr` as "vals" """ return self.getAllValidatorRoutines(attr="vals") def getAllValidatorRoutineLabels(self): """ Shorthand for calling getAllValidatorRoutines with `attr` as "labels" """ return self.getAllValidatorRoutines(attr="labels") def getValidator(self): """ Get the validator associated with this Component. Returns ------- BaseStandaloneRoutine or None Validator Routine object """ # return None if we have no such param if "validator" not in self.params: return None # return None if no validator is selected if self.params['validator'].val in ("", None, "None", "none"): return None # strip spaces from param name = self.params['validator'].val.strip() # look for Components matching validator name for rt in self.exp.routines.values(): for comp in rt: if comp.name == name: return comp def writeRoutineStartValidationCode(self, buff): """ WWrite Routine start code to validate this stimulus against the specified validator. Parameters ---------- buff : StringIO String buffer to write code to. """ # get validator validator = self.getValidator() # if there is no validator, don't write any code if validator is None: return # if there is a validator, write its code indent = validator.writeRoutineStartValidationCode(buff, stim=self) # if validation code indented the buffer, dedent buff.setIndentLevel(-indent, relative=True) def writeEachFrameValidationCode(self, buff): """ Write each frame code to validate this stimulus against the specified validator. Parameters ---------- buff : StringIO String buffer to write code to. """ # get validator validator = self.getValidator() # if there is no validator, don't write any code if validator is None: return # if there is a validator, write its code indent = validator.writeEachFrameValidationCode(buff, stim=self) # if validation code indented the buffer, dedent buff.setIndentLevel(-indent, relative=True) def getFullDocumentation(self, fmt="rst"): """ Automatically generate documentation for this Component. We recommend using this as a starting point, but checking the documentation yourself afterwards and adding any more detail you'd like to include (e.g. usage examples) Parameters ---------- fmt : str Format to write documentation in. One of: - "rst": Restructured text (numpy style) -"md": Markdown (mkdocs style) """ # make sure format is correct assert fmt in ("md", "rst"), ( f"Unrecognised format {fmt}, allowed formats are 'md' and 'rst'." ) # define templates for md and rst h1 = { 'md': "# %s", 'rst': ( "-------------------------------\n" "%s\n" "-------------------------------" ) }[fmt] h2 = { 'md': "## %s", 'rst': ( "%s\n" "-------------------------------" ) }[fmt] h3 = { 'md': "### %s", 'rst': ( "%s\n" "===============================" ) }[fmt] h4 = { 'md': "#### `%s`", 'rst': "%s" }[fmt] # start off with nothing content = "" # header and class docstring content += ( f"{h1 % type(self).__name__}\n" f"{textwrap.dedent(self.__doc__ or '')}\n" f"\n" ) # attributes content += ( f"{h4 % 'Categories:'}\n" f" {', '.join(self.categories)}\n" f"{h4 % 'Works in:'}\n" f" {', '.join(self.targets)}\n" f"\n" ) # beta warning if self.beta: content += ( f"**Note: Since this is still in beta, keep an eye out for bug fixes.**\n" f"\n" ) # params heading content += ( f"{h2 % 'Parameters'}\n" f"\n" ) # sort params by category byCateg = {} for param in self.params.values(): if param.categ not in byCateg: byCateg[param.categ] = [] byCateg[param.categ].append(param) # iterate through categs for categ, params in byCateg.items(): # write a heading for each categ content += ( f"{h3 % categ}\n" f"\n" ) # add each param... for param in params: # write basics (heading and description) content += ( f"{h4 % param.label}\n" f" {param.hint}\n" ) # if there are options, display them if bool(param.allowedVals) or bool(param.allowedLabels): # if no allowed labels, use allowed vals options = param.allowedLabels or param.allowedVals # handle callable methods if callable(options): content += ( f"\n" f" Options are generated live, so will vary according to your setup.\n" ) else: # write heading content += ( f" \n" f" Options:\n" ) # add list item for each option for opt in options: content += ( f" - {opt}\n" ) # add newline at the end content += "\n" return content @property def name(self): return self.params['name'].val @name.setter def name(self, value): self.params['name'].val = value @property def disabled(self): return bool(self.params['disabled']) @disabled.setter def disabled(self, value): self.params['disabled'].val = value @property def currentLoop(self): # Get list of active loops loopList = self.exp.flow._loopList if len(loopList): # If there are any active loops, return the highest level return self.exp.flow._loopList[-1].params['name'] else: # Otherwise, we are not in a loop, so loop handler is just experiment handler return "thisExp" class BaseDeviceComponent(BaseComponent): """ Base class for most components which interface with a hardware device. """ # list of class strings (readable by DeviceManager) which this component's device could be deviceClasses = [] def __init__( self, exp, parentName, # basic name='', startType='time (s)', startVal='', stopType='duration (s)', stopVal='', startEstim='', durationEstim='', # device deviceLabel="", # data saveStartStop=True, syncScreenRefresh=False, # testing disabled=False ): # initialise base component 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 ) # require hardware self.exp.requirePsychopyLibs( ['hardware'] ) # --- Device params --- self.order += [ "deviceLabel" ] # label to refer to device by self.params['deviceLabel'] = Param( deviceLabel, valType="str", inputType="single", categ="Device", label=_translate("Device label"), hint=_translate( "A label to refer to this Component's associated hardware device by. If using the " "same device for multiple components, be sure to use the same label here." ) ) class BaseVisualComponent(BaseComponent): """Base class for most visual stimuli """ categories = ['Stimuli'] targets = [] iconFile = Path(__file__).parent / "unknown" / "unknown.png" tooltip = "" def __init__(self, exp, parentName, name='', units='from exp settings', color='white', fillColor="", borderColor="", pos=(0, 0), size=(0, 0), ori=0, colorSpace='rgb', opacity="", contrast=1, startType='time (s)', startVal='', stopType='duration (s)', stopVal='', startEstim='', durationEstim='', saveStartStop=True, syncScreenRefresh=True, validator="", disabled=False): super(BaseVisualComponent, self).__init__( exp, parentName, name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim, saveStartStop=saveStartStop, syncScreenRefresh=syncScreenRefresh, disabled=disabled) self.exp.requirePsychopyLibs( ['visual']) # needs this psychopy lib to operate self.order += [ "color", "fillColor", "borderColor", "colorSpace", "opacity", "size", "pos", "units", "anchor", "ori", ] msg = _translate("Units of dimensions for this stimulus") self.params['units'] = Param(units, valType='str', inputType="choice", categ='Layout', allowedVals=['from exp settings', 'deg', 'cm', 'pix', 'norm', 'height', 'degFlatPos', 'degFlat'], hint=msg, label=_translate("Spatial units")) msg = _translate("Foreground color of this stimulus (e.g. $[1,1,0], red )") self.params['color'] = Param(color, valType='color', inputType="color", categ='Appearance', allowedTypes=[], updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Foreground color")) msg = _translate("In what format (color space) have you specified " "the colors? (rgb, dkl, lms, hsv)") self.params['colorSpace'] = Param(colorSpace, valType='str', inputType="choice", categ='Appearance', allowedVals=['rgb', 'dkl', 'lms', 'hsv'], updates='constant', hint=msg, label=_translate("Color space")) msg = _translate("Fill color of this stimulus (e.g. $[1,1,0], red )") self.params['fillColor'] = Param(fillColor, valType='color', inputType="color", categ='Appearance', updates='constant', allowedTypes=[], allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Fill color")) msg = _translate("Border color of this stimulus (e.g. $[1,1,0], red )") self.params['borderColor'] = Param(borderColor, valType='color', inputType="color", categ='Appearance', updates='constant',allowedTypes=[], allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Border color")) msg = _translate("Opacity of the stimulus (1=opaque, 0=fully transparent, 0.5=translucent). " "Leave blank for each color to have its own opacity (recommended if any color is None).") self.params['opacity'] = Param(opacity, valType='num', inputType="single", categ='Appearance', updates='constant', allowedTypes=[], allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Opacity")) msg = _translate("Contrast of the stimulus (1.0=unchanged contrast, " "0.5=decrease contrast, 0.0=uniform/no contrast, " "-0.5=slightly inverted, -1.0=totally inverted)") self.params['contrast'] = Param(contrast, valType='num', inputType='single', allowedTypes=[], categ='Appearance', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Contrast")) msg = _translate("Position of this stimulus (e.g. [1,2] )") self.params['pos'] = Param(pos, valType='list', inputType="single", categ='Layout', updates='constant', allowedTypes=[], allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Position [x,y]")) msg = _translate("Size of this stimulus (either a single value or " "x,y pair, e.g. 2.5, [1,2] ") self.params['size'] = Param(size, valType='list', inputType="single", categ='Layout', updates='constant', allowedTypes=[], allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Size [w,h]")) self.params['ori'] = Param(ori, valType='num', inputType="spin", categ='Layout', updates='constant', allowedTypes=[], allowedVals=[-360,360], allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=_translate("Orientation of this stimulus (in deg)"), label=_translate("Orientation")) self.params['syncScreenRefresh'].readOnly = True # --- Testing --- self.params['validator'] = Param( validator, valType="code", inputType="choice", categ="Testing", allowedVals=self.getAllValidatorRoutineVals, allowedLabels=self.getAllValidatorRoutineLabels, label=_translate("Validate with..."), hint=_translate( "Name of validator Component/Routine to use to check the timing of this stimulus." ) ) def integrityCheck(self): """ Run component integrity checks. """ super().integrityCheck() # run parent class checks first win = alerttools.TestWin(self.exp) # get units for this stimulus if 'units' in self.params: # e.g. BrushComponent doesn't have this units = self.params['units'].val else: units = None if units == 'use experiment settings': units = self.exp.settings.params[ 'Units'].val # this 1 uppercase if not units or units == 'use preferences': units = prefs.general['units'] # tests for visual stimuli alerttools.testSize(self, win, units) alerttools.testPos(self, win, units) alerttools.testAchievableVisualOnsetOffset(self) alerttools.testValidVisualStimTiming(self) alerttools.testFramesAsInt(self) def writeFrameCode(self, buff): """Write the code that will be called every frame """ params = self.params buff.writeIndented(f"\n") buff.writeIndented(f"# *{params['name']}* updates\n") # writes an if statement to determine whether to draw etc indented = self.writeStartTestCode(buff) if indented: buff.writeIndented(f"{params['name']}.setAutoDraw(True)\n") # 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: # 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(f"{params['name']}.setAutoDraw(False)\n") # to get out of the if statement buff.setIndentLevel(-indented, relative=True) def writeFrameCodeJS(self, buff): """Write the code that will be called every frame """ params = self.params if "PsychoJS" not in self.targets: buff.writeIndented(f"// *{params['name']}* not supported by PsychoJS\n") return # set parameters that need updating every frame # do any params need updating? (this method inherited from _base) if self.checkNeedToUpdate('set every frame'): buff.writeIndentedLines(f"\nif ({params['name']}.status === PsychoJS.Status.STARTED){{ " f"// only update if being drawn\n") 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.writeIndented("}\n") buff.writeIndentedLines(f"\n// *{params['name']}* updates\n") # writes an if statement to determine whether to draw etc indented = self.writeStartTestCodeJS(buff) if indented: buff.writeIndentedLines(f"{params['name']}.setAutoDraw(true);\n") # to get out of the if statement while indented > 0: buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines( "}\n" "\n" ) indented -= 1 # writes an if statement to determine whether to draw etc indented = self.writeStopTestCodeJS(buff) if indented: buff.writeIndentedLines(f"{params['name']}.setAutoDraw(false);\n") # to get out of the if statement while indented > 0: buff.setIndentLevel(-1, relative=True) buff.writeIndentedLines( "}\n" "\n" ) indented -= 1
64,957
Python
.py
1,468
32.222752
148
0.55515
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,593
__init__.py
psychopy_psychopy/psychopy/experiment/components/progress/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path from psychopy.experiment.components import Param, _translate, getInitVals, BaseVisualComponent class ProgressComponent(BaseVisualComponent): """ """ categories = ['Stimuli'] targets = ['PsychoPy', 'PsychoJS'] version = "2023.2.0" iconFile = Path(__file__).parent / 'progress.png' tooltip = _translate('Progress: Present a progress bar, with values ranging from 0 to 1.') beta = True def __init__(self, exp, parentName, name='prog', startType='time (s)', startVal=0, stopType='duration (s)', stopVal='', startEstim='', durationEstim='', saveStartStop=True, syncScreenRefresh=True, progress=0, color="white", fillColor="None", borderColor="white", colorSpace="rgb", opacity=1, lineWidth=4, pos=(0, 0), size=(0.5, 0.5), anchor="center-left", ori=0, units="height", disabled=False): 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(ProgressComponent, self).__init__( exp, parentName, name=name, units=units, color=color, fillColor=fillColor, borderColor=borderColor, pos=pos, size=size, ori=ori, colorSpace=colorSpace, opacity=opacity, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim, saveStartStop=saveStartStop, syncScreenRefresh=syncScreenRefresh, disabled=disabled ) self.type = 'Progress' # Change labels for color params self.params['color'].label = _translate("Bar color") self.params['color'].hint = _translate( "Color of the filled part of the progress bar." ) self.params['fillColor'].label = _translate("Back color") self.params['fillColor'].hint = _translate( "Color of the empty part of the progress bar." ) self.params['borderColor'].label = _translate("Border color") self.params['borderColor'].hint = _translate( "Color of the line around the progress bar." ) # --- Basic --- self.params['progress'] = Param( progress, valType='code', inputType="single", categ='Basic', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=_translate( "Value between 0 (not started) and 1 (complete) to set the progress bar to." ), label=_translate("Progress")) # --- Appearance --- 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')) # --- Layout --- 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')) def writeInitCode(self, buff): # Get inits inits = getInitVals(self.params, target="PsychoPy") inits['depth'] = -self.getPosInRoutine() # Create object code = ( "%(name)s = visual.Progress(\n" " win, name='%(name)s',\n" " progress=%(progress)s,\n" " pos=%(pos)s, size=%(size)s, anchor=%(anchor)s, units=%(units)s,\n" " barColor=%(color)s, backColor=%(fillColor)s, borderColor=%(borderColor)s, " "colorSpace=%(colorSpace)s,\n" " lineWidth=%(lineWidth)s, opacity=%(opacity)s, ori=%(ori)s,\n" " depth=%(depth)s\n" ")\n" ) buff.writeIndentedLines(code % inits) def writeInitCodeJS(self, buff): # Get inits inits = getInitVals(self.params, target="PsychoJS") inits['depth'] = -self.getPosInRoutine() # Create object code = ( "%(name)s = new visual.Progress({\n" " win: psychoJS.window, name: '%(name)s',\n" " progress: %(progress)s,\n" " pos: %(pos)s, size: %(size)s, anchor: %(anchor)s, units: %(units)s,\n" " barColor: %(color)s, backColor: %(fillColor)s, borderColor: %(borderColor)s, " "colorSpace: %(colorSpace)s,\n" " lineWidth: %(lineWidth)s, opacity: %(opacity)s, ori: %(ori)s,\n" " depth: %(depth)s\n" "})\n" ) buff.writeIndentedLines(code % inits)
5,516
Python
.py
118
34.669492
101
0.549016
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,594
__init__.py
psychopy_psychopy/psychopy/experiment/components/grating/__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 GratingComponent(BaseVisualComponent): """A class for presenting grating stimuli""" categories = ['Stimuli'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'grating.png' tooltip = _translate('Grating: present cyclic textures, prebuilt or from a ' 'file') def __init__(self, exp, parentName, name='grating', image='sin', mask='', sf='', interpolate='linear', units='from exp settings', color='$[1,1,1]', colorSpace='rgb', contrast=1.0, pos=(0, 0), size=(0.5, 0.5), anchor="center", ori=0, phase=0.0, texRes='128', draggable=False, startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, blendmode='avg', startEstim='', durationEstim=''): super(GratingComponent, self).__init__( exp, parentName, name=name, units=units, color=color, colorSpace=colorSpace, contrast=contrast, pos=pos, size=size, ori=ori, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Grating' self.url = "https://www.psychopy.org/builder/components/grating.html" self.order += [ 'tex', 'mask', 'phase', 'sf', 'texture resolution', 'interpolate', # Texture tab ] # params msg = _translate("The (2D) texture of the grating - can be sin, sqr," " sinXsin... or a filename (including path)") self.params['tex'] = Param( image, valType='file', inputType="file", allowedVals=["sin", "sqr", "sinXsin"], allowedTypes=[], categ='Texture', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Texture")) msg = _translate("An image to define the alpha mask (ie shape)- " "gauss, circle... or a filename (including path)") self.params['mask'] = Param( mask, valType='file', inputType="file", allowedVals=["gauss", "circle"], allowedTypes=[], categ='Texture', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Mask")) msg = _translate("Spatial frequency of image repeats across the " "grating in 1 or 2 dimensions, e.g. 4 or [2,3]") self.params['sf'] = Param( sf, valType='num', inputType="single", allowedTypes=[], categ='Texture', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Spatial frequency")) 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("Spatial positioning of the image on the grating " "(wraps in range 0-1.0)") self.params['phase'] = Param( phase, valType='num', inputType="single", allowedTypes=[], categ='Texture', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Phase (in cycles)")) msg = _translate( "Resolution of the texture for standard ones such as sin, sqr " "etc. For most cases a value of 256 pixels will suffice") self.params['texture resolution'] = Param( texRes, valType='num', inputType="choice", allowedVals=['32', '64', '128', '256', '512'], categ='Texture', 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("OpenGL Blendmode: avg gives traditional transparency," " add is important to combine gratings)]") self.params['blendmode'] = Param( blendmode, valType='str', inputType="choice", allowedVals=['avg', 'add'], categ='Appearance', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("OpenGL blend mode")) 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 # replaces variable params with defaults inits = getInitVals(self.params) code = ("%s = visual.GratingStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " tex=%(tex)s, mask=%(mask)s, anchor=%(anchor)s,\n" % inits + " ori=%(ori)s, pos=%(pos)s, draggable=%(draggable)s, size=%(size)s, " % inits + "sf=%(sf)s, phase=%(phase)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s,\n" % inits + " opacity=%(opacity)s, contrast=%(contrast)s, blendmode=%(blendmode)s,\n" % inits + # no newline - start optional parameters " texRes=%(texture resolution)s" % inits) 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: if inits[paramName].val in [None, 'None', 'none', '', 'sin']: inits[paramName].valType = 'code' inits[paramName].val = 'undefined' code = ("{inits[name]} = new visual.GratingStim({{\n" " win : psychoJS.window,\n" " name : '{inits[name]}', {units}\n" " tex : {inits[tex]}, mask : {inits[mask]},\n" " ori : {inits[ori]}, \n" " pos : {inits[pos]},\n" " draggable: {inits[draggable]},\n" " anchor : {inits[anchor]},\n" " sf : {inits[sf]}, phase : {inits[phase]},\n" " size : {inits[size]},\n" " color : new util.Color({inits[color]}), opacity : {inits[opacity]},\n" " contrast : {inits[contrast]}, blendmode : {inits[blendmode]},\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)
9,162
Python
.py
178
38.303371
125
0.541243
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,595
__init__.py
psychopy_psychopy/psychopy/experiment/components/textbox/__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, alert from psychopy.experiment.components import BaseVisualComponent, Param, getInitVals, _translate from ..keyboard import KeyboardComponent class TextboxComponent(BaseVisualComponent): """An event class for presenting text-based stimuli """ categories = ['Stimuli', 'Responses'] targets = ['PsychoPy', 'PsychoJS'] version = "2020.2.0" iconFile = Path(__file__).parent / 'textbox.png' tooltip = _translate('Textbox: present text stimuli but cooler') beta = True def __init__(self, exp, parentName, name='textbox', # effectively just a display-value text=_translate('Any text\n\nincluding line breaks'), placeholder=_translate("Type here..."), font='Arial', units='from exp settings', bold=False, italic=False, color='white', colorSpace='rgb', opacity="", pos=(0, 0), size=(0.5, 0.5), letterHeight=0.05, ori=0, speechPoint="", draggable=False, anchor='center', alignment='center', lineSpacing=1.0, padding=0, # gap between box and text startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim='', overflow="visible", languageStyle='LTR', fillColor="None", borderColor="None", borderWidth=2, flipHoriz=False, flipVert=False, editable=False, autoLog=True): super(TextboxComponent, 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 = 'Textbox' self.url = "https://www.psychopy.org/builder/components/textbox.html" self.order += [ # controls order of params within tabs "editable", "text", "usePlaceholder", "placeholder", # Basic tab "borderWidth", "opacity", # Appearance tab "font", "letterHeight", "lineSpacing", "bold", "italic", # Formatting tab ] self.order.insert(self.order.index("units"), "padding") # Add "padding" just before spatial units # params _allow3 = ['constant', 'set every repeat', 'set every frame'] # list self.params['color'].label = _translate("Text color") 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.depends.append( { "dependsOn": "editable", # if... "condition": "==True", # meets... "param": "placeholder", # then... "true": "show", # should... "false": "hide", # otherwise... } ) self.params['placeholder'] = Param( placeholder, valType='str', inputType="single", categ='Basic', updates='constant', allowedUpdates=_allow3[:], hint=_translate("Placeholder text to show when there is no text contents."), label=_translate("Placeholder 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['flipHoriz'] = Param( flipHoriz, valType='bool', inputType="bool", allowedTypes=[], categ='Layout', updates='constant', hint=_translate("horiz = left-right reversed; vert = up-down" " reversed; $var = variable"), label=_translate("Flip horizontal")) self.params['flipVert'] = Param( flipVert, valType='bool', inputType="bool", allowedTypes=[], categ='Layout', updates='constant', hint=_translate("horiz = left-right reversed; vert = up-down" " reversed; $var = variable"), label=_translate("Flip vertical")) 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['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")) 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['lineSpacing'] = Param( lineSpacing, valType='num', inputType="single", allowedTypes=[], categ='Formatting', updates='constant', hint=_translate("Defines the space between lines"), label=_translate("Line spacing")) 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("Which point on the stimulus should be anchored to its exact position?"), label=_translate("Anchor")) self.params['alignment'] = Param( alignment, valType='str', inputType="choice", categ='Formatting', allowedVals=['center', 'top-center', 'bottom-center', 'center-left', 'center-right', 'top-left', 'top-right', 'bottom-left', 'bottom-right', ], updates='constant', hint=_translate("How should text be laid out within the box?"), label=_translate("Alignment")) self.params['overflow'] = Param( overflow, valType='str', inputType="choice", categ='Layout', allowedVals=['visible', 'scroll', 'hidden', ], updates='constant', hint=_translate("If the text is bigger than the textbox, how should it behave?"), label=_translate("Overflow")) self.params['speechPoint'] = Param( speechPoint, valType='list', inputType="single", categ='Appearance', updates='constant', allowedUpdates=_allow3[:], direct=False, hint=_translate("If specified, adds a speech bubble tail going to that point on screen."), label=_translate("Speech point [x,y]") ) 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['editable'] = Param( editable, valType='bool', inputType="bool", allowedTypes=[], categ='Basic', updates='constant', hint=_translate("Should textbox be editable?"), label=_translate("Editable?")) self.params['autoLog'] = Param( autoLog, valType='bool', inputType="bool", allowedTypes=[], categ='Data', updates='constant', hint=_translate( 'Automatically record all changes to this in the log file'), label=_translate("Auto log")) 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') inits['depth'] = -self.getPosInRoutine() code = ( "%(name)s = visual.TextBox2(\n" " win, text=%(text)s, placeholder=%(placeholder)s, font=%(font)s,\n" " ori=%(ori)s, pos=%(pos)s, draggable=%(draggable)s, " + unitsStr + " letterHeight=%(letterHeight)s,\n" " size=%(size)s, borderWidth=%(borderWidth)s,\n" " color=%(color)s, colorSpace=%(colorSpace)s,\n" " opacity=%(opacity)s,\n" " bold=%(bold)s, italic=%(italic)s,\n" " lineSpacing=%(lineSpacing)s, speechPoint=%(speechPoint)s,\n" " padding=%(padding)s, alignment=%(alignment)s,\n" " anchor=%(anchor)s, overflow=%(overflow)s,\n" " fillColor=%(fillColor)s, borderColor=%(borderColor)s,\n" " flipHoriz=%(flipHoriz)s, flipVert=%(flipVert)s, languageStyle=%(languageStyle)s,\n" " editable=%(editable)s,\n" " name='%(name)s',\n" " depth=%(depth)s, autoLog=%(autoLog)s,\n" ")\n" ) buff.writeIndentedLines(code % inits) 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.TextBox({\n" " win: psychoJS.window,\n" " name: '%(name)s',\n" " text: %(text)s,\n" " placeholder: %(placeholder)s,\n" " font: %(font)s,\n" " pos: %(pos)s, \n" " draggable: %(draggable)s,\n" " letterHeight: %(letterHeight)s,\n" " lineSpacing: %(lineSpacing)s,\n" " size: %(size)s," + unitsStr + " ori: %(ori)s,\n" " color: %(color)s, colorSpace: %(colorSpace)s,\n" " fillColor: %(fillColor)s, borderColor: %(borderColor)s,\n" " languageStyle: %(languageStyle)s,\n" " bold: %(bold)s, italic: %(italic)s,\n" " opacity: %(opacity)s,\n" " padding: %(padding)s,\n" " alignment: %(alignment)s,\n" " overflow: %(overflow)s,\n" " editable: %(editable)s,\n" " multiline: true,\n" " anchor: %(anchor)s,\n") buff.writeIndentedLines(code % inits) depth = -self.getPosInRoutine() code = (" depth: %.1f \n" "});\n\n" % (depth)) buff.writeIndentedLines(code) depth = -self.getPosInRoutine() def writeRoutineStartCode(self, buff): # Give alert if in the same routine as a Keyboard component if self.params['editable'].val: routine = self.exp.routines[self.parentName] for sibling in routine: if isinstance(sibling, KeyboardComponent): alert(4405, strFields={'textbox': self.params['name'], 'keyboard': sibling.params['name']}) code = ( "%(name)s.reset()" ) buff.writeIndentedLines(code % self.params) BaseVisualComponent.writeRoutineStartCode(self, buff) def writeRoutineStartCodeJS(self, buff): if self.params['editable']: # 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.setText(%(text)s);\n" "%(name)s.refresh();\n" ) buff.writeIndentedLines(code % inits) BaseVisualComponent.writeRoutineStartCodeJS(self, buff) 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 if self.params['editable']: buff.writeIndentedLines(f"{currLoop.params['name']}.addData('{name}.text',{name}.text)\n") # 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 if self.params['editable']: buff.writeIndentedLines(f"psychoJS.experiment.addData('{name}.text',{name}.text)\n") # get parent to write code too (e.g. store onset/offset times) super().writeRoutineEndCodeJS(buff) def integrityCheck(self): super().integrityCheck() # run parent class checks first alerttools.testFont(self) # Test whether font is available locally
16,374
Python
.py
322
36.468944
111
0.534115
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,596
__init__.py
psychopy_psychopy/psychopy/experiment/components/roi/__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.experiment.components.polygon import PolygonComponent class RegionOfInterestComponent(PolygonComponent): """A class for using one of several eyetrackers to follow gaze""" categories = ['Eyetracking'] targets = ['PsychoPy'] version = "2021.2.0" iconFile = Path(__file__).parent / 'eyetracker_roi.png' tooltip = _translate('Region Of Interest: Define a region of interest for use with eyetrackers') beta = True def __init__(self, exp, parentName, name='roi', units='from exp settings', endRoutineOn="none", shape='triangle', nVertices=4, pos=(0, 0), size=(0.5, 0.5), ori=0, startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim='', timeRelativeTo='roi onset', lookDur=0.1, debug=False, save='every look'): PolygonComponent.__init__(self, exp, parentName, name=name, units=units, shape=shape, nVertices=nVertices, pos=pos, size=size, ori=ori, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'RegionOfInterest' self.url = "https://www.psychopy.org/builder/components/roi.html" self.exp.requirePsychopyLibs(['iohub', 'hardware']) # params self.order += ['config'] # first param after the name # Delete all appearance parameters for param in list(self.params).copy(): if self.params[param].categ in ["Appearance", "Texture"]: del self.params[param] # Fix units as default self.params['units'].allowedVals = ['from exp settings'] self.params['endRoutineOn'] = Param(endRoutineOn, valType='str', inputType='choice', categ='Basic', allowedVals=["look at", "look away", "none"], hint=_translate("Under what condition should this ROI end the Routine?"), label=_translate("End Routine on...") ) self.depends.append( {"dependsOn": "endRoutineOn", # must be param name "condition": "=='none'", # val to check for "param": "lookDur", # param property to alter "true": "hide", # what to do with param if condition is True "false": "show", # permitted: hide, show, enable, disable } ) self.params['lookDur'] = Param(lookDur, valType='num', inputType='single', categ='Basic', hint=_translate("Minimum dwell time within roi (look at) or outside roi (look away)."), label=_translate("Min. look time") ) self.params['debug'] = Param( debug, valType='bool', inputType='bool', categ='Testing', hint=_translate("In debug mode, the ROI is drawn in red. Use this to see what area of the " "screen is in the ROI."), label=_translate("Debug mode") ) self.params['save'] = Param( save, valType='str', inputType="choice", categ='Data', allowedVals=['first look', 'last look', 'every look', 'none'], direct=False, hint=_translate( "What looks on this ROI should be saved to the data output?"), label=_translate("Save...")) self.params['timeRelativeTo'] = Param( timeRelativeTo, valType='str', inputType="choice", categ='Data', allowedVals=['roi onset', 'experiment', 'routine'], updates='constant', direct=False, hint=_translate( "What should the values of roi.time should be " "relative to?"), label=_translate("Time relative to...")) def writePreWindowCode(self, buff): pass 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'] # do writing of init inits = getInitVals(params, 'PsychoPy') inits['depth'] = -self.getPosInRoutine() code = ( "%(name)s = visual.ROI(win, name='%(name)s', device=eyetracker,\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "debug=%(debug)s,\n" "shape=%(shape)s,\n" + unitsStr + "pos=%(pos)s, size=%(size)s, \n" "anchor=%(anchor)s, ori=0.0, depth=%(depth)s\n" ")\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) def writeInitCodeJS(self, buff): pass def writeRoutineStartCode(self, buff): inits = getInitVals(self.params, 'PsychoPy') BaseVisualComponent.writeRoutineStartCode(self, buff) code = ( "# clear any previous roi data\n" "%(name)s.reset()\n" ) buff.writeIndentedLines(code % inits) def writeFrameCode(self, buff): """Write the code that will be called every frame """ # do writing of init inits = getInitVals(self.params, 'PsychoPy') # Write start code indented = self.writeStartTestCode(buff) if indented: code = ( "%(name)s.setAutoDraw(True)\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-indented, relative=True) # String to get time if inits['timeRelativeTo'] == 'roi onset': timing = "%(name)s.clock.getTime()" elif inits['timeRelativeTo'] == 'experiment': timing = "globalClock.getTime()" elif inits['timeRelativeTo'] == 'routine': timing = "routineTimer.getTime()" else: timing = "globalClock.getTime()" # Assemble code indented = self.writeActiveTestCode(buff) code = ( f"# check whether %(name)s has been looked in\n" f"if %(name)s.isLookedIn:\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( f"if not %(name)s.wasLookedIn:\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( f"%(name)s.timesOn.append({timing}) # store time of first look\n" f"%(name)s.timesOff.append({timing}) # store time looked until\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( f"else:\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( f"%(name)s.timesOff[-1] = {timing} # update time looked until\n" ) buff.writeIndentedLines(code % inits) if self.params['endRoutineOn'].val == "look at": code = ( "if %(name)s.currentLookTime > %(lookDur)s: # check if they've been looking long enough\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "continueRoutine = False # end Routine on sufficiently long look\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) buff.setIndentLevel(-1, relative=True) code = ( f"%(name)s.wasLookedIn = True # if %(name)s is still looked at next frame, it is not a new look\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( f"else:\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( f"if %(name)s.wasLookedIn:" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( f"%(name)s.timesOff[-1] = {timing} # update time looked until\n" ) buff.writeIndentedLines(code % inits) if self.params['endRoutineOn'].val == "look away": buff.setIndentLevel(-1, relative=True) code = ( f"# check if last look outside roi was long enough\n" f"if len(%(name)s.timesOff) == 0 and %(name)s.clock.getTime() > %(lookDur)s:\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( f"continueRoutine = False # end Routine after sufficiently long look outside roi\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( f"elif len(%(name)s.timesOff) > 0 and %(name)s.clock.getTime() - %(name)s.timesOff[-1] > %(lookDur)s:\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( f"continueRoutine = False # end Routine after sufficiently long look outside roi\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( f"%(name)s.wasLookedIn = False # if %(name)s is looked at next frame, it is a new look\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) buff.setIndentLevel(-indented, relative=True) code = ( f"else:\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( f"%(name)s.clock.reset() # keep clock at 0 if roi hasn't started / has finished\n" f"%(name)s.wasLookedIn = False # if %(name)s is looked at next frame, it is a new look\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) # Write stop code indented = self.writeStopTestCode(buff) if indented: code = ( "%(name)s.setAutoDraw(False)\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-indented, relative=True) 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 look': index = "[0]" elif self.params['save'] == 'last look': index = "[-1]" else: index = "" if self.params['save'] != 'none': code = ( f"{currLoop.params['name']}.addData('{name}.numLooks', {name}.numLooks)\n" f"if {name}.numLooks:\n" f" {currLoop.params['name']}.addData('{name}.timesOn', {name}.timesOn{index})\n" f" {currLoop.params['name']}.addData('{name}.timesOff', {name}.timesOff{index})\n" f" # calculate and store dwell times i.e. the duration between look onsets and offsets\n" f" {name}.dwellTime = 0.0\n" f" for i in range(len({name}.timesOn)):\n" f" {name}.dwellTime += {name}.timesOff[i] - {name}.timesOn[i]\n" f" {currLoop.params['name']}.addData('{name}.dwellTime', {name}.dwellTime)\n" f"else:\n" f" {currLoop.params['name']}.addData('{name}.timesOn', \"\")\n" f" {currLoop.params['name']}.addData('{name}.timesOff', \"\")\n" ) buff.writeIndentedLines(code) def writeExperimentEndCode(self, buff): pass
12,802
Python
.py
286
33.374126
120
0.564312
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,597
__init__.py
psychopy_psychopy/psychopy/experiment/components/routineSettings/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path from psychopy.experiment.components import BaseComponent, Param, _translate from psychopy.experiment.utils import CodeGenerationException class RoutineSettingsComponent(BaseComponent): """ """ categories = ['Other'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'routineSettings.png' tooltip = _translate('Settings for this Routine.') version = "2023.2.0" def __init__( self, exp, parentName, # Basic name='', desc="", # Flow skipIf="", forceNonSlip=False, # Window useWindowParams=False, color="$[0,0,0]", colorSpace="rgb", backgroundImg="", backgroundFit="none", # Testing disabled=False ): self.type = 'RoutineSettings' 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(RoutineSettingsComponent, self).__init__(exp, parentName, name=parentName, disabled=disabled) self.order += [] # --- Params --- # Delete inapplicable params del self.params['startType'] del self.params['startVal'] del self.params['startEstim'] del self.params['syncScreenRefresh'] # Modify disabled label self.params['disabled'].label = _translate("Disable Routine") # Modify stop type param self.params['stopType'].categ = "Flow" self.params['stopType'].allowedVals = ['duration (s)', 'frame N', 'condition'] self.params['stopType'].hint = _translate( "When should this Routine end, if not already ended by a Component?" ) # Mofidy stop val param self.params['stopVal'].categ = "Flow" self.params['stopVal'].label = _translate("Timeout") self.params['stopVal'].hint = _translate( "When should this Routine end, if not already ended by a Component? Leave blank for endless." ) # Modify stop estim param self.params['durationEstim'].categ = "Flow" # --- Flow params --- self.order += [ "forceNonSlip", "skipIf", ] self.params['forceNonSlip'] = Param( forceNonSlip, valType="code", inputType="bool", categ="Flow", hint=_translate( "If this Routine ended by hitting its max duration, reset the timer by subtracting the max duration rather than resetting to 0. Only tick this if you're sure you know how long the Routine is going to take, otherwise you'll get incorrect timestamps in the next Routine!" ), label=_translate("Non-slip timing") ) self.params['skipIf'] = Param( skipIf, valType='code', inputType="single", categ='Flow', updates='constant', hint=_translate( "Skip this Routine if the value in this contorl evaluates to True. Leave blank to not skip." ), label=_translate("Skip if...")) # --- Documentation params --- self.params['desc'] = Param( desc, valType="str", inputType="multi", categ="Basic", updates="constant", hint=_translate( "Some descriptive text to give information about this Routine. " "This won't affect how it runs, it's purely for your own " "reference!" ), label=_translate("Description"), direct=False ) # --- Window params --- self.order += [ "useWindowParams", "color", "colorSpace", "backgroundImg", "backgroundFit" ] self.params['useWindowParams'] = Param( useWindowParams, valType="bool", inputType="bool", categ="Window", label=_translate("Different window settings?"), hint=_translate( "Should the appearance of the window change while this Routine " "is running?" )) self.params['color'] = Param( color, valType='color', inputType="color", categ="Window", label=_translate("Background color"), hint=_translate( "Color of the screen this Routine (e.g. black, $[1.0,1.0,1.0]," " $variable. Right-click to bring up a " "color-picker.)" )) self.params['colorSpace'] = Param( colorSpace, valType='str', inputType="choice", categ="Window", hint=_translate("Needed if color is defined numerically (see " "PsychoPy documentation on color spaces)"), allowedVals=['rgb', 'dkl', 'lms', 'hsv', 'hex'], label=_translate("Color space")) self.params['backgroundImg'] = Param( backgroundImg, valType="str", inputType="file", categ="Window", 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="Window", allowedVals=("none", "cover", "contain", "fill", "scale-down"), hint=_translate("How should the background image scale to fit the window size?"), label=_translate("Background fit") ) # useWindowParams should toggle all window params for thisParam in ( "color", "colorSpace", "backgroundImg", "backgroundFit"): self.depends += [{ "dependsOn": "useWindowParams", # if... "condition": "", # is... "param": thisParam, # then... "true": "show", # should... "false": "hide", # otherwise... }] # --- Data params --- self.params['saveStartStop'].hint = _translate( "Save the start and stop times of this Routine (according to the global clock) to the data file." ) def writeRoutineStartCode(self, buff): # Sanitize params = self.params.copy() if params['stopVal'] in ("None", None, ""): params['stopVal'].val = "None" # store start times code = ( "# store start times for %(name)s\n" "%(name)s.tStartRefresh = win.getFutureFlipTime(clock=globalClock)\n" "%(name)s.tStart = globalClock.getTime(format='float')\n" "%(name)s.status = STARTED\n" ) buff.writeIndentedLines(code % self.params) # add to data file if requested if self.params['saveStartStop']: code = ( "thisExp.addData('%(name)s.started', %(name)s.tStart)\n" ) buff.writeIndentedLines(code % params) # calculate expected Routine duration if self.params['stopType'] == "duration (s)": code = ( "%(name)s.maxDuration = %(stopVal)s\n" ) buff.writeIndentedLines(code % params) # Skip Routine if condition is met if params['skipIf'].val not in ('', None, -1, 'None'): code = ( "# skip Routine %(name)s if its 'Skip if' condition is True\n" "%(name)s.skipped = continueRoutine and not (%(skipIf)s)\n" "continueRoutine = %(name)s.skipped\n" ) buff.writeIndentedLines(code % params) # Change window appearance for this Routine (if requested) if params['useWindowParams']: code = ( "win.color = %(color)s\n" "win.colorSpace = %(colorSpace)s\n" "win.backgroundImage = %(backgroundImg)s\n" "win.backgroundFit = %(backgroundFit)s\n" ) buff.writeIndentedLines(code % params) def writeRoutineStartCodeJS(self, buff): # Sanitize params = self.params.copy() if params['stopVal'] in ("None", None, ""): params['stopVal'].val = "None" # Store Routine start time (UTC) if self.params['saveStartStop']: code = ( "psychoJS.experiment.addData('%(name)s.started', globalClock.getTime());\n" ) buff.writeIndentedLines(code % params) # Skip Routine if condition is met if params['skipIf'].val not in ('', None, -1, 'None'): code = ( "// skip this Routine if its 'Skip if' condition is True\n" "continueRoutine = continueRoutine && !(%(skipIf)s);\n" "maxDurationReached = false\n" ) buff.writeIndentedLines(code % params) # calculate expected Routine duration if self.params['stopType'] == "duration (s)": code = ( "%(name)sMaxDuration = %(stopVal)s\n" ) buff.writeIndentedLines(code % params) # Change window appearance for this Routine (if requested) if params['useWindowParams']: code = ( "%(name)sStartWinParams = {\n" " 'color': psychoJS.window.color,\n" " 'colorSpace': psychoJS.window.colorSpace,\n" " 'backgroundImage': psychoJS.window.backgroundImage,\n" " 'backgroundFit': psychoJS.window.backgroundFit,\n" "};\n" "psychoJS.window.color = %(color)s;\n" "psychoJS.window.colorSpace = %(colorSpace)s;\n" "psychoJS.window.backgroundImage = %(backgroundImg)s;\n" "psychoJS.window.backgroundFit = %(backgroundFit)s;\n" ) buff.writeIndentedLines(code % params) def writeStartCode(self, buff): pass def writeInitCode(self, buff): pass def writeInitCodeJS(self, buff): pass def writeFrameCode(self, buff): # Sanitize params = self.params.copy() # Get current loop if len(self.exp.flow._loopList): params['loop'] = self.exp.flow._loopList[-1] # last (outer-most) loop else: params['loop'] = self.exp._expHandler # Write stop test if self.params['stopVal'].val not in ('', None, -1, 'None'): if self.params['stopType'].val == 'duration (s)': # Stop after given number of seconds code = ( f"# is it time to end the Routine? (based on local clock)\n" f"if tThisFlip > %(name)s.maxDuration-frameTolerance:\n" f" %(name)s.maxDurationReached = True\n" ) elif self.params['stopType'].val == 'frame N': # Stop at given frame num code = ( f"# is it time to end the Routine? (based on frames since Routine start)\n" f"if frameN >= %(stopVal)s:\n" ) elif self.params['stopType'].val == 'condition': # Stop when condition is True code = ( f"# is it time to end the Routine? (based on condition)\n" f"if bool(%(stopVal)s):\n" ) else: msg = "Didn't write any stop line for stopType=%(stopType)s" raise CodeGenerationException(msg % params) # Contents of if statement code += ( " continueRoutine = False\n" ) buff.writeIndentedLines(code % self.params) def writeFrameCodeJS(self, buff): # Sanitize params = self.params.copy() # Get current loop if len(self.exp.flow._loopList): params['loop'] = self.exp.flow._loopList[-1] # last (outer-most) loop else: params['loop'] = self.exp._expHandler # Write stop test if self.params['stopVal'].val not in ('', None, -1, 'None'): if self.params['stopType'].val == 'duration (s)': # Stop after given number of seconds code = ( f"// is it time to end the Routine? (based on local clock)\n" f"if (t > %(name)sMaxDuration) {{\n" f" %(name)sMaxDurationReached = true\n" ) elif self.params['stopType'].val == 'frame N': # Stop at given frame num code = ( f"// is it time to end the Routine? (based on frames since Routine start)\n" f"if (frameN >= %(stopVal)s) {{\n" ) elif self.params['stopType'].val == 'condition': # Stop when condition is True code = ( f"// is it time to end the Routine? (based on condition)\n" f"if (Boolean(%(stopVal)s)) {{\n" ) else: msg = "Didn't write any stop line for stopType=%(stopType)s" raise CodeGenerationException(msg % params) # Contents of if statement code += ( " continueRoutine = false\n" "}\n" ) buff.writeIndentedLines(code % self.params) def writeRoutineEndCode(self, buff): params = self.params.copy() # store stop times code = ( "# store stop times for %(name)s\n" "%(name)s.tStop = globalClock.getTime(format='float')\n" "%(name)s.tStopRefresh = tThisFlipGlobal\n" ) buff.writeIndentedLines(code % params) # add to data file if requested if self.params['saveStartStop']: code = ( "thisExp.addData('%(name)s.stopped', %(name)s.tStop)\n" ) buff.writeIndentedLines(code % params) # Restore window appearance after this Routine (if changed) if params['useWindowParams']: code = ( "setupWindow(expInfo=expInfo, win=win)\n" ) buff.writeIndentedLines(code % params) def writeRoutineEndCodeJS(self, buff): params = self.params.copy() # Store Routine start time (UTC) if self.params['saveStartStop']: code = ( "psychoJS.experiment.addData('%(name)s.stopped', globalClock.getTime());\n" ) buff.writeIndentedLines(code % params) # Restore window appearance after this Routine (if changed) if params['useWindowParams']: code = ( "psychoJS.window.color = %(name)sStartWinParams['color'];\n" "psychoJS.window.colorSpace = %(name)sStartWinParams['colorSpace'];\n" "psychoJS.window.backgroundImage = %(name)sStartWinParams['backgroundImage'];\n" "psychoJS.window.backgroundFit = %(name)sStartWinParams['backgroundFit'];\n" ) buff.writeIndentedLines(code % params) 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
15,700
Python
.py
358
31.603352
285
0.545152
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,598
__init__.py
psychopy_psychopy/psychopy/experiment/components/dots/__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.experiment.components import BaseVisualComponent, Param, getInitVals, _translate class DotsComponent(BaseVisualComponent): """An event class for presenting Random Dot stimuli""" categories = ['Stimuli'] targets = ['PsychoPy'] iconFile = Path(__file__).parent / 'dots.png' tooltip = _translate('Dots: Random Dot Kinematogram') def __init__(self, exp, parentName, name='dots', nDots=100, direction=0.0, speed=0.1, coherence=1.0, dotSize=2, dotLife=3, signalDots='same', noiseDots='direction', refreshDots='repeat', fieldShape='circle', fieldSize=1.0, fieldAnchor="center", fieldPos=(0.0, 0.0), color='$[1.0,1.0,1.0]', colorSpace='rgb', opacity="", units='from exp settings', startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim=''): super(DotsComponent, self).__init__( exp, parentName, name=name, units=units, color=color, colorSpace=colorSpace, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Dots' self.url = "https://www.psychopy.org/builder/components/dots.html" # Put dot/field size and position where regular size and position are in param order self.order.insert(self.order.index("size"), "dotSize") self.order.insert(self.order.index("size"), "fieldSize") self.order.insert(self.order.index("pos"), "fieldPos") self.order += [ "nDots", "dir", "speed" # Dots tab ] # params msg = _translate("Number of dots in the field (for circular fields" " this will be average number of dots)") self.params['nDots'] = Param( nDots, valType='int', inputType="spin", categ='Dots', updates='constant', hint=msg, label=_translate("Number of dots")) msg = _translate("Direction of motion for the signal dots (degrees)") self.params['dir'] = Param( direction, valType='num', inputType="spin", categ='Dots', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Direction")) msg = _translate("Speed of the dots (displacement per frame in the" " specified units)") self.params['speed'] = Param( speed, valType='num', inputType="single", categ='Dots', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Speed")) msg = _translate("Coherence of the dots (fraction moving in the " "signal direction on any one frame)") self.params['coherence'] = Param( coherence, valType='num', inputType="single", categ='Dots', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Coherence")) msg = _translate("Size of the dots IN PIXELS regardless of " "the set units") self.params['dotSize'] = Param( dotSize, valType='num', inputType="spin", categ='Layout', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Dot size")) msg = _translate("Number of frames before each dot is killed and " "randomly assigned a new position") self.params['dotLife'] = Param( dotLife, valType='num', inputType="spin", categ='Dots', hint=msg, label=_translate("Dot life-time")) msg = _translate("On each frame are the signals dots remaining " "the same or changing? See Scase et al.") self.params['signalDots'] = Param( signalDots, valType='str', inputType="choice", allowedVals=['same', 'different'], categ='Dots', hint=msg, label=_translate("Signal dots")) msg = _translate("When should the whole sample of dots be refreshed") self.params['refreshDots'] = Param( refreshDots, valType='str', inputType="choice", allowedVals=['none', 'repeat'], categ='Dots', allowedUpdates=[], hint=msg, direct=False, label=_translate("Dot refresh rule")) msg = _translate("What governs the behaviour of the noise dots? " "See Scase et al.") self.params['noiseDots'] = Param( noiseDots, valType='str', inputType="choice", categ='Dots', allowedVals=['direction', 'position', 'walk'], hint=msg, label=_translate("Noise dots")) self.params['fieldShape'] = Param( fieldShape, valType='str', inputType="choice", allowedVals=['circle', 'square'], categ='Layout', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=_translate("What is the shape of the field?"), label=_translate("Field shape")) msg = _translate("What is the size of the field " "(in the specified units)?") self.params['fieldSize'] = Param( fieldSize, valType='num', inputType="single", categ='Layout', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Field size")) msg = _translate( "Where is the field centred (in the specified units)?") self.params['fieldPos'] = Param( fieldPos, valType='list', inputType="single", categ='Layout', updates='constant', allowedUpdates=['constant', 'set every repeat', 'set every frame'], hint=msg, label=_translate("Field position")) self.params['anchor'] = Param( fieldAnchor, 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 field should be anchored to its exact position?"), label=_translate("Field anchor")) # Reword colour parameters self.params['color'].label = _translate("Dot color") self.params['colorSpace'].label = _translate("Dot color space") del self.params['size'] # should be fieldSize del self.params['pos'] # should be fieldPos del self.params['ori'] # should be dir for dots 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 # do writing of init # replaces variable params with sensible defaults inits = getInitVals(self.params) depth = -self.getPosInRoutine() code = ("%s = visual.DotStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " nDots=%(nDots)s, dotSize=%(dotSize)s,\n" % inits + " speed=%(speed)s, dir=%(dir)s, coherence=%(coherence)s,\n" % inits + " fieldPos=%(fieldPos)s, fieldSize=%(fieldSize)s, fieldAnchor=%(anchor)s, fieldShape=%(fieldShape)s,\n" % inits + " signalDots=%(signalDots)s, noiseDots=%(noiseDots)s,dotLife=%(dotLife)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s, opacity=%(opacity)s,\n" % inits + " depth=%.1f)\n" % depth) buff.writeIndentedLines(code) def writeRoutineStartCode(self,buff): super(DotsComponent, self).writeRoutineStartCode(buff) if self.params['refreshDots'].val in ['repeat', 'Repeat']: buff.writeIndented("%(name)s.refreshDots()\n" %self.params)
9,039
Python
.py
173
39.421965
132
0.568739
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)
5,599
__init__.py
psychopy_psychopy/psychopy/experiment/components/mouse/__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 import re class MouseComponent(BaseComponent): """An event class for checking the mouse location and buttons at given timepoints """ categories = ['Responses'] targets = ['PsychoPy', 'PsychoJS'] iconFile = Path(__file__).parent / 'mouse.png' tooltip = _translate('Mouse: query mouse position and buttons') def __init__(self, exp, parentName, name='mouse', startType='time (s)', startVal=0.0, stopType='duration (s)', stopVal=1.0, startEstim='', durationEstim='', save='on click', forceEndRoutineOnPress="any click", storeCorrect=False, correctAns="", timeRelativeTo='mouse onset'): super(MouseComponent, self).__init__( exp, parentName, name=name, startType=startType, startVal=startVal, stopType=stopType, stopVal=stopVal, startEstim=startEstim, durationEstim=durationEstim) self.type = 'Mouse' self.url = "https://www.psychopy.org/builder/components/mouse.html" self.exp.requirePsychopyLibs(['event']) self.order += [ 'forceEndRoutineOnPress', # Basic tab 'saveMouseState', 'timeRelativeTo', 'newClicksOnly', 'clickable', 'saveParamsClickable', # Data tab ] # params msg = _translate( "How often should the mouse state (x,y,buttons) be stored? " "On every video frame, every click or just at the end of the " "Routine?") self.params['saveMouseState'] = Param( save, valType='str', inputType="choice", categ='Data', allowedVals=['final', 'on click', 'on valid click', 'every frame', 'never'], hint=msg, direct=False, label=_translate("Save mouse 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', 'correct click'], updates='constant', direct=False, hint=msg, label=_translate("End Routine on press")) msg = _translate("What should the values of mouse.time should be " "relative to?") self.params['timeRelativeTo'] = Param( timeRelativeTo, valType='str', inputType="choice", categ='Data', allowedVals=['mouse onset', 'experiment', 'routine'], updates='constant', hint=msg, direct=False, label=_translate("Time relative to")) msg = _translate('If the mouse button is already down when we start ' 'checking then wait for it to be released before ' 'recording as a new click.' ) self.params['newClicksOnly'] = Param( True, valType='bool', inputType="bool", categ='Basic', updates='constant', hint=msg, label=_translate("New clicks only")) 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='Basic', 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 mouse. 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=[], direct=False, hint=msg, label=_translate("Store params for clicked")) 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' object? To specify an area, remember that you can create a shape Component with 0 " "opacity.") self.params['correctAns'] = Param( correctAns, valType='list', inputType="single", allowedTypes=[], categ='Data', updates='constant', hint=msg, direct=False, label=_translate("Correct answer")) @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 mouse was inside our 'clickable' objects\n" "gotValidClick = False\n" "clickableList = environmenttools.getFromNames(%(clickable)s, namespace=locals())\n" "for obj in clickableList:\n" " # is this object clicked on?\n" " if obj.contains(%(name)s):\n" " gotValidClick = True\n") buff.writeIndentedLines(code % self.params) # store clicked object if there was one code = "" for paramName in self._clickableParamsList: code += ( f" %(name)s.clicked_{paramName}.append(obj.{paramName})\n" ) buff.writeIndentedLines(code % self.params) # if storing every click and got an invalid click, store None for all params when there was no valid click if self.params['saveMouseState'].val not in ['on valid click', 'never']: code = "if not gotValidClick:\n" for paramName in self._clickableParamsList: code += ( f" %(name)s.clicked_{paramName}.append(None)\n" ) buff.writeIndentedLines(code % self.params) def _writeCorrectAnsCode(self, buff): code = ( "# check whether click was in correct object\n" "if gotValidClick:\n" " _corr = 0\n" " _corrAns = environmenttools.getFromNames(%(correctAns)s, namespace=locals())\n" " for obj in _corrAns:\n" " # is this object clicked on?\n" " if obj.contains(%(name)s):\n" " _corr = 1\n" " %(name)s.corr.append(_corr)\n" ) # Write force end code if self.params['forceEndRoutineOnPress'] == 'correct click': code += ( " if corr:\n" " continueRoutine = False # end routine on correct answer\n" ) buff.writeIndentedLines(code % self.params) def _writeCorrectAnsCodeJS(self, buff): code = ( "// check whether click was in correct object\n" "if (gotValidClick) {\n" " corr = 0;\n" " corrAns = eval( %(correctAns)s);\n" " for (let obj of [corrAns]) {\n" " if (obj.contains(%(name)s)) {\n" " corr = 1;\n" " };\n" " };\n" " %(name)s.corr.push(corr);\n" ) # Write force end code if self.params['forceEndRoutineOnPress'] == 'correct click': code += ( " if (corr) {\n" " // end routine on correct answer\n" " continueRoutine = false;\n" " };\n" ) buff.writeIndentedLines(code % self.params) # Close if statement code = ( "};\n" ) buff.writeIndentedLines(code % self.params) def _writeClickableObjectsCodeJS(self, buff): # code to check if clickable objects were clicked code = ( "// check if the mouse was inside our 'clickable' objects\n" "gotValidClick = false;\n" "%(name)s.clickableObjects = eval(%(clickable)s)\n;" "// make sure the mouse's clickable objects are an array\n" "if (!Array.isArray(%(name)s.clickableObjects)) {\n" " %(name)s.clickableObjects = [%(name)s.clickableObjects];\n" "}\n" "// iterate through clickable objects and check each\n" "for (const obj of %(name)s.clickableObjects) {\n" " if (obj.contains(%(name)s)) {\n" " gotValidClick = true;\n" ) for paramName in self._clickableParamsList: code += ( f" %(name)s.clicked_{paramName}.push(obj.{paramName});\n" ) code += ( " }\n" "}\n" ) buff.writeIndentedLines(code % self.params) # if storing every click and got an invalid click, store None for all params when there was no valid click if self.params['saveMouseState'].val not in ['on valid click', 'never']: code = "if (!gotValidClick) {\n" for paramName in self._clickableParamsList: code += ( f" %(name)s.clicked_{paramName}.push(null);\n" ) code += "}\n" buff.writeIndentedLines(code % self.params) def writeInitCode(self, buff): code = ("%(name)s = event.Mouse(win=win)\n" "x, y = [None, None]\n" "%(name)s.mouseClock = core.Clock()\n") buff.writeIndentedLines(code % self.params) def writeInitCodeJS(self, buff): code = ("%(name)s = new core.Mouse({\n" " win: psychoJS.window,\n" "});\n" "%(name)s.mouseClock = new util.Clock();\n") buff.writeIndentedLines(code % self.params) def writeRoutineStartCode(self, buff): """Write the code that will be called at the start of the routine """ # 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['saveMouseState'].val in ['every frame', 'on click', 'on valid click']: code += ("%(name)s.x = []\n" "%(name)s.y = []\n" "%(name)s.leftButton = []\n" "%(name)s.midButton = []\n" "%(name)s.rightButton = []\n" "%(name)s.time = []\n") if self.params['storeCorrect']: code += ( "%(name)s.corr = []\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.mouseClock.reset()\n" buff.writeIndentedLines(code % self.params) def writeRoutineStartCodeJS(self, buff): """Write the code that will be called at the start of the routine""" code = ("// setup some python lists for storing info about the %(name)s\n") if self.params['saveMouseState'].val in ['every frame', 'on click', 'on valid click']: code += ("// current position of the mouse:\n" "%(name)s.x = [];\n" "%(name)s.y = [];\n" "%(name)s.leftButton = [];\n" "%(name)s.midButton = [];\n" "%(name)s.rightButton = [];\n" "%(name)s.time = [];\n") if self.params['storeCorrect']: code += ( "%(name)s.corr = [];\n" ) if self.params['clickable'].val: for clickableObjParam in self._clickableParamsList: code += "%s.clicked_%s = [];\n" % (self.params['name'], clickableObjParam) code += "gotValidClick = false; // until a click is received\n" if self.params['timeRelativeTo'].val.lower() == 'routine': code += "%(name)s.mouseClock.reset();\n" buff.writeIndentedLines(code % self.params) def writeFrameCode(self, buff): """Write the code that will be called every frame""" forceEnd = self.params['forceEndRoutineOnPress'].val # get a clock for timing timeRelative = self.params['timeRelativeTo'].val.lower() if timeRelative == 'experiment': self.clockStr = 'globalClock' elif timeRelative in ['routine', 'mouse onset']: self.clockStr = '%s.mouseClock' % self.params['name'].val 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 = "" if self.params['timeRelativeTo'].val.lower() == 'mouse onset': code += "%(name)s.mouseClock.reset()\n" if self.params['newClicksOnly']: code += ( "prevButtonState = %(name)s.getPressed()" " # if button is down already this ISN'T a new click\n") else: code += ( "prevButtonState = [0, 0, 0]" " # if now button is down we will treat as 'new' click\n") buff.writeIndentedLines(code % 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) # 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['saveMouseState'].val not in ['every frame', 'on click', 'on valid click'] and forceEnd == 'never'): return # 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 def _buttonPressCode(buff, dedent): """Code compiler for mouse button events""" code = ("buttons = %(name)s.getPressed()\n" "if buttons != prevButtonState: # button state changed?") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(1, relative=True) dedent += 1 buff.writeIndented("prevButtonState = buttons\n") code = ("if sum(buttons) > 0: # state changed to a new click\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(1, relative=True) dedent += 1 # keep track of whether something's been written hasContent = False # write code to check clickable stim, if there are any if self.params['clickable'].val: self._writeClickableObjectsCode(buff) hasContent = True # write code to check correct stim, if there are any if self.params['storeCorrect']: self._writeCorrectAnsCode(buff) hasContent = True # if current if statement has no content, add a pass if not hasContent: buff.writeIndentedLines( "pass" ) return buff, dedent # No mouse tracking, end routine on any or valid click if self.params['saveMouseState'].val in ['never', 'final'] and forceEnd != "never": buff, dedentAtEnd = _buttonPressCode(buff, dedentAtEnd) if forceEnd == 'valid click': # does valid response end the trial? code = ("if gotValidClick: \n" " continueRoutine = False # end routine on response\n") buff.writeIndentedLines(code) buff.setIndentLevel(-dedentAtEnd, relative=True) else: buff.writeIndented('continueRoutine = False # end routine on response') buff.setIndentLevel(-dedentAtEnd, relative=True) elif self.params['saveMouseState'].val != 'never': mouseCode = ("x, y = {name}.getPos()\n" "{name}.x.append(x)\n" "{name}.y.append(y)\n" "buttons = {name}.getPressed()\n" "{name}.leftButton.append(buttons[0])\n" "{name}.midButton.append(buttons[1])\n" "{name}.rightButton.append(buttons[2])\n" "{name}.time.append({clockStr}.getTime())\n".format(name=self.params['name'], clockStr=self.clockStr)) # Continuous mouse tracking if self.params['saveMouseState'].val in ['every frame']: buff.writeIndentedLines(mouseCode) # Continuous mouse tracking for all button press if forceEnd == 'never' and self.params['saveMouseState'].val in ['on click', 'on valid click']: buff, dedentAtEnd = _buttonPressCode(buff, dedentAtEnd) if self.params['saveMouseState'].val in ['on click']: buff.writeIndentedLines(mouseCode) elif self.params['clickable'].val and self.params['saveMouseState'].val in ['on valid click']: code = ( "if gotValidClick:\n" ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) buff.writeIndentedLines(mouseCode) buff.setIndentLevel(-1, relative=True) # Mouse tracking for events that end routine elif forceEnd != "never": buff, dedentAtEnd = _buttonPressCode(buff, dedentAtEnd) # Save all mouse events on button press if self.params['saveMouseState'].val in ['on click']: buff.writeIndentedLines(mouseCode) elif self.params['clickable'].val and self.params['saveMouseState'].val in ['on valid click']: code = ( "if gotValidClick:\n" ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) buff.writeIndentedLines(mouseCode) buff.setIndentLevel(-1, relative=True) # also write code about clicked objects if needed. if self.params['clickable'].val: # does valid response end the trial? if forceEnd == 'valid click': code = ("if gotValidClick:\n" " continueRoutine = False # end routine on response\n") buff.writeIndentedLines(code) # does any response end the trial? if forceEnd == 'any click': code = ("\n" "continueRoutine = False # end routine on response\n") buff.writeIndentedLines(code) elif forceEnd == 'correct click': code = ( "if %(name)s.corr and %(name)s.corr[-1]:\n" " continueRoutine = False # end routine on response\n" ) else: pass # forceEnd == 'never' # 'if' statement of the time test and button check buff.setIndentLevel(-dedentAtEnd, relative=True) def writeFrameCodeJS(self, buff): """Write the code that will be called every frame""" forceEnd = self.params['forceEndRoutineOnPress'].val # get a clock for timing timeRelative = self.params['timeRelativeTo'].val.lower() if timeRelative == 'experiment': self.clockStr = 'globalClock' elif timeRelative in ['routine', 'mouse onset']: self.clockStr = '%s.mouseClock' % 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['saveMouseState'].val not in ['every frame', 'on click', 'on valid 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.writeStartTestCodeJS(buff) if indented: code = "%(name)s.status = PsychoJS.Status.STARTED;\n" if self.params['timeRelativeTo'].val.lower() == 'mouse onset': code += "%(name)s.mouseClock.reset();\n" % self.params if self.params['newClicksOnly']: code += ( "prevButtonState = %(name)s.getPressed();" " // if button is down already this ISN'T a new click\n") else: code += ( "prevButtonState = [0, 0, 0];" " // if now button is down we will treat as 'new' click\n") buff.writeIndentedLines(code % self.params) # to get out of the if statement for n in range(indented): buff.setIndentLevel(-1, relative=True) buff.writeIndented("}\n") # test for stop (only if there was some setting for duration or stop) indented = self.writeStopTestCodeJS(buff) if indented: buff.writeIndented("%(name)s.status = PsychoJS.Status.FINISHED;\n" % self.params) # to get out of the if statement for n in range(indented): buff.setIndentLevel(-1, relative=True) buff.writeIndented("}\n") # if STARTED and not FINISHED! indented = self.writeActiveTestCodeJS(buff) if indented: # write param checking code if (self.params['saveMouseState'].val in ['on click', 'on valid click'] or forceEnd in ['any click', 'correct click', 'valid click']): code = ("_mouseButtons = %(name)s.getPressed();\n") buff.writeIndentedLines(code % self.params) # buff.setIndentLevel(1, relative=True) # dedentAtEnd += 1 code = "if (!_mouseButtons.every( (e,i,) => (e == prevButtonState[i]) )) { // button state changed?\n" buff.writeIndented(code) buff.setIndentLevel(1, relative=True) indented += 1 buff.writeIndented("prevButtonState = _mouseButtons;\n") code = ("if (_mouseButtons.reduce( (e, acc) => (e+acc) ) > 0) { // state changed to a new click\n") buff.writeIndentedLines(code % self.params) buff.setIndentLevel(1, relative=True) indented += 1 elif self.params['saveMouseState'].val == 'every frame': code = "_mouseButtons = %(name)s.getPressed();\n" % self.params buff.writeIndented(code) # also write code about clicked objects if needed. if self.params['clickable'].val: self._writeClickableObjectsCodeJS(buff) # also write code about correct objects if needed if self.params['storeCorrect']: self._writeCorrectAnsCodeJS(buff) if self.params['saveMouseState'].val in ['on click', 'on valid click', 'every frame']: storeCode = ( "_mouseXYs = %(name)s.getPos();\n" "%(name)s.x.push(_mouseXYs[0]);\n" "%(name)s.y.push(_mouseXYs[1]);\n" "%(name)s.leftButton.push(_mouseButtons[0]);\n" "%(name)s.midButton.push(_mouseButtons[1]);\n" "%(name)s.rightButton.push(_mouseButtons[2]);\n" % self.params ) storeCode += ("%s.time.push(%s.getTime());\n" % (self.params['name'], self.clockStr)) if self.params['clickable'].val and self.params['saveMouseState'].val in ['on valid click']: code = ( "if (gotValidClick === true) { \n" ) buff.writeIndentedLines(code) buff.setIndentLevel(+1, relative=True) buff.writeIndentedLines(storeCode) buff.setIndentLevel(-1, relative=True) code = ( "}\n" ) buff.writeIndentedLines(code) else: buff.writeIndentedLines(storeCode) # does the response end the trial? if forceEnd == 'any click': code = ("// end routine on response\n" "continueRoutine = false;\n") buff.writeIndentedLines(code) elif forceEnd == 'valid click': code = ("if (gotValidClick === true) { // end routine on response\n" " continueRoutine = false;\n" "}\n") buff.writeIndentedLines(code) else: pass # forceEnd == 'never' # to get out of the if statement for n in range(indented): buff.setIndentLevel(-1, relative=True) buff.writeIndented("}\n") def writeRoutineEndCode(self, buff): # some shortcuts name = self.params['name'] # do this because the param itself is not a string! store = self.params['saveMouseState'].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 " "mouse events so doesn't know how to handle mouse with " "StairHandler\n") else: code = ("# store data for %s (%s)\n" % (currLoop.params['name'], currLoop.type)) buff.writeIndentedLines(code) if store == 'final': # for the o # buff.writeIndented("# get info about the %(name)s\n" # %(self.params)) code = ("x, y = {name}.getPos()\n" "buttons = {name}.getPressed()\n").format(name=self.params['name']) # also write code about clicked objects if needed. buff.writeIndentedLines(code) if self.params['clickable'].val: buff.writeIndented("if sum(buttons):\n") buff.setIndentLevel(+1, relative=True) self._writeClickableObjectsCode(buff) buff.setIndentLevel(-1, relative=True) if currLoop.type != 'StairHandler': code = ( "{loopName}.addData('{name}.x', x)\n" "{loopName}.addData('{name}.y', y)\n" "{loopName}.addData('{name}.leftButton', buttons[0])\n" "{loopName}.addData('{name}.midButton', buttons[1])\n" "{loopName}.addData('{name}.rightButton', buttons[2])\n" ) if self.params['storeCorrect']: code += ( "{loopName}.addData('{name}.corr', {name}.corr)\n" ) buff.writeIndentedLines( code.format(loopName=currLoop.params['name'], name=name)) # then add `trials.addData('mouse.clicked_name',.....)` if self.params['clickable'].val: for paramName in self._clickableParamsList: code = ( "if len({name}.clicked_{param}):\n" " {loopName}.addData('{name}.clicked_{param}', " "{name}.clicked_{param}[0])\n" ) buff.writeIndentedLines( code.format(loopName=currLoop.params['name'], name=name, param=paramName)) elif store != 'never': # buff.writeIndented("# save %(name)s data\n" %(self.params)) mouseDataProps = ['x', 'y', 'leftButton', 'midButton', 'rightButton', 'time'] if self.params['storeCorrect']: mouseDataProps += ['corr'] # possibly add clicked params if we have clickable objects if self.params['clickable'].val: for paramName in self._clickableParamsList: mouseDataProps.append("clicked_{}".format(paramName)) # use that set of properties to create set of addData commands for property in mouseDataProps: 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 = ("%s.addData('%s.%s', %s.%s)\n" % (currLoop.params['name'], name, property, name, property)) buff.writeIndented(code) # get parent to write code too (e.g. store onset/offset times) super().writeRoutineEndCode(buff) def writeRoutineEndCodeJS(self, buff): """Write code at end of routine""" # some shortcuts name = self.params['name'] # do this because the param itself is not a string! store = self.params['saveMouseState'].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 " "mouse events so doesn't know how to handle mouse with " "StairHandler*/\n") else: code = ("// store data for %s (%s)\n" % (currLoop.params['name'], currLoop.type)) buff.writeIndentedLines(code) if store == 'final': code = ("_mouseXYs = {name}.getPos();\n" "_mouseButtons = {name}.getPressed();\n") if currLoop.type != 'StairHandler': code += ( "psychoJS.experiment.addData('{name}.x', _mouseXYs[0]);\n" "psychoJS.experiment.addData('{name}.y', _mouseXYs[1]);\n" "psychoJS.experiment.addData('{name}.leftButton', _mouseButtons[0]);\n" "psychoJS.experiment.addData('{name}.midButton', _mouseButtons[1]);\n" "psychoJS.experiment.addData('{name}.rightButton', _mouseButtons[2]);\n" ) if self.params['storeCorrect']: code += ( "psychoJS.experiment.addData('{name}.corr', {name}.corr);\n" ) buff.writeIndentedLines(code.format(name=name)) # For clicked objects... if self.params['clickable'].val: for paramName in self._clickableParamsList: code = ( "if ({name}.clicked_{param}.length > 0) {{\n" " psychoJS.experiment.addData('{name}.clicked_{param}', " "{name}.clicked_{param}[0]);}}\n".format(name=name, param=paramName)) buff.writeIndentedLines(code) elif store != 'never': # buff.writeIndented("# save %(name)s data\n" %(self.params)) mouseDataProps = ['x', 'y', 'leftButton', 'midButton', 'rightButton', 'time'] if self.params['storeCorrect']: mouseDataProps += ['corr'] # possibly add clicked params if we have clickable objects if self.params['clickable'].val: for paramName in self._clickableParamsList: mouseDataProps.append("clicked_{}".format(paramName)) # use that set of properties to create set of addData commands for property in mouseDataProps: code = ("psychoJS.experiment.addData('%s.%s', %s.%s);\n" % (name, property, name, property)) buff.writeIndented(code) buff.writeIndentedLines("\n")
35,364
Python
.py
686
36.59621
146
0.529964
psychopy/psychopy
1,662
900
218
GPL-3.0
9/5/2024, 5:09:29 PM (Europe/Amsterdam)